Skip to content

Service Mesh & the Sidecar Pattern ​

"The network should be transparent to applications. When network and application problems do occur it should be easy to determine the source of the problem." — Envoy documentation, What is Envoy

Summary: A sidecar is a helper process that runs next to your application in the same pod; a service mesh puts a proxy sidecar (or a per-node proxy) next to every workload and a control plane above them, so that mutual TLS, retries, timeouts, traffic splitting, policy and golden metrics come from configuration instead of from library code in every service. Focus: The sidecar pattern and Kubernetes native sidecars, data plane (Envoy, linkerd2-proxy) and control plane (Istiod, Linkerd, Consul), xDS, injection and traffic capture, ambient and eBPF meshes, the Istio objects with YAML, Linkerd and Gateway API equivalents, retries and circuit breaking at the proxy, observability and what the app must still do, costs and operations, debugging with istioctl and the Envoy admin interface, and a Go sidecar and Laravel mesh-aware app with tests. Learning goal: Decide whether a mesh, a library, a gateway only, or an ambient/eBPF mesh fits a system; configure routing, retries, timeouts, mTLS and policy without creating retry storms; make an application behave correctly behind a proxy (header propagation, idempotent handlers, readiness); and debug a 503 from the proxy's own tools.

This chapter sits in the Observability & Operations group, after Containers & Kubernetes and before Serverless & Event-Driven Compute. It owns the mechanics and operations of the mesh. The architecture decision (gateway, BFF, mesh as styles) is in API Gateway, BFF & Service Mesh; mutual TLS itself is in Mutual TLS & Securing Service-to-Service Traffic; the retry, timeout and breaker theory is in Timeouts, Retries & Jitter and Circuit Breaker; tracing and metrics in Observability; fault injection in Chaos Engineering & Game Days; pod networking in Kubernetes Networking; service discovery in Service Discovery.

Page map ​

If you are looking forGo to
The whole page in four tablesEverything in one minute
Why a proxy next to every app existsWhy it exists
Envoy, Istio, Linkerd, ambient, native sidecars: where they come fromWhere it comes from
A helper container in the same pod, native sidecarsSidecar pattern, Native sidecars
Envoy, linkerd2-proxy, Istiod, xDSData plane, Control plane and xDS
How traffic gets into the proxyInjection and traffic capture
ztunnel, waypoint, Cilium, eBPFAmbient and eBPF meshes
mTLS, SPIFFE identity, PeerAuthenticationmTLS and identity
VirtualService, DestinationRule, canary, splittingRouting and splitting
Retries and timeouts at the proxyRetries and timeouts
Circuit breaking, outlier detectionCircuit breaking
Mirroring and fault injectionMirroring and faults
Golden metrics, tracing, access logsObservability
AuthorizationPolicy, rate limitingPolicy
Gateway, egress gateway, ServiceEntry, Sidecar scoping, multi-clusterGateways and scoping
Gateway API, HTTPRoute, GAMMAGateway API
Linkerd, ServiceProfile, ConsulLinkerd and Consul
Kafka, databases and non-HTTP through the meshTCP and protocol sniffing
Latency, CPU, memory, upgrades, on-callCosts
What the app must doApp behaviour
Ports, xDS variants, error flagsMechanics
CodeGo, Laravel
Real failures and fixesSolving the classic problems
Mesh or library or gatewayChoosing
Monolith to many clustersIn architecture
Run itLab

Everything in one minute ​

PieceWhat it isPlain words
SidecarA second container in the same podA helper that shares the app's network and disk
Data planeThe proxies that carry requests (Envoy, linkerd2-proxy, ztunnel)The roads and toll booths
Control planeIstiod, the Linkerd control plane, Consul serversThe traffic office that tells every booth the rules
xDSEnvoy's discovery APIs (LDS, RDS, CDS, EDS, SDS)The language the office uses to push rules
InjectionA webhook adds the proxy container to new podsThe proxy is installed for you
Ambient modeIstio with a per-node ztunnel and optional waypoints, no sidecarsOne proxy per building instead of per flat
CapabilityDone byConfigured with
mTLS and workload identityProxy + control-plane CAPeerAuthentication (Istio), automatic (Linkerd)
Routing, canary, splittingProxyVirtualService + DestinationRule, HTTPRoute
Retries, timeoutsClient-side proxyVirtualService retries/timeout, Linkerd annotations
Circuit breaking, outlier detectionClient-side proxyDestinationRule connectionPool, outlierDetection
Golden metrics, access logsBoth proxiesTelemetry API, access log format
AuthorizationServer-side proxyAuthorizationPolicy, Linkerd Server + AuthorizationPolicy
Trace propagationThe applicationCopy headers yourself
CostTypical sizeWhere it hurts
LatencyTwo extra proxy hops per callTail latency (p99), chatty call chains
CPU and memoryAbout 0.20 vCPU and 60 MB per sidecar at 1000 req/s in Istio 1.24Many small pods
OperationsControl plane, CRDs, upgrades, certificatesOn-call and upgrade windows
DebuggingOne more hop that can answer 503"Is it the app or the proxy?"
ChoiceUse whenSkip when
Library (Resilience4j, go-kit, Laravel HTTP client)One or two languages, few servicesMany languages, policy must be uniform
API gateway onlyEdge concerns: auth, rate limit, TLSYou need service-to-service mTLS and policy
Sidecar meshUniform mTLS, L7 control, many teamsSmall team, few services
Ambient / eBPFL4 security first, lower per-pod costYou need a mature L7 feature you cannot get without a waypoint

Why it exists ​

Once an application is split into services, every call needs the same boring work: find an instance, encrypt, authenticate the caller, time out, retry, record a metric, pass a trace. Doing this in a library means one implementation per language and a redeploy of every service for each fix. Putting it into a proxy next to each workload moves it out of the code and into configuration that one team owns.

Libraries in the appProxy next to the app (mesh)
Language supportOne port per languageAny language, one implementation
Change a timeoutRedeploy each serviceApply one config object
Upgrade the logicDependency bump + deploy everywhereRoll the proxy (still a pod restart in sidecar mode)
Failure domainInside the app processA second process that can fail separately
CostLibrary CPU in the processExtra processes, hops and control plane
VisibilityWhatever each team instrumentsUniform metrics for all traffic

An everyday picture: a company can train every employee to handle visitors, security badges and call logs (libraries), or put a receptionist at every office door who does it the same way for everyone (sidecar). The receptionist is consistent and replaceable, but you pay a salary per door and a visitor now passes one more desk. Ambient mode is one receptionist per floor, and a "waypoint" is a specialist you add only for floors that need more than badge checks.

Three common misunderstandings, up front ​

  • "A mesh makes my services resilient." It gives you tools (timeouts, retries, circuit breaking). Bad settings multiply load; the app must still be idempotent and have fallbacks.
  • "The mesh gives me distributed tracing for free." The proxies emit spans, but only the application can copy traceparent and x-request-id from the inbound request to its outbound calls. Without that the spans do not join.
  • "Sidecar-less means proxy-less." Ambient mode still has proxies (ztunnel per node, waypoints per namespace or service); they just do not run inside your pods.
Control plane configures; data plane carries the trafficControl plane: Istiodservice discovery + config + CAxDS over gRPC (port 15012)Pod: ordersPod: inventoryapp:8080 plain HTTPEnvoy sidecarin 15006, out 15001Envoy sidecarin 15006, out 15001app:8080 plain HTTPiptables (istio-init or CNI) redirectsall pod traffic through the proxyone network namespace per pod:app and proxy share localhostmTLSencrypted, both sidespresent certificatesxDS pushxDS push+ workload certificates

Where it comes from ​

The Envoy docs state the design goal and the out-of-process idea directly: Envoy "is a self contained process that is designed to run alongside every application server", so "each application sends and receives messages to and from localhost and is unaware of the network topology", and a single deployment works for "Java, C++, Go, PHP, Python, etc." (Envoy docs, What is Envoy). Istio uses Envoy as its sidecar data plane and Istiod as the control plane; Linkerd uses its own Rust micro-proxy, linkerd2-proxy, and says it is "designed specifically for the service mesh use case and is not designed as a general-purpose proxy" (Linkerd architecture docs). Cilium builds its mesh on eBPF in the kernel and an Envoy per node for L7 (Cilium service mesh docs).

Kubernetes made the sidecar a first-class thing: "Kubernetes implements sidecar containers as a special case of init containers; sidecar containers remain running after Pod startup", the feature was first available in v1.28, active by default since v1.29, and stable since v1.33 (Kubernetes docs, Sidecar Containers). Istio's ambient mode removes the per-pod proxy: "ambient mode is often informally referred to as 'sidecar-less mesh'" (Istio ambient overview). Dates of the first Envoy or Linkerd releases are not stated on the pages read for this chapter and are left out on purpose.

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, a definition, a flow, real scenarios, how products provide it, and the fix or configuration.

The sidecar pattern Must-know ​

In plain words: a sidecar is a second process placed next to your app, in the same pod, so it shares localhost and volumes and lives and dies with the app.

Common misunderstanding: "a sidecar is a service mesh." A sidecar is the placement pattern. A log shipper, a config reloader, a secret fetcher or a local web server are sidecars too; a mesh is the system built from proxy sidecars plus a control plane.

Definition: Kubernetes: "Sidecar containers are the secondary containers that run along with the main application container within the same Pod", used "to enhance or to extend the functionality of the primary app container" without changing its code. They "share the same network and storage namespaces with the primary container".

text
     Pod (one network namespace, shared volumes)
1    app container          writes /var/log/app.log      GET localhost:15000/...
2    sidecar: log shipper   tails the same file          ships to the log backend
3    sidecar: config sync   pulls config to /etc/app     app reloads on SIGHUP
4    sidecar: proxy         intercepts app's connections adds mTLS, retries, metrics
5    all four share localhost, volumes and the pod's lifetime

Real scenario: Fluent Bit tailing logs; a Vault agent writing secrets to a tmpfs volume; a config reloader that watches a ConfigMap; Envoy or linkerd2-proxy handling traffic; a Cloud SQL proxy giving the app a local database port.

Sidecar jobExample productsShares with the app
ProxyEnvoy (Istio), linkerd2-proxy, Consul Envoylocalhost network
Log shipperFluent Bit, VectorA log volume
Secret fetcherVault Agent, external-secrets reloadersA memory volume
Config reloaderConfigMap watchersA config volume
Local serverNGINX in front of PHP-FPMThe pod network
ProsCons
Any language, no code changeOne more process to size, update and monitor
Shared lifecycle, simple deploymentResources are paid per pod
Clear isolation of the helper's codeStartup and shutdown ordering bugs
Uniform behaviour across servicesA bad sidecar can take the pod down

Fix / how to use it: use a sidecar when the helper must share the app's network or files and live exactly as long as it does; use a separate Deployment or a DaemonSet when it does not. Declare resource requests for the sidecar, a readiness probe, and a version you control.

Kubernetes native sidecars Must-know ​

In plain words: you write the sidecar as an init container with restartPolicy: Always; Kubernetes starts it first, keeps it running, and stops it last.

Common misunderstanding: "a sidecar is just another entry in containers." That works but gives no ordering: the app can start before the proxy is ready (it sends traffic into a closed port), and a Job never completes because the sidecar keeps running.

Definition: an init container with restartPolicy: Always is a restartable init container, the Kubernetes sidecar. The kubelet starts the next init container when the sidecar's started status is true (a running process, or its startupProbe succeeding); its readinessProbe result feeds Pod readiness; on termination "the kubelet postpones terminating sidecar containers until the main application container has fully stopped" and then stops sidecars in reverse order. In a Job the sidecar does not block completion.

text
     kubelet                       pod: orders
1    start init: sidecar           restartPolicy: Always, startupProbe /ready
2    sidecar startupProbe OK       "started" = true
3    start regular init (if any)   runs to completion, in order
4    start container: app          proxy already listening, no lost first requests
5    SIGTERM                       app stops first
6    app exited -> stop sidecar    proxy still served the app's last outbound calls

Real scenario: an app that calls a database through a proxy at boot (it would fail without the proxy); a nightly Job with a log shipper that must not keep the Job running; a rollout where the proxy must outlive the app's graceful shutdown. Linkerd says: "As of Linkerd 2.20, the proxy is deployed by default as a native sidecar container"; Istio offers holdApplicationUntilProxyStarts as the older workaround ("delay application startup until the pod proxy is ready").

OptionStart orderJob completesStop order
Plain extra containerNone guaranteedNo (sidecar keeps running)Unordered
holdApplicationUntilProxyStarts (Istio)Hook delays the appNeeds extra handlingDrain via terminationDrainDuration
Native sidecar (init + restartPolicy: Always)Before the appYesAfter the app

Fix / how to use it:

yaml
# A Deployment whose sidecar is a Kubernetes native sidecar: an init container
# with restartPolicy: Always. It starts before the app, keeps running, and is
# stopped after the app on Pod termination.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: orders
  labels:
    app: orders
spec:
  replicas: 3
  selector:
    matchLabels:
      app: orders
  template:
    metadata:
      labels:
        app: orders
        version: v1
    spec:
      initContainers:
        - name: sidecar
          image: registry.example.com/platform/sidecar:1.0.0
          restartPolicy: Always # this line turns an init container into a sidecar
          ports:
            - containerPort: 15006 # inbound
            - containerPort: 15090 # metrics
          startupProbe: # the next container starts only when this succeeds
            httpGet:
              path: /ready
              port: 15090
            periodSeconds: 1
            failureThreshold: 30
          readinessProbe: # its result also decides Pod readiness
            httpGet:
              path: /ready
              port: 15090
          resources:
            requests: { cpu: 100m, memory: 64Mi }
            limits: { memory: 128Mi }
      containers:
        - name: app
          image: registry.example.com/shop/orders:2.4.1
          ports:
            - containerPort: 8080
              name: http-web # name prefix http- is how Istio picks the protocol
          readinessProbe:
            httpGet:
              path: /healthz/ready
              port: 8080
          resources:
            requests: { cpu: 250m, memory: 256Mi }
---
apiVersion: v1
kind: Service
metadata:
  name: orders
spec:
  selector:
    app: orders
  ports:
    - name: http-web
      port: 80
      targetPort: 8080
      appProtocol: http

Data plane: Envoy and linkerd2-proxy Must-know ​

In plain words: the data plane is the set of proxies that actually carry every request.

Common misunderstanding: "the control plane is in the request path." It is not: istiod or the Linkerd control plane push config; requests only touch the proxies. If the control plane is down, existing proxies keep working with their last config; you just cannot change anything or get new certificates.

