Guide / System design Fundamentals
Microservice patterns
API gateway vs BFF, service discovery, sagas (orchestration vs choreography), CQRS and event sourcing, the strangler migration and service mesh, with when each is worth its cost.
Microservices trade local simplicity for distributed complexity. This page covers the patterns interviewers expect once you say “services”: how requests enter, how services find each other, how data stays consistent and how you migrate.
Fundamentals#
M.1 When to split (and when not to)#
Split when teams block each other, parts need to scale or deploy independently, failure isolation matters, or technologies differ. Do not split for “scalability” alone: a modular monolith scales a long way. Costs: network latency and partial failure, distributed transactions, versioned contracts, tracing and on-call burden. Boundaries should follow business capabilities (bounded contexts from domain-driven design: orders, payments, catalogue), with each service owning its data (no shared database tables across services).
M.2 Entry points: gateway, BFF, aggregator#
| Pattern | What it does | Use when | Watch out |
|---|---|---|---|
| API gateway | One entry: routing, auth, rate limiting, TLS, request/response transformation, caching | Always for public APIs | Becomes a bottleneck or a “god” layer if business logic creeps in |
| BFF (backend for frontend) | A gateway per client type (web, mobile, partner) shaping data for that client | Mobile and web need very different payloads | More services to run; duplicate logic |
| Aggregator / composition | Calls several services and merges the result | Screens need data from many services | Latency = slowest call; use parallel calls, timeouts, partial responses |
| GraphQL gateway / federation | One schema stitched across services | Many clients, flexible queries | Cost control, N+1 across services |
M.3 Service discovery and communication#
- Discovery: services register in a registry (Consul, etcd, Kubernetes DNS and
Service), and callers resolve names. In Kubernetes DNS plus aServiceis enough; client-side discovery (gRPC resolvers) when you need per-request balancing. - Sync (REST/gRPC): simple request-response, but couples availability (if B is down, A fails). Apply timeouts, retries, circuit breakers (Failure and recovery).
- Async (events/queues): decouples availability and time; needs idempotent consumers and handles eventual consistency (Messaging).
- Rule of thumb: commands that need an answer now → sync; notifications and propagation of facts → events. Avoid long synchronous chains (A→B→C→D multiplies latency and failure probability: five services at 99.9% each give ~99.5%).
M.4 Data consistency across services#
No cross-service ACID transactions. Use:
- Saga: a sequence of local transactions with compensating actions. Orchestration: a coordinator (Temporal, Step Functions, a saga service) tells each step what to do and triggers compensations on failure; easy to see and test. Choreography: services react to each other’s events; loose coupling but the flow is implicit and hard to debug beyond ~4 steps.
- Transactional outbox + idempotent consumers for reliable event publication (Messaging).
- Two-phase commit is rare across services (blocking, availability cost).
- Compensations must be idempotent and may fail (refund fails: retry, then alert a human); design semantic locks (an order in
PENDINGstate) to hide intermediate states.
Example order saga: create order(PENDING) → reserve stock → charge payment → confirm order. If payment fails: release stock, cancel order. Each step has a timeout and a retry policy; the saga state is persisted.
M.5 CQRS and event sourcing#
- CQRS: separate the write model (normalised, enforces invariants) from read models (denormalised projections per query, possibly in other stores like Elasticsearch or Redis) updated by events. Gains independent scaling and fast reads; costs eventual consistency and more moving parts.
- Event sourcing: store the sequence of events as the source of truth; current state = fold of events (with snapshots). Gains audit, time travel, rebuildable projections; costs query complexity, event schema evolution, and replay time. Use for ledgers, audit-heavy domains, collaborative editing; not for plain CRUD.
M.6 Migration and evolution#
- Strangler fig: put a routing layer in front of the monolith; carve out one capability at a time to a new service, routing its traffic there; shrink the monolith gradually. Use feature flags and shadow traffic to compare results.
- Anti-corruption layer: a translation layer so the new model is not polluted by the legacy model.
- Branch by abstraction / parallel run: run old and new implementations and compare outputs before switching.
- Database split: first separate schemas in the same DB, then move data with CDC, then switch ownership; avoid shared tables.
M.7 Service mesh and sidecars#
A mesh (Istio, Linkerd) runs a proxy next to each service to provide mTLS, retries, timeouts, traffic shifting (canary), telemetry and policy without library code. Benefits: uniform behaviour across languages. Costs: extra latency (~1 ms), resource overhead, operational complexity. Use it when you have dozens of services and need uniform security and observability.
M.8 Cross-cutting concerns#
Centralised config and secrets, distributed tracing (trace ID propagated in headers), structured logging with correlation IDs, contract testing (consumer-driven, e.g. Pact), API versioning, per-service SLOs, standard health endpoints, and platform paved roads (templates, CI/CD, observability by default).
Most asked questions#
1. Monolith or microservices? Start with a modular monolith; split when teams or scaling needs diverge, and say the costs.
2. How do you handle a transaction across services? Saga with compensations (orchestrated for complex flows), outbox for reliable events, idempotent steps; avoid distributed 2PC.
3. What does an API gateway do? Routing, authentication, rate limiting, TLS termination, aggregation, caching, observability; keep business logic out.
4. How do services find each other? DNS or a registry (Consul, Kubernetes services), with client-side or proxy load balancing.
5. Sync vs async between services? Sync when the caller needs the result now; async for decoupling, bursts and fan-out; prefer async for cross-boundary writes.
6. How do you migrate a monolith? Strangler fig: route by capability, extract the most independent and valuable piece first, own its data, run in parallel, retire gradually.
7. What is CQRS? Separate write and read models so each can be optimised and scaled, linked by events.
Senior-level questions#
1. “Our microservices all deploy together. What went wrong?” A distributed monolith: shared database, tight versioned contracts, synchronous chains, no backward compatibility. Fix with data ownership, backward-compatible APIs and events, consumer-driven contract tests and independent pipelines.
2. “A request fans out to 12 services and p99 is terrible.” Tail latency is dominated by the slowest call: cut fan-out (aggregate or precompute), parallelise, set per-call timeouts with partial results, cache, hedge reads, and deliver non-critical parts asynchronously.
3. “Saga compensation fails. Now what?” Retry with backoff (compensation must be idempotent), then park in a failed state with alerts and a manual or automated resolution workflow; make the system able to show users a consistent status.
4. “How do you handle a breaking change in an event that 12 consumers use?” Version the event type, dual-publish for a migration window, track consumer adoption, use a schema registry with compatibility checks, then remove the old version.
5. “How do you decide service boundaries?” By bounded contexts and data ownership, change frequency (things that change together stay together), team structure (Conway’s law), and transaction boundaries (avoid splitting what must be updated atomically).
6. “Where would you not use a service mesh?” Small estates or latency-critical paths where the sidecar overhead and operational cost exceed the benefits; use libraries or gateway features instead.
Quiz#
1. Five sequential calls each at 99.9% availability: overall?
About 0.999^5 ≈ 99.5%, which is roughly 44 hours of downtime a year compared with 8.8 hours for a single 99.9% service. Availability multiplies down along a synchronous chain.
2. Orchestration vs choreography in one line each?
Orchestration: a central coordinator directs steps. Choreography: services react to events with no coordinator.
3. Why not share one database between services?
Shared schema couples deployments and contracts, prevents independent scaling and evolution, and makes ownership unclear.
4. What is the strangler fig pattern?
Incrementally replace a legacy system by routing capabilities to new services behind a facade until the old system can be removed.
5. What makes a compensation action safe?
It is idempotent, retryable, and handles partially completed states.