Design Patterns Senior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. How does the "signals" model (Solid, Preact Signals, Angular Signals) differ from React's model?
Correct answer: Only the dependent places update, without re-rendering the component
A signal is a reactive value (Observer): reading registers a dependency, and writing updates exactly its subscribers (text, an attribute, a computation). React instead re-renders the component and diffs the virtual tree; the React Compiler reduces that cost, but the model is different.
2. What's the main trade-off of micro-frontends?
Correct answer: Independent teams and deploys at the cost of complexity, duplication and UX consistency
Micro-frontends are justified with many autonomous teams and a large product: each part is deployed separately. The cost is duplicated dependencies, complex integration, shared design, routing and communication between parts. Smaller teams usually do fine with a modular monolith.
3. Why is React declared as a
sharedsingleton in Module Federation?Correct answer: Two copies of React in one app break hooks and context
Hooks and context are tied to a specific React instance: a component from a remote module with its own copy causes "Invalid hook call", and contexts aren't visible. Shared singleton dependencies require coordinating versions between teams.
4. How does the Strangler Fig pattern work when migrating a legacy frontend?
Correct answer: The new system gradually takes over routes and features of the old one until it disappears
For example, a proxy routes
/checkoutto the new Next.js app and everything else to the old one. Risks are lower than with a "big rewrite": value is delivered gradually, and you can roll back at any step.5. What does CQRS mean?
Correct answer: Separate models for writing (commands) and reading (queries)
The read model can be optimized for display (denormalized views), and the write model for business rules. It adds complexity and often eventual consistency, so it's used in complex domains, not by default. On the frontend, a similar idea is separating mutations and queries, as in TanStack Query.
6. What is Event Sourcing?
Correct answer: State is a log of events, and the current value is derived from it
Instead of "balance = 100", events like "deposited 150" and "withdrew 50" are stored. This gives a full audit trail and the ability to replay and recompute state. Redux with time travel is the frontend counterpart: state = a fold of actions.
7. What is a Bounded Context in DDD?
Correct answer: A boundary where the model's terms are unambiguous
An "order" means different things in the catalog, payments and shipping, and a single model for all of them becomes a compromise. Contexts separate models and connect via explicit integrations. It's a good basis for splitting into modules, services and micro-frontends.
8. What's the idea of hexagonal architecture (Ports & Adapters)?
Correct answer: The core uses port interfaces; adapters implement them
A port is an interface such as
PaymentPort; adapters are Stripe, a mock, a test implementation. The core knows nothing about HTTP, the DB or the UI. The idea is close to Clean Architecture and DIP; on the frontend, ports are often expressed as hooks or injected services.9. When does Clean Architecture on the frontend become harmful?
Correct answer: When layers outnumber the real business logic
For a CRUD interface, a "use case → repository → mapper → DTO" chain for every button is over-engineering: lots of code with no benefit. Architecture should match domain complexity; sometimes separating UI, state and the API layer is enough.
10. How do you automatically enforce architectural import rules (e.g. FSD layers)?
Correct answer: With boundary linters in CI (dependency-cruiser, Steiger)
Rules like "features don't import widgets" and "no cycles" are checked in CI. Without automation, architecture degrades over time. TypeScript doesn't check layers by itself.
11. What is an Anti-Corruption Layer?
Correct answer: A translation layer that keeps a foreign model out of yours
Integration with a legacy API or a third-party SDK through adapters and mapping: odd field names, error codes and formats stay at the boundary. This reduces vendor lock-in: changing the provider affects only that layer.
12. How does an RxJS Observable differ from a Promise?
Correct answer: An Observable is a lazy, cancellable stream; a Promise is a single value
A promise starts immediately, delivers one value and can't be cancelled. An Observable starts on subscription, can emit many values (events, WebSocket), is cancelled by unsubscribing and has operators (
debounceTime,switchMap). It's an implementation of Observer + Iterator.13. What do statecharts (XState) offer compared to a flat finite state machine?
Correct answer: Nested and parallel states without an explosion in their number
A flat machine for a complex process (a video player, a multi-step form) grows quickly. Nested and parallel states, transition guards and side effects are described declaratively, and the diagram can be visualized and tested.
14. What is the Backend for Frontend (BFF) pattern?
Correct answer: A server layer tailored to a specific client
A mobile app and the web need different data. A BFF combines requests to microservices, strips unnecessary fields, and holds secrets and the session. Next.js with Route Handlers and Server Components often plays this role.
15. What is the expression problem, and how does it show up in TS?
Correct answer: Unions are easy to extend with operations, classes with new types
With a discriminated union, adding a new handler function is easy, but a new variant requires editing every
switch. In OOP with classes, adding a new type is easy, but a new operation is expensive (solved with Visitor). The choice depends on what will change more often.16. What does "functional core, imperative shell" mean?
Correct answer: Logic as pure functions, effects in a thin outer layer
Calculations, validation and state transitions are easy to test without mocks, while requests, timers and the DOM are isolated at the edges. Redux reducers with effects in middleware, or TanStack Query, are examples of this separation.
17. What is the "Hollywood principle", and how does it show up in React?
Correct answer: "Don't call us": the framework calls your code
You describe components, and React decides when to render them and call effects and handlers. This distinguishes a framework from a utility library that you call. Render props and callbacks are local forms of the same principle.
18. What is a Composition Root?
Correct answer: A single place where the dependency graph is assembled
Concrete implementations (API client, logger, storage) are created and wired at the entry point (
main, a root layout with providers), and the rest of the code receives abstractions. This keeps dependencies visible and replaceable.19. Why is Service Locator often considered an anti-pattern compared to DI?
Correct answer: Dependencies are hidden: they aren't visible in the signature
locator.get('api')inside a function is an implicit dependency: a test has to set up a global registry, and errors show up at runtime. With DI, dependencies are visible in the parameters.useContextis close to a locator but is scoped to the tree and typed.20. What's wrong with a "God Context" - one React Context holding all of the app's state?
Correct answer: Any change wakes up every consumer
Changing the theme re-renders the cart, and typing in the search form re-renders the whole catalog. Besides, all modules become coupled through one object. Split the context by domain and change frequency, or use a store with selectors.
21. What is temporal coupling?
Correct answer: Call order matters, but the interface doesn't express it
For example,
client.init()must be called beforeclient.send(), or there's an error. Better to make the wrong order impossible: a factory that returns a ready object, or a Builder that hands out the object only after the mandatory steps.22. What does Conway's law state?
Correct answer: Architecture mirrors team communication
Three teams tend to create three modules or services. This is used deliberately (the "inverse Conway maneuver"): teams are structured to match the desired architecture. Micro-frontends and microservices are largely organizational decisions.
23. How does the MobX approach differ from Redux architecturally?
Correct answer: MobX - mutable observable objects; Redux - an immutable store and explicit actions
MobX tracks dependencies automatically and updates precisely, but the flow of changes is less explicit. Redux requires more code, but changes go through actions and reducers - easier to debug and replay. The choice is a trade-off between convenience and predictability.
24. Why is separating "server" and "client" state considered an important architectural decision?
Correct answer: They have different jobs: caching and syncing versus UI
Server data is a copy that goes stale: it needs caching, invalidation, retries and deduplication (TanStack Query, RTK Query, RSC). UI state (whether a dialog is open, a form draft) belongs to the client. Mixing them in one store leads to manual syncing and bugs.
25. What is Islands Architecture?
Correct answer: Static HTML with independent interactive "islands"
Most of the page is HTML without JS, and JS loads only for interactive widgets (Astro, Fresh). This reduces JS size and time to interactivity for content sites. React Server Components solve a similar problem within the React tree.
26. What's the right way to evolve the public API of a shared component library?
Correct answer: SemVer, a deprecation period and codemods
A breaking change is a major version; before removing an API, mark it deprecated with a warning and instructions. Codemods (like those for Next.js and React) automate migration. This way the library evolves without breaking dozens of apps.
27. What is an ADR (Architecture Decision Record)?
Correct answer: A record of the context, the decision and its consequences
ADRs are kept next to the code so that a year later it's clear why, say, TanStack Query was chosen over Redux. This reduces repeated debates and helps new team members.
28. Why is the order of middleware or interceptors in a chain of responsibility risky?
Correct answer: The result depends on the order of the handlers
Token refresh must come before the retry, caching after authorization, error transformation at the end. The order should be set explicitly in one place and covered by tests.
29. What distinguishes a Value Object?
Correct answer: Equality by value, immutability, its own invariants
Money(100, 'USD')equals anotherMoney(100, 'USD'), and operations return new objects. Validation in one place rules out a "negative amount" throughout the code. In TS, branded types with factories are close to this.30. What is an Aggregate in DDD?
Correct answer: A group of objects with a root through which changes go
For example, an order with line items: items can be changed only through
Order, which enforces invariants (total, limits). An aggregate is a consistency and transaction boundary.31. What does the Command-Query Separation (CQS) principle require?
Correct answer: A method either changes state or returns data
A query function without side effects is predictable and safe to call repeatedly (e.g. during render). There are exceptions (
stack.pop()), but the principle helps avoid surprises like a getter that makes a request. CQRS is the architectural extension of this idea.32. What does the "Tell, Don't Ask" principle mean?
Correct answer: Ask an object to act instead of deciding for it
Instead of
if (cart.items.length > 0 && !cart.locked) cart.items.push(x)-cart.add(x), with the rules inside. This keeps invariants close to the data and reduces "envious" functions.33. What does the Fail Fast principle mean?
Correct answer: Fail immediately and explicitly on invalid data
Validating configuration and input on startup or at the boundary (Zod schemas, assertion functions) gives a clear error next to the cause, rather than a mysterious
undefinedten calls later.34. What's the risk of Postel's law ("be liberal in what you accept")?
Correct answer: Tolerating errors entrenches them in clients
If an API accepts malformed data, clients start relying on it, and fixing it becomes a breaking change. The modern approach is to validate input strictly and version changes explicitly.
35. How should the UI account for eventual consistency in an event-driven system?
Correct answer: Show intermediate statuses and roll back optimistic updates
After a command is sent, the data in a list may not update immediately. The UI shows a "processing" status, applies an optimistic change and updates it on an event (WebSocket, a refetch) or rolls it back on error.
36. How does redux-saga differ from listener middleware and thunks?
Correct answer: A saga describes complex async flows with generators
Generators with
take,raceandcanceleffects let you describe long-running processes declaratively and test them step by step. The cost is complexity and a learning curve. RTK recommends thunks and listener middleware for most tasks.37. Why is normalizing data in a frontend store an architectural pattern rather than a micro-optimization?
Correct answer: Each entity is stored once by id - no desync
If a user appears both in a list and in comments, denormalized copies drift apart. An
{ ids, entities }table gives a single source of truth and fast updates by id. The cost is assembling data with selectors.38. How do you use Strategy for A/B tests without cluttering components with conditions?
Correct answer: Choose the implementation at the boundary and pass it inward
A factory or provider picks the component/strategy by flag, and the rest of the code works with a common interface. After the experiment, the losing variant is removed in one place, without hunting for conditions across the project.
39. What are afferent and efferent coupling of a module?
Correct answer: How many modules depend on it, and how many it depends on
A module many others depend on (high afferent coupling) should be stable and abstract - e.g.
shared/ui. A module depending on many others is unstable. The instability metric helps spot violations of dependency direction.40. How does a modular monolith differ from microservices (micro-frontends)?
Correct answer: One build and deploy, but strict module boundaries inside
A modular monolith gives most of the benefits of separation (boundaries, ownership, public APIs) without distributed complexity. It's often the right first step: modules can be extracted later if a real need arises.
41. What are domain events on the frontend, and why are they useful?
Correct answer: Messages about domain facts for independent modules
The checkout module publishes an event, and analytics, the cart and notifications react without being directly coupled. It's Pub/Sub at the domain level; it's important to maintain an event catalog and type the payloads.
42. How does the Circuit Breaker pattern help the client when an API fails?
Correct answer: After a series of errors it temporarily stops sending requests
States: closed (requests go through), open (immediate failure or fallback), half-open (trial requests). This prevents an avalanche of retries to a failed service and gives the user a fast response with degraded functionality.
43. When is the Visitor pattern justified in a TypeScript project?
Correct answer: When node types are stable but operations keep growing
Visitor is handy for ASTs, documents and editor block trees: new operations (rendering, export, validation) are added without changing the nodes. If new nodes are added often, every visitor has to change - that's the expression problem.
44. How do you implement reliable undo in a collaborative editor with several users editing?
Correct answer: Undo your own operations while accounting for others' (OT/CRDT)
A global rollback to a snapshot would destroy other people's changes. In collaborative systems, undo is a new inverse operation on the current state that accounts for concurrent edits. Command and Memento work locally, but collaboration needs OT or CRDT models.
45. What does a Facade over a third-party UI library (e.g. your own
<Button>on top of MUI) give you?Correct answer: Your own stable API and replacing the library in one place
The app uses only your components with the variants you need, and the library details are hidden. A major version upgrade or migration affects only the wrapper layer. The downside is maintaining the wrappers and not leaking the library's whole API through.
46. What's the difference between "implementation inheritance" and "interface inheritance"?
Correct answer: The first takes the parent's code, the second only the contract
A class's
extendspulls in the implementation and creates strong coupling to the parent.implementsor structural typing define only the contract. Most "composition over inheritance" advice is specifically about implementation inheritance.47. Why is the Saga pattern (orchestration) in distributed processes relevant to the frontend?
Correct answer: A multi-step process with compensating actions
Placing an order: reserve the item → pay → ship; if payment fails, the reservation must be cancelled. The frontend should reflect intermediate statuses and the outcome of compensations rather than treating the operation as atomic.
48. How do Server Components change architecture compared to an SPA?
Correct answer: Data and logic on the server, interactivity on the client
The
'use client'boundary becomes an architectural decision: where state and handlers live, and where data and secrets are accessed. Client JS shrinks, and part of the client-side API and cache layer disappears, but new questions arise - server-side caching and props serialization.49. What is an "internal platform" (design system + shared packages), and when should you extract one?
Correct answer: Shared components and tools, once several products use them
When several teams copy the same buttons, forms, build configs and linters, a platform with versioning and an owner is extracted. A platform built too early for a single product is a premature abstraction and needless bureaucracy.
50. What is the "second-system effect" in architectural decisions?
Correct answer: The tendency to overload the second version of a system with every postponed idea
Fred Brooks's term: after a successful first system, the architect designs the second one "properly", adding everything previously left out, and ends up with an overcomplicated product. An argument for incremental change, YAGNI and Strangler Fig instead of a "big rewrite".
51. What problem does the Transactional Outbox pattern solve?
Correct answer: Saving data and publishing an event atomically
Without it, a crash between "save" and "publish" loses events or publishes events for unsaved data. Consumers must be idempotent.
52. How does an API Gateway differ from a Backend for Frontend?
Correct answer: A gateway is shared; a BFF serves one client
Often both exist: a gateway at the edge and BFFs behind it per web/mobile app.
53. What is the core idea of the actor model?
Correct answer: Independent actors communicate only via messages
No shared mutable state means no locks. XState actors and Web Workers follow similar ideas in the frontend.
54. Why distinguish release, experiment, ops and permission toggles?
Correct answer: They differ in lifetime and management needs
Release toggles should live days or weeks; permission toggles may live forever. Mixing them leads to forgotten flags.
55. How does an "event notification" differ from "event-carried state transfer"?
Correct answer: State transfer includes the data in the event
Carrying state reduces coupling at runtime but duplicates data and makes event schemas a contract to version.
56. What characterizes a microkernel (plugin) architecture, as in VS Code?
Correct answer: A small stable core with plugin extension points
The extension API must evolve compatibly; isolation (separate processes, sandboxes) protects the core from faulty plugins.
57. What does "parse, don't validate" mean?
Correct answer: Turn input into a precise type once
A validator returning
booleanloses information; a parser returningEmailor an error keeps the proof in the type.58. Two packages:
checkoutneeds to send emails, andnotificationsimplements email sending. Following DIP, who owns the interface?Correct answer: The consumer (
checkout) defines the interface it needs;notificationsimplements itHigh-level policy then doesn't depend on low-level details, and implementations can be swapped or faked in tests.
59. What does the Stable Dependencies Principle say?
Correct answer: Volatile modules should depend on stable ones
If a stable, widely used module depends on a volatile one, every change ripples through many dependents.
60. Why does the Acyclic Dependencies Principle matter in a monorepo?
Correct answer: Cycles prevent independent builds and releases
Break cycles by extracting a shared module or inverting a dependency through an interface.
61. What is connascence?
Correct answer: A measure of coupling between parts of code
Prefer weaker forms (by name) over stronger ones (by position or meaning), especially across module boundaries.
62. What does the Law of Leaky Abstractions say?
Correct answer: All non-trivial abstractions leak what they hide
An ORM hides SQL until a query is slow; a fetch wrapper hides HTTP until caching misbehaves. Design for the leaks.
63. What does Hyrum's Law imply for a widely used component library?
Correct answer: Every observable behavior will be depended on
Minimize observable surface, test behavior consumers rely on and communicate changes with changelogs and codemods.
64. How does Chesterton's fence apply to refactoring legacy code?
Correct answer: Find out why odd-looking code was added
Git blame, linked tickets, ADRs and characterization tests reveal the reasons behind strange code.
65. What is the Bulkhead pattern?
Correct answer: Isolating resources per dependency
Example: a separate connection pool for a slow reporting service keeps checkout requests working.
66. How does the Cache-Aside pattern work?
Correct answer: The app checks the cache, then loads on a miss
It's simple and common, but stale data and stampedes on popular keys must be handled.
67. What is a retry storm, and how is it prevented?
Correct answer: Retries at many layers multiply the load
Three layers each retrying 3 times turn one failing request into up to 27 calls.
68. What do consumer-driven contract tests (e.g. Pact) give a frontend and backend?
Correct answer: The backend verifies what the frontend relies on
They're faster and more targeted than full end-to-end environments for catching integration drift.
69. What is an architectural fitness function?
Correct answer: An automated check of an architectural rule
Running them in CI keeps architecture from eroding silently as the codebase grows.
70. How does trunk-based development relate to feature flags?
Correct answer: Unfinished features hide behind flags on main
Short-lived branches reduce merge conflicts; flags decouple deployment from release.
71. What is a key trade-off of a monorepo compared to many repositories?
Correct answer: Atomic cross-package changes, at a tooling cost
Tools like Nx and Turborepo add affected-only builds and caching; without them monorepo CI slows down.
72. How does saga orchestration differ from choreography?
Correct answer: Orchestration has a central coordinator
Orchestration is easier to follow and change; choreography reduces coupling to a coordinator but spreads the flow across services.
73. What is a "distributed monolith"?
Correct answer: Separately deployed services released together
It combines distributed-system costs with monolith coupling. Shared databases and synchronous call chains are typical causes.
74. Why are Value Objects useful for money amounts on the frontend?
const total = Money.of(1999, 'EUR').add(Money.of(500, 'EUR'));Correct answer: They bundle amount and currency with their rules
Immutable value objects compare by value and centralize formatting and rounding rules.
75. Why use queues to decouple a slow operation (e.g. generating a PDF report) from a user request?
Correct answer: The request returns quickly; workers do the job
The UI shows a pending status and gets notified (polling, WebSocket, email) when the job completes.