Definition: Envoy is "an L7 proxy and communication bus" with an L3/L4 filter chain and an HTTP L7 filter layer, first-class HTTP/2, service discovery, active and passive health checking, and an admin interface. linkerd2-proxy is a Rust micro-proxy with "transparent, zero-config proxying for HTTP, HTTP/2, and arbitrary TCP protocols", automatic Prometheus metrics, automatic TLS and latency-aware L7 load balancing. In Linkerd's words, the outbound proxy handles "service discovery, load balancing, circuit breakers, retries, and timeouts" and the inbound proxy enforces authorization policy.

text
     app -> outbound proxy -> network -> inbound proxy -> app
1    app opens a connection to orders:80 (plain)
2    outbound proxy picks an endpoint (EDS), applies route, timeout, retries
3    outbound proxy opens mTLS to the endpoint's inbound proxy
4    inbound proxy checks identity + AuthorizationPolicy, records metrics
5    inbound proxy forwards plain HTTP to the app on localhost
ProxyLanguageUsed byConfig sourceScope
EnvoyC++Istio, Consul, Cilium (L7), Contour, Gateway API implementationsxDS from a management serverGeneral purpose
linkerd2-proxyRustLinkerdgRPC from the Linkerd destination serviceMesh only
ztunnelRustIstio ambientxDS from IstiodL4 only: mTLS, authn, L4 authz, telemetry
WaypointEnvoyIstio ambientxDS from IstiodL7 for a namespace or service

Fix / how to use it: treat the proxy as part of the pod's SLO: set requests and limits, watch its restarts, and know its admin port (Envoy 15000, Prometheus 15090 in Istio).

Control plane and xDS Must-know ​

In plain words: the control plane knows which pods exist and what rules you wrote, and sends each proxy exactly the config it needs.

Common misunderstanding: "a config change is instant everywhere." Istio documents that "a configuration change will take some time to propagate to all the sidecars", seconds on large deployments, and that "up to 100 requests may be required for weighted version distribution to be observed".

Definition: Envoy "discovers its various dynamic resources via the filesystem or by querying one or more management servers. Collectively, these discovery services and their corresponding APIs are referred to as xDS." Resource types include Listener (LDS), RouteConfiguration (RDS), Cluster (CDS), ClusterLoadAssignment (EDS) and TLS Secret (SDS). Four transport variants exist: State of the World, Incremental, Aggregated Discovery Service (ADS) and Incremental ADS.

text
     Envoy sidecar                         Istiod
1    connect gRPC stream (15012, mTLS)     authenticates the pod identity
2    subscribe CDS, EDS, LDS, RDS, SDS     builds config from Services + CRDs
3                                          pushes Listeners, Routes, Clusters, Endpoints
4    ACK each version                      istioctl proxy-status shows SYNCED
5    kubectl apply VirtualService          Istiod recomputes, pushes deltas, Envoy ACKs
Control planeProxy APICA / identityNotes
Istio (Istiod)xDS to Envoy and ztunnelBuilt-in CA, SPIFFE-style identitiesOne binary: Pilot, Citadel, injector
LinkerdgRPC destination + identity servicesidentity service signs CSRsProxy injector is an admission webhook
Consul service meshxDS to EnvoyConsul CA or VaultWorks outside Kubernetes too
CiliumxDS to per-node Envoy for L7SPIFFE-based mutual autheBPF handles L3/L4

Istiod's CPU scales with "the rate of deployment changes", "the rate of configuration changes" and "the number of proxies connecting to Istiod", and it is horizontally scalable; "at large scale, configuration scoping is highly recommended" (Istio performance page). See Sidecar scoping.

Fix / how to use it: watch push latency and proxy-status; scope config per namespace; run several Istiod replicas.

Sidecar injection and traffic capture Must-know ​

In plain words: a webhook adds the proxy to your pod at creation, and iptables rules force all pod traffic through it.

Common misunderstanding: "injection needs no privileges." Unless you use the Istio CNI plugin, the istio-init container needs NET_ADMIN and NET_RAW to set iptables, which the baseline and restricted Pod Security levels block; UID 1337 is reserved for the proxy.

Definition: Istio uses "a mutating webhook admission controller": label a namespace istio-injection=enabled (or a pod sidecar.istio.io/inject: "true") and new pods get the sidecar. Linkerd's proxy injector reacts to the annotation linkerd.io/inject: enabled and adds proxy-init and linkerd-proxy. Traffic capture uses iptables: Istio's Envoy listens on 15006 for inbound and 15001 for outbound; Linkerd's linkerd-init does the same.

text
     kubectl apply deployment             API server           webhook
1    POST pod spec                        calls mutating webhooks
2                                         istio-injection=enabled? -> add istio-proxy (+ istio-init)
3    pod scheduled                        istio-init sets iptables: inbound -> 15006, outbound -> 15001
4    app calls inventory:80               iptables redirect -> Envoy 15001 -> mTLS -> peer 15006
5    existing pods                        NOT changed: restart them to inject
ProductEnableCaptureBypass
IstioNamespace label istio-injection=enabled; pod label sidecar.istio.io/injectistio-init iptables or Istio CNItraffic.sidecar.istio.io/excludeOutboundPorts
Linkerdlinkerd.io/inject: enabledlinkerd-init or Linkerd CNIskip ports (those bypass the proxy entirely)
ConsulAnnotation consul.hashicorp.com/connect-injectinit container / CNITransparent proxy exclusions

Fix / how to use it:

yaml
# Pod-level knobs that matter in practice (Istio sidecar mode).
apiVersion: apps/v1
kind: Deployment
metadata:
  name: batch-worker
spec:
  selector:
    matchLabels:
      app: batch-worker
  template:
    metadata:
      labels:
        app: batch-worker
        sidecar.istio.io/inject: "true" # per-pod switch; namespace label istio-injection=enabled is the usual way
      annotations:
        proxy.istio.io/config: |
          holdApplicationUntilProxyStarts: true
          terminationDrainDuration: 20s
        sidecar.istio.io/proxyCPU: 100m
        sidecar.istio.io/proxyCPULimit: 500m # set the limit explicitly when you set the request
        sidecar.istio.io/proxyMemory: 128Mi
        sidecar.istio.io/proxyMemoryLimit: 256Mi
        traffic.sidecar.istio.io/excludeOutboundPorts: "5432" # database traffic bypasses the proxy
    spec:
      containers:
        - name: app
          image: registry.example.com/shop/worker:1.8.0

Ambient and eBPF meshes Important ​

In plain words: move the proxy out of the pod: one small proxy per node for encryption and identity, and a shared proxy per namespace only for the services that need L7 features.

Common misunderstanding: "ambient replaces sidecars everywhere now." Both modes coexist in one mesh ("pods and workloads using sidecar mode can co-exist within the same mesh as pods that use ambient mode"), and L7 routing still needs a waypoint.

Definition: Istio ambient "splits Istio's functionality into two distinct layers": the ztunnel secure overlay (per-node, Rust, L3/L4: "mTLS, authentication, L4 authorization and telemetry", tunnelling over HBONE, an HTTP CONNECT based protocol) and optional waypoint proxies (Envoy, run outside the app pods, "installed, upgraded, and scale independently from applications") for L7 authorization, telemetry and VirtualService routing. Cilium service mesh uses eBPF for "IP, TCP, and UDP" processing and a proxy such as Envoy for "HTTP, gRPC, and DNS".

text
     client pod A          node X ztunnel        node Y ztunnel        server pod B
1    plain TCP to B        captures, adds mTLS identity of A
2                          HBONE tunnel (mTLS)   verifies A, L4 authz
3    (L7 needed?)  ----->  via waypoint Envoy: routes, retries, L7 authz
4                                                forwards to B, plain
AspectSidecarAmbient ztunnel onlyAmbient + waypointCilium
Proxy locationIn every podOne per nodePer namespace or serviceKernel + per-node Envoy
L7 featuresYesNoYesYes (via Envoy)
Pod restart to adoptYesNoNoNo
Measured cost (Istio 1.24, 1000 rps of 1 KB)0.20 vCPU, 60 MB per sidecar0.06 vCPU, 12 MB per ztunnel0.25 vCPU, 60 MB per waypointNot measured on the pages read

Fix / how to use it: start with ambient L4 (mTLS and L4 authorization for a namespace), add a waypoint only where you use L7 policy or routing, and keep sidecars for workloads that need per-pod isolation. Figures are from Istio's own page for 1.24 on a CNCF lab cluster; yours will differ.

Where the proxy livesSidecar modeone Envoy per pod, L4 + L7Istio, Linkerd, Consulapp AEnvoyapp BEnvoy+ per-pod identity and policy- proxy memory and CPU x pods- restart pod to upgrade proxyIstio ambient modeper-node L4, optional L7no proxy in the podapp Aapp Bztunnel (per node)mTLS, identity, L4 authz, HBONEwaypoint (optional)Envoy for L7 routing and policyCilium service mesheBPF in the kernel for L3/L4Envoy per node for L7app Aapp BeBPF datapathload balancing, policy, no proxy hopper-node EnvoyHTTP, gRPC parsing when needed

mTLS and workload identity (SPIFFE) Must-know ​

In plain words: each workload gets a short-lived certificate that says who it is, and the two proxies check each other's certificates on every connection.

Common misunderstanding: "mTLS means authorization." mTLS proves who the caller is and encrypts the hop. Whether that caller may call this path is a separate policy (AuthorizationPolicy).

Definition: Linkerd "automatically enables mutually-authenticated Transport Layer Security (mTLS) for all TCP traffic between meshed pods"; the identity service "acts as a TLS Certificate Authority that accepts CSRs from proxies and returns signed certificates". Istio's identity model uses a first-class service identity (SPIFFE-style, for example cluster.local/ns/shop/sa/checkout). In Istio PeerAuthentication has modes PERMISSIVE (accept mTLS and plaintext, the default when unset) and STRICT (mTLS only); the docs advise using permissive as the intermediate step when moving to strict. The wire handshake, certificates and rotation belong to Mutual TLS and TLS in Practice.

text
     orders proxy                    inventory proxy
1    ClientHello + SNI               
2                                    ServerHello + certificate (SPIFFE id of inventory)
3    verify id against "inventory"   request client certificate
4    send certificate (id of orders)
5                                    verify; AuthorizationPolicy: principal orders allowed?
6    encrypted request ------------> plain request to app on localhost
AspectIstioLinkerdNotes
DefaultPERMISSIVE unless a policy sets STRICTmTLS on for meshed TCP trafficBoth leave non-meshed traffic outside
Non-mTLS trafficPlaintext allowed in permissiveNon-meshed pods, skip ports, kubelet probesVerify with tooling
Certificate lifetime knobsIstiod CA settingsTrust anchor expires after 365 days by defaultRotate before expiry
Common failureDestinationRule without ISTIO_MUTUAL gives 503 UFMulti-cluster needs a shared trust anchor

Fix / how to use it:

yaml
# Strict mTLS for the namespace, then identity-based authorization.
apiVersion: security.istio.io/v1
kind: PeerAuthentication
metadata:
  name: default
  namespace: shop
spec:
  mtls:
    mode: STRICT # PERMISSIVE accepts plaintext too: use it only while migrating
---
# A health port that the kubelet calls without a mesh certificate.
apiVersion: security.istio.io/v1
kind: PeerAuthentication
metadata:
  name: orders-health
  namespace: shop
spec:
  selector:
    matchLabels:
      app: orders
  mtls:
    mode: STRICT
  portLevelMtls:
    9090:
      mode: DISABLE
---
# Only the checkout service account may POST to /orders; everything else is
# implicitly denied because an ALLOW policy exists for this workload.
apiVersion: security.istio.io/v1
kind: AuthorizationPolicy
metadata:
  name: orders-allow-checkout
  namespace: shop
spec:
  selector:
    matchLabels:
      app: orders
  action: ALLOW
  rules:
    - from:
        - source:
            principals: ["cluster.local/ns/shop/sa/checkout"] # SPIFFE-style identity
      to:
        - operation:
            methods: ["POST"]
            paths: ["/orders*"]
---
# DENY is evaluated before ALLOW: block a known-bad path for everyone.
apiVersion: security.istio.io/v1
kind: AuthorizationPolicy
metadata:
  name: orders-deny-admin
  namespace: shop
spec:
  selector:
    matchLabels:
      app: orders
  action: DENY
  rules:
    - to:
        - operation:
            paths: ["/admin*"]

Traffic management: routing, splitting, canary Must-know ​

In plain words: decide, per request, which version of a service gets it, without touching the code or the Kubernetes Service.

Common misunderstanding: "a 90/10 split means exactly 9 of every 10 requests." It converges over many requests; Istio notes up to 100 requests may be needed to see the weights.

Definition: In Istio a VirtualService defines how requests to a host are routed (matches, weights, timeouts, retries, fault injection, mirroring) and a DestinationRule defines what happens after routing: subsets by label, load balancing ("by default, Istio uses a least requests load balancing policy"), TLS mode, connection pool and outlier detection. Subsets are the unit of canary: v1 and v2 labelled pods behind one Service.

text
     client proxy                          rules                    pods
1    GET reviews/ (end-user: qa)           match header qa     ->   v2
2    GET reviews/ (everyone else)          90 -> v1, 10 -> v2  ->   v1 or v2
3    raise to 25, 50, 100 while error rate and p99 stay inside the SLO
4    error rate climbs on v2               set v2 weight 0 (one object, instant rollback)
TechniqueObjectUse
Header matchVirtualService match.headersInternal testers, dark launches
Weighted splitroute[].weightCanary, A/B
Mirrormirror + mirrorPercentageCompare without user impact
SubsetDestinationRule subsetsVersion selection by pod label
Gateway APIHTTPRoute backendRefs.weightPortable canary

Fix / how to use it:

yaml
# Canary + retries + timeout + circuit breaking + outlier detection for "reviews".
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
  name: reviews
spec:
  hosts:
    - reviews
  http:
    - match: # internal testers always get v2
        - headers:
            end-user:
              exact: qa
      route:
        - destination:
            host: reviews
            subset: v2
    - route: # everyone else: 90/10 canary
        - destination:
            host: reviews
            subset: v1
          weight: 90
        - destination:
            host: reviews
            subset: v2
          weight: 10
      timeout: 3s # whole request, all attempts
      retries:
        attempts: 2
        perTryTimeout: 1s
        retryOn: gateway-error,connect-failure,refused-stream
---
apiVersion: networking.istio.io/v1
kind: DestinationRule
metadata:
  name: reviews
