Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Microservices

Intent

Decompose the system into small services that each own one capability and its data, and that build, deploy, and scale independently.

When It Helps

  • Multiple autonomous teams need to ship without blocking each other.
  • Different parts of the system have very different scaling or availability needs.
  • The domain has stable, well-understood bounded contexts worth isolating.

Structure

flowchart LR
  Clients --> GW[API Gateway]
  GW --> S1[Service: Orders]
  GW --> S2[Service: Catalog]
  GW --> S3[Service: Billing]
  S1 --> DB1[(Orders DB)]
  S2 --> DB2[(Catalog DB)]
  S3 --> DB3[(Billing DB)]
  S1 <-->|sync API or async events| S3

Deployment unit: each service is its own artifact, pipeline, and runtime (container set or serverless unit). Communication: synchronous calls (HTTP/gRPC) for queries plus asynchronous events for state changes; no shared in-process calls. Data ownership: strict per-service databases — services never share tables, only APIs or events.

Rules

  1. Each service owns its data exclusively; access from outside happens only through its API or published events.
  2. Services deploy independently — a deploy of one must never require a lockstep deploy of another.
  3. Prefer backward-compatible API evolution over coordinated breaking changes.
  4. Each service carries its own health checks, dashboards, and runbooks; there is no single shared runtime to hide behind.

Illustrative Snippet

Illustrative pseudocode — not runnable.

# sketch: per-service deploy + owned data
service orders:
  deploy: orders:v42 (3 replicas, scales on queue depth)
  db: orders_db (owned, no external access)
  publishes: order.placed

service billing:
  deploy: billing:v17 (2 replicas, scales on CPU)
  db: billing_db (owned)
  subscribes: order.placed -> charge()

# forbidden: billing querying orders_db directly

Basic Recap

Microservices divide a system into independently deployable capabilities with explicit APIs and private data ownership. Teams can release and scale a service without shipping the rest of the system. The architecture replaces in-process calls with networks, partial failures, versioned contracts, and distributed data decisions. It is an organizational and operational commitment, not merely a smaller code layout.

Complex Scenario

An online shop runs catalog, cart, inventory, orders, and payment as separate services. Checkout needs a timely reservation and payment result, while recommendations can arrive later. Each service owns its database and scaling policy, and a gateway applies caller authentication. A flash sale creates a burst concentrated on inventory rather than evenly across the system.

flowchart LR
  Clients["Web and mobile clients"] --> Gateway["API gateway"]
  Gateway --> Cart["Cart service"]
  Gateway --> Orders["Orders service"]
  Gateway --> Catalog["Catalog service"]
  Orders --> Inventory["Inventory service"]
  Orders --> Payment["Payment service"]
  Cart --> CartDB[("Cart DB")]
  Catalog --> CatalogDB[("Catalog DB")]
  Inventory --> StockDB[("Stock DB")]
  Orders --> OrderDB[("Order DB")]
  Payment --> Ledger[("Payment ledger")]
  Orders --> Events[("Order events")]
  Events --> Recommendations["Recommendation worker"]

Failure walkthrough. Traffic spikes tenfold and inventory replicas saturate; orders retry immediately, multiplying load until gateway deadlines expire and payment calls queue behind doomed reservations. Mitigate by scaling inventory on reservation latency and queue depth, propagating one end-to-end deadline, using jittered retry budgets and circuit breakers, and moving noncritical recommendations to events. Payment must never be retried blindly after an ambiguous response; its operation key supports safe status recovery.

Edge cases — concurrent purchases need atomic stock reservation, retries need stable operation keys, and partial failure needs a saga that releases stock or records a compensating refund. Ordering across order and stock events is guaranteed only per documented key.

Sketch (illustrative pseudocode, not runnable):

request checkout:
  trace_id: propagated
  total_deadline: 2500ms
  operation_key: client_generated_uuid

call orders -> inventory:
  timeout: min(600ms, remaining_deadline)
  retries: 1_if_budget_allows
  circuit_breaker: open_after_50_percent_timeouts

service inventory:
  autoscale_on: [reservation_p95, pending_reservations]
  min_replicas: 6
  reservation: conditional_write(stock > requested)

recovery:
  payment_unknown -> query_by_operation_key
  reservation_abandoned -> expire_after_2m

Trade-offs

  • Benefit: independent scaling and deployment — hot services scale alone and teams release on their own cadence.
  • Benefit: fault and technology isolation — one service can fail or adopt a new stack without forcing the whole system along.
  • Cost: distributed operations — service discovery, versioning, retries, tracing, and many pipelines multiply operational load.
  • Cost: data consistency gets harder — cross-service transactions become sagas or eventual consistency instead of one database commit.

When to Use / When Not to Use

Use when:

  • Capabilities needing independent scaling, deploys, and data ownership.

Avoid when:

  • One team with uniform scale — Modular Monolith is cheaper.

Anti-pattern / Failure Mode

  • Misuse: Shared database across services with distributed transactions everywhere.
  • Review signal: Chatty synchronous calls recreating the monolith over the network.

Failure Modes / Trade-offs

  • Distributed monolith: services share tables, release trains, or deep synchronous call chains, so none can fail or deploy independently.
  • Chatty boundaries: an entity per service creates many network calls for one screen. Measure user operations before drawing service boundaries.
  • Retry amplification: every layer repeats the same attempt policy, turning one slowdown into a multiplicative storm. One caller should own the retry decision within a shared deadline.
  • Ownership trade-off: autonomous deployment and focused scaling are powerful, but tracing, contract tests, data reconciliation, and on-call coverage become permanent costs.

Constraint-based use / avoid

ConstraintRecommendation
Multiple autonomous teams with stable bounded contextsUse services where ownership and release independence solve measured coordination problems.
Very different scaling or availability targets per capabilityUse independently scalable services with explicit dependency budgets.
Team lacks mature observability and on-call capacityAvoid broad decomposition; a modular monolith has a smaller operational burden.
Strict end-to-end latency below a few millisecondsAvoid deep service chains; colocate critical decisions and use events for secondary work.
Compliance scope differs sharply between payment and contentUse separate deployables only if credentials, networks, and audit ownership are separated too.
  • Modular Monolith — prefer it first when boundaries are uncertain; it is cheaper to run than services.
  • Event-Driven — the common way microservices stay decoupled, reacting to events instead of chaining calls.
  • SOA — an earlier, coarser-grained take on reusable services, often with a central bus instead of independent services.
  • You Build It, You Run It — ownership per service.
  • Event-Driven Payments — duplicate-safe processing across services.