Skip to content

Microservices Infrastructure Patterns

Advanced 52 min read Part 10 of 18

The plumbing that makes microservices work: service discovery, sidecars, service meshes, API composition, BFFs, configuration and distributed tracing.

Summary#

Once a system is split into many services, a set of infrastructure patterns becomes necessary just to make the services find each other, talk safely, stay configured and stay debuggable. Service discovery maps service names to live instances. Sidecars and service meshes move networking concerns such as retries, mutual TLS and telemetry out of application code. API composition and backends for frontends assemble responses from several services. Externalised configuration and distributed tracing keep a fleet of services manageable. Choosing between synchronous and asynchronous calls decides how failures spread.

Why It Exists#

In a monolith, a function call is a jump in memory: it takes nanoseconds, it never gets lost, the callee is always "there", and a stack trace shows the whole path of a request. Splitting the monolith into services replaces each of those calls with a network call, and every assumption breaks.

  • Where is the callee? Instances start, stop, move and scale every few minutes in a container platform. Their IP addresses change. Hard-coding hosts in a config file stops working at the first autoscaling event.
  • Is the callee healthy? One of twelve instances may be stuck in garbage collection or half-deployed. Sending it traffic produces timeouts for a twelfth of users.
  • Is the call safe? Traffic between services crosses networks shared with other workloads. Without encryption and identity, any compromised pod can impersonate any service.
  • What happens on failure? Each call can time out, fail or succeed slowly. Without consistent timeouts and retries, one slow service ties up threads in every service that calls it, and the failure cascades.
  • What did this request do? A single page load may touch 30 services. When it is slow, no single service's logs explain why.
  • How is each service configured? Two hundred services with three environments each means six hundred configurations, plus secrets, plus feature flags, all of which must change without redeploying.

Each of these problems used to be solved separately inside each service, in each language, by each team, often differently. The patterns on this page are the standard solutions, increasingly provided by the platform rather than by application code. They are what the industry learned, often painfully, at companies such as Netflix, Google, Twitter, Lyft and Uber as they ran thousands of services.

How It Works#

The patterns fit into a typical production architecture. The sections below start with that big picture, then cover how services find each other, how they call each other, how the network layer is handled by sidecars and meshes, how responses are composed for clients, and how configuration and tracing keep the system operable.

A typical microservice architecture#

Most production microservice systems, whatever their domain, contain the same building blocks:

  1. Clients: web browsers, mobile apps, partner systems and internal tools.
  2. Edge: DNS, a CDN for static assets and cached responses, and a load balancer that terminates TLS and spreads connections. See Load Balancing.
  3. API gateway, sometimes per client type as a backend for frontend: one entry point that authenticates requests, applies rate limits, routes to services and sometimes composes responses. See API Gateway.
  4. Identity provider: issues and validates tokens, such as OAuth 2.0 access tokens and OpenID Connect ID tokens, so services do not handle passwords.
  5. Services: each owning one business capability and its own data, deployed as several stateless instances, usually in containers on Kubernetes or on serverless platforms.
  6. Data stores per service: relational databases, key-value stores, search indexes and caches, never shared directly between services.
  7. Message broker or event log: Kafka, RabbitMQ, SQS or similar, for asynchronous commands and events between services.
  8. Service discovery and load balancing between services: a registry, DNS or a mesh, so services find healthy instances of each other.
  9. Configuration and secrets management: a config service, a secret store and feature flags.
  10. Observability: centralised logs, metrics, distributed traces and alerting.
  11. Delivery platform: CI/CD pipelines, container registry, deployment automation with canaries and rollbacks.

A typical microservice architecture, in depth#

The request path. A typical read request flows as follows. The client resolves the domain through DNS and connects to the nearest edge. Static assets come from the CDN. The API call reaches the load balancer, which forwards it to a gateway instance. The gateway validates the access token, often a JWT whose signature it checks locally against the identity provider's public keys, applies a per-client rate limit, and routes by path to the right service. That service may call two or three others, ideally in parallel, reads its own database or cache, and returns. Every hop adds the trace context to the request headers, so the whole path can be reconstructed later.

Latency budget. A useful mental model is that each synchronous hop inside one data centre costs about 0.5 to 2 ms of network and serialisation overhead, plus whatever the callee does. A request that passes through a load balancer, a gateway and three services in sequence spends perhaps 5 to 10 ms in pure plumbing before any database work. That is fine for a 200 ms page budget, but it explains why deep synchronous call chains are discouraged: ten sequential hops can spend more time in plumbing than in business logic, and their tail latencies add up.

Write paths are different. Writes typically go to the one service that owns the data, which commits locally and then publishes an event. Other services that care, such as search indexing, notifications and analytics, consume the event asynchronously. This keeps the synchronous write path short and isolates the user from failures in downstream consumers. See Event-Driven Architecture.

What is in the platform and what is in the service. A key design decision is which concerns are provided by the platform, such as the mesh, the gateway, the CI/CD system and the observability stack, and which are left to each service. Moving more into the platform gives consistency and lets service teams focus on business logic, but it needs a strong platform team. A common split in mature organisations is: the platform owns discovery, mTLS, retries and timeouts at the network level, telemetry collection, deployment, and configuration delivery; services own business logic, data, idempotency, domain-level fallbacks and their own dashboards and alerts.

Common components lists. Descriptions of the "essential components of a production microservice application" vary, but they consistently include an API gateway, service registry and discovery, load balancing, a CDN for static content, configuration management, messaging, centralised logging and monitoring, distributed tracing, an identity and access layer, and automated CI/CD. If one of these is missing, its job is usually being done badly in every service.

Service discovery#

Service discovery answers one question: given a logical service name, such as payments, which network addresses currently host healthy instances of it?

It has three parts:

  • A service registry: a database of service names and their live instances, with addresses, ports, metadata such as version or zone, and health. Examples: Consul, etcd, ZooKeeper, Netflix Eureka, and in Kubernetes the API server's Endpoints and EndpointSlice objects.
  • Registration: how instances get into the registry. In self-registration, each instance registers itself on start-up and sends heartbeats, and is removed when heartbeats stop or when it deregisters on shutdown. In third-party registration, a separate registrar, such as the Kubernetes control plane or a tool like Registrator, watches the deployment platform and updates the registry, so services contain no discovery code.
  • Health checking: the registry, or an agent next to each instance, regularly checks an HTTP endpoint such as /healthz, a TCP port or a script, and marks failing instances unhealthy so they stop receiving traffic.

There are two ways to use the registry.

Client-side discovery. The calling service queries the registry, or a local cache of it, gets the list of healthy instances, and picks one itself using a load-balancing algorithm such as round robin, least requests or power of two choices. Netflix's Eureka with its Ribbon client library was the classic example. It saves a network hop and lets the client make smart choices, such as preferring instances in its own zone, but every client in every language needs the discovery and balancing logic.

Server-side discovery. The caller sends the request to a stable address, a load balancer or router, which queries the registry and forwards to a healthy instance. AWS Elastic Load Balancers in front of auto-scaling groups and Kubernetes Services work this way. Clients stay simple, and any language works, but there is an extra hop and the router must be highly available.

A service mesh is a hybrid: discovery and balancing happen on the client side, but inside the sidecar proxy rather than in application code, so the application just calls a name.

Service discovery, in depth#