spec:
  host: reviews
  trafficPolicy:
    tls:
      mode: ISTIO_MUTUAL # match the mesh-wide mTLS or requests fail with 503 UF
    connectionPool:
      tcp:
        maxConnections: 100
      http:
        http1MaxPendingRequests: 50 # beyond this the proxy answers 503 UO
        maxRequestsPerConnection: 0
    outlierDetection:
      consecutive5xxErrors: 5
      interval: 10s
      baseEjectionTime: 30s
      maxEjectionPercent: 50 # never eject more than half of the pool
  subsets:
    - name: v1
      labels:
        version: v1
    - name: v2
      labels:
        version: v2

Retries and timeouts at the proxy Must-know ​

In plain words: the client-side proxy waits a limited time and, if the call failed in a retryable way, sends it again.

Common misunderstanding: "retries are free resilience." Linkerd's own docs: "automatically retrying a request that changes system state each time it is called can be disastrous", and "retries by definition will increase the load on your system".

Definition: Istio: "The Envoy timeout for HTTP requests is disabled in Istio by default" and "the default retry behavior for HTTP requests is to retry twice before returning the error", with an interval of "25ms+" chosen by Istio. retries.attempts, perTryTimeout and retryOn (for example gateway-error,connect-failure,refused-stream) are set per route; timeout covers the whole request including retries. Linkerd configures retry.linkerd.io/http, retry.linkerd.io/limit, retry.linkerd.io/timeout and timeout.linkerd.io/request as annotations on an HTTPRoute or Service, performed "on the outbound (client) side" and, since 2.16, timeouts and retries compose. The theory (backoff, jitter, budgets) is in Timeouts, Retries & Jitter.

text
     client proxy (timeout 3s, attempts 2, perTryTimeout 1s)         server
1    attempt 1 ------------------------------------------------>   503 (overloaded)
2    wait 25 ms+ (jittered)
3    attempt 2 ------------------------------------------------>   200
4    whole call took 40 ms; the app saw one success and never knew
5    if attempt 3 would pass 3 s total, the route timeout returns 504 instead
KnobIstioLinkerdEnvoy (underneath)
Total timeouttimeouttimeout.linkerd.io/requestroute timeout
Per attemptperTryTimeoutretry.linkerd.io/timeoutper_try_timeout
Max retriesattemptsretry.linkerd.io/limitnum_retries
What to retryretryOnretry.linkerd.io/http: 5xx (or gRPC classes)retry_on
BudgetNot in VirtualService; use circuit breaker limitsRetry budget in ServiceProfile eraRetry circuit breaker
DefaultsTimeout off, 2 retriesNo retries unless configuredDepends on config

Fix / how to use it: retry at one layer only (see Retry amplification), make retried endpoints idempotent, and set the app's own timeout below the route timeout.

Circuit breaking and outlier detection Important ​

In plain words: limit how much you pile onto one instance, and stop sending to instances that keep failing.

Common misunderstanding: "the mesh circuit breaker is the same as Resilience4j's." In Istio circuit breaking is a connection and request limit per host (connectionPool), while outlier detection ejects bad hosts from the load balancing pool; neither tracks a closed/open/half-open state per dependency like a library breaker. See Circuit Breaker.

Definition: Istio: "in a circuit breaker, you set limits for calls to individual hosts within a service, such as the number of concurrent connections or how many times calls to this host have failed". Envoy: "outlier detection and ejection is the process of dynamically determining whether some number of hosts in an upstream cluster are performing unlike the others and removing them from the healthy load balancing set", a form of passive health checking. Settings: consecutive5xxErrors, interval, baseEjectionTime, maxEjectionPercent.

text
     proxy pool for reviews: 4 pods                          failures
1    pod-3 returns 5xx x5 in a row                           consecutive5xxErrors reached
2    pod-3 ejected for baseEjectionTime (30 s, grows each time)
3    traffic spreads over pods 1, 2, 4                       maxEjectionPercent keeps >= half in
4    after 30 s pod-3 returns to the pool; one more failure ejects it for longer
LimitFieldWhat happens when exceeded
Concurrent connectionsconnectionPool.tcp.maxConnectionsNew connections queue or fail
Pending requestsconnectionPool.http.http1MaxPendingRequestsProxy answers 503 with flag UO
Bad hostoutlierDetection.consecutive5xxErrorsHost ejected from the pool
Ejection capmaxEjectionPercentNever eject more than this share

Fix / how to use it: same YAML as routing; set maxEjectionPercent so a shared dependency outage cannot eject the whole pool.

Mirroring and fault injection Important ​

In plain words: mirroring sends a copy of live traffic to a new version; fault injection makes the proxy fail or delay requests on purpose.

Common misunderstanding: "mirrored traffic is harmless." The response is discarded, but a mirrored POST still executes on v2 and writes to whatever v2 is connected to.

Definition: "Mirroring sends a copy of live traffic to a mirrored service. The mirrored traffic happens out of band of the critical request path" (Istio mirroring task). Istio fault injection offers two kinds: delays ("timing failures") and aborts ("crash failures", HTTP error codes or TCP failures), applied at the application layer; the traffic-management docs note fault injection "can not be combined with retry or timeout configuration on the same virtual service". The practice of game days is in Chaos Engineering.

text
     client -> proxy                      v1 (serves)            v2 (shadow)
1    GET /reviews                         ----------------->     200 to the user
2                                         copy of 20% ------->   200 discarded
3    compare v2's latency and errors in the dashboards; the user never sees v2
4    fault: 0.1% of requests get +5 s -> does the caller's timeout fire?

Fix / how to use it:

yaml
# Two separate experiments, shown as two VirtualServices for two hosts.
# 1) Fault injection: 0.1% of ratings requests get a 5 s delay, 0.05% get a 503.
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
  name: ratings
spec:
  hosts:
    - ratings
  http:
    - fault:
        delay:
          percentage:
            value: 0.1
          fixedDelay: 5s
        abort:
          percentage:
            value: 0.05
          httpStatus: 503
      route:
        - destination:
            host: ratings
            subset: v1
---
# 2) Mirroring: v1 serves the user, a copy of 20% of the requests goes to v2.
# The mirrored response is discarded; writes would hit v2's database too.
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
  name: httpbin
spec:
  hosts:
    - httpbin
  http:
    - route:
        - destination:
            host: httpbin
            subset: v1
      mirror:
        host: httpbin
        subset: v2
      mirrorPercentage:
        value: 20.0
ExperimentSafe forNot safe for
MirrorReads, idempotent calls, stateless v2Writes into shared stores, billing calls
Delay faultTesting timeouts and retriesSame VirtualService that also sets retries
Abort faultTesting fallbacksProduction without a rollback switch

Observability: golden metrics, tracing, access logs Must-know ​

In plain words: because every request passes a proxy, you get request count, errors and latency per service without instrumenting each app; stitching one request across services still needs the app's help.

Common misunderstanding: "the mesh traces for me." Istio: "Applications must propagate this information in HTTP headers, so that when proxies send spans, the backend can join them together into a single trace."

Definition: Istio generates metrics based on "the four golden signals of monitoring (latency, traffic, errors, and saturation)", distributed trace spans and access logs; by default only a small subset of Envoy statistics is enabled to limit CPU. Headers to forward: W3C traceparent and tracestate, for Zipkin the B3 set (x-b3-traceid, x-b3-spanid, x-b3-parentspanid, x-b3-sampled, x-b3-flags), plus x-request-id, Envoy's correlation id. Linkerd and Istio expose Prometheus metrics (Istio: Envoy 15090, merged 15020). The stack itself is in Observability.

text
     client -> A -> B -> C         trace id 0af7...319c
1    client sends no trace         ingress proxy creates traceparent 00-0af7...-aaaa-01
2    A's proxy: span A             app A reads headers
3    app A calls B WITHOUT copying headers
4    B's proxy sees no trace       starts a NEW trace: spans A and B are in different traces
5    app A copies traceparent      B's span becomes a child: one trace
SignalSourceNeeds app code?
Request rate, error rate, latency histogramBoth proxiesNo
Saturation (in-flight, queue)Proxy statsNo
Access log per requestProxyNo (enable it)
Spans per hopProxyNo
Joined traceProxy + appYes: copy headers
Business metricsAppYes

Fix / how to use it: the Go and Laravel code below copies the headers; a library such as OpenTelemetry does it automatically when instrumented.

What happens on each hoporders apphttp://inventoryclient sidecaroutbound proxyserver sidecarinbound proxyinventory app:8080 plain HTTPcopies traceparent andx-request-id to the call(only the app can)load balancing, timeout,retries, circuit breaking,outlier detection, starts mTLSterminates mTLS, checksAuthorizationPolicy,records golden metricsanswers; must be safeto call twice if themesh retriesCost per requesttwo extra proxy hops (client and server sidecar), each a few ms at p99 in Istio's published teststwo TLS sessions reused across requests, so the handshake is paid once per connectionCPU and memory in every pod, plus control-plane pushes on every config changelocalhostmTLS over the pod networklocalhost

Authorization policy and rate limiting Important ​

In plain words: decide who may call what, using the caller's verified identity, enforced in the callee's proxy.

Common misunderstanding: "no policy means deny." In Istio, if there are no ALLOW policies for a workload the request is allowed; once any ALLOW policy exists, everything not matched is denied.

Definition: Istio AuthorizationPolicy actions are CUSTOM, DENY, ALLOW and AUDIT; evaluation order: CUSTOM, then DENY, then ALLOW ("if there are no ALLOW policies for the workload, allow the request"). Rules match from.source.principals, to.operation (methods, paths) and when conditions. Linkerd uses Server (a port of a workload), AuthorizationPolicy and MeshTLSAuthentication. Rate limiting is not an AuthorizationPolicy: Envoy supports local and global rate limiting filters, and a gateway is the usual place (Rate Limiting). Policy theory: Authorization Models.

text
     request from checkout -> orders POST /orders
1    CUSTOM policies?      none
2    DENY /admin*?         no match
3    ALLOW exists?         yes: principal cluster.local/ns/shop/sa/checkout, POST /orders*  -> match -> allowed
4    request from cart -> orders POST /orders: ALLOW exists, no rule matches -> 403 "RBAC: access denied"
ControlIstioLinkerd
Whoprincipals (SPIFFE-style)MeshTLSAuthentication identities
Whatoperation methods and pathsServer port; HTTPRoute for paths
DefaultAllow if no ALLOW policyconfig.linkerd.io/default-inbound-policy (default all-unauthenticated)
AuditAUDIT actionaudit default policy

Fix / how to use it: istio-security.yaml above; for rate limiting put the limiter at the gateway or in the app and keep the mesh for identity and routing.

Gateways, egress, ServiceEntry, Sidecar scoping, multi-cluster Important ​

In plain words: gateways are proxies at the mesh edge; a ServiceEntry teaches the mesh about outside services; the Sidecar resource tells proxies to ignore everything they do not need.

Common misunderstanding: "the Sidecar resource blocks traffic." Istio: "A common misunderstanding is that restricting the configuration amounts to blocking the traffic", and "the sidecar is not able to enforce an outbound traffic restriction"; use an egress gateway for that.

Definition: an ingress Gateway is "an entry point into the mesh"; an egress gateway is "a symmetrical concept; it defines exit points from the mesh", used so traffic leaving the mesh passes dedicated nodes for policy and monitoring. ServiceEntry registers external hosts (MESH_EXTERNAL, resolution: DNS). The Sidecar resource scopes egress hosts ("to prune out unneeded configuration, to improve scalability of the mesh"). Multi-cluster: Istio deployment models and Linkerd's multi-cluster need shared trust (Linkerd: a shared trust anchor) and cross-cluster gateways or flat networking.

text
     pod -> external API
1    app calls api.payments.example.com:443 (TLS)
2    no ServiceEntry: proxy uses PassthroughCluster, no metrics or policy
3    ServiceEntry + (optional) egress gateway: metrics, timeouts, audit, firewall allow-list at one IP
ObjectScopePurpose
GatewayEdge workloadIngress listeners, TLS, hosts
VirtualService bound to a GatewayHostsRoute external requests inward
ServiceEntryMeshRegister external or VM services
Egress gatewayEdge workloadSingle controlled exit
SidecarNamespace or workloadLimit config pushed to proxies
Multi-clusterCluster setShared trust, cross-cluster discovery

Fix / how to use it:

yaml
# Edge objects: ingress Gateway, ServiceEntry for an external API, and a
# Sidecar resource that limits what every proxy in "shop" has to know.
apiVersion: networking.istio.io/v1
kind: Gateway
metadata:
  name: shop-gateway
  namespace: shop
spec:
  selector:
    istio: ingressgateway
  servers:
    - port:
        number: 443
        name: https
        protocol: HTTPS
      tls:
        mode: SIMPLE
        credentialName: shop-example-com-cert # a Kubernetes Secret
      hosts:
        - shop.example.com
---
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
  name: shop
  namespace: shop
spec:
  hosts:
    - shop.example.com
  gateways:
    - shop-gateway
  http:
    - route:
        - destination:
            host: orders
            port:
              number: 80
---
# Register an external HTTPS API so it gets metrics, timeouts and policy.
apiVersion: networking.istio.io/v1
kind: ServiceEntry
metadata:
  name: payments-api
  namespace: shop
spec:
  hosts:
    - api.payments.example.com
  location: MESH_EXTERNAL
  resolution: DNS
  ports:
    - number: 443
      name: tls
      protocol: TLS
---
# Configuration scoping: proxies in "shop" only receive config for their own
# namespace, the control namespace and the one external host. Fewer clusters
# and routes per proxy means less memory and faster xDS pushes.
apiVersion: networking.istio.io/v1
kind: Sidecar
metadata:
  name: default
  namespace: shop
spec:
  egress:
    - hosts:
        - "./*"
        - "istio-system/*"

Gateway API and GAMMA Important ​

In plain words: Kubernetes' standard routing objects (Gateway, HTTPRoute) are becoming the shared language, so routes are not Istio-only or Linkerd-only.

Common misunderstanding: "an HTTPRoute for a mesh attaches to a Gateway." For a mesh it attaches to a Service through parentRefs.

Definition: Gateway API docs: the GAMMA initiative support for service mesh "has been part of the Standard Channel since v1.1.0 and is considered GA"; "individual route resources (such as HTTPRoute) are associated directly with Service resources". A route in the Service's namespace is a producer route; one in another namespace is a consumer route and affects only that namespace's clients. When routes are attached, requests that match none are rejected. Istio's docs say it "supports the Kubernetes Gateway API and intends to make it the default API for traffic management in the future"; Linkerd uses HTTPRoute too.

text
1    HTTPRoute reviews-canary  parentRefs: Service reviews
2    rule 1: header end-user=qa -> reviews-v2
3    rule 2: weights 90 / 10    -> reviews-v1 / reviews-v2, timeouts.request 3s
4    request matching no rule   -> rejected (routes attached to a Service)

Fix / how to use it:

yaml
# Gateway API for a mesh (GAMMA): the route attaches to a Service, not a Gateway.
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: reviews-canary
  namespace: shop
spec:
  parentRefs:
    - group: ""
      kind: Service
      name: reviews
      port: 80
  rules:
    - matches:
        - headers:
            - name: end-user
              value: qa
      backendRefs:
        - name: reviews-v2
          port: 80
    - backendRefs:
        - name: reviews-v1
          port: 80
          weight: 90
        - name: reviews-v2
          port: 80
          weight: 10
      timeouts:
        request: 3s

Linkerd and Consul equivalents Good to know ​

In plain words: same ideas, different objects; Linkerd stays small and automatic, Consul reaches beyond Kubernetes.

Common misunderstanding: "ServiceProfile is the current way to configure Linkerd routes." Linkerd says that before 2.16 retries and timeouts used ServiceProfiles; they are still supported, but "if a ServiceProfile is defined for a Service, proxies will use the ServiceProfile retry configuration and ignore any retry annotations", so the two must not be mixed.

Definition: Linkerd: control plane (destination, identity, proxy injector) plus linkerd2-proxy per pod, native sidecar by default since 2.20; retries and timeouts via annotations on HTTPRoute/GRPCRoute; retries "do not work with headless services". Consul service mesh runs Envoy sidecars driven by Consul servers (intentions for authorization) and works on VMs and Kubernetes (stated here from general knowledge; the Consul docs were not saved for this chapter).

NeedIstioLinkerdConsul service mesh
Route and splitVirtualService + DestinationRuleHTTPRoute (weights)Service router/splitter, or Gateway API
Retries and timeoutsVirtualService fieldsHTTPRoute annotations (older: ServiceProfile)Service defaults
mTLSPeerAuthenticationAutomaticAutomatic via CA
AuthorizationAuthorizationPolicyServer + AuthorizationPolicy + MeshTLSAuthenticationIntentions
ProxyEnvoylinkerd2-proxyEnvoy

Fix / how to use it:

yaml
# Linkerd equivalents. Retries and timeouts are annotations on an HTTPRoute
# (Linkerd 2.16+), authorization is Server + AuthorizationPolicy + MeshTLSAuthentication.
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: reviews-route
  namespace: shop
  annotations:
    retry.linkerd.io/http: "5xx"
    retry.linkerd.io/limit: "2"
    retry.linkerd.io/timeout: 1s
    timeout.linkerd.io/request: 3s
spec:
  parentRefs:
    - name: reviews
      kind: Service
      group: core
      port: 80
  rules:
    - backendRefs:
        - name: reviews-v1
          port: 80
          weight: 90
        - name: reviews-v2
          port: 80
          weight: 10
---
apiVersion: policy.linkerd.io/v1beta1
kind: Server
metadata:
  name: orders-http
  namespace: shop
spec:
  podSelector:
    matchLabels:
      app: orders
  port: http-web
  proxyProtocol: HTTP/1
---
apiVersion: policy.linkerd.io/v1alpha1
kind: MeshTLSAuthentication
metadata:
  name: checkout-only
  namespace: shop
spec:
  identities:
    - "checkout.shop.serviceaccount.identity.linkerd.cluster.local"
---
apiVersion: policy.linkerd.io/v1alpha1
kind: AuthorizationPolicy
metadata:
  name: orders-allow-checkout
  namespace: shop
spec:
  targetRef:
    group: policy.linkerd.io
    kind: Server
    name: orders-http
  requiredAuthenticationRefs:
    - name: checkout-only
      kind: MeshTLSAuthentication
      group: policy.linkerd.io

TCP passthrough, brokers, databases, protocol sniffing Important ​

In plain words: a mesh proxies any TCP, but it can only do HTTP things (routing, retries, per-route metrics) if it knows the protocol.

Common misunderstanding: "put Kafka or MySQL in the mesh and you get the same features as HTTP." Istio: automatic detection works for HTTP and HTTP/2; "if the protocol cannot automatically be determined, traffic will be treated as plain TCP traffic", and "server first protocols, such as MySQL, are incompatible with automatic protocol selection". Non-TCP (UDP) "will continue to function as normal, without any interception".

Definition: protocol sniffing inspects the first bytes of a connection; explicit selection uses the Service port name (http-web, tcp-kafka) or appProtocol, which "takes precedence over the port name". Supported values include http, http2, https, tcp, tls, grpc; mongo, mysql, redis are experimental. With plain TCP you still get mTLS and L4 metrics, not retries or L7 routing.

text
     producer -> Kafka broker through the mesh
1    port named tcp-kafka (opaque TCP)         proxy does mTLS + L4 bytes/connections only
2    broker advertised.listeners return pod IPs  clients connect to each broker directly; check that the mesh can reach them
3    long-lived connections                     sidecar drain on rollout must outlast them
4    a retry setting on an HTTP route           does not apply: the proxy does not parse Kafka
TrafficMesh givesMesh does not giveAdvice
HTTP/1.1, HTTP/2, gRPCEverything L7Name ports http-, grpc-
Kafka, AMQP, Redis (RabbitMQ, Kafka, Redis Streams)mTLS, L4 metrics, TCP policyRetries, routing, per-message metricsKeep client-side broker retries; see messaging
PostgreSQL, MySQLEncryption, L4 policyL7 features; server-first sniffing failsName port tcp-, or exclude the port from interception
UDPNothingNot interceptedUse CNI/network policy

Fix / how to use it: exclude database ports from capture when the proxy adds latency or breaks the wire protocol (excludeOutboundPorts), and accept that you lose mTLS and metrics for them. The reasons the app should not retry blindly are in Service Communication.

What a mesh costs Must-know ​

In plain words: every request goes through two more processes, and every pod carries one.

Common misunderstanding: "the overhead is negligible." Istio's own page: "telemetry filters (logging, tracing, and metrics) are known to have a moderate impact", and Envoy's collection time "affects average and tail latencies" because the worker is busy.

Definition: the published Istio 1.24 numbers (mesh of 1000 services, 2000 pods, 70,000 requests per second; 1000 req/s with 1 KB payload): a sidecar with 2 worker threads about 0.20 vCPU and 60 MB; a waypoint 0.25 vCPU and 60 MB; a ztunnel 0.06 vCPU and 12 MB. Latency charts compare no mesh, ambient L4, ambient L4+L7 and sidecar at p90 and p99 on a CNCF lab cluster ("different hardware will give different values"). Memory depends on the configuration the proxy holds.

CostSize or shapeMitigation
Latency per hopTwo proxies per call in sidecar mode; ztunnel pair in ambientFewer hops, keep-alive, disable unused telemetry
CPU / memoryPer pod, proportional to podsSidecar scoping, ambient for L4-only, set concurrency unset
Control planeScales with config churn and proxy countScope config, run replicas
Upgrade painProxy version skew, restart every pod in sidecar modeRevision-based canary upgrade, ambient
DebuggingA 503 may come from the proxy, not the appistioctl, access logs, response flags
ComplexityCRDs, certificates, trust anchors, webhooksStart small; one team owns it
"Mesh for mesh's sake"Adopted without a requirementWrite the problem first (see Choosing)

Back-of-envelope (inference, not from a source): 400 pods at 0.2 vCPU and 60 MB per sidecar at the documented load is about 80 vCPU and 24 GB of memory for the data plane alone; ambient L4 for the same pods needs a ztunnel per node (for 40 nodes about 2.4 vCPU and 0.5 GB at the documented load).

Fix / how to use it: measure with your own traffic; put a number on the latency you can afford (Latency Budgets) before adopting.

How application code must behave Must-know ​

In plain words: the mesh handles the network; your code must still carry headers, tolerate retried requests, and report readiness honestly.

Common misunderstanding: "the sidecar made my POST safe to retry." It did the opposite if you configured retries on non-idempotent routes: your handler can now run twice.

Definition: four duties. (1) Header propagation: copy x-request-id, traceparent, tracestate, baggage (and B3 if used) to every outbound call made while serving the request. (2) Idempotency: any route the mesh may retry must tolerate duplicates (API Idempotency). (3) Readiness: expose liveness and readiness separately; Istio rewrites HTTP, TCP and gRPC probes because the kubelet has no mesh certificate and iptables makes every TCP port look open. (4) Timeouts: keep the app's call timeout below the route timeout, and speak plain HTTP in the pod.

text
     inbound request                         app                           outbound call
1    x-request-id: r1, traceparent: 00-T-S1-01
2                                            middleware stores r1, T       
3                                            business code calls inventory with the context
4                                                                          x-request-id: r1, traceparent: 00-T-S2-01 (new span id)
5    mesh retries the call (503)             handler is idempotent (key k1): second run is a no-op
DutyGoLaravel 13
Propagate headerspropagate.Middleware + propagate.TransportPropagateMeshHeaders + Http::mesh() macro
Idempotent handlersKey table, ON CONFLICT DO NOTHINGSame SQL, Idempotency-Key header
ReadinessSeparate /healthz/readyReadinessController
Plain HTTP in podhttp.ListenAndServetrustProxies for 127.0.0.1

Fix / how to use it: see the Go and Laravel sections and the SQL below.

sql
CREATE TABLE processed_requests (
    idempotency_key text PRIMARY KEY,
    request_id      text NOT NULL,
    response_status int  NOT NULL,
    response_body   jsonb NOT NULL,
    created_at      timestamptz NOT NULL DEFAULT now()
);
-- First run inserts one row and does the work; a mesh retry inserts 0 rows (ON CONFLICT DO NOTHING).
INSERT INTO processed_requests (idempotency_key, request_id, response_status, response_body)
VALUES ('pay-7f3a', 'req-9c1', 201, '{"charge_id":"ch_100"}')
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING idempotency_key;
sql
-- The mesh may replay a request (retryOn: connect-failure, 503, reset). The
-- first attempt can have succeeded even though the caller saw an error, so
-- the handler must make the second run a no-op. PostgreSQL syntax.
CREATE TABLE processed_requests (
    idempotency_key  text        PRIMARY KEY,
    request_id       text        NOT NULL,          -- x-request-id of the first attempt, for the trace
    response_status  int         NOT NULL,
    response_body    jsonb       NOT NULL,
    created_at       timestamptz NOT NULL DEFAULT now()
);

-- Run in the SAME transaction as the business write.
BEGIN;
INSERT INTO processed_requests (idempotency_key, request_id, response_status, response_body)
VALUES ('pay-7f3a', 'req-9c1', 201, '{"charge_id": "ch_100"}')
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING idempotency_key;
-- 0 rows returned => a replay: skip the business write and return the stored row.
-- 1 row returned  => first run: do the write, then COMMIT.
COMMIT;

-- Replay path: return what the first attempt answered.
SELECT response_status, response_body FROM processed_requests WHERE idempotency_key = 'pay-7f3a';

-- Housekeeping: keys only need to live as long as callers (and mesh retries) can replay.
DELETE FROM processed_requests WHERE created_at < now() - interval '24 hours';

Mechanics ​

Ports and listeners in an Istio sidecar ​

Applications must not use the ports Envoy uses. From Istio's application requirements:

PortProtocolPurposePod-internal only
15000TCPEnvoy admin (commands, diagnostics)Yes
15001TCPEnvoy outbound captureNo
15006TCPEnvoy inbound captureNo
15008HTTP/2HBONE mTLS tunnel (ambient)No
15020HTTPMerged Prometheus telemetry (agent, Envoy, app)No
15021HTTPHealth checksNo
15090HTTPEnvoy Prometheus telemetryNo
15012 (Istiod)gRPCxDS and CA, TLS and mTLS (production)No

Every sidecar has a listener on 0.0.0.0:15006 (iptables sends all inbound pod traffic there) and one on 0.0.0.0:15001 (all outbound). The 15001 listener hands the request to the virtual listener that best matches the original destination, otherwise to PassthroughCluster, which connects directly (so unknown destinations still work, without mesh features). The pod must not run its app as UID 1337.

xDS in detail ​

ResourceAPICarries
ListenerLDSPorts, filter chains
RouteConfigurationRDSVirtual hosts, route matches, timeouts, retries
ClusterCDSUpstream groups, load balancing, circuit breakers, outlier detection
ClusterLoadAssignmentEDSEndpoint IPs of a cluster
SecretSDSCertificates and keys

Transport variants (from the xDS protocol doc): State of the World with one stream per resource type; Incremental xDS (deltas, lazy loading); Aggregated Discovery Service (SotW on one stream, for explicit sequencing); Incremental ADS. Separate streams give eventual consistency; ADS gives ordering when you need make-before-break updates.

Reading the sync state ​

istioctl proxy-status columns are CDS, LDS, EDS, RDS, ISTIOD and VERSION. SYNCED: Envoy acknowledged the last config Istiod sent. NOT SENT: Istiod sent nothing, usually because there was nothing to send. STALE: Istiod sent an update and got no acknowledgement, "a networking issue between Envoy and Istiod or a bug". A proxy missing from the list is not connected to Istiod.

Protocol selection rules ​

Name the Service port <protocol>[-<suffix>] (for example http-web, tcp-kafka) or set appProtocol, which wins over the name. Without either, Istio sniffs HTTP and HTTP/2 and otherwise treats the stream as TCP. Gateways do not sniff: unless a protocol is stated they forward HTTP as HTTP/1.1.

Error responses and flags you will see ​

