TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท infrastructure ยท kubernetes ยท networking ยท microservices ยท security

Service mesh

A layer of proxies next to every workload, configured by a central control plane, that gives service-to-service traffic mTLS, retries, timeouts, traffic splitting and telemetry without changing application code.

15 min6 animations

๐Ÿ“š Builds onโš“ Kubernetes

๐Ÿ–จ๏ธ Cheat sheet

A concierge at every door

Picture a big apartment block. Ana lives in one flat and writes letters to Ben in another. Ben, in turn, writes to Cleo. Every resident used to handle the hard parts alone: checking who a letter really came from, knocking again when nobody answered, keeping notes of what was sent.

That's a lot of chores, and every resident did them a little differently. So the building puts a concierge at every flat door. Ana just hands her letter to her own concierge. Her concierge walks it to Ben's concierge, who hands it in. The replies come back the same way.

The residents don't change at all. All the chores move to the concierges, and the building office tells every concierge the same rules. That whole arrangement is called a service mesh.

Why a service mesh

In a microservice system every service needs the same cross-cutting concerns for the calls it makes and receives:

  • encryption and authentication between services (mTLS);
  • retries, timeouts and failure isolation;
  • load balancing and traffic splitting for releases;
  • metrics, access logs and trace spans for every request.

Putting these in libraries means re-implementing them per language, keeping every team's version in sync, and redeploying every service to change a policy. A service mesh moves them out of the application into a proxy that sits next to every workload and handles all of its network traffic. The application keeps calling http://payments:8080 as before.

TermMeaning
Data planeThe proxies that carry every request (Envoy in Istio, linkerd2-proxy in Linkerd)
Control planeThe central component that configures the proxies and issues identities (istiod in Istio)
SidecarA proxy container added to each pod, next to the app container
Workload identityA cryptographic identity per workload, derived from its Kubernetes service account

A mesh builds on Kubernetes: it hooks into pod creation, uses Services for discovery and is configured with custom resources.

A concierge at every door4 steps
๐Ÿšช Ana's flat๐Ÿšช Ben's flat๐ŸขBuilding office๐Ÿ™‹โ€โ™€๏ธAna๐Ÿ›Ž๏ธAna's concierge๐Ÿ›Ž๏ธBen's concierge๐Ÿ™‹โ€โ™‚๏ธBen
Press play and watch it happen!

How the concierge gets to the door

Whenever a new flat opens, the building office posts a concierge at its door straight away. Nobody has to ask. Then the door is rewired, so every letter going in or out passes the concierge. Even if Ana forgets the concierge exists, she can't slip a letter past.

The building office never carries letters itself. It writes the rules and sends them to every concierge. If the office closes for an afternoon, the concierges carry on with the last rules they were given. The concierges who carry the letters are called the data plane.

Data plane, control plane and sidecar injection

In Istio's sidecar mode you label a namespace with istio-injection=enabled. From then on a mutating admission webhook rewrites every new pod in it, adding:

  • an istio-proxy container running Envoy;
  • an istio-init init container (or, with the Istio CNI plugin, a node agent instead) that installs iptables NAT rules in the pod's network namespace.

Those rules redirect all outbound TCP to Envoy on port 15001 and all inbound TCP to port 15006. Envoy's own traffic (it runs as UID 1337) is excluded, so it doesn't loop back to itself. The app opens a normal connection to payments:8080; the kernel hands it to Envoy, which recovers the original destination and forwards the request.

The control plane, istiod, watches the Kubernetes API for Services, endpoints and mesh resources, and pushes the resulting listeners, routes, clusters and endpoints to every proxy over Envoy's xDS APIs. It also signs each workload's certificate (see below). It is not on the request path: if istiod is unavailable, existing proxies keep serving with their last configuration. Config changes, new pods and certificate renewals wait until it is back.

Linkerd works the same way with its own Rust proxy, linkerd2-proxy, injected when a namespace or workload has the linkerd.io/inject: enabled annotation.