The registry is critical infrastructure. If the registry is down and clients cannot resolve names, nothing can call anything. Registries are therefore replicated, and clients cache the last known instance list so they keep working through a registry outage. This makes registry consistency an interesting trade-off:

  • CP registries, such as ZooKeeper, etcd and Consul's catalog, which are replicated by consensus protocols, give a consistent view but refuse writes, and in some configurations reads, when they lose a majority. See Leader Election and Coordination.
  • AP registries, such as Eureka, replicate peer to peer and keep serving possibly stale data during partitions. Netflix chose this explicitly: a stale list with a few dead instances, which clients' retries can route around, is better than no list at all. Eureka also has a self-preservation mode: if many instances stop heartbeating at once, it assumes a network problem rather than mass death, and stops expiring registrations.

For discovery, staleness is usually tolerable as long as clients handle dead instances with timeouts, retries to a different instance and outlier ejection. That is why AP behaviour, or CP with aggressive client-side caching, is the norm.

Heartbeats, TTLs and the speed of detection. With heartbeats every 10 seconds and expiry after three misses, a crashed instance can receive traffic for up to 30 seconds. Shorter intervals detect failures faster but increase registry load: 10,000 instances heartbeating every second is 10,000 writes per second to the registry. Practical systems combine a moderate heartbeat interval with client-side passive health checking, where a client that sees consecutive errors from an instance stops using it immediately, without waiting for the registry. Consul uses a gossip protocol, Serf, based on SWIM, among its agents for fast, scalable failure detection. See Failure Detection and Gossip.

Graceful shutdown. Discovery also matters when instances stop deliberately, during deploys. The correct sequence is: deregister, or fail the readiness check; wait long enough for clients and load balancers to notice, often 5 to 15 seconds; stop accepting new connections; finish in-flight requests; then exit. Skipping the wait causes a burst of errors on every deployment, one of the most common sources of avoidable 5xx errors in Kubernetes. A preStop sleep hook exists largely for this reason.

DNS-based discovery. DNS is the oldest discovery system and is still widely used: a service name resolves to instance IPs, with SRV records adding ports and weights. Its weaknesses are caching and limited health information. Resolvers and client libraries may cache records longer than the TTL, the JVM historically cached DNS lookups indefinitely under some security settings, and a DNS answer says nothing about load. DNS works well for coarse, slowly changing targets, such as a Kubernetes Service's virtual IP, and poorly for rapidly changing individual pod addresses.

How Kubernetes does it. In Kubernetes, discovery is built in. A Service object selects pods by label. The control plane keeps EndpointSlice objects listing the ready pods behind each Service, using each pod's readiness probe. Cluster DNS, CoreDNS, resolves payments.prod.svc.cluster.local to the Service's stable ClusterIP. On each node, kube-proxy programs iptables or IPVS rules, or an eBPF data plane such as Cilium replaces it, so that connections to the ClusterIP are translated to one of the ready pod IPs. This is server-side discovery implemented in each node's kernel, without a separate load-balancer hop. One limitation is that balancing happens per connection, not per request, so a long-lived HTTP/2 or gRPC connection pins all its requests to one pod; meshes and client-side gRPC balancing solve this. See Containers and Kubernetes.

Load-balancing choices on the client side. Round robin is simple but ignores load. Least outstanding requests sends to the instance with the fewest in-flight calls. Power of two choices picks two instances at random and sends to the less loaded, which is nearly as good as checking all instances and needs far less state, a result from Michael Mitzenmacher's work on balanced allocations. Zone-aware routing keeps traffic in the caller's availability zone to cut latency and cross-zone data-transfer cost, spilling over only when the local zone is unhealthy or overloaded. Envoy and gRPC implement all of these.

Synchronous vs asynchronous inter-service calls#

Services talk in two basic styles.

Synchronous request-response. The caller sends a request, usually HTTP with JSON or gRPC with Protocol Buffers, and waits for the reply. It is simple to write, easy to reason about, and the caller gets an answer, or an error, immediately. It is the natural fit for queries, such as "get this user's profile", and for commands whose result the caller needs right away, such as "authorise this payment".

Asynchronous messaging. The caller puts a message on a broker and continues without waiting. The message is either a command to one consumer, such as "send this email", through a queue, or an event describing something that happened, such as "OrderPlaced", published to any number of subscribers through a topic. The broker stores the message until the consumer processes it. See Message Queues and Pub/Sub and Event Streaming.

The core difference is temporal coupling. With synchronous calls, the caller and callee must both be up and fast at the same moment. With messaging, the broker decouples them in time: the producer succeeds even if the consumer is down, and the consumer catches up later.

AspectSynchronous: HTTP, gRPCAsynchronous: queue or event log
Caller waitsYesNo
AvailabilityProduct of all services in the chainProducer depends only on the broker
Latency to the userSum of the chain, or the slowest branchFast acknowledgement; work completes later
ConsistencyImmediate resultEventual; the user may see "processing"
Failure handlingTimeouts, retries, circuit breakersRetries, dead-letter queues, idempotent consumers
Load spikesPass straight through to the calleeAbsorbed by the queue
DebuggingEasier: one call stack per request, with tracingHarder: flows are spread over time and consumers
Best forQueries, commands needing an immediate answerSide effects, fan-out, long work, integration between contexts

Availability maths. If a request synchronously depends on five services, each available 99.9% of the time, the request succeeds only when all five are up: 0.999⁵ ≈ 99.5%, about 3.6 hours of failure a month instead of 43 minutes. With 20 services in the chain, it falls to about 98%. Making the non-essential steps asynchronous, such as sending the confirmation email and updating recommendations, removes them from this product.

Orchestration vs choreography. When a business process spans services, there are two ways to coordinate it:

  • Orchestration: one component, the orchestrator, tells each service what to do and in which order, by commands or calls, and tracks the state of the process. The flow is explicit, visible in one place and easy to change, but the orchestrator becomes a central dependency and can grow into a "god service" if business logic leaks into it. Workflow engines such as Temporal, AWS Step Functions and Camunda are orchestrators. See Workflow Engines and Temporal.
  • Choreography: each service reacts to events and publishes its own events, with no central coordinator. OrderPlaced triggers Payment, PaymentAuthorised triggers Inventory, StockReserved triggers Shipping. Services are loosely coupled and independently changeable, but the overall flow exists only implicitly, spread across services, which makes it hard to see, debug and change once more than a few steps are involved.

A common rule of thumb is choreography for simple, loosely related reactions, such as "when an order ships, notify the customer", and orchestration for multi-step business processes with compensations, such as order fulfilment sagas. See Distributed Transactions and Sagas.

Synchronous vs asynchronous calls, in depth#

Choosing a synchronous protocol. REST over HTTP with JSON is universal, human-readable and works through every proxy and browser, which is why it dominates public and edge APIs. gRPC uses HTTP/2 and Protocol Buffers: binary encoding that is several times smaller and faster to parse than JSON, multiplexed streams over one connection, generated clients in many languages from a single .proto contract, deadlines built into the protocol, and streaming in both directions. It is the common choice for internal service-to-service calls at scale. Its costs are that it needs HTTP/2 end to end, it is not directly usable from browsers without gRPC-Web or a translating proxy, and its connection-level multiplexing interacts badly with connection-level load balancing, as described above. GraphQL suits client-facing aggregation more than service-to-service calls. See API Styles.

Timeouts and deadline propagation. Every synchronous call needs a timeout, and the timeouts in a chain must be consistent. If the gateway gives up after 2 seconds but the service behind it waits 5 seconds for its own downstream, that service wastes resources on a request nobody is waiting for. The fix is deadline propagation: the edge sets an absolute deadline, and each hop passes the remaining time to the next, with each service refusing work whose deadline has already passed. gRPC propagates deadlines natively; with HTTP, teams use a header carrying the remaining budget.

Retries without storms. Retries hide transient failures, but naive retries multiply load exactly when a service is struggling. If each of three layers retries three times, one user request can become 3 × 3 × 3 = 27 calls to the bottom service. Good practice is: retry only idempotent operations, or make operations idempotent with idempotency keys; retry at one layer, usually closest to the caller that can make the decision; use exponential backoff with jitter; and cap retries with a retry budget, such as "retries may add at most 10% to normal traffic", which Envoy and Finagle support. See Idempotency and Resilience Patterns.

Circuit breakers and bulkheads. A circuit breaker stops calling a dependency that is failing, failing fast instead, and periodically lets a trial request through to test recovery. A bulkhead gives each dependency its own limited pool of threads or connections, so one slow dependency cannot exhaust all of a service's resources. Netflix's Hystrix library popularised both; it entered maintenance mode in 2018, and its ideas live on in resilience4j, Envoy's outlier detection and connection limits, and service meshes.

Asynchronous request-reply. Sometimes a caller needs a result but should not block, for example a report that takes two minutes. The pattern is: the caller sends a command with a correlation ID and a reply address; the service accepts it immediately, often returning HTTP 202 with a status URL; the result arrives later as a reply message, a webhook, or a status the client polls. This gives the decoupling of messaging with a result at the end. See Handling Long-Running Tasks.

Message design. For asynchronous integration, events should be named in the past tense, carry a unique ID for deduplication, the aggregate ID and version for ordering, a timestamp, and a schema version. Publishing reliably needs the transactional outbox: write the event to an outbox table in the same database transaction as the state change, and relay it to the broker afterwards, so a crash cannot leave the state changed without the event, or the reverse. Consumers must be idempotent, because brokers deliver at least once. See Delivery Semantics.

Mixing the styles. Real systems use both. A typical checkout synchronously validates the cart, prices it and authorises payment, because the user needs those answers within a second, then asynchronously reserves stock, notifies the warehouse, sends emails and updates analytics. A good design question for every inter-service interaction is: does the caller need the answer before it can respond to its own caller? If not, make it asynchronous.

API composition#

In a monolith, a screen that shows an order with its items, the customer's name, the shipment status and the payment state is one SQL join. With database-per-service, those facts live in four services, and no database can join them. API composition solves this for queries: a composer calls each service that owns part of the data, and merges the results in memory.

The composer can be:

  • the API gateway, for simple aggregation;
  • a backend for frontend, when composition is specific to one client type;
  • a dedicated composite service, such as an "order details" service, when the logic is substantial.

Good composers call independent services in parallel, so the latency is that of the slowest call rather than the sum, and handle partial failure explicitly: if the recommendations service times out, return the order page without recommendations rather than failing the whole response.

API composition, in depth#

Its limits. Composition is the simplest way to query across services, but it has three weaknesses:

  • Latency and availability: the response depends on every service involved, so its availability is the product of theirs, and its latency is that of the slowest call. Timeouts and fallbacks per dependency are essential.
  • Large in-memory joins: "find all orders over 100 dollars from gold-tier customers in the last month" requires fetching many orders and many customers and joining them in the composer, which is slow and memory-hungry. Composition works for fetching one entity and its related data by ID, and poorly for filtering and sorting across services.
  • Chatty calls: an N + 1 pattern, fetching a list and then calling another service once per item, multiplies calls. Batch endpoints, such as "get customers by IDs", cut this to one call per service.

The alternative: a read model. When composition is too slow or the query needs cross-service filtering, build a materialised view: a dedicated query service subscribes to events from the owning services and maintains a denormalised table or search index designed for that query. This is CQRS applied across services. It trades freshness, the view is eventually consistent, and extra infrastructure for fast, independent queries. See Event Sourcing and CQRS.

GraphQL federation. GraphQL makes composition declarative: each service exposes a part of a single graph schema, and a gateway or router, such as Apollo Router, plans each query, calls the relevant services, called subgraphs, and stitches the results together. Clients ask for exactly the fields they need. Federation is effectively API composition with a query planner, and inherits the same latency and N + 1 concerns, which DataLoader-style batching addresses.

Choosing. Use composition for detail pages and simple aggregations by ID; use a read model for lists, searches, dashboards and anything with cross-service filters; use federation when many client teams need flexible access to a large graph.

Backends for frontends#

A single general-purpose API often serves no client well. A mobile app on a slow network wants small, pre-shaped payloads and few round trips; a web app wants richer data; a smart TV wants something else again; partners want stable, versioned contracts. The Backend for Frontend (BFF) pattern, named and described by Sam Newman in 2015 from his work with teams such as SoundCloud's, gives each client type its own thin backend, owned by the team that builds that client. Each BFF composes calls to the underlying services and shapes the responses for its client.

The essentials:

  • one BFF per client experience, not per service;
  • the BFF contains presentation and aggregation logic only; business rules stay in the domain services, or they will be duplicated across BFFs;
  • the client team owns its BFF, so it can change the API at the speed of the UI without negotiating with a central API team.

This page covers BFF as one of the composition options; the full treatment, including request flow, ownership models, GraphQL as an alternative and the risks of duplicated logic, is in API Gateway: BFF pattern.

The sidecar pattern#

A sidecar is a helper process that runs next to each instance of a service, sharing its lifecycle and its host, typically as a second container in the same Kubernetes pod, sharing the pod's network namespace and optionally its volumes. The application stays focused on business logic, and the sidecar handles a cross-cutting concern: proxying network traffic, collecting logs, refreshing certificates, fetching configuration or secrets.

The name comes from a motorcycle sidecar: attached, travelling everywhere the motorcycle goes, but a separate unit. Brendan Burns and David Oppenheimer described sidecar, together with the related ambassador and adapter patterns, in "Design Patterns for Container-based Distributed Systems" (HotCloud 2016), drawing on Google's experience with Borg and Kubernetes.

  • Sidecar: extends or enhances the main container, such as a log shipper that tails the app's log files and sends them to a central store, or a proxy that adds mutual TLS.
  • Ambassador: a proxy that represents a remote service to the app. The app talks to localhost, and the ambassador handles discovery, sharding, retries or the connection to a database cluster.
  • Adapter: presents the app's output in a standard form to the outside, such as converting an application's custom metrics into Prometheus format.

Why not just a library? A library must be written, upgraded and kept consistent in every language the organisation uses, and upgrading it means redeploying every service. A sidecar is language-independent, can be upgraded by the platform team without touching application code, and isolates the concern's resources and failures in its own process. The costs are an extra process per instance, an extra local network hop, and more moving parts to deploy and debug.

The sidecar pattern, in depth#

Common sidecars in production.

  • Network proxies, such as Envoy or linkerd2-proxy, intercepting all inbound and outbound traffic: the basis of a service mesh.
  • Log and telemetry agents, such as Fluent Bit or an OpenTelemetry Collector, although these often run once per node, as a DaemonSet, rather than once per pod, to save resources.
  • Secret and certificate agents, such as the Vault Agent injector, which authenticates to Vault, writes secrets to a shared in-memory volume and renews them.
  • Configuration reloaders, which watch a config source and signal the app when it changes.
  • Database proxies, such as Cloud SQL Auth Proxy, which handle authentication and encrypted connections to a managed database.
  • Distributed application runtimes, such as Dapr, whose sidecar offers building blocks, such as state stores, pub/sub, service invocation, secrets and workflows, through a local HTTP or gRPC API, letting the app swap the underlying broker or store by configuration.

Lifecycle problems. Sidecars must start before the app needs them and stop after it no longer does, which plain Kubernetes containers did not guarantee: an app could start before its proxy was ready and fail its first calls, or a batch job's pod would never complete because the proxy kept running. Kubernetes added native sidecar containers, init containers with restartPolicy: Always, as a beta feature enabled by default in version 1.29, so sidecars start before and stop after the main containers.

Resource cost. Each sidecar consumes CPU and memory per pod. An Envoy sidecar commonly uses tens of megabytes of memory and a fraction of a CPU core under modest load, though its memory grows with the size of the configuration it receives, which in a large mesh can reach hundreds of megabytes if every proxy is told about every service. With 5,000 pods, even 50 MB each is 250 GB of memory spent on proxies. Scoping each proxy's configuration to the services it actually calls, such as Istio's Sidecar resource, is an important optimisation.

Per-node agents as the alternative. For concerns that do not need per-instance isolation, such as log shipping and metrics scraping, a per-node agent is cheaper than a per-pod sidecar. The same reasoning led to sidecar-less service mesh designs, described below.

Service mesh#

A service mesh is a dedicated infrastructure layer for service-to-service communication. It is made of two parts:

  • The data plane: a proxy next to every service instance, usually a sidecar, that intercepts every inbound and outbound request. Envoy, created at Lyft and open-sourced in 2016, is the most widely used data-plane proxy; Linkerd uses its own lightweight Rust proxy.
  • The control plane: a central component that configures all the proxies, distributing routing rules, service discovery data, security policies and certificates. Istio's control plane is istiod; Linkerd's is its control plane deployment.

Because every request passes through a proxy on both ends, the mesh can provide, without changing application code:

  • Traffic management: load balancing per request, retries, timeouts, circuit breaking and outlier ejection, traffic splitting for canary releases, mirroring, fault injection for testing.
  • Security: mutual TLS between all services, with automatically issued and rotated certificates, cryptographic service identity, and authorisation policies such as "only the checkout service may call payments".
  • Observability: uniform metrics for every call, such as request rate, error rate and latency per service pair, plus access logs and trace spans, so every service gets "golden signals" without instrumentation.

Service mesh, in depth#

How traffic is intercepted. In a sidecar mesh, an init container or a CNI plugin installs iptables rules in the pod's network namespace that redirect all inbound and outbound TCP traffic to the proxy's ports. The application calls http://payments:8080 as usual; the kernel redirects the connection to the local Envoy, which resolves payments to its healthy endpoints, picks one, opens or reuses an mTLS connection to that pod's Envoy, and forwards the request. The receiving Envoy terminates mTLS, checks the authorisation policy against the caller's identity, records metrics and passes the request to the application on localhost.

The xDS protocol. Envoy is configured dynamically through a set of gRPC APIs collectively called xDS: the Listener, Route, Cluster and Endpoint Discovery Services, plus a Secret Discovery Service for certificates. The control plane streams updates, such as new endpoints when a pod starts, without restarting proxies. xDS has become a de facto standard: gRPC clients can consume it directly for proxyless mesh mode, and several control planes speak it.

Identity and mTLS. Istio and Linkerd give each workload a cryptographic identity, following the SPIFFE standard in Istio's case, encoded in a short-lived X.509 certificate, such as one for the identity of the checkout service account in the prod namespace. Certificates are issued by the mesh's certificate authority and rotated automatically, often every 24 hours. Mutual TLS means both sides present certificates, so each knows who it is talking to, and authorisation policies refer to identities rather than to IP addresses, which change constantly. This is the core of a zero-trust network inside the cluster: being on the network grants nothing.

Latency and resource overhead. A mesh adds two proxy hops per call, one at each end. Published benchmarks vary widely with configuration and load, but typical figures are on the order of a millisecond or less of added median latency per call, more at the tail, and noticeable CPU spent on TLS and HTTP parsing. For a request that crosses five services, this matters for latency-critical paths and for cost at large scale. Linkerd's Rust proxy is designed to be small and fast; Envoy is more feature-rich and configurable.

Sidecar-less meshes. To reduce the cost and operational friction of a sidecar in every pod, newer designs split the work. Istio's ambient mode, which reached general availability in Istio 1.24 in 2024, runs a per-node ztunnel that handles layer-4 concerns, mTLS, identity and TCP telemetry, for all pods on the node, and optional per-namespace or per-service waypoint proxies, Envoy instances, only where layer-7 features such as HTTP routing, retries and header-based policy are needed. Cilium uses eBPF programs in the Linux kernel for layer-4 networking, load balancing and policy, with a per-node Envoy for layer 7. Proxyless gRPC has applications use gRPC libraries that consume xDS directly. The trade-off is less per-pod isolation, a shared per-node component whose failure affects all pods on the node, and in some cases fewer features.

When a mesh is worth it. A mesh pays off when an organisation has many services, often more than a few dozen, in several languages, and needs uniform mTLS, fine-grained traffic control for progressive delivery, and consistent telemetry. It is not worth it for a handful of services in one language, where a good RPC library with retries, timeouts and tracing, plus TLS at the ingress, is simpler. A mesh is also complex software: misconfigured retries, overly broad config propagation and certificate expiry have caused real outages. Adopt it incrementally, namespace by namespace, starting with observability and mTLS in permissive mode before enforcing policies.

Mesh vs gateway. A gateway manages north-south traffic, entering the system from outside, with concerns like API keys, user authentication, rate limits per client and request transformation. A mesh manages east-west traffic, between services inside, with concerns like service identity, mTLS, retries and per-service-pair telemetry. Many deployments use both, and some products, such as Istio's ingress gateway built on Envoy, blur the line. See API Gateway.

Configuration management#

Every service needs configuration: database endpoints, connection pool sizes, timeouts, feature flags, third-party API keys. With hundreds of services across several environments, configuration becomes a system in its own right.

The core principle, from the Twelve-Factor App methodology published by Heroku engineers in 2011, is to separate configuration from code: the same build artefact is promoted through development, staging and production, and only its configuration differs. Configuration is supplied from outside, through environment variables, mounted files or a configuration service.

A mature setup distinguishes three kinds of configuration:

  • Static configuration, set at deploy time and changed by redeploying: ports, resource limits, endpoints. Stored in Git and applied through Kubernetes ConfigMaps, Helm values or Terraform. GitOps tools such as Argo CD and Flux apply what is in Git to the cluster.
  • Dynamic configuration, changed at run time without a deploy: timeouts, rate limits, cache TTLs, kill switches. Served by a configuration service, such as Consul KV, etcd, Spring Cloud Config, AWS AppConfig or Azure App Configuration, with services either polling or receiving pushed updates through watches.
  • Secrets: passwords, API keys, certificates. Never in Git in plain text, never baked into images. Stored in a secret manager such as HashiCorp Vault, AWS Secrets Manager, Google Secret Manager or Azure Key Vault, injected at run time, rotated regularly, and access-controlled and audited per service.

Feature flags are a special kind of dynamic configuration that turn code paths on or off per user, percentage or segment, decoupling deploying code from releasing a feature. Products such as LaunchDarkly, Unleash, Flagsmith and the open OpenFeature standard manage them.

Configuration management, in depth#

Configuration changes are deployments. A large share of production incidents are caused by configuration changes rather than code changes: a timeout set too low, a feature flag enabled for everyone, a malformed rule pushed globally. Treat configuration with the same discipline as code:

  • Version control and review: every change in Git, reviewed, with history and authorship.
  • Validation: schemas and type checks in CI, plus semantic checks, such as "timeout must be less than the caller's deadline", so a malformed value never reaches production.
  • Staged rollout: apply the change to one instance, then one zone, then everywhere, with automatic health checks between stages and fast rollback.
  • Defaults and fallbacks: if the config service is unavailable, services keep the last known good configuration rather than failing.

Facebook described its approach in "Holistic Configuration Management at Facebook" (Chunqiang Tang and colleagues, SOSP 2015): configuration is code, with tools such as Configerator compiling, validating, reviewing and canary-testing configuration changes before distributing them through a tree of proxies to hundreds of thousands of servers, with thousands of configuration changes committed every day.

Push vs pull. Pull, where each instance polls every 30 to 60 seconds, is simple and robust, but slow to propagate and generates load from many instances. Push, through long-lived watches such as Consul's blocking queries or etcd's watch API, propagates in seconds, but needs more careful client logic for reconnection and avoiding thundering herds after a control-plane restart. Many systems combine both: watches for speed and periodic full refreshes as a safety net.

Applying dynamic changes safely in code. A service reading dynamic configuration should validate each new value, apply it atomically, swapping a whole configuration object rather than individual fields, log the change with its version, and expose the current config version in its metrics, so that a change can be correlated with a behaviour change on a dashboard.

Secrets in depth. Good secret management uses short-lived, dynamically generated credentials where possible: Vault can create a database user with a one-hour lease on request and revoke it automatically, so a leaked credential expires quickly. Workload identity, such as IAM roles for Kubernetes service accounts, lets services authenticate to cloud APIs without any static secret at all. Secrets mounted as files in memory-backed volumes are preferable to environment variables, which can leak through crash dumps, child processes and debug endpoints.

Feature flag hygiene. Flags accumulate. Each one is a branch in the code that must be tested in both states, and stale flags turn into hidden configuration debt. Teams set an owner and an expiry for each release flag, remove flags once a feature is fully rolled out, and keep operational flags, such as kill switches for expensive features, deliberately and documented.

Distributed tracing#

In a monolith, a slow request can be profiled in one process. In a microservice system, one user request fans out across many services, queues and databases, and each service's logs show only its own small part. When the checkout page takes 3 seconds, the question "where did the time go?" has no answer from any single service. Averages across services do not help either: the slow requests may all share a path through one overloaded instance of one dependency.

Distributed tracing answers it by following each request across process boundaries.

  • A trace represents one end-to-end request, identified by a trace ID generated at the edge.
  • A span represents one unit of work within it, such as an incoming HTTP request handled by a service, an outgoing call or a database query. Each span has a span ID, its parent span's ID, a start time, a duration, a name, attributes such as the HTTP route and status, and events such as errors.
  • Context propagation carries the trace ID and the current span ID from caller to callee in request headers, or in message metadata for asynchronous calls. The standard format is W3C Trace Context, whose traceparent header carries a version, the trace ID, the parent span ID and sampling flags.
  • Each service reports its spans to a collector, and a tracing backend assembles them by trace ID into a tree, shown as a waterfall timeline.

The idea was described in Google's Dapper paper ("Dapper, a Large-Scale Distributed Systems Tracing Infrastructure", Benjamin Sigelman and colleagues, Google Technical Report, 2010), which inspired Twitter's Zipkin, Uber's Jaeger, and eventually the vendor-neutral OpenTelemetry project, formed in 2019 by merging OpenTracing and OpenCensus, which now provides the standard APIs, SDKs and collector for traces, metrics and logs. See Observability.

Distributed tracing, in depth#

Why tracing is needed, concretely. Tracing answers questions that logs and metrics alone cannot:

  • Where is the latency? The waterfall shows which span dominates, whether calls run in sequence that could run in parallel, and whether a service waits on a lock, a pool or a slow downstream.
  • What is the dependency graph? Aggregated traces reveal which services actually call which, how often, and with what error rates: a live architecture diagram, often surprising.
  • Why did this request fail? A failed span marks where the error originated, rather than where it surfaced as a generic 500 error several hops later.
  • What changed? Comparing traces before and after a deployment shows new calls, extra round trips or an N + 1 pattern introduced by a code change.

Sampling. Recording every span of every request is expensive: a system serving 100,000 requests a second with 20 spans each produces 2 million spans a second, and at about 1 KB per span that is 2 GB a second of tracing data. Systems therefore sample.

  • Head-based sampling decides at the start of the trace, such as keeping 1% of traces, and propagates the decision in the traceparent flags so every service agrees. It is cheap and simple, but it decides before knowing whether the request will be slow or fail, so rare errors are often missed. Dapper sampled at low rates such as 1 in 1,024 for high-traffic services.
  • Tail-based sampling buffers all spans for a trace for a few seconds in collectors, then decides with the full picture: keep every trace with an error or with latency above the 99th percentile, plus a small random fraction of the rest. It captures the interesting traces, at the cost of buffering and routing all spans of a trace to the same collector. The OpenTelemetry Collector supports it.

Propagation through asynchronous hops. For a message on a queue, the producer writes the trace context into message headers, and the consumer starts a span that is linked to the producer's span. Because a consumer may process a batch of messages from many traces, OpenTelemetry uses span links rather than strict parent-child relationships for such cases. Without propagation through queues, traces stop at the first asynchronous hop, which is exactly where many delays hide.

Correlating the three pillars. Tracing is most useful when connected to logs and metrics: services write the trace ID into every log line, so a trace can be opened from an error log and vice versa; metrics can carry exemplars, example trace IDs attached to histogram buckets, so a latency spike on a dashboard links directly to sample traces of the slow requests.

Instrumentation. OpenTelemetry offers automatic instrumentation for common frameworks and clients, such as HTTP servers, gRPC, database drivers and Kafka clients, through agents or libraries, so most spans come for free; teams add manual spans around important business steps. A service mesh can emit spans for every hop without any code, but it cannot propagate context through the application from the incoming to the outgoing request, so the application must still forward the trace headers for traces to connect.

Costs and pitfalls. Tracing overhead is usually small, a few microseconds per span, but high-cardinality attributes, such as user IDs on every span, can explode storage costs in some backends. Clock skew between hosts can make child spans appear to start before their parents; backends correct for this approximately. And traces are only useful if people look at them: most teams make them the first stop in incident investigation.

The wider catalogue of microservice patterns#

The patterns above are the infrastructure core, but microservice design draws on a larger catalogue. Chris Richardson's microservices pattern language, at microservices.io and in his book "Microservices Patterns" (Manning, 2018), groups them by the problem they solve. A practical summary:

ProblemPatternsWhere covered
DecompositionDecompose by business capability; decompose by subdomain; strangler figMonolith vs Microservices, Domain-Driven Design
Data managementDatabase per service; saga; transactional outbox; CQRS; event sourcing; API compositionDistributed Transactions, Event Sourcing and CQRS
CommunicationRemote procedure invocation; messaging; idempotent consumer; domain eventsThis page, Message Queues
External APIAPI gateway; backend for frontendAPI Gateway
DiscoveryClient-side discovery; server-side discovery; service registry; self and third-party registrationThis page
ReliabilityCircuit breaker; bulkhead; retry with backoff; timeout; rate limiting; fallbackResilience Patterns
DeploymentService instance per container; serverless deployment; sidecar; service meshThis page, Serverless
Cross-cutting concernsMicroservice chassis; externalised configurationThis page
ObservabilityLog aggregation; application metrics; distributed tracing; health check API; exception tracking; audit loggingThis page, Observability
SecurityAccess token; mutual TLS; zero trustThis page
TestingConsumer-driven contract test; service component testMonolith vs Microservices

Two entries deserve a note here:

  • Microservice chassis. A framework or template that every new service starts from, bundling logging, metrics, tracing, health checks, config loading and RPC clients with sensible defaults. Spring Boot with Spring Cloud, Go kit and internal "golden path" templates are examples. A chassis gives consistency within one language; a mesh and sidecars give it across languages; most organisations use both.
  • Health check API. Every service exposes endpoints that report whether it is live, meaning the process is not stuck and should not be restarted, and whether it is ready, meaning it can serve traffic now, with its dependencies reachable and its caches warm. Kubernetes uses them as liveness and readiness probes. Confusing the two is a classic mistake: a liveness check that fails when the database is down makes Kubernetes restart every instance at once, turning a database blip into a full outage.

Best practices for building microservices#

Lessons repeated across many organisations' experience:

  1. Design around business capabilities, with one team owning each service end to end, including its on-call.
  2. Give each service its own data store, and integrate only through APIs and events.
  3. Keep services stateless, storing session and state in databases or caches, so instances can be added, removed and replaced freely.
  4. Prefer asynchronous communication for anything the caller does not need immediately, and keep synchronous chains shallow.
  5. Version APIs and evolve them compatibly: add fields, never remove or repurpose them without a deprecation period; test with consumer-driven contracts.
  6. Make every call safe to fail: timeouts everywhere, idempotent operations, limited retries with backoff, circuit breakers and graceful degradation.
  7. Automate delivery: CI/CD per service, containers, infrastructure as code, canary releases and automatic rollback. See Deployment and CI/CD.
  8. Instrument from day one: structured logs with trace IDs, RED metrics, meaning rate, errors and duration, per endpoint, traces, and dashboards and alerts owned by the service team.
  9. Secure by default: mTLS between services, least-privilege authorisation, secrets in a secret manager, and dependency scanning.
  10. Invest in a paved road: a platform that makes the right way the easy way, with templates, a chassis, the mesh and self-service infrastructure.

Lessons from large adopters#

Netflix. Netflix moved from a monolithic DVD-rental application in its own data centre to hundreds of microservices on AWS between roughly 2009 and 2016, after a major database corruption in 2008 made a single point of failure painfully clear. Along the way it open-sourced much of the infrastructure that defined early microservice practice: Eureka for discovery, Ribbon for client-side load balancing, Hystrix for circuit breakers and bulkheads, Zuul as its edge gateway, Archaius for dynamic configuration, and Chaos Monkey for deliberately killing instances in production so that every service is forced to tolerate failure. Lessons it has repeatedly shared publicly include: design for failure because everything fails; prefer availability and graceful degradation, such as showing a generic list when personalisation is down; give teams freedom with responsibility; and invest heavily in the platform and in observability. Over time it moved parts of this stack to newer tools, such as gRPC for inter-service calls, as the industry's shared infrastructure matured.

Airbnb. Airbnb has described in conference talks its evolution from a large Ruby on Rails monolith, the "monorail", to a service-oriented architecture starting around 2017 and 2018, motivated by deployment contention as engineering grew. It later described a hybrid of micro and macro services, concerned that too many fine-grained services created excessive coordination and dependency complexity, with aggregation layers and a unified data access approach. The general lesson is that the granularity of services is itself a design choice to revisit, not a target to maximise.

Common thread. The companies that succeeded with microservices invested as much in the infrastructure, the discovery, mesh, configuration, observability and delivery described on this page, as in the services themselves. Organisations that split services without that infrastructure usually report the distributed-monolith problems described in Monolith vs Microservices.

When to Use It#

These patterns are needed as soon as you run more than a handful of services, but each has its own trigger:

  • Service discovery: whenever instances are dynamic, through autoscaling, containers or frequent deploys. On Kubernetes or a cloud load balancer you get it built in; use a registry such as Consul when services span several platforms or data centres.
  • Synchronous calls: for queries and for commands whose result the caller needs before it can respond. Asynchronous messaging: for side effects, fan-out to many consumers, long-running work, load levelling and integration between bounded contexts.
  • API composition: for detail views assembled by ID from a few services. Switch to a read model when queries filter or sort across services.
  • BFF: when several client types, such as web, iOS, Android and TV, need materially different APIs and have their own teams.
  • Sidecars: when a cross-cutting concern must be consistent across many languages, or upgraded without touching applications.
  • Service mesh: when you have dozens of services or more, several languages, a need for uniform mTLS and zero-trust policy, fine-grained traffic shifting for canaries, and consistent telemetry, and a platform team to run it.
  • Externalised configuration and secrets management: always, from the first service; dynamic configuration and feature flags once you need to change behaviour without deploying.
  • Distributed tracing: as soon as a request crosses more than two or three services, and certainly before your first serious latency incident.

When NOT to Use It#

  • A small system of a few services in one language does not need a mesh; an RPC library with timeouts, retries and tracing, plus TLS at the edge, is simpler and cheaper.
  • Do not build your own registry, mesh or tracing system. Use the platform's built-in discovery, open-source projects or managed services; custom infrastructure is a permanent tax.
  • Do not use API composition for cross-service search or reporting; build a read model or send the data to a warehouse.
  • Do not create a BFF per screen or per feature; one per client experience is enough, and none if there is only one client.
  • Do not make everything asynchronous: if the user needs an answer now, a queue in the middle adds latency and complexity without benefit.
  • Do not adopt microservices just to use these patterns. If the organisation does not need independent deployment, a modular monolith avoids the whole category of problems this page solves. See Monolith vs Microservices.

How to Implement It#

  1. Start with the platform's built-in discovery: Kubernetes Services and DNS, or cloud load balancers. Add readiness probes and graceful shutdown with a pre-stop delay to every service.
  2. Standardise the RPC layer: choose REST or gRPC for internal calls, generate clients from contracts, and set default timeouts, deadline propagation and retry policies in a shared chassis or the mesh.
  3. Decide sync vs async per interaction with the question "does the caller need the answer to respond?". Use an outbox for reliable events and idempotent consumers everywhere.
  4. Put a gateway at the edge for authentication, rate limiting and routing. Add BFFs only when client needs diverge, and composite services or read models for cross-service views.
  5. Externalise configuration from day one: static config in Git with GitOps, secrets in a secret manager, dynamic config and feature flags in a dedicated service with staged rollout.
  6. Instrument everything with OpenTelemetry: automatic instrumentation for frameworks, trace IDs in every log line, RED metrics per endpoint, and a sampling strategy that keeps errors and slow traces.
  7. Adopt a mesh only when the signals appear, incrementally: telemetry first, then mTLS in permissive mode, then strict mTLS and authorisation policies, then traffic management for canaries.
  8. Document the paved road: templates and guides so that a new service gets discovery, config, telemetry, security and deployment for free.

A canary release with retries and timeouts, configured in Istio rather than in code:

apiVersion: networking.istio.io/v1
kind: DestinationRule
metadata: { name: payments }
spec:
  host: payments.prod.svc.cluster.local
  trafficPolicy:
    outlierDetection:            # eject instances that keep failing
      consecutive5xxErrors: 5
      interval: 10s
      baseEjectionTime: 30s
  subsets:
    - { name: stable, labels: { version: v1 } }
    - { name: canary, labels: { version: v2 } }
---
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata: { name: payments }
spec:
  hosts: [payments.prod.svc.cluster.local]
  http:
    - timeout: 2s                # whole call, including retries
      retries:
        attempts: 2
        perTryTimeout: 800ms
        retryOn: "connect-failure,refused-stream,unavailable"
      route:
        - destination: { host: payments.prod.svc.cluster.local, subset: stable }
          weight: 95
        - destination: { host: payments.prod.svc.cluster.local, subset: canary }
          weight: 5
TechnologyFits when
Kubernetes Services, CoreDNS, EndpointSlicesDefault discovery for services on Kubernetes
ConsulDiscovery, health checks and KV config across VMs, Kubernetes and several data centres
etcd, ZooKeeperStrongly consistent registries and coordination, usually inside other platforms
Netflix Eureka with Spring CloudJVM services wanting client-side discovery; older Spring Cloud stacks
EnvoyHigh-performance L7 proxy for sidecars, gateways and meshes
IstioFeature-rich mesh: traffic management, mTLS, policy; sidecar or ambient mode
LinkerdSimpler, lightweight mesh with a Rust proxy; mTLS and telemetry with low overhead
CiliumeBPF networking, policy and mesh features at the kernel level
DaprSidecar runtime giving portable pub/sub, state, invocation and workflow APIs
gRPC, REST with OpenAPIInternal RPC with generated clients; public and browser-facing APIs
Kafka, RabbitMQ, SQS and SNS, NATSAsynchronous events and commands between services
Apollo Federation, GraphQL MeshComposition of many services into one client-facing graph
Vault, AWS Secrets Manager, GCP Secret ManagerSecrets with rotation, leases and audit
Argo CD, Flux; AWS AppConfig, Consul KVGitOps static config; dynamic config with staged rollout
LaunchDarkly, Unleash, Flagsmith, OpenFeatureFeature flags and progressive releases
OpenTelemetry with Jaeger, Zipkin, Grafana Tempo or a vendorDistributed tracing with standard instrumentation

Trade-offs#

OptionProsConsPick when
Client-side discoveryNo extra hop; smart, zone-aware balancingLogic in every client and languageOne main language, or a mesh doing it in the sidecar
Server-side discoverySimple clients; any languageExtra hop; the router must be highly availableMixed languages; platform load balancers available
Synchronous callsSimple; immediate answersTemporal coupling; availability multiplies down the chainQueries and commands that need a result now
Asynchronous messagingDecoupled; absorbs spikes; fan-outEventual consistency; harder debugging; broker to runSide effects, long work, integration
OrchestrationExplicit flow; easy to monitor and changeCentral component; risk of a god serviceMulti-step processes with compensations
ChoreographyLoose coupling; no coordinatorImplicit flow; hard to trace and changeA few simple reactions to events
API compositionSimple; fresh dataLatency and availability of all parts; no cross-service filteringDetail views by ID
Read model via CQRSFast, flexible queriesEventual consistency; more infrastructureLists, searches, dashboards
Libraries or chassisNo extra process; fastPer-language; upgrades need redeploysOne or two languages; small fleets
Sidecar service meshUniform features across languages; no code changesCPU, memory and latency per pod; complexityLarge polyglot fleets needing mTLS and traffic control
Sidecar-less mesh: ambient, eBPFLower overhead; simpler pod lifecycleShared per-node component; newerLarge fleets sensitive to sidecar cost
Head-based samplingCheap; simpleMisses rare errors and slow requestsHigh-volume baseline tracing
Tail-based samplingKeeps the interesting tracesBuffering and collector routing costDebugging tail latency and errors

Common Pitfalls#

  • Deep synchronous call chains. Ten services calling each other in sequence multiply latency and failure probability; flatten with parallel calls, caching, read models and asynchronous steps.
  • Retry storms. Retries at every layer multiply load during an incident; retry at one layer, with backoff, jitter and a budget.
  • Missing or inconsistent timeouts. A default infinite timeout in one HTTP client can hang threads across the whole fleet; set timeouts on every call and propagate deadlines.
  • Liveness probes that check dependencies, causing mass restarts when a shared database is slow; liveness should check only the process itself.
  • No graceful shutdown, causing errors on every deploy as instances disappear while still registered.
  • Connection-level balancing for gRPC, pinning all traffic to a few pods; use request-level balancing in the client or the mesh.
  • Adopting a mesh too early or all at once, before there is a platform team to run it, leading to opaque failures and certificate or configuration outages.
  • Sending every proxy the whole mesh configuration, wasting memory and slowing updates in large clusters.
  • Configuration changes without review, validation or staged rollout, a leading cause of large outages.
  • Secrets in environment files, images or Git.
  • Traces that stop at queues because context is not propagated in message headers.
  • A shared "common" library that contains business logic, coupling every service's release to it.
  • A gateway or BFF that accumulates business rules, turning into a new monolith in the middle of the architecture.

Real-World Examples#

  • Netflix built and open-sourced Eureka, Ribbon, Hystrix, Zuul and Archaius as it moved to hundreds of microservices on AWS, and popularised chaos engineering with Chaos Monkey; much of the early microservices vocabulary comes from its engineering blog and talks.
  • Lyft created Envoy to make its network transparent to applications while moving from a monolith to services, and open-sourced it in 2016; Envoy became the data plane for Istio and many other meshes and gateways, and a graduated CNCF project.
  • Google described Dapper in 2010; its ideas underpin Zipkin, created at Twitter, Jaeger, created at Uber and donated to the CNCF, and OpenTelemetry. Google, IBM and Lyft announced Istio in 2017.
  • Twitter built Finagle, a JVM RPC library providing load balancing, retries with budgets, circuit breaking and tracing, an example of the library approach that preceded meshes. Linkerd's first version was built on Finagle by former Twitter engineers at Buoyant.
  • Kubernetes made server-side discovery, readiness and liveness probes, ConfigMaps and Secrets standard platform features, so most teams now get the basics without extra infrastructure.
  • Facebook described its configuration management system, including Configerator, at SOSP 2015, with configuration treated as code and canary-tested before reaching its fleet.

In the Interview#

Deep Dive: The maths of call chains, fan-out and retriesShow

Availability in series. A request that synchronously depends on n services, each with availability a, has availability aⁿ. With a = 99.95%:

Services in the chainAvailabilityDowntime per 30 days
199.95%about 22 minutes
599.75%about 1.8 hours
1099.50%about 3.6 hours
3098.51%about 10.7 hours

This is why critical paths should depend on as few services as possible, and why fallbacks, which turn a hard dependency into a soft one, are so valuable: if a dependency's failure degrades the response instead of failing it, it drops out of the product.

Fan-out and tail latency. If a composer calls 20 services in parallel and each has a 1% chance of taking longer than its 99th percentile, the chance that at least one is slow is 1 − 0.99²⁰ ≈ 18%. So almost one request in five sees at least one slow dependency, and the composer's median latency is close to its dependencies' 99th percentile. Remedies, from "The Tail at Scale" by Jeffrey Dean and Luiz André Barroso (CACM 2013), include hedged requests, sending a second copy of a slow request to another instance after, say, the 95th-percentile latency, and keeping only the first answer, which costs a few percent more load and sharply cuts the tail, and dropping optional dependencies after a tight timeout.

Retry amplification. If each of k layers retries r times on failure, a persistent failure at the bottom generates (r + 1)ᵏ attempts. With three layers each making one initial attempt plus two retries, that is 3³ = 27 attempts per user request. At 1,000 user requests per second, the struggling bottom service receives 27,000 requests per second exactly when it is least able to handle them. A retry budget caps retries as a fraction of normal requests, such as 10%, so the worst-case amplification is 1.1 times, not 27.

Timeout budgets. Suppose the edge budget is 1,000 ms. The gateway spends 20 ms, so the checkout service has 980 ms. Checkout calls pricing and payments in sequence: if pricing usually takes 50 ms with a 99th percentile of 150 ms, give it a 200 ms timeout; payments then has at most 780 ms remaining, minus checkout's own processing. With deadline propagation, payments knows its exact remaining budget and can skip a retry that could not finish in time. Without it, each hop sets independent timeouts that are either too short, causing false failures, or too long, wasting resources on abandoned requests.

Mesh overhead at scale. If each proxy hop adds about 0.5 ms at the median and a request crosses six services, that is twelve proxy traversals, roughly 6 ms of added median latency, and more at the tail. With 2,000 pods and a 100 MB sidecar each, the mesh costs 200 GB of memory, perhaps the capacity of a few large nodes. These are the numbers to weigh against the benefits, and they explain the appeal of per-node designs such as ambient mode.

Deep Dive: Anatomy of one request through a meshed Kubernetes systemShow

Follow a single request, a customer placing an order, through a typical production stack.

  1. DNS and edge. The app resolves api.example.com to a cloud load balancer's addresses. TLS terminates at the load balancer or at the ingress gateway, an Envoy deployment managed by the mesh.
  2. Ingress gateway. It validates the user's JWT signature against cached identity-provider keys, applies a per-user rate limit with counters in Redis, generates a trace ID because none exists, writes a traceparent header, and routes POST /orders to the orders Service.
  3. Discovery and balancing. The gateway's Envoy already holds the endpoints for orders, pushed by istiod over xDS from the Kubernetes EndpointSlices. It picks the less loaded of two random ready pods in the same zone, and opens, or reuses, an mTLS connection to that pod's sidecar.
  4. Inbound sidecar. The orders pod's Envoy terminates mTLS, verifies the caller's SPIFFE identity, checks the authorisation policy allowing the ingress gateway to call orders, records request metrics and a span, and passes the request to the application on localhost.
  5. Application logic. The orders service validates the cart, then calls pricing and inventory in parallel over gRPC with a 300 ms deadline derived from the remaining budget, forwarding the trace headers. Each outbound call goes through its own sidecar, which applies the retry policy, a single retry on connection failure, and outlier detection.
  6. Local transaction. It writes the order and an OrderPlaced outbox row in one PostgreSQL transaction, using a password fetched at start-up by the Vault agent sidecar, and returns 201 Created with the order ID.
  7. Asynchronous continuation. A relay, such as Debezium reading the database's change log, publishes OrderPlaced to Kafka, with the trace context in the message headers. Payments, notifications and analytics consume it independently, each starting spans linked to the original trace.
  8. Observability. Every proxy and service exports spans to an OpenTelemetry Collector, which applies tail sampling, keeping this trace if it errored or took longer than 500 ms. Logs carry the trace ID. Mesh metrics show request rate, errors and latency for each pair, gateway to orders, orders to pricing and so on.
  9. Configuration. The orders service's feature flag "new-pricing-engine" is evaluated locally from a flag SDK that receives updates by streaming, so a kill switch takes effect in seconds without a deployment.

Each step is one of this page's patterns, and each could be done in application code instead; the trend over the past decade has been to push steps 2 to 4 and 8 into the platform, so that services contain mainly steps 5 to 7.

Deep Dive: How the infrastructure layer evolvedShow

First generation: libraries, roughly 2010 to 2016. Companies running many services at scale built fat client libraries: Netflix's OSS stack, Twitter's Finagle, Google's internal Stubby RPC system, the predecessor of gRPC. Discovery, load balancing, retries, circuit breaking and tracing lived in the library. This worked well inside one language ecosystem, mostly the JVM at Netflix and Twitter, but every new language needed a port, and upgrades required every team to redeploy.

Second generation: sidecar proxies and meshes, 2016 onwards. Lyft's Envoy showed that a high-performance out-of-process proxy could do the same job for any language. Linkerd, from Buoyant, coined the term service mesh, and Istio, from Google, IBM and Lyft in 2017, added a full control plane. Kubernetes made the sidecar easy to inject. This moved networking concerns from developers to platform teams, at the cost of a proxy per pod.

Third generation: sidecar-less and kernel-level, 2022 onwards. To cut cost and complexity, Istio's ambient mode moved layer-4 work to per-node tunnels and layer-7 work to optional waypoint proxies; Cilium used eBPF in the kernel; gRPC gained proxyless xDS support. At the same time, Kubernetes added native sidecar containers to fix lifecycle problems for those who keep sidecars.

Standardisation. Alongside the architectural shifts, the industry converged on standards: OpenTelemetry for telemetry, W3C Trace Context for propagation, SPIFFE for workload identity, xDS for proxy configuration, the Kubernetes Gateway API for ingress and mesh routing, and OpenFeature for feature flags. Standards make the pieces replaceable, which is the same goal microservices pursue at the application level.

What stays constant. Across the generations, the problems remain the ones listed at the top of this page: finding instances, calling them safely, securing traffic, configuring behaviour and understanding requests. The tools change; the patterns and their trade-offs do not.

Key Takeaways#

  • Splitting a system into services turns function calls into network calls; the infrastructure patterns exist to make those calls findable, safe, secure, configurable and observable.
  • Service discovery maps names to healthy instances through a registry, with client-side or server-side lookup; Kubernetes provides server-side discovery built in. Pair it with health checks and graceful shutdown.
  • Choose synchronous calls only when the caller needs the answer now; use asynchronous messaging, with an outbox and idempotent consumers, for everything else. Availability multiplies down synchronous chains.
  • Use orchestration for multi-step processes and choreography for simple reactions.
  • API composition suits detail views by ID; read models suit cross-service queries; BFFs tailor APIs per client experience.
  • Sidecars move cross-cutting concerns out of application code; a service mesh runs them fleet-wide with a control plane, giving mTLS, traffic control and telemetry, at a real cost in latency, resources and complexity.
  • Externalise configuration, treat config changes like code changes with review, validation and staged rollout, and keep secrets in a secret manager.
  • Distributed tracing, with trace context propagated through every hop including queues, is the only practical way to see where time and errors go in a request that crosses many services.