What you seeMeaningWhere to look
503 flag NRNo route configuredDestinationRule, VirtualService, Service port name
503 flag UOUpstream overflow, circuit breaker trippedDestinationRule connectionPool
503 flag UFFailed to connect upstreammTLS mode mismatch (DestinationRule tls.mode), peer down
503 flag UCUpstream connection terminationHeadless service via PassthroughCluster, app closed the connection
503 UH "no healthy upstream"No healthy endpoint in the poolOutlier ejection, no ready pods (flag name from Envoy's list, not saved here)
504 UT "upstream request timeout"Route timeout or per-try timeout firedtimeout, perTryTimeout, app latency (flag name from Envoy's list, not saved here)
403 "RBAC: access denied"AuthorizationPolicy deniedpolicy order, kubectl get authorizationpolicy -A
Linkerd l5d-* headers ignoredPer-request policy disabledInstall flag --allow-l5d-request-headers; never enable for untrusted clients

Istio notes that response flags sit "after the response code" in the default access log; with a custom format include %RESPONSE_FLAGS%.

Debug commands ​

text
$ istioctl proxy-status                              # who is connected, which config is SYNCED
$ istioctl proxy-config listeners orders-7d9 -n shop # 15001 / 15006 and virtual listeners
$ istioctl proxy-config routes    orders-7d9 -n shop # RDS: matches, timeouts, retries
$ istioctl proxy-config clusters  orders-7d9 -n shop # CDS: outbound|80||inventory.shop.svc...
$ istioctl proxy-config endpoints orders-7d9 -n shop # EDS: which IPs, healthy or not
$ kubectl logs orders-7d9 -c istio-proxy -n shop     # access log with response flags
$ kubectl exec orders-7d9 -c istio-proxy -- curl -s localhost:15000/config_dump   # Envoy admin
$ kubectl exec orders-7d9 -c istio-proxy -- curl -s localhost:15000/stats | grep upstream_rq_retry
$ kubectl exec orders-7d9 -c istio-proxy -- curl -s -X POST 'localhost:15000/logging?level=debug'

The Envoy admin interface "allows destructive operations to be performed" and "potentially exposes private information", so keep it on localhost (Istio binds 15000 pod-internal).

Go ​

The Go module academy/service-mesh-sidecar has three packages and two commands: sidecar (a minimal proxy), propagate (the application side) and cmd/lab plus cmd/sidecar. Everything is the standard library.

Before ​

An app that works alone but drops the trace, retries in an unbounded loop and has one probe for everything:

go
// Before: an app that works alone but is invisible to the mesh.
// It drops the headers the sidecar needs to join spans into one trace,
// retries on its own with no limit, and has no readiness separate from liveness.
package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
)

func main() {
	mux := http.NewServeMux()

	mux.HandleFunc("/orders", func(w http.ResponseWriter, r *http.Request) {
		// New outbound request: nothing from the inbound request is copied.
		// The sidecar sees an unrelated trace for every hop.
		var body []byte
		var err error
		for attempt := 0; attempt < 10; attempt++ { // fixed, unbounded-ish retry loop
			resp, e := http.Get("http://inventory:8080/stock")
			if e != nil {
				err = e
				continue
			}
			body, err = io.ReadAll(resp.Body)
			resp.Body.Close()
			break
		}
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadGateway)
			return
		}
		fmt.Fprintf(w, "stock: %s\n", body)
	})

	// One endpoint for everything: the kubelet probe says "ready" even when
	// the database is down, so traffic keeps arriving.
	mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})

	log.Fatal(http.ListenAndServe(":8080", mux))
}

After ​

The sidecar. A local listener that forwards to the app with a total timeout, a per-try timeout, retries only for idempotent requests (or requests with an Idempotency-Key), a retry budget, golden metrics and header injection. It is built on httputil.ReverseProxy with Rewrite (the supported replacement for Director) and a retrying RoundTripper.

go
// Package sidecar is a minimal sidecar-style proxy: a local listener that
// forwards to the application in the same pod, with a total timeout, per-try
// timeouts, budgeted retries, golden-signal metrics and header propagation.
// It shows the mechanics; production meshes use Envoy or linkerd2-proxy.
package sidecar

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"errors"
	"net"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings"
	"time"
)

// Config describes one sidecar instance.
type Config struct {
	Target        *url.URL      // the application, usually http://127.0.0.1:8080
	Timeout       time.Duration // whole request, all attempts (Envoy route timeout)
	PerTryTimeout time.Duration // one attempt (Envoy per_try_timeout)
	MaxRetries    int
	RetryRatio    float64 // retries allowed per request, e.g. 0.2
	Backoff       func(n int) time.Duration
	Transport     http.RoundTripper // nil: http.DefaultTransport
}

// Proxy is the sidecar: Handler serves traffic, Stats feeds the metrics port.
type Proxy struct {
	Handler http.Handler
	Stats   *Stats
}

// New builds a Proxy. It never modifies the application; it only sits in front of it.
func New(cfg Config) *Proxy {
	stats := &Stats{}
	rt := &RetryTransport{
		Base:          cfg.Transport,
		PerTryTimeout: cfg.PerTryTimeout,
		MaxRetries:    cfg.MaxRetries,
		Budget:        NewBudget(cfg.RetryRatio, 10),
		Stats:         stats,
		Backoff:       cfg.Backoff,
	}
	rp := &httputil.ReverseProxy{
		Rewrite: func(pr *httputil.ProxyRequest) {
			pr.SetURL(cfg.Target)
			pr.Out.Host = pr.In.Host // keep the original authority, like a transparent proxy
			pr.SetXForwarded()
			propagate(pr.In, pr.Out)
		},
		Transport: rt,
		ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
			// Same texts Envoy writes, so dashboards and tests look familiar.
			switch {
			case errors.Is(err, context.DeadlineExceeded), isTimeout(err):
				stats.Timeouts.Add(1)
				http.Error(w, "upstream request timeout", http.StatusGatewayTimeout)
			case errors.Is(err, errBodyTooLarge):
				http.Error(w, "request body too large to retry", http.StatusRequestEntityTooLarge)
			default:
				http.Error(w, "upstream connect error or disconnect/reset before headers", http.StatusServiceUnavailable)
			}
		},
	}
	h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		stats.Requests.Add(1)
		stats.InFlight.Add(1)
		defer func() {
			stats.InFlight.Add(-1)
			stats.Observe(time.Since(start))
		}()
		if cfg.Timeout > 0 {
			ctx, cancel := context.WithTimeout(r.Context(), cfg.Timeout)
			defer cancel()
			r = r.WithContext(ctx)
		}
		sw := &statusWriter{ResponseWriter: w}
		rp.ServeHTTP(sw, r)
		if sw.status >= 500 {
			stats.Responses5xx.Add(1)
		}
	})
	return &Proxy{Handler: h, Stats: stats}
}

// Admin returns the metrics and readiness handler for the sidecar's own port.
func (p *Proxy) Admin() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("/stats/prometheus", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/plain; version=0.0.4")
		p.Stats.WritePrometheus(w)
	})
	mux.HandleFunc("/ready", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
	return mux
}

// propagate makes sure the application sees x-request-id and a traceparent.
// An inbound traceparent gets a new span id (this hop is a span of its own);
// without one the sidecar starts a trace, which is what an ingress proxy does.
func propagate(in, out *http.Request) {
	if in.Header.Get("x-request-id") == "" {
		out.Header.Set("x-request-id", randHex(16))
	}
	if tp := childTraceparent(in.Header.Get("traceparent")); tp != "" {
		out.Header.Set("traceparent", tp)
	} else {
		out.Header.Set("traceparent", "00-"+randHex(16)+"-"+randHex(8)+"-01")
	}
}

func childTraceparent(tp string) string {
	p := strings.Split(tp, "-")
	if len(p) != 4 || p[0] != "00" || len(p[1]) != 32 || len(p[2]) != 16 || len(p[3]) != 2 {
		return ""
	}
	return strings.Join([]string{"00", p[1], randHex(8), p[3]}, "-")
}

func randHex(n int) string {
	b := make([]byte, n)
	if _, err := rand.Read(b); err != nil {
		panic(err)
	}
	return hex.EncodeToString(b)
}

func isTimeout(err error) bool {
	var ne net.Error
	return errors.As(err, &ne) && ne.Timeout()
}

type statusWriter struct {
	http.ResponseWriter
	status int
}

func (s *statusWriter) WriteHeader(code int) {
	if s.status == 0 {
		s.status = code
	}
	s.ResponseWriter.WriteHeader(code)
}

func (s *statusWriter) Write(b []byte) (int, error) {
	if s.status == 0 {
		s.status = http.StatusOK
	}
	return s.ResponseWriter.Write(b)
}

// Unwrap lets http.ResponseController reach the real writer (flushing, deadlines).
func (s *statusWriter) Unwrap() http.ResponseWriter { return s.ResponseWriter }
go
package sidecar

import (
	"bytes"
	"context"
	"io"
	"math/rand/v2"
	"net/http"
	"strconv"
	"sync/atomic"
	"time"
)

// maxBuffered is the largest request body the proxy buffers so it can replay it.
// Bigger bodies are sent once and never retried (Envoy has a similar buffer limit).
const maxBuffered = 1 << 20

// RetryTransport is the client half of a sidecar: it sends the request to the
// local application with a per-try timeout and retries only what is safe.
type RetryTransport struct {
	Base          http.RoundTripper
	PerTryTimeout time.Duration
	MaxRetries    int // retries after the first attempt
	Budget        *Budget
	Stats         *Stats
	// Backoff returns the pause before retry number n (1-based). Nil means
	// full jitter over 25ms * 2^(n-1), the same floor Istio documents (25ms+).
	Backoff func(n int) time.Duration
}

// Retriable says whether a result deserves another attempt: a connection
// error, or 502/503/504 (Envoy's gateway-error class).
func Retriable(status int, err error) bool {
	if err != nil {
		return true
	}
	return status == http.StatusBadGateway || status == http.StatusServiceUnavailable || status == http.StatusGatewayTimeout
}

// Idempotent says whether replaying the request cannot do harm: a safe or
// idempotent method (RFC 9110), or a request that carries an Idempotency-Key.
func Idempotent(r *http.Request) bool {
	switch r.Method {
	case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPut, http.MethodDelete:
		return true
	}
	return r.Header.Get("Idempotency-Key") != ""
}

func (t *RetryTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	base := t.Base
	if base == nil {
		base = http.DefaultTransport
	}
	var body []byte
	canReplay := Idempotent(req)
	if req.Body != nil && req.Body != http.NoBody {
		b, err := io.ReadAll(io.LimitReader(req.Body, maxBuffered+1))
		req.Body.Close()
		if err != nil {
			return nil, err
		}
		if len(b) > maxBuffered {
			return nil, errBodyTooLarge // read bytes are gone, so the request cannot even be sent once
		}
		body = b
	}
	if t.Budget != nil {
		t.Budget.Deposit()
	}
	for attempt := 0; ; attempt++ {
		ctx, cancel := context.WithCancel(req.Context())
		var timer *time.Timer
		var fired atomic.Bool
		if t.PerTryTimeout > 0 {
			timer = time.AfterFunc(t.PerTryTimeout, func() { fired.Store(true); cancel() })
		}
		out := req.Clone(ctx)
		if body != nil {
			out.Body = io.NopCloser(bytes.NewReader(body))
			out.ContentLength = int64(len(body))
		}
		out.Header.Set("x-sidecar-attempt-count", strconv.Itoa(attempt+1))
		resp, err := base.RoundTrip(out)
		if err != nil && fired.Load() {
			err = context.DeadlineExceeded // our own per-try timer, not a client cancel
		}

		status := 0
		if resp != nil {
			status = resp.StatusCode
		}
		last := attempt >= t.MaxRetries || !canReplay || !Retriable(status, err) || req.Context().Err() != nil
		if !last && t.Budget != nil && !t.Budget.Withdraw() {
			if t.Stats != nil {
				t.Stats.RetriesDenied.Add(1)
			}
			last = true
		}
		if last {
			if err != nil {
				cancel()
				if timer != nil {
					timer.Stop()
				}
				return nil, err
			}
			resp.Body = &cancelOnClose{ReadCloser: resp.Body, cancel: cancel, timer: timer}
			return resp, nil
		}
		// Retry: drop this attempt completely before sleeping.
		if resp != nil {
			io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
			resp.Body.Close()
		}
		cancel()
		if timer != nil {
			timer.Stop()
		}
		if t.Stats != nil {
			t.Stats.Retries.Add(1)
		}
		select {
		case <-time.After(t.backoff(attempt + 1)):
		case <-req.Context().Done():
			return nil, req.Context().Err()
		}
	}
}

func (t *RetryTransport) backoff(n int) time.Duration {
	if t.Backoff != nil {
		return t.Backoff(n)
	}
	ceil := 25 * time.Millisecond << (n - 1)
	return time.Duration(rand.Int64N(int64(ceil)) + 1)
}

type cancelOnClose struct {
	io.ReadCloser
	cancel context.CancelFunc
	timer  *time.Timer
}

func (c *cancelOnClose) Close() error {
	err := c.ReadCloser.Close()
	if c.timer != nil {
		c.timer.Stop()
	}
	c.cancel()
	return err
}
go
package sidecar

import "sync"

// Budget limits retries to a fraction of the traffic, like Envoy's retry
// budget or Linkerd's retry budget: every first attempt earns Ratio tokens
// (up to Max) and every retry spends one. During a full outage the budget
// drains and retries stop, so the mesh cannot multiply the load.
type Budget struct {
	mu     sync.Mutex
	tokens float64
	Ratio  float64
	Max    float64
}

// NewBudget returns a budget that allows about ratio retries per request.
func NewBudget(ratio, max float64) *Budget {
	return &Budget{Ratio: ratio, Max: max, tokens: max}
}

// Deposit is called once per first attempt.
func (b *Budget) Deposit() {
	b.mu.Lock()
	b.tokens += b.Ratio
	if b.tokens > b.Max {
		b.tokens = b.Max
	}
	b.mu.Unlock()
}

// Withdraw reports whether a retry may be sent.
func (b *Budget) Withdraw() bool {
	b.mu.Lock()
	defer b.mu.Unlock()
	if b.tokens < 1 {
		return false
	}
	b.tokens--
	return true
}
go
package sidecar

import (
	"fmt"
	"io"
	"sync/atomic"
	"time"
)

// Upper bounds of the latency buckets in milliseconds (the last bucket is +Inf).
var bucketsMs = []int64{5, 10, 25, 50, 100, 250, 500, 1000}

// Stats holds the four golden signals a mesh proxy gives for free:
// latency, traffic, errors and saturation (in-flight requests).
type Stats struct {
	Requests      atomic.Int64 // traffic: requests accepted
	Responses5xx  atomic.Int64 // errors: final responses with status >= 500
	Retries       atomic.Int64 // extra attempts sent upstream
	RetriesDenied atomic.Int64 // retries refused by the budget
	Timeouts      atomic.Int64 // requests ended by a timeout
	InFlight      atomic.Int64 // saturation: requests being served now
	latency       [9]atomic.Int64
	latencySumMs  atomic.Int64
}

// Observe records one finished request.
func (s *Stats) Observe(d time.Duration) {
	ms := d.Milliseconds()
	i := 0
	for i < len(bucketsMs) && ms > bucketsMs[i] {
		i++
	}
	s.latency[i].Add(1)
	s.latencySumMs.Add(ms)
}

// WritePrometheus writes the counters in the Prometheus text format, the same
// shape a real sidecar exposes on its metrics port (Envoy: 15090, Istio agent: 15020).
func (s *Stats) WritePrometheus(w io.Writer) {
	fmt.Fprintf(w, "sidecar_requests_total %d\n", s.Requests.Load())
	fmt.Fprintf(w, "sidecar_responses_5xx_total %d\n", s.Responses5xx.Load())
	fmt.Fprintf(w, "sidecar_retries_total %d\n", s.Retries.Load())
	fmt.Fprintf(w, "sidecar_retries_denied_total %d\n", s.RetriesDenied.Load())
	fmt.Fprintf(w, "sidecar_timeouts_total %d\n", s.Timeouts.Load())
	fmt.Fprintf(w, "sidecar_in_flight %d\n", s.InFlight.Load())
	var cum int64
	for i, ub := range bucketsMs {
		cum += s.latency[i].Load()
		fmt.Fprintf(w, "sidecar_request_duration_ms_bucket{le=\"%d\"} %d\n", ub, cum)
	}
	cum += s.latency[len(bucketsMs)].Load()
	fmt.Fprintf(w, "sidecar_request_duration_ms_bucket{le=\"+Inf\"} %d\n", cum)
	fmt.Fprintf(w, "sidecar_request_duration_ms_sum %d\n", s.latencySumMs.Load())
	fmt.Fprintf(w, "sidecar_request_duration_ms_count %d\n", cum)
}

Tests for the sidecar cover: GET retried until success, POST sent once, POST with Idempotency-Key replayed with the same body, the retry budget capping amplification, per-try timeout, total timeout giving 504, connection error giving 503, header injection and the metrics text.

go
package sidecar

import (
	"io"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"sync/atomic"
	"testing"
	"time"
)

func noBackoff(int) time.Duration { return 0 }

func newProxy(t *testing.T, app http.Handler, mod func(*Config)) (*Proxy, *httptest.Server) {
	t.Helper()
	upstream := httptest.NewServer(app)
	t.Cleanup(upstream.Close)
	u, _ := url.Parse(upstream.URL)
	cfg := Config{Target: u, Timeout: 2 * time.Second, PerTryTimeout: 300 * time.Millisecond,
		MaxRetries: 2, RetryRatio: 1, Backoff: noBackoff}
	if mod != nil {
		mod(&cfg)
	}
	p := New(cfg)
	front := httptest.NewServer(p.Handler)
	t.Cleanup(front.Close)
	return p, front
}

func do(t *testing.T, method, url string, hdr map[string]string) (int, string) {
	t.Helper()
	req, _ := http.NewRequest(method, url, strings.NewReader("payload"))
	for k, v := range hdr {
		req.Header.Set(k, v)
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()
	b, _ := io.ReadAll(resp.Body)
	return resp.StatusCode, string(b)
}

// failFirst answers 503 for the first n calls, then 200.
func failFirst(n int32, calls *atomic.Int32) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if calls.Add(1) <= n {
			http.Error(w, "boom", http.StatusServiceUnavailable)
			return
		}
		io.Copy(io.Discard, r.Body)
		w.Write([]byte("ok"))
	})
}

func TestGETIsRetriedUntilSuccess(t *testing.T) {
	var calls atomic.Int32
	p, front := newProxy(t, failFirst(2, &calls), nil)
	code, body := do(t, http.MethodGet, front.URL, nil)
	if code != 200 || body != "ok" || calls.Load() != 3 {
		t.Fatalf("code=%d body=%q calls=%d", code, body, calls.Load())
	}
	if p.Stats.Retries.Load() != 2 {
		t.Errorf("retries = %d, want 2", p.Stats.Retries.Load())
	}
}

func TestPOSTWithoutKeyIsNeverRetried(t *testing.T) {
	var calls atomic.Int32
	_, front := newProxy(t, failFirst(5, &calls), nil)
	code, _ := do(t, http.MethodPost, front.URL, nil)
	if code != 503 || calls.Load() != 1 {
		t.Fatalf("POST must be sent once: code=%d calls=%d", code, calls.Load())
	}
}

func TestPOSTWithIdempotencyKeyIsRetriedWithSameBody(t *testing.T) {
	var calls atomic.Int32
	var bodies []string
	app := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		b, _ := io.ReadAll(r.Body)
		bodies = append(bodies, string(b))
		if calls.Add(1) == 1 {
			http.Error(w, "boom", 503)
			return
		}
		w.Write([]byte("ok"))
	})
	_, front := newProxy(t, app, nil)
	code, _ := do(t, http.MethodPost, front.URL, map[string]string{"Idempotency-Key": "k1"})
	if code != 200 || len(bodies) != 2 || bodies[0] != "payload" || bodies[1] != "payload" {
		t.Fatalf("code=%d bodies=%v", code, bodies)
	}
}

func TestRetryBudgetStopsAmplification(t *testing.T) {
	var calls atomic.Int32
	p, front := newProxy(t, failFirst(1<<20, &calls), func(c *Config) {
		c.RetryRatio = 0.1 // one retry per ten requests once the initial tokens are spent
		c.MaxRetries = 3
	})
	const n = 100
	for i := 0; i < n; i++ {
		do(t, http.MethodGet, front.URL, nil)
	}
	// 100 first attempts + at most 10 initial tokens + 100*0.1 earned = 120 calls.
	if got := calls.Load(); got > 125 {
		t.Fatalf("budget did not cap retries: %d upstream calls for %d requests", got, n)
	}
	if p.Stats.RetriesDenied.Load() == 0 {
		t.Error("expected denied retries to be counted")
	}
}

func TestPerTryTimeoutRetriesASlowAttempt(t *testing.T) {
	var calls atomic.Int32
	app := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if calls.Add(1) == 1 {
			time.Sleep(400 * time.Millisecond) // longer than the 300 ms per-try timeout
		}
		w.Write([]byte("ok"))
	})
	_, front := newProxy(t, app, nil)
	code, _ := do(t, http.MethodGet, front.URL, nil)
	if code != 200 || calls.Load() != 2 {
		t.Fatalf("code=%d calls=%d", code, calls.Load())
	}
}

func TestTotalTimeoutGives504(t *testing.T) {
	app := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(300 * time.Millisecond) })
	p, front := newProxy(t, app, func(c *Config) {
		c.Timeout = 100 * time.Millisecond
		c.PerTryTimeout = 0
	})
	code, body := do(t, http.MethodGet, front.URL, nil)
	if code != http.StatusGatewayTimeout || !strings.Contains(body, "upstream request timeout") {
		t.Fatalf("code=%d body=%q", code, body)
	}
	if p.Stats.Timeouts.Load() != 1 || p.Stats.Responses5xx.Load() != 1 {
		t.Errorf("stats: timeouts=%d 5xx=%d", p.Stats.Timeouts.Load(), p.Stats.Responses5xx.Load())
	}
}

func TestConnectErrorGives503(t *testing.T) {
	u, _ := url.Parse("http://127.0.0.1:1") // nothing listens on port 1
	p := New(Config{Target: u, Timeout: time.Second, MaxRetries: 1, RetryRatio: 1, Backoff: noBackoff})
	front := httptest.NewServer(p.Handler)
	defer front.Close()
	code, body := do(t, http.MethodGet, front.URL, nil)
	if code != 503 || !strings.Contains(body, "upstream connect error") {
		t.Fatalf("code=%d body=%q", code, body)
	}
}

func TestHeadersAreInjectedAndForwarded(t *testing.T) {
	var got http.Header
	app := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { got = r.Header.Clone() })
	_, front := newProxy(t, app, nil)

	do(t, http.MethodGet, front.URL, nil)
	if len(got.Get("x-request-id")) != 32 || !strings.HasPrefix(got.Get("traceparent"), "00-") || got.Get("x-sidecar-attempt-count") != "1" {
		t.Errorf("sidecar must start request id and trace: %v", got)
	}

	do(t, http.MethodGet, front.URL, map[string]string{
		"x-request-id": "abc",
		"traceparent":  "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01",
	})
	if got.Get("x-request-id") != "abc" ||
		!strings.HasPrefix(got.Get("traceparent"), "00-0af7651916cd43dd8448eb211c80319c-") ||
		strings.Contains(got.Get("traceparent"), "b7ad6b7169203331") {
		t.Errorf("existing ids must be kept, span id renewed: %v", got)
	}
}

func TestMetricsAreExposed(t *testing.T) {
	var calls atomic.Int32
	p, front := newProxy(t, failFirst(1, &calls), nil)
	do(t, http.MethodGet, front.URL, nil)
	rec := httptest.NewRecorder()
	p.Admin().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/stats/prometheus", nil))
	out := rec.Body.String()
	for _, want := range []string{"sidecar_requests_total 1", "sidecar_retries_total 1", "sidecar_in_flight 0",
		`sidecar_request_duration_ms_bucket{le="+Inf"} 1`} {
		if !strings.Contains(out, want) {
			t.Errorf("metrics missing %q in:\n%s", want, out)
		}
	}
}

The application side. Middleware stores x-request-id, traceparent, tracestate and baggage in the request context; a RoundTripper stamps them on every outbound request with a fresh span id.

go
// Package propagate is the application side of a service mesh: the proxy can
// emit spans, but only the app can carry trace headers from an inbound request
// to the outbound calls it makes while serving it.
package propagate

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"net/http"
	"strings"
)

// Headers the mesh needs the app to forward. traceparent and tracestate are
// the W3C Trace Context headers; x-request-id is Envoy's request correlation id.
var Forwarded = []string{"x-request-id", "traceparent", "tracestate", "baggage"}

type ctxKey struct{}

// Carrier holds the header values of one inbound request.
type Carrier map[string]string

// FromContext returns the carrier stored by Middleware (nil if absent).
func FromContext(ctx context.Context) Carrier {
	c, _ := ctx.Value(ctxKey{}).(Carrier)
	return c
}

// Middleware copies the forwarded headers into the request context. A missing
// x-request-id is created so that logs of this service can still be joined.
func Middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		c := Carrier{}
		for _, h := range Forwarded {
			if v := r.Header.Get(h); v != "" {
				c[h] = v
			}
		}
		if c["x-request-id"] == "" {
			c["x-request-id"] = randHex(16)
		}
		w.Header().Set("x-request-id", c["x-request-id"])
		next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, c)))
	})
}

// Transport stamps the carrier of the request's context onto every outbound
// request. traceparent gets a fresh span id (a child span) with the same
// trace id, which is what a tracing backend needs to build the tree.
type Transport struct{ Base http.RoundTripper }

func (t Transport) RoundTrip(r *http.Request) (*http.Response, error) {
	base := t.Base
	if base == nil {
		base = http.DefaultTransport
	}
	c := FromContext(r.Context())
	if len(c) == 0 {
		return base.RoundTrip(r)
	}
	r2 := r.Clone(r.Context()) // never mutate the caller's request
	for _, h := range Forwarded {
		if v, ok := c[h]; ok && r2.Header.Get(h) == "" {
			r2.Header.Set(h, v)
		}
	}
	if tp := ChildTraceparent(c["traceparent"]); tp != "" {
		r2.Header.Set("traceparent", tp)
	}
	return base.RoundTrip(r2)
}

// ChildTraceparent keeps the trace id and flags of a valid version-00
// traceparent and replaces the parent id with a new random span id.
// It returns "" for an invalid input.
func ChildTraceparent(tp string) string {
	p := strings.Split(tp, "-")
	if len(p) != 4 || p[0] != "00" || len(p[1]) != 32 || len(p[2]) != 16 || len(p[3]) != 2 {
		return ""
	}
	if p[1] == strings.Repeat("0", 32) {
		return ""
	}
	return strings.Join([]string{"00", p[1], randHex(8), p[3]}, "-")
}

func randHex(n int) string {
	b := make([]byte, n)
	if _, err := rand.Read(b); err != nil {
		panic(err) // crypto/rand failing means the OS is broken
	}
	return hex.EncodeToString(b)
}
go
package propagate

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func TestChildTraceparent(t *testing.T) {
	in := "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"
	out := ChildTraceparent(in)
	p := strings.Split(out, "-")
	if len(p) != 4 || p[1] != "0af7651916cd43dd8448eb211c80319c" || p[3] != "01" {
		t.Fatalf("trace id or flags changed: %q", out)
	}
	if p[2] == "b7ad6b7169203331" || len(p[2]) != 16 {
		t.Fatalf("span id was not replaced: %q", out)
	}
	for _, bad := range []string{"", "garbage", "01-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01",
		"00-00000000000000000000000000000000-b7ad6b7169203331-01"} {
		if ChildTraceparent(bad) != "" {
			t.Errorf("accepted invalid traceparent %q", bad)
		}
	}
}

func TestMiddlewareAndTransportForwardHeaders(t *testing.T) {
	var got http.Header
	downstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		got = r.Header.Clone()
	}))
	defer downstream.Close()

	client := &http.Client{Transport: Transport{}}
	app := Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		req, _ := http.NewRequestWithContext(r.Context(), http.MethodGet, downstream.URL, nil)
		resp, err := client.Do(req)
		if err != nil {
			t.Error(err)
			return
		}
		resp.Body.Close()
	}))

	in := httptest.NewRequest(http.MethodGet, "/", nil)
	in.Header.Set("x-request-id", "req-123")
	in.Header.Set("traceparent", "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01")
	rec := httptest.NewRecorder()
	app.ServeHTTP(rec, in)

	if got.Get("x-request-id") != "req-123" {
		t.Errorf("x-request-id not forwarded: %q", got.Get("x-request-id"))
	}
	if !strings.HasPrefix(got.Get("traceparent"), "00-0af7651916cd43dd8448eb211c80319c-") ||
		strings.Contains(got.Get("traceparent"), "b7ad6b7169203331") {
		t.Errorf("traceparent must keep trace id and change span id: %q", got.Get("traceparent"))
	}
	if rec.Header().Get("x-request-id") != "req-123" {
		t.Errorf("response must echo x-request-id")
	}
}

func TestMiddlewareCreatesRequestID(t *testing.T) {
	rec := httptest.NewRecorder()
	Middleware(http.NotFoundHandler()).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
	if len(rec.Header().Get("x-request-id")) != 32 {
		t.Errorf("expected generated 32-hex id, got %q", rec.Header().Get("x-request-id"))
	}
}

func TestTransportWithoutContextIsPassThrough(t *testing.T) {
	var got http.Header
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { got = r.Header.Clone() }))
	defer s.Close()
	resp, err := (&http.Client{Transport: Transport{}}).Get(s.URL)
	if err != nil {
		t.Fatal(err)
	}
	resp.Body.Close()
	if got.Get("x-request-id") != "" {
		t.Errorf("must not invent headers outside a request: %q", got.Get("x-request-id"))
	}
}

Running it as a pod sidecar: cmd/sidecar listens on 15006 (inbound) and 15090 (metrics, /ready).

go
// Command sidecar runs the minimal proxy next to an application:
// inbound traffic on :15006 is forwarded to the app on 127.0.0.1:8080,
// metrics and readiness are served on :15090 (same ports Istio's Envoy uses).
package main

import (
	"log"
	"net/http"
	"net/url"
	"os"
	"time"

	"academy/service-mesh-sidecar/sidecar"
)

func main() {
	target := os.Getenv("APP_URL")
	if target == "" {
		target = "http://127.0.0.1:8080"
	}
	u, err := url.Parse(target)
	if err != nil {
		log.Fatal(err)
	}
	p := sidecar.New(sidecar.Config{
		Target:        u,
		Timeout:       5 * time.Second,
		PerTryTimeout: 1500 * time.Millisecond,
		MaxRetries:    2,
		RetryRatio:    0.2,
	})
	go func() { log.Fatal(http.ListenAndServe(":15090", p.Admin())) }()
	srv := &http.Server{Addr: ":15006", Handler: p.Handler, ReadHeaderTimeout: 5 * time.Second}
	log.Fatal(srv.ListenAndServe())
}

The Go angle ​

  • Use Rewrite, not Director: with Rewrite the outbound request has hop-by-hop headers and forwarding headers already removed, so a client cannot spoof X-Forwarded-For. ProxyRequest.SetURL and SetXForwarded are provided for exactly this.
  • A RoundTripper is the right place for retries: it sees both the request and the response, and ReverseProxy reuses it for every request. Never mutate the caller's request; clone it.
  • Retry only what is safe: a request body must be buffered to be replayed, so the sidecar caps it (1 MiB) and refuses to send larger bodies it could not replay.
  • context carries the deadline: the total timeout is a context, the per-try timeout a timer that cancels one attempt; a timer fired by us is reported as a timeout, not as a client cancel.
  • net/http clients without a Timeout wait forever; behind a mesh the route timeout will end the call, but the app should still set its own, shorter one.

Laravel ​

Before ​

The typical first version: a controller calls a service with Http::get, drops the inbound headers, keeps the default 30 s timeout (longer than any mesh route timeout, so the proxy cuts the call first and the app sees a reset), and has only /up for health:

php
Route::get('/orders/{id}', fn (string $id) => Http::get("http://inventory/stock/{$id}")->json());

After ​

Header propagation. MeshContext is bound with scoped() so Laravel Octane starts every request fresh ("instances registered using the scoped method will be flushed whenever the Laravel application starts a new lifecycle, such as when a Laravel Octane worker processes a new request or when a Laravel queue worker processes a new job"). The middleware fills it; an Http::macro builds a client that carries the headers.

php
<?php

namespace App\Mesh;

/**
 * Header values of the inbound request that must reach every outbound call.
 * Bound with scoped() so Octane starts every request with a fresh instance.
 */
final class MeshContext
{
    /** Headers the sidecar needs the application to forward (case-insensitive). */
    public const FORWARDED = ['x-request-id', 'traceparent', 'tracestate', 'baggage'];

    /** @var array<string,string> */
    private array $headers = [];

    /** @param array<string,string> $headers */
    public function fill(array $headers): void
    {
        $this->headers = $headers;
    }

    /** @return array<string,string> */
    public function headers(): array
    {
        return $this->headers;
    }

    public function requestId(): ?string
    {
        return $this->headers['x-request-id'] ?? null;
    }
}
php
<?php

namespace App\Http\Middleware;

use App\Mesh\MeshContext;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;

/**
 * Reads the headers the sidecar added to the inbound request and keeps them
 * for the outbound calls of this request (see MeshServiceProvider's Http macro).
 * Without this the sidecar cannot join its spans into one trace.
 */
class PropagateMeshHeaders
{
    public function __construct(private readonly MeshContext $mesh)
    {
    }

    public function handle(Request $request, Closure $next): Response
    {
        $headers = [];
        foreach (MeshContext::FORWARDED as $name) {
            $value = $request->header($name);
            if (is_string($value) && $value !== '') {
                $headers[$name] = $value;
            }
        }
        // Direct calls (local development, health checks from outside the mesh)
        // have no sidecar, so create the id the sidecar would have created.
        $headers['x-request-id'] ??= (string) Str::uuid();

        $this->mesh->fill($headers);
        Log::withContext(['request_id' => $headers['x-request-id']]);

        $response = $next($request);
        $response->headers->set('x-request-id', $headers['x-request-id']);

        return $response;
    }
}
php
<?php

namespace App\Providers;

use App\Mesh\MeshContext;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\ServiceProvider;

class MeshServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // scoped(): flushed for every request or queued job, which is what
        // Laravel Octane needs; singleton() would leak ids between requests.
        $this->app->scoped(MeshContext::class);
    }

    public function boot(): void
    {
        // Http::mesh('orders') -> a client for http://orders (plain HTTP in the pod;
        // the sidecar adds mTLS), carrying the inbound trace headers, with a
        // deadline shorter than the sidecar's route timeout so the app fails first
        // and no retry happens behind its back.
        Http::macro('mesh', function (string $service): PendingRequest {
            /** @var MeshContext $ctx */
            $ctx = app(MeshContext::class);

            return Http::baseUrl("http://{$service}")
                ->withHeaders($ctx->headers())
                ->connectTimeout(1)
                ->timeout((float) config('mesh.call_timeout', 2.5))
                ->acceptJson();
        });
    }
}

Registration, config and routes. The sidecar connects from localhost, so trustProxies(at: ['127.0.0.1']); the middleware is prepended so every later layer and log line has the request id.

php
<?php

use App\Http\Middleware\PropagateMeshHeaders;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        // The sidecar connects from 127.0.0.1 inside the pod; trust it so
        // X-Forwarded-Proto/For describe the real client and scheme.
        $middleware->trustProxies(at: ['127.0.0.1']);

        // First in the stack: every later middleware and log line has the request id.
        $middleware->prepend(PropagateMeshHeaders::class);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })
    ->create();
php
<?php

// config/mesh.php
return [
    // Seconds the app waits for one downstream call. Keep it BELOW the mesh route
    // timeout (e.g. Istio VirtualService timeout: 3s) so the app decides the fallback.
    'call_timeout' => (float) env('MESH_CALL_TIMEOUT', 2.5),

    // Inside the pod the app speaks plain HTTP to its sidecar; the proxy does mTLS.
    // Do not configure client certificates here and do not call https:// services
    // by name, or the sidecar sees opaque TLS and can neither route nor measure it.
    'scheme' => 'http',

    // Sidecar readiness: on shutdown keep serving for this long after SIGTERM so
    // in-flight and late-routed requests drain (match terminationGracePeriodSeconds).
    'shutdown_grace_seconds' => (int) env('MESH_SHUTDOWN_GRACE', 15),
];
php
<?php

use App\Http\Controllers\ReadinessController;
use App\Http\Middleware\MeshPeerIdentity;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Route;

Route::get('/healthz/live', [ReadinessController::class, 'live']);
Route::get('/healthz/ready', [ReadinessController::class, 'ready']);

// A call that keeps the trace: the macro adds x-request-id and traceparent.
Route::get('/orders/{id}', function (string $id) {
    $stock = Http::mesh('inventory')
        ->get('/stock/'.$id)
        ->throw()
        ->json();

    return ['order' => $id, 'stock' => $stock];
});

// Retries are safe only with an idempotency key: the mesh may replay this POST.
Route::post('/payments', function (\Illuminate\Http\Request $request) {
    abort_unless($request->hasHeader('Idempotency-Key'), 400, 'Idempotency-Key required');

    return Http::mesh('payments')
        ->withHeaders(['Idempotency-Key' => $request->header('Idempotency-Key')])
        ->post('/charges', $request->only('amount', 'currency'))
        ->throw()
        ->json();
})->middleware(MeshPeerIdentity::class.':spiffe://cluster.local/ns/shop/sa/checkout');

Readiness and peer identity. Separate liveness and readiness; optional authorization from the mTLS identity the sidecar forwards in X-Forwarded-Client-Cert.

php
<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * Two separate answers. Liveness: "the process is not wedged" (no dependencies).
 * Readiness: "send me traffic now" (dependencies this pod cannot work without).
 * With a sidecar both probes are rewritten or forwarded by the mesh, so the
 * app must answer on plain HTTP inside the pod.
 */
class ReadinessController
{
    public function live()
    {
        return response()->json(['status' => 'alive']);
    }

    public function ready()
    {
        $checks = [];

        try {
            DB::select('select 1');
            $checks['database'] = true;
        } catch (\Throwable $e) {
            Log::warning('readiness: database failed', ['error' => $e->getMessage()]);
            $checks['database'] = false;
        }

        try {
            Cache::store()->get('readiness-probe');
            $checks['cache'] = true;
        } catch (\Throwable $e) {
            $checks['cache'] = false;
        }

        // A cache outage degrades the app but must not remove every pod from rotation.
        $ready = $checks['database'];

        return response()->json(['status' => $ready ? 'ready' : 'not-ready', 'checks' => $checks], $ready ? 200 : 503);
    }
}
php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Optional: authorize by the caller's mesh identity. The sidecar terminates mTLS
 * and passes the verified client certificate details in X-Forwarded-Client-Cert
 * (Envoy's XFCC header). Trust it ONLY when the pod accepts traffic exclusively
 * through the sidecar (STRICT mTLS and no hostPort/NodePort bypass); otherwise
 * any client can forge it.
 */
class MeshPeerIdentity
{
    /** @param string ...$allowed e.g. spiffe://cluster.local/ns/shop/sa/checkout */
    public function handle(Request $request, Closure $next, string ...$allowed): Response
    {
        $xfcc = (string) $request->header('x-forwarded-client-cert', '');

        if (! preg_match('/URI=([^;,]+)/', $xfcc, $m) || ! in_array($m[1], $allowed, true)) {
            abort(403, 'peer identity not allowed');
        }

        return $next($request);
    }
}

Feature test (written, not run in this environment):

php
<?php

namespace Tests\Feature;

use Illuminate\Support\Facades\Http;
use Tests\TestCase;

class MeshHeadersTest extends TestCase
{
    public function test_outbound_calls_carry_the_inbound_trace_headers(): void
    {
        Http::fake(['inventory/*' => Http::response(['qty' => 3])]);

        $traceparent = '00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01';

        $this->withHeaders(['x-request-id' => 'req-1', 'traceparent' => $traceparent])
            ->getJson('/orders/42')
            ->assertOk()
            ->assertHeader('x-request-id', 'req-1');

        Http::assertSent(fn ($request) => $request->hasHeader('x-request-id', 'req-1')
            && $request->hasHeader('traceparent', $traceparent));
    }

    public function test_request_id_is_created_when_no_sidecar_added_one(): void
    {
        Http::fake(['inventory/*' => Http::response(['qty' => 3])]);

        $response = $this->getJson('/orders/42')->assertOk();

        $this->assertNotEmpty($response->headers->get('x-request-id'));
    }

    public function test_readiness_is_503_when_the_database_is_down(): void
    {
        config(['database.default' => 'broken']);
        config(['database.connections.broken' => ['driver' => 'sqlite', 'database' => '/nonexistent/db.sqlite']]);

        $this->getJson('/healthz/ready')->assertStatus(503);
    }
}

The Laravel angle ​

  • Http::macro registers a reusable client, and withHeaders merges headers into the request; connectTimeout() and timeout() set the deadlines; Http::retry() exists, but with a mesh doing retries do not add a second layer (see Retry amplification).
  • Octane keeps the application in memory between requests, so request state must never live in a singleton or a static property. scoped() bindings are flushed per request or queue job; Laravel's Octane docs also warn against injecting the container or request into singletons.
  • Inside the pod the app speaks plain HTTP: no client certificates in Guzzle, no https:// to in-mesh services. mTLS is the sidecar's job.
  • Octane is served "behind a traditional web server" in production (Nginx or Apache in front); with a mesh the sidecar plays the part of the TLS-terminating front, and NGINX may be a second sidecar or the same pod's front container.
  • Queue workers run without an inbound request: there is nothing to propagate, so jobs should carry the request_id as a payload field if you want a trace link.

Solving the classic problems ​

Retry amplification across app and mesh ​

Retry amplification: 3 x 3 x 3 = 27 callsApp retry loop3 attempts (library)Sidecar retries3 attempts (retries: attempts: 2)Failing servicereceives 3 x 3 = 9 per user callone user requesteach app attempteach sidecar attemptFix1. Retry at exactly one layer (the mesh is simplest to change, the app knows idempotency)2. Cap retries with a budget (a fraction of traffic) so an outage drains it3. Application timeout shorter than the mesh route timeout, so it never retries behind your back
SolutionHowAdvantageCost or limit
Retry at one layerRemove app-side loops or set mesh attempts: 1Predictable loadNeeds agreement between teams
Retry budgetRetries as a fraction of traffic (see the Go Budget)An outage drains retriesIstio VirtualService has no budget; Linkerd and Envoy have budget-style limits
retryOn narrowconnect-failure,refused-stream rather than 5xxRetries only what never reached the appMisses overload that the app reports
App timeout below route timeoutApp 2.5 s, route 3 sApp decides the fallbackMust keep both numbers in sync
Idempotency keysIdempotency-Key + the SQL table aboveDuplicates become no-opsStorage and TTL

A trace that breaks at one service ​

Symptom: Jaeger shows two short traces instead of one. Cause: one service in the chain does not copy traceparent. Fix: add the middleware and transport; verify by sending a request with a known traceparent and checking that downstream access logs show the same trace id (the Go lab prints this).

Startup race and shutdown drops ​

Symptom: first requests after a deploy fail with connection refused, or in-flight requests fail on scale-down. Causes: the app starts before the proxy listens; the proxy exits before the app's last calls. Fixes: Kubernetes native sidecars (start before, stop after), or Istio's holdApplicationUntilProxyStarts: true ("delay application startup until the pod proxy is ready", default false) and terminationDrainDuration (default 5 s) for connections to finish.

text
     scale-down timeline
1    pod gets SIGTERM; endpoint removal reaches proxies with a delay (eventual consistency)
2    late requests still arrive for a few seconds
3    app keeps serving during the grace period, then exits; native sidecar stops after it
4    proxy drains connections for terminationDrainDuration, then exits

Jobs and CronJobs that never finish ​

A proxy in containers keeps running after the Job's main container exits, so the Job never completes. Use native sidecars: Kubernetes states the sidecar "does not prevent the Job from completing after the main container has finished".

Mesh config bloat ​

Symptom: every proxy uses hundreds of MB and pushes take long. Cause: by default every proxy is programmed to reach every workload. Fix: the Sidecar resource with egress.hosts limited to the namespace and istio-system, plus exportTo on services; the Istio performance page says scoping is "highly recommended at large scale".

Server-first protocols and sniffing delays ​

MySQL speaks first, so sniffing waits for client bytes that never come, and connections stall or fail. Fix: name the port tcp-mysql (or appProtocol: tcp), or exclude the port from interception.

Debugging a 503 ​

text
1    curl from the client pod returns 503; response header server: envoy, access log flag NR / UF / UH / UO
2    NR  -> no route: istioctl proxy-config routes; check port name http-*, hosts, namespace
3    UF  -> connect failed: mTLS mismatch? kubectl get peerauthentication,destinationrule -A
4    UH  -> no healthy upstream: istioctl proxy-config endpoints; any ready pods? ejected by outlier detection?
5    UO  -> overflow: DestinationRule connectionPool limits too low for the load
6    none of the above -> the 503 came from the app: compare with the app's own log and x-request-id

Choosing ​

Few services,one language?Need mTLS oridentity policy?Need L7 per-servicerouting, retries, splits?Sidecar mesh orambient + waypointsLibrary + gatewayno meshGateway + librariesTLS at the edgeL4-only meshambient ztunnel, Ciliumbudget operations time:upgrades, debugging, on-callyesnonoyesnoyes
SituationRecommendationExtra techniqueReason
5 services, one language, one teamLibrary (Resilience4j in Java, go-kit in Go, Laravel HTTP client)Gateway at the edgeA mesh costs more than it saves
40 services, 4 languages, zero-trust requirementSidecar mesh (Linkerd for low operational load, Istio for the widest features)Strict mTLS, AuthorizationPolicyOne implementation of security everywhere
Need only encryption and identity between podsIstio ambient (ztunnel) or CiliumAdd a waypoint only where L7 is neededLowest per-pod cost
Public API, rate limits, auth at the edgeAPI gateway only (see API Gateway, BFF & Service Mesh)WAF, rate limitingThe mesh does not replace edge concerns
Heavy Kafka or database trafficKeep it outside capture or as opaque TCPClient-side broker retriesThe proxy cannot add L7 value there
Regulated environment, audit of every callMesh with access logs and AuthorizationPolicy AUDITEgress gatewayUniform evidence
Existing VM estate plus KubernetesConsul service mesh or Istio with VM supportMesh gatewaysSame policy across platforms
QuestionSidecar meshAmbient / eBPFLibraryGateway only
Uniform mTLS without codeYesYesNoEdge only
L7 routing per serviceYesWith waypointIn codeAt the edge
Per-pod costHighLowNoneNone
Adoption without restartsNoYesNoYes
Maturity of toolingHighNewerHighHigh

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

A single Laravel or Go process has no service-to-service traffic, so there is nothing for a mesh to do. Sidecars still make sense for helpers: a log shipper, a Vault agent, a local proxy to a managed database. Put the pieces that need only the pod's files or localhost in a native sidecar; keep TLS and rate limiting at the ingress or load balancer (Load Balancing).

Modular monolith: boundaries without the network ​

Modules call each other in-process, so retries and timeouts are function-level decisions. Design the module interfaces with a deadline and idempotency in mind now, because when a module becomes a service the mesh will add its own retries and timeouts to those calls.

Microservices: every arrow gets a proxy ​

Checkout calls Pricing, Inventory and Payments. In sidecar mode each arrow is client proxy then server proxy: mTLS between them, a route with a 3 s timeout and two retries on connect-failure, an outlier-detection ejection for a bad Inventory pod, an AuthorizationPolicy that only lets Checkout POST /charges. The Payments handler uses the idempotency table; the apps copy headers so one trace spans all four services. Without those app duties the mesh can still encrypt and measure, but not trace or retry safely. See Service Communication for the style decisions and Strangler Fig for moving traffic gradually with weighted routes.

Distributed data: replicas, caches, regions ​

The mesh does not move data; it moves requests. Locality-aware load balancing and outlier detection can keep calls inside a zone and eject a lagging replica's endpoint, but replica lag, read-your-writes and failover are database and application concerns (Replication Topologies). Multi-cluster meshes need shared trust and cross-cluster discovery; a regional outage then shifts traffic by configuration, and databases must be ready for it. Databases reached through the mesh are opaque TCP: you get mTLS and L4 metrics, not query-level features.

Scaling path: 1x, 10x, 100x ​

ScalePodsWhat changes
1xUnder about 20 servicesLibrary plus gateway; add a sidecar for helpers only
10xAround 100 to 400 podsMesh pays off for uniform mTLS; use Sidecar scoping from day one; revision-based upgrades
100xThousands of pods, many clustersAmbient for L4 to cut per-pod cost, waypoints where needed, multiple Istiod replicas, multi-cluster trust, a platform team that owns the mesh

Lab: sidecar retries, budget and trace in one process ​

The Go lab runs two apps, each behind its own sidecar, in one process (it was run; output below). The Istio part is labelled "expected, not run" (no cluster here).

text
$ cd docs/snippets/system-design/service-mesh-sidecar/go && go run ./cmd/lab
request 1: status=200
  inventory saw x-request-id=req-lab-1
  inventory saw trace id=0af7651916cd43dd8448eb211c80319c (same as client)
12 requests, 12 returned 200; inventory app received 17 calls
--- inventory sidecar metrics ---
sidecar_requests_total 12
sidecar_responses_5xx_total 0
sidecar_retries_total 5
sidecar_retries_denied_total 0
sidecar_timeouts_total 0
sidecar_in_flight 0

Reading it: 12 user requests, 5 hidden retries (17 upstream calls), no user-visible error; the same trace id and request id reached the second hop. Latency bucket counts vary per run.

Experiments to try:

  1. Set RetryRatio: 0 in the lab and rerun: the first transient failures stay visible as 503s.
  2. Change the app to fail always: sidecar_retries_denied_total grows once the 10 initial tokens are spent; calls to the app stay near 1 + ratio per request.
  3. Remove propagate.Transport from the orders app: the inventory app sees a different trace id (the trace breaks).
  4. Change the before path to retry 10 times inside a mesh that also retries: count upstream calls (amplification).

Istio lab (expected, not run): apply istio-routing.yaml to a cluster with istio-injection=enabled, then:

text
$ istioctl proxy-status                     # expected: all pods SYNCED
$ for i in $(seq 100); do curl -s reviews/ ; done | sort | uniq -c    # expected: about 90 v1, 10 v2 (can need ~100 requests to converge)
$ kubectl scale deploy/reviews-v1 --replicas=0                     # expected: requests fail with 503 UH during the gap

Common misconceptions ​

BeliefReality
A mesh is the same as an API gatewayA gateway handles north-south edge traffic; a mesh handles service-to-service traffic (the ingress gateway is only the mesh's front door)
The control plane carries my requestsRequests go proxy to proxy; the control plane only configures them
mTLS gives authorizationIt gives identity and encryption; AuthorizationPolicy decides access
Retries make everything reliableUn-budgeted, multi-layer retries multiply load and replay non-idempotent calls
The mesh traces automaticallyProxies emit spans; apps must copy traceparent and x-request-id
Ambient means no proxiesztunnel per node and waypoints still exist
The Sidecar resource blocks trafficIt scopes configuration; blocking needs an egress gateway and policy
Istio has a default timeoutThe HTTP request timeout is disabled by default; the default retry is 2 attempts
Everything in the namespace is protected once injectedNon-meshed pods, skip ports and permissive mode still allow plaintext
A mesh is freeAbout 0.20 vCPU and 60 MB per sidecar at 1000 req/s in Istio 1.24, plus two hops, upgrades and on-call

Cheat sheet ​

TopicWhat to remember
SidecarSame pod, shared network and volumes; native sidecar = init container with restartPolicy: Always
Data planeEnvoy, linkerd2-proxy, ztunnel, waypoint
Control planeIstiod, Linkerd destination and identity, Consul; configures, does not carry traffic
xDSLDS, RDS, CDS, EDS, SDS over gRPC; SotW, incremental, ADS
InjectionNamespace label istio-injection=enabled; Linkerd annotation linkerd.io/inject: enabled; restart pods
Captureiptables to 15006 inbound and 15001 outbound; UID 1337 reserved
mTLSPERMISSIVE then STRICT; DestinationRule ISTIO_MUTUAL when needed
RoutingVirtualService (where) + DestinationRule (how, subsets)
RetriesDefault 2 attempts, timeout off; one layer only; idempotent routes only
BreakingconnectionPool limits and outlierDetection ejection, not a stateful breaker
PolicyCUSTOM, DENY, ALLOW order; ALLOW present means default deny
ObservabilityGolden metrics free; headers traceparent, x-request-id are yours
ProtocolsName ports http-, tcp-; server-first protocols break sniffing
Debugistioctl proxy-status, proxy-config, access log flags NR UO UF UC, Envoy admin 15000
Cost0.20 vCPU and 60 MB per sidecar (Istio 1.24, 1000 rps); ztunnel 0.06 vCPU and 12 MB

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What turns an init container into a Kubernetes sidecar, and what does that change for startup, shutdown and Jobs? Good to know ​

Answer

Answer: restartPolicy: Always on an entry in initContainers. It starts before the app (after its startup probe passes), keeps running, is stopped after the app, and does not stop a Job from completing.

2 — Is the control plane in the request path? What happens if Istiod is down? Must-know ​

Answer

Answer: No. Proxies keep working with their last config; you cannot change config or issue new certificates until it returns.

3 — Name the xDS resource types and what each carries. Good to know ​

Answer

Answer: Listener (LDS: ports, filter chains), RouteConfiguration (RDS: matches, timeouts, retries), Cluster (CDS: upstream groups, breakers), ClusterLoadAssignment (EDS: endpoints), Secret (SDS: certificates).

4 — Why can a pod fail to start in a namespace with restricted Pod Security under Istio, and what is the fix? Important ​

Answer

Answer: istio-init needs NET_ADMIN and NET_RAW, blocked by baseline and restricted levels. Use the Istio CNI plugin or a privileged namespace.

5 — In ambient mode, which component does mTLS and which does L7 routing? Good to know ​

Answer

Answer: ztunnel (per node, L4, over HBONE) does mTLS, authentication and L4 authorization; a waypoint proxy (Envoy) does L7 routing and L7 authorization.

6 — A VirtualService sets attempts: 3, the app also retries three times. How many calls can one user request cause, and what do you change? Must-know ​

Answer

Answer: Up to 3 x 3 = 9 (more with several layers). Retry at one layer, add a budget, make the app timeout shorter than the route timeout.

7 — You applied a DestinationRule and requests to the service now return 503 flag UF. What is the likely cause? Important ​

Answer

Answer: A TLS mode mismatch: the DestinationRule lacks trafficPolicy.tls.mode: ISTIO_MUTUAL while the server requires mTLS, so the client proxy sends plaintext.

8 — Why do traces break between two services even with a mesh, and how do you fix it? Must-know ​

Answer

Answer: The app did not copy traceparent (and x-request-id) from the inbound to the outbound request. Add propagation middleware and an instrumented client.

9 — What does an Istio AuthorizationPolicy do if no ALLOW policy exists for a workload? What if one exists but nothing matches? Important ​

Answer

Answer: No ALLOW policy: allowed. An ALLOW policy exists and nothing matches: denied (403 "RBAC: access denied"). DENY is evaluated first.

10 — Why does MySQL through an Istio sidecar need an explicit port name? Good to know ​

Answer

Answer: MySQL is a server-first protocol, which is incompatible with automatic protocol selection; name the port tcp-mysql or exclude it from interception.

11 — When is a mesh not justified? Must-know ​

Answer

Answer: Few services in one language, a small team, no zero-trust requirement; a library plus a gateway costs less and is easier to debug.

12 — What must a handler do when the mesh may replay its request? Important ​

Answer

Answer: Be idempotent: an idempotency key with a unique constraint (ON CONFLICT DO NOTHING) so the second run returns the stored response.

Glossary ​

TermMeaning
SidecarA helper container in the same pod as the app
Sidecar patternCo-locating a helper process to extend an app without changing its code
Native sidecarInit container with restartPolicy: Always; ordered start and stop
Init containerA container that runs before the app containers in a pod
Service meshProxies next to workloads plus a control plane providing mTLS, routing, policy, telemetry
Data planeThe proxies that carry traffic
Control planeThe component that configures the proxies (Istiod, Linkerd, Consul)
EnvoyC++ L7 proxy used by Istio, Consul and others
linkerd2-proxyLinkerd's Rust micro-proxy
IstiodIstio's consolidated control plane binary
xDSEnvoy discovery APIs: LDS, RDS, CDS, EDS, SDS
Sidecar injectionAdding the proxy container via a mutating webhook
Ambient meshIstio data plane without per-pod proxies
ztunnelPer-node L4 proxy of ambient mode
Waypoint proxyEnvoy deployed for L7 features in ambient mode
HBONEHTTP CONNECT based tunnel between ambient components
CiliumCNI with an eBPF-based service mesh
eBPFKernel programs used for networking without a proxy hop
mTLSTLS where both sides present certificates
SPIFFE identityA workload identity URI, e.g. spiffe://cluster.local/ns/shop/sa/checkout
Traffic managementRouting, splitting, retries, timeouts at the proxy
VirtualServiceIstio object defining routes for a host
DestinationRuleIstio object defining subsets, load balancing, TLS, pools, outlier detection
GatewayEdge proxy listener configuration
ServiceEntryRegisters an external service in the mesh
PeerAuthenticationIstio mTLS mode policy (PERMISSIVE, STRICT)
AuthorizationPolicyAllow, deny, audit or custom access rules
Traffic splittingWeighted routing between versions
CanaryGradual rollout to a small share of traffic
Traffic mirroringSending a copy of traffic to another version
Fault injectionDeliberate delays or aborts for testing
RetriesResending a failed request
TimeoutsLimits on how long to wait
Circuit breakingLimits on connections and requests per host
Outlier detectionPassive ejection of misbehaving hosts
Rate limitingLimiting request rate per client or route
Golden metricsLatency, traffic, errors, saturation
Distributed tracingFollowing one request across services
Header propagationCopying trace headers from inbound to outbound requests
x-request-idEnvoy's request correlation header
traceparentW3C Trace Context header
Egress gatewayControlled exit point from the mesh
Multi-clusterOne mesh across clusters with shared trust
Gateway APIKubernetes standard API (Gateway, HTTPRoute)
HTTPRouteGateway API route object; attaches to a Service in GAMMA
ServiceProfileLinkerd's older per-route config CRD
LinkerdCNCF mesh with its own Rust proxy
Consul service meshHashiCorp mesh using Envoy sidecars
Latency overheadTime added by proxy hops
Resource overheadCPU and memory of the proxies
Operational complexityThe cost of running and upgrading the mesh
istioctlIstio CLI, including proxy-status and proxy-config
Envoy adminLocal admin interface on port 15000
Access logPer-request proxy log with response flags
Protocol sniffingDetecting HTTP from the first bytes of a connection
TCP passthroughForwarding bytes without L7 handling
ReadinessA probe that decides whether a pod receives traffic

References ​

Built by Morteza Negahi