๐Ÿ”ง Going deeper

Startup and shutdown ordering: a classic sidecar problem is the app starting before its proxy is ready (early calls fail) or a Job's pod never finishing because the proxy keeps running. Kubernetes native sidecar containers (init containers with restartPolicy: Always) start before and stop after the app containers, and both Istio and Linkerd can use them.

Injection and interception4 steps
๐Ÿ  Ana's flat๐Ÿ“ Moving-in form๐ŸขBuilding office๐Ÿ™‹โ€โ™€๏ธAna๐ŸšชBen's door
Press play and watch it happen!

ID badges and locked pouches

How does Ben's concierge know a letter really came from Ana's flat? The building office gives every concierge an ID badge with the flat's name on it. Before any letter changes hands, both concierges show each other their badges, and the letter travels in a locked pouch that only the other concierge can open. Showing badges both ways like this is called mutual TLS.

Badges expire after a day, so a stolen one is soon useless. The concierge picks up a fresh badge from the office well before the old one runs out, without anyone noticing.

At first, concierges still accept unlocked letters, so flats can join the scheme one by one. Once the office sends the strict rule, anyone without a badge who walks up to Ben's door is turned away.

Workload identity and automatic mTLS

Each workload's identity is its Kubernetes service account, written as a SPIFFE ID in the certificate's SAN: spiffe://cluster.local/ns/shop/sa/orders (trust domain, namespace, service account).

In Istio, the agent in each pod generates a private key and sends a certificate signing request to istiod, which acts as the mesh's certificate authority. istiod checks the pod's service account token, signs a short-lived certificate (24 hours by default) and the agent delivers it to Envoy over the SDS API. The private key never leaves the pod, and certificates are rotated automatically before they expire.

When two meshed workloads talk, their proxies run a mutual TLS handshake: both present certificates and both verify them against the mesh CA. That gives encryption in transit and authenticated peer identities, which authorization policies can then use ("only sa/orders may call POST /pay on payments").

  • Istio's PeerAuthentication defaults to PERMISSIVE: proxies accept both mTLS and plaintext, which eases migration. Set STRICT to reject plaintext from workloads outside the mesh.
  • Linkerd turns on mTLS by default for TCP traffic between meshed pods, with 24-hour proxy certificates.

The mesh authenticates services, not end users. A user's JWT still has to be checked by the app or by a policy.

Badges and locked pouches5 steps
๐ŸขBuilding office๐Ÿ›Ž๏ธAna's concierge๐Ÿ›Ž๏ธBen's concierge
Press play and watch it happen!

Traffic rules from the office

Ben has done up a new flat next door and wants to try it out. The office tells Ana's concierge: take 9 letters in 10 to Ben's old flat and 1 in 10 to the new one. If the new flat copes, the office sends a new rule and more letters go there. Trying something new with a few letters first is called a canary release.

Ben's old flat has two front doors, and either can take a letter. The rules also say how to handle trouble. If nobody answers a door, knock once more at another of Ben's doors, but don't stand there forever: after a short wait, give up and tell Ana. And if one door keeps failing, stop knocking there for a while.

Traffic management

Because every request passes a proxy that understands HTTP and gRPC, the mesh can route per request rather than per connection. In Istio, a DestinationRule names subsets of a service by label and sets connection policy, and a VirtualService routes to them:

1apiVersion: networking.istio.io/v12kind: VirtualService3metadata: { name: payments }4spec:5  hosts: [payments]6  http:7    - route:8        - destination: { host: payments, subset: v1 }9          weight: 9010        - destination: { host: payments, subset: v2 }11          weight: 1012      timeout: 2s13      retries: { attempts: 2, perTryTimeout: 500ms, retryOn: "5xx,connect-failure" }14---15apiVersion: networking.istio.io/v116kind: DestinationRule17metadata: { name: payments }18spec:19  host: payments20  subsets:21    - { name: v1, labels: { version: v1 } }22    - { name: v2, labels: { version: v2 } }23  trafficPolicy:24    outlierDetection: { consecutive5xxErrors: 5, interval: 10s, baseEjectionTime: 30s }
  • Weights split traffic for canaries and blue/green; match on headers can send internal testers to v2 only.
  • Timeouts bound the whole call; perTryTimeout bounds each attempt.
  • Retries happen in the proxy, on another endpoint where possible.
  • Outlier detection is the mesh's circuit breaker: an endpoint that returns too many consecutive errors is ejected from the load-balancing pool for a while, then let back in. connectionPool limits cap concurrent connections and pending requests.

Retries multiply across layers: an app retrying 3 times through a mesh retrying 3 times can send 16 requests to a struggling service. Pick one layer, and check your mesh's default retry policy (Istio retries twice by default on connection failures and 503s) before adding your own. Retrying a non-idempotent request can repeat its side effect.

Splitting, retries and ejection5 steps
๐Ÿ  Ben's old flat๐ŸขBuilding office๐Ÿ™‹โ€โ™€๏ธAna๐Ÿ›Ž๏ธAna's concierge๐ŸšชDoor 1๐ŸšชDoor 2๐ŸกBen's new flat
Press play and watch it happen!

The delivery book, and what residents still do

Every concierge writes each delivery in a shared delivery book: from whom, to whom, how long it took, and whether it worked. Without any resident lifting a finger, the office can see which doors are slow or failing.

There is one thing a concierge can't know: which letters a resident sent because of a letter they received. So when Ana's letter makes Ben write to Cleo, Ben must copy the reference number from Ana's letter onto his. Then the book shows one story from start to finish, called a trace. If Ben forgets, the book shows two unrelated stories.

So residents can stop knocking twice and stop carrying their own locks. But they still copy reference numbers, and because concierges sometimes knock again, Ben must cope with getting the same letter twice.

Observability, and what stays in your Spring app

Every proxy records each request it handles, so you get observability for every meshed service without instrumenting it: the golden metrics (request rate, success or error rate, latency distribution) per source and destination, access logs, and, once a tracing backend is configured, a span for each hop. Istio exposes these as Prometheus metrics such as istio_requests_total and istio_request_duration_milliseconds.

Distributed tracing needs the app's help. The proxy sees an inbound request and, later, some outbound ones, but can't tell which outbound call was caused by which inbound request. Your service must copy the trace headers from each incoming request to the outgoing calls it triggers: W3C traceparent and tracestate, or the B3 x-b3-* set, plus x-request-id in Istio.

In Spring Boot 3 and later, Micrometer Tracing (with the OpenTelemetry or Brave bridge) does that for clients built from the auto-configured builders:

1@Configuration2class Clients {3    @Bean4    RestClient payments(RestClient.Builder builder) {   // auto-configured: propagates traceparent5        return builder.baseUrl("http://payments:8080").build();   // plain HTTP: the sidecar adds mTLS6    }7}8 9@Service10class Checkout {11    private final RestClient payments;12 13    Checkout(RestClient payments) { this.payments = payments; }14 15    void pay(Order order) {16        payments.post().uri("/pay")17                .header("Idempotency-Key", order.id())   // the mesh may retry: let payments dedupe18                .body(new PaymentRequest(order.id(), order.total()))19                .retrieve()20                .toBodilessEntity();21    }22}
You can usually removeYou still own
Keystores and truststores for service-to-service TLSPropagating trace headers (or using instrumented clients)
Client-side retries the mesh already does (or the mesh's, but not both)Idempotency of anything that may be retried
Client-side load balancing and service discovery clientsBusiness fallbacks, and what a timeout means to the user
Per-service metrics plumbing for request counts and latencyEnd-user authentication and authorization on your data

A RestClient built with RestClient.create() or new RestTemplate() skips the observation setup, so its calls start new traces.

The delivery book and the reference number4 steps
Ana's flatBen's flatCleo's flatDelivery book012345๐Ÿ™‹โ€โ™€๏ธAna๐Ÿ›Ž๏ธAna's concierge๐Ÿ™‹โ€โ™‚๏ธBen๐Ÿ›Ž๏ธBen's concierge๐Ÿ™‹Cleo๐Ÿ›Ž๏ธCleo's concierge
Press play and watch it happen!

Fewer concierges, and when to skip them

A concierge at every door costs a lot: many people to pay, and two extra handoffs for every letter. Some buildings instead put one shared concierge desk on each floor. It checks badges and locks pouches for every flat on that floor. Only flats whose letters need reading and sorting, such as splitting or knocking again, call in a specialist sorting room. This way of working is called ambient mode.

And if the building has three flats and everyone knows each other, it may need no concierges at all.

Sidecarless meshes, Istio vs Linkerd, and the costs

Istio ambient mode (generally available since Istio 1.24) drops the per-pod sidecar:

  • ztunnel, a per-node proxy (DaemonSet), handles L4 for every pod on its node: mTLS with the pod's own identity, L4 authorization and TCP telemetry. Traffic between nodes goes through an mTLS tunnel called HBONE.
  • Waypoint proxies (Envoy) are deployed only where you need L7 features (HTTP routing, retries, L7 policy) and attached to a namespace, service or pod with the istio.io/use-waypoint label; traffic for those destinations goes ztunnel โ†’ waypoint โ†’ ztunnel.

Apps are added by labelling the namespace, and no pod restart is needed. Cilium's service mesh takes a similar route: eBPF in the kernel for L4 and a per-node Envoy for L7.

IstioLinkerd
ProxyEnvoy (C++), or ztunnel and waypoints in ambient modelinkerd2-proxy (Rust, built for the mesh)
ScopeBroad: rich L7 routing, ingress and egress gateways, VMs, multi-clusterFocused: mTLS, retries, timeouts, splitting, metrics
mTLSAutomatic, PERMISSIVE by default, STRICT opt-inOn by default between meshed pods
Trade-offMore features and more to learn and operateLighter and simpler, fewer knobs

Costs to weigh:

  • Latency: each call passes two extra proxies (one per side). Usually small, but it adds up across long call chains and shows at the tail.
  • Resources: a sidecar per pod multiplies CPU and memory by pod count; ambient mode is largely about cutting this.
  • Complexity: another layer to upgrade (sidecar upgrades restart pods), to debug when a request fails, and many custom resources to learn. A bad mesh config can break every service at once.

When not to use one: a handful of services, one language with a good resilience library, no requirement for encrypted and authenticated service-to-service traffic, or no team to run it. Kubernetes Services, NetworkPolicies, TLS at the ingress and a library like Resilience4j often cover it.

One concierge desk per floor4 steps
Floor 1Floor 2๐ŸขBuilding office๐Ÿ™‹โ€โ™€๏ธAna๐Ÿ™‹โ€โ™‚๏ธDan๐Ÿ›Ž๏ธFloor 1 desk๐Ÿ›Ž๏ธFloor 2 desk๐Ÿ™‹โ€โ™‚๏ธBen
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Service mesh, told the same way as the story.
  1. The building office closes for an afternoon. What happens to the letters?
  2. Ana forgets the concierge exists and aims her letter straight at Ben. Why does it still go through her concierge?
  3. When nobody answers at Ben's door, Ana's concierge sometimes knocks again. What must Ben's own letter-handling cope with?
  4. Ana's letter makes Ben write to Cleo. What does Ben have to do so the delivery book shows one story?
  5. Why would a building swap a concierge at every door for one shared desk per floor?
Answer every question to check.Passing marks Service mesh as done.
Got the hang of Service mesh? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿš€ Shipping to productionStep 6 of 10

โ† Previous on the pathโš“ KubernetesNext on the path โ†’๐ŸŽก Load balancing