Shelves / Software Architecture
SA·141
Microservices
Microservices as an architecture and an organisational model: what they are and the problems they solve, finding service boundaries (business capabilities, bounded contexts, team cognitive load), service ownership and Team Topologies, API contracts and versioning, deployment independence, database per service and distributed data, distributed transactions with sagas and outbox, service discovery, configuration, communication styles, retries and resilience, observability, platform engineering, and an honest account of the costs (operational complexity, network failures, consistency, testing, debugging), plus migration with the strangler fig and the anti-patterns to avoid.
Start here: independent services, and the bill for independence
Microservices split a system into small services, each owned by one team, deployed independently, with its own data, talking over the network. The benefits are mostly organisational: teams can ship without coordinating releases, scale and choose technology per service, and contain failures. The costs are mostly technical: every call that used to be a function call is now a network request that can be slow, fail, or arrive twice, and every piece of data is owned by one service and only eventually consistent everywhere else.
What fan-out does to latency and success
Each service usually answers in 2–4 ms, but 1% of its calls take 50 ms (a garbage-collection pause, a cold cache) and 0.5% fail. A page that needs data from several services:
1 call, sequential: p50 3.8 ms p99 51.0 ms page fully successful 99.8%
5 calls, sequential: p50 19.1 ms p99 67.9 ms page fully successful 96.0%
5 calls, parallel: p50 5.3 ms p99 52.3 ms page fully successful 97.8%
10 calls, parallel: p50 6.8 ms p99 54.4 ms page fully successful 94.7%
Calling in parallel kept the typical page fast, but the tail came along: with ten calls, the chance that at least one is slow is 1 − 0.99¹⁰ ≈ 10%, so one page in ten waits for the slowest service. Rare slowness in each service becomes common slowness for users (tail-latency amplification, described in Google's "The Tail at Scale"). Success multiplied the same way: ten services each 99.5% successful give pages that fully succeed only about 95% of the time. Each service looked healthy on its own dashboard; the page didn't.
What makes microservices worth it anyway
- Independent deployability: a team ships its service many times a day without a release train.
- Team ownership: service boundaries match team boundaries (Conway's law), so most changes need one team.
- Targeted scaling and isolation: scale the hot service; a crash in recommendations doesn't take down checkout.
And what you must build to cope with the costs: timeouts and retries with budgets, hedged or cached responses for tail latency, graceful degradation (show the page without recommendations), contract tests (Volume 11, chapter 117), distributed tracing (Volume 9), the outbox for events, and a platform that makes all of that the default.
How deep to go in microservices
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain what microservices are, their benefits and their costs |
| L2 | Build a service with its own data, a versioned API, health checks, timeouts and tracing |
| L3 | Explain boundary finding, data ownership, sagas, contract testing and fan-out tail effects |
| L4 | Diagnose distributed failures (tail latency, cascading errors, chatty calls) from traces and metrics |
| L5 | Decide service boundaries and platform needs, and plan migration from a monolith |
| L6 | Run a microservice organisation: team topologies, platform engineering, standards and governance |
What microservices are
Microservices is an architectural style in which an application is built as a suite of small, independently deployable services, each:
- implementing a business capability (one bounded context, chapter 138);
- owning its data (no other service reads or writes its database directly);
- communicating through well-defined network APIs (HTTP/gRPC) and/or events;
- owned by one team responsible for building, deploying and operating it ("you build it, you run it");
- deployable independently of other services, without coordinated releases.
(James Lewis and Martin Fowler's 2014 article defined the characteristics; the style grew from practices at Amazon, Netflix and others.) Size is not the point; independence is: independent deployment, independent scaling, independent failure, independent team decisions.
Problems microservices solve
- Team scaling: dozens or hundreds of engineers can't work efficiently in one codebase with one release train; services let teams own and release independently (organisational scaling is the strongest driver).
- Independent deployment: change one capability and ship it without regression-testing and releasing everything.
- Independent scaling: scale the hot path (search, checkout) without scaling the rest; use different resource profiles.
- Fault isolation: a failure in recommendations shouldn't break checkout (only if designed for it, chapter 130 of Vol. 12).
- Technology heterogeneity: choose a different language or datastore where it genuinely helps (use sparingly).
- Evolvability: replace or rewrite one service without touching others.
The costs
Microservices trade code complexity for operational and distributed-systems complexity:
| Cost | What it means |
|---|---|
| Operational complexity | Many deployables, pipelines, configurations, dashboards, alerts, on-call rotations; need for a platform (Kubernetes, service mesh, CI/CD, observability) and platform engineers |
| Network failures | Every call can be slow, fail, or partially succeed: timeouts, retries, idempotency, circuit breakers become mandatory (Vol. 5, Vol. 12 ch. 130) |
| Data consistency | No ACID transactions across services: sagas, outbox, eventual consistency, reconciliation (Vol. 12 ch. 129, 131) |
| Testing complexity | End-to-end tests across services are slow and flaky; need contract tests, test environments, service virtualisation (Vol. 11) |
| Debugging | A request spans many processes: distributed tracing, correlation IDs, centralised logs are prerequisites (Vol. 9) |
| Latency | Network hops add milliseconds each; chatty call graphs add up |
| Duplication and inconsistency | Cross-cutting concerns (auth, logging, resilience) implemented N times unless provided by the platform/libraries |
| Coordination for cross-cutting changes | A feature spanning services needs coordinated API changes and rollouts |
| Cost | More infrastructure, data transfer and tooling per unit of functionality |
Martin Fowler's Microservice Premium: microservices only pay off above a certain level of system complexity. "Monolith first" (or rather, modular monolith first, chapter 140) is common advice: discover boundaries in a modular monolith, then extract services when the forces justify it.
Service boundaries
Getting boundaries right is the most important microservices decision. Wrong boundaries produce a distributed monolith: services that must change, deploy and fail together, with all the costs of distribution and none of the benefits.
Heuristics
- Business capabilities (what the business does: catalogue management, pricing, order management, payments, fulfilment, customer support), which are stable over time even as processes change.
- Bounded contexts from DDD: a service implements one bounded context (or a part of one when scaling demands, but never spans several).
- Data ownership and transactional boundaries: data that must be strongly consistent together belongs in one service; if two services constantly need a transaction across them, they're probably one service.
- Change cadence and coupling: things that change together for the same reasons belong together; check version-control history (files frequently changed together).
- Team cognitive load (Team Topologies): a service (or set) should fit a team's capacity to understand and operate it.
- Volatility and risk isolation: separate volatile or risky parts (experimental features, third-party integrations) from stable cores.
- Non-functional differences: distinct scaling, latency, availability or security requirements (PCI scope isolated in a payments service).
Granularity
Too coarse: services that are monoliths themselves (lose independence). Too fine ("nanoservices": a service per entity or per function): chatty communication, distributed transactions everywhere, operational overhead per tiny service. Signs of too fine: services that always deploy together; requests that need 10+ synchronous hops; services with one or two endpoints and no meaningful logic; shared data models between services.
Neal Ford and Mark Richards' granularity disintegrators (reasons to split: scope and function, code volatility, scalability, fault tolerance, security, extensibility) versus integrators (reasons to keep together: database transactions, workflow and choreography complexity, shared code, data relationships) give a structured way to decide (Software Architecture: The Hard Parts).
Service ownership
- One team owns each service end to end: code, data, API contracts, deployment, operations, on-call, cost, security. Shared ownership becomes no ownership.
- Teams can own several services; a service should not have several owner teams.
- Team Topologies (Skelton & Pais) structures this: stream-aligned teams own business capabilities end to end; platform teams provide internal products (deployment, observability, data infrastructure) as self-service; enabling teams help others adopt practices; complicated-subsystem teams own specialised components (ML models, video codecs).
- Service catalogue (Backstage, OpsLevel, Port, Cortex): every service registered with owner, on-call, documentation, APIs, dependencies, SLOs, maturity scorecards.
API contracts
Services interact through contracts: synchronous APIs (REST/gRPC/GraphQL, Vol. 12 ch. 132) and asynchronous events (schemas in a registry, Vol. 12 ch. 131).
- Contract-first: define OpenAPI/proto/AsyncAPI specs, review them, generate code.
- Consumer needs drive contracts; consumer-driven contract tests (Pact) verify providers don't break consumers (Vol. 11 ch. 117).
- Hide internals: never expose database schemas or internal domain models; contracts are a published language (chapter 138).
- Tolerant readers: consumers ignore unknown fields; providers make additive changes.
- Coarse-grained, intention-revealing operations (
POST /orders/{id}/cancellation) rather than fine-grained CRUD that forces clients to orchestrate business logic.
Versioning
- Prefer backward-compatible evolution (additive changes, new optional fields, new endpoints) so providers and consumers deploy independently.
- For breaking changes: run old and new versions side by side (URI/media-type versions for HTTP, new proto packages
v2, new event types/topics), migrate consumers (tracked via contract tests and telemetry), then retire the old version. - Expand and contract for data and APIs.
- Deprecation policies with timelines; never break consumers silently.
- Lockstep deployments ("service A v12 must be deployed with service B v7") are a sign of a distributed monolith.
Deployment independence
Independent deployability is the defining property:
- Separate build and deployment pipelines per service (or per service within a monorepo with affected-target builds).
- Backward-compatible APIs and schemas so deployment order doesn't matter.
- Database per service: schema changes don't ripple to other teams.
- Progressive delivery: canaries, feature flags, automated rollback per service (Vol. 6 ch. 84, Vol. 8).
- Containers and orchestration (Kubernetes) or serverless/managed runtimes provide uniform packaging and scheduling.
- Monorepo vs polyrepo: both work; monorepos ease atomic refactors and shared tooling (Bazel, Nx, Pants, Gradle), polyrepos give hard isolation (Vol. 8 ch. 92). Independence comes from contracts and pipelines, not repository layout.
Data: database per service
Each service owns its data; others access it only through the service's API or events. This preserves encapsulation (internal schema can change) and independent deployment.
Consequences and patterns:
- No cross-service joins: compose data via API calls (API composition in a BFF), or maintain local read copies fed by events (event-carried state transfer), or build CQRS read models combining data from several services (Vol. 12 ch. 127).
- Shared database anti-pattern: services reading each other's tables couple their schemas and deployments; it's the most common cause of distributed monoliths. If a shared database is temporarily unavoidable (migration), restrict to schema-per-service with access controls.
- Polyglot persistence is possible (each service picks the right store), but every extra technology costs operational expertise.
- Reference data (countries, currencies) can be replicated to services that need it.
- Reporting and analytics: stream data from all services into a warehouse/lakehouse via CDC or events, rather than querying service databases.
Distributed transactions
Business operations spanning services (place order → reserve stock → charge payment → schedule shipping) can't use a single ACID transaction. Options (Vol. 5 ch. 73, Vol. 12 ch. 131):
- Sagas: sequences of local transactions with compensating actions, via choreography (events) or orchestration (a coordinator or durable workflow engine such as Temporal, Step Functions, Camunda).
- Transactional outbox for reliable event publication with local state changes.
- Idempotent consumers and idempotency keys on commands.
- Reservations (semantic locks) and pending states visible to users.
- Reconciliation jobs that detect and repair divergence.
- Two-phase commit / XA across services: generally avoided (blocking, availability and coupling costs), though some databases support it internally.
If a use case needs strong atomicity across two services frequently, reconsider the boundary: the data may belong in one service.
Service discovery
Services need to find each other's network locations as instances come and go:
| Approach | How | Examples |
|---|---|---|
| DNS-based (platform) | Stable service names resolve to virtual IPs or endpoint lists | Kubernetes Services + CoreDNS (orders.shop.svc.cluster.local), cloud service discovery (Cloud Map), Consul DNS |
| Client-side discovery | Clients query a registry and load-balance themselves | Netflix Eureka + Spring Cloud LoadBalancer, Consul with client libraries, gRPC xDS |
| Server-side discovery | Clients call a load balancer/router that knows the instances | Cloud load balancers, API gateways |
| Service mesh | Sidecar or node proxies handle discovery, load balancing, mTLS, retries, telemetry | Istio (sidecar or ambient), Linkerd, Cilium service mesh, Consul Connect |
On Kubernetes, DNS-based discovery via Services is the default; a mesh adds identity-based security, traffic management and uniform telemetry (Vol. 6 ch. 83, Vol. 10 ch. 111).
Configuration
- Externalise configuration from code and images (twelve-factor app): environment variables, mounted files, configuration services.
- Separate config from secrets: secrets in a secrets manager (Vault/OpenBao, cloud secret managers) injected at runtime (Vol. 10 ch. 111).
- Configuration services and GitOps: Kubernetes ConfigMaps managed via GitOps (Argo CD/Flux), Spring Cloud Config, AWS AppConfig, Consul KV; validate configuration in CI; roll out config changes progressively (config pushes cause many outages).
- Feature flags (OpenFeature with LaunchDarkly, Unleash, Flagsmith, flagd) separate deployment from release and enable kill switches.
- Services should fail fast at startup on missing/invalid configuration and cache configuration so a config-service outage doesn't break running instances (static stability, Vol. 12 ch. 125).
Communication styles
| Style | Use for | Watch out for |
|---|---|---|
| Synchronous request/response (REST, gRPC) | Queries needing immediate answers; commands where the caller must know the result now | Temporal coupling, cascading failures, latency chains |
| Asynchronous messaging/events | Propagating facts, decoupling, workflows, load leveling | Eventual consistency, duplicates, ordering, observability |
| Request + async completion (202 + callback/webhook/status) | Long-running operations | Client complexity |
Guidelines:
- Avoid deep synchronous call chains: availability multiplies (five services at 99.9% each → 99.5%, Vol. 12 ch. 125). Prefer one level of synchronous calls from a BFF/orchestrator, with events for the rest.
- Don't build a distributed monolith by RPC: if service A must synchronously call B, C, D for every request, they're tightly coupled; consider local data copies via events.
- Choose gRPC for internal high-throughput calls, REST/GraphQL at the edge, events for integration (Vol. 12 ch. 132).
Retries and resilience
Network calls fail; services must be designed to tolerate it (Vol. 12 ch. 130):
- Timeouts and deadlines on every call, propagated across hops.
- Retries with exponential backoff, jitter and budgets, only for idempotent or idempotency-keyed operations, at one layer.
- Circuit breakers, bulkheads, load shedding, graceful degradation with fallbacks for non-critical dependencies.
- Idempotent APIs (idempotency keys) so retries are safe end to end.
- Implement once: in a service mesh (timeouts, retries, outlier detection, mTLS) or shared libraries/platform SDKs, configured per dependency; avoid double retries across layers.
Observability
A microservices system is unmanageable without observability (Vol. 9):
- Distributed tracing (OpenTelemetry) across every service hop, including asynchronous messages (trace context in message headers).
- Correlation/request IDs in logs; structured, centralised logging.
- RED metrics (rate, errors, duration) per service and per endpoint; USE metrics for resources; dependency metrics (calls to each downstream).
- SLOs per service and per user journey; alerts on burn rates.
- Service maps derived from traces; dependency inventories in the service catalogue.
- Consistent telemetry conventions provided by the platform (auto-instrumentation, shared libraries, mesh telemetry).
The platform
At scale, microservices require a platform that makes the right thing easy:
- Golden paths / paved roads: service templates (Backstage software templates, cookiecutter) with CI/CD, observability, security, health checks, resilience defaults and documentation built in.
- Internal developer platform: self-service environments, deployments, databases, queues, secrets, feature flags.
- Policy as code (OPA/Kyverno) for security and compliance guardrails.
- Platform engineering teams treat the platform as a product for internal developers (Team Topologies' platform team).
Without a platform, every team reinvents deployment, monitoring and resilience, multiplying cost and inconsistency.
Migrating from a monolith
The strangler fig pattern (Martin Fowler, named after vines that gradually envelop a host tree): incrementally build new functionality or extract existing functionality as services around the monolith, routing traffic to the new service piece by piece, until the old system can be retired.
Steps:
- Put a routing facade (API gateway, reverse proxy, BFF) in front of the monolith.
- Choose a first candidate: a capability with clear boundaries, business value and manageable coupling (often new functionality, or a read-heavy, low-risk capability).
- Build the service with its own data; synchronise data from the monolith (CDC, events, dual writes temporarily) behind an anti-corruption layer.
- Route a slice of traffic (feature flags, percentage canaries, specific tenants), compare results (shadow traffic, parallel run), then cut over.
- Remove the old code path from the monolith; repeat.
Alternatives and complements: branch by abstraction (introduce an interface in the monolith, implement it with a client to the new service, switch), parallel run (run both, compare outputs), change data capture to keep data in sync during migration, and modularising the monolith first (chapter 140), which makes extraction far easier.
Anti-patterns
| Anti-pattern | Symptom | Remedy |
|---|---|---|
| Distributed monolith | Services deploy together, share databases or schemas, call each other synchronously in long chains | Redraw boundaries around capabilities; database per service; events; backward-compatible APIs |
| Shared database | Multiple services read/write the same tables | Data ownership; APIs/events; migration via CDC |
| Nanoservices | Tiny services with trivial logic, chatty calls | Merge into coarser services |
| Entity services | CustomerService, OrderService as CRUD wrappers; business logic in orchestrators |
Capability-oriented services owning behaviour and data |
| Chatty APIs | Many fine-grained calls per user action | Coarse-grained operations, BFF aggregation, local read models |
| Shared libraries with business logic | Upgrading a library forces coordinated releases | Share only infrastructure/utility libraries; business logic stays in owning services |
| Synchronous everything | Cascading failures, high latency | Async events where possible; resilience patterns |
| No platform | Each team reinvents deployment, monitoring | Invest in platform engineering and golden paths |
| Microservices for a small team | 3 engineers operating 20 services | Modular monolith until team/scale requires more |
| Big-bang rewrite | Years-long rewrite, never finished | Strangler fig, incremental extraction |
Is it worth it? A checklist
Microservices are likely worth their cost when most of these hold:
- Many teams (roughly more than 3–5) working on one product, slowed by coordination and shared releases.
- Clear, stable domain boundaries are known (often discovered in a modular monolith first).
- Parts of the system have significantly different scaling, availability, security or release needs.
- The organisation can invest in a platform (CI/CD, Kubernetes or serverless, observability, security) and in distributed-systems skills.
- Teams can own services end to end, including operations.
If not, a modular monolith delivers most of the modularity at a fraction of the cost.
Lab: fan-out, tail latency and compound failure
Ten Python http.server services on the lab machine (ports 8411–8420, TCP_NODELAY, keep-alive), each sleeping 2–4 ms (uniform) except 1% of calls at 50 ms, and failing 0.5% of calls with HTTP 500. A client issued 600 page requests per configuration, calling services sequentially or through a 16-thread pool. The latency distribution is synthetic, chosen to resemble a healthy service with occasional pauses; real services have heavier tails.
Experiment 1: sequential versus parallel fan-out
| Calls per page | Mode | p50 | p99 | Pages fully successful | Theory: no slow call / all succeed |
|---|---|---|---|---|---|
| 1 | — | 3.8 ms | 51.0 ms | 99.8% | 99.0% / 99.5% |
| 5 | sequential | 19.1 ms | 67.9 ms | 96.0% | 95.1% / 97.5% |
| 5 | parallel | 5.3 ms | 52.3 ms | 97.8% | 95.1% / 97.5% |
| 10 | parallel | 6.8 ms | 54.4 ms | 94.7% | 90.4% / 95.1% |
Measured success tracks 0.995ⁿ within sampling noise (600 pages gives about ±1%). Sequential calls add their latencies (5 × ~3.8 ms ≈ 19 ms); parallel calls cost the maximum of n latencies, which keeps the median low but pulls the slow tail into many more pages. At 10 calls, about one page in ten is dominated by a 50 ms pause somewhere; at 100 calls (common in large microservice systems), it would be 63%.
Experiment 2: reducing the tail
Techniques, each testable in this lab:
| Technique | How | Cost |
|---|---|---|
| hedged requests | after the service's p95 (say 5 ms), send a second copy; take whichever returns first | ~5% extra load |
| timeouts + defaults | cap each optional call at, e.g., 10 ms and render without it | degraded content occasionally |
| fewer calls | a backend-for-frontend aggregates, or data is replicated via events into the service that needs it | more data duplication |
| caching | per-service caches for slow-changing data (chapter 126 of Volume 12) | staleness |
Jeff Dean and Luiz Barroso's "The Tail at Scale" (2013) reported that, in a Bigtable benchmark reading 1,000 keys, deferring a hedged request until 10 ms cut 99.9th-percentile latency from about 1,800 ms to 74 ms while sending just 2% more requests: the same mechanism as the first row.
Experiment 3: the organisational side, measured
The benefit side of microservices is measured in delivery, not latency. The DORA metrics (deployment frequency, lead time for changes, change failure rate, time to restore) per team are the honest test: if splitting into services doesn't improve them, the distribution costs above are being paid for nothing. Track them before and after any split.
Try it yourself
- Implement hedging in the client (submit a second call after 5 ms if the first hasn't returned) and rerun the 10-call parallel case. What happens to p99 and to total requests?
- Make 3 of the 10 calls optional with a 10 ms timeout and a default; measure p99 and "pages fully successful".
- Add a service that calls two others (a chain) and measure how depth and fan-out combine.
- Run the same page as a modular monolith (in-process function calls with the same sleeps) and compare p50, p99 and success.
Revision sheet: microservices
Key ideas
- Microservices: independently deployable services owned by teams, each with its own data, around business capabilities.
- Boundaries: bounded contexts, business capabilities, team cognitive load; avoid entity services (CRUD per table).
- Organisation: Conway's law and the inverse Conway manoeuvre; Team Topologies (stream-aligned, platform, enabling, complicated-subsystem teams).
- Communication: synchronous (REST/gRPC) for queries; asynchronous events for propagation; avoid long synchronous chains.
- Data: database per service; sagas for cross-service workflows; CQRS/read models for queries spanning services.
- Resilience: timeouts, budgets, breakers, bulkheads, hedging, graceful degradation.
- Operations: CI/CD per service, observability (tracing essential), service mesh or libraries, platform engineering.
- Migration: strangler fig from a monolith, module by module, behind stable APIs.
Numbers to remember
- Lab: 10 parallel calls → ~10% of pages hit a 1%-per-service slow path; page success 94.7% with 99.5% services.
- P(at least one slow among n) = 1 − (1 − p)ⁿ; success = sⁿ.
- "The Tail at Scale": hedging after 10 ms cut p99.9 from ~1,800 ms to 74 ms for ~2% extra requests.
Pitfalls
- Distributed monolith: services that must deploy together or share a database.
- Chatty synchronous chains; entity services.
- Splitting before boundaries are understood.
- No platform: every team reinventing deployment, logging, auth.
- Per-service dashboards hiding user-level failure.
- Ignoring DORA metrics to judge whether the split helped.
Glossary
- Distributed monolith: services coupled so tightly they behave as one deployment.
- BFF: backend for frontend, aggregating calls for one client type.
- Hedged request: duplicate request to cut tail latency.
- Strangler fig: incremental replacement of a monolith.
- DORA metrics: deployment frequency, lead time, change failure rate, time to restore.