TExcelTAD
Home › Kubernetes › Service Meshes

Service Meshes

Once a system has dozens of services, the same questions come up for every connection between them: is this traffic encrypted? Is the caller allowed to call me? What happens when the callee is slow? Which service is producing the errors? You can answer them in every application's code, in every language, or you can move the answers into the network. A service mesh puts a proxy next to every workload, gives each workload a cryptographic identity, and configures all proxies centrally.

How a mesh is built

text
             control plane (istiod / Linkerd control plane)
         certificates, routing config, policy  │
          ┌────────────────────────────────────┼─────────────────────┐
          ▼                                    ▼                     ▼
 ┌─ Pod: web ───────────┐            ┌─ Pod: api ───────────┐   ┌─ Pod: db … ─┐
 │ app ──► proxy ───────┼── mTLS ───►│ proxy ──► app        │   │             │
 └──────────────────────┘            └──────────────────────┘   └─────────────┘
          data plane: every byte between services passes through proxies

Three data-plane designs are in use today:

Model Who proxies Notes
Sidecar (Istio classic, Linkerd) One proxy container per Pod, injected by a mutating webhook Full L7 features everywhere; costs CPU/memory per Pod, and upgrades restart Pods
Ambient / sidecarless (Istio ambient) A per-node ztunnel for mTLS and L4, optional per-namespace waypoint proxies for L7 Much lower overhead; you add L7 only where you need it
eBPF + per-node proxy (Cilium service mesh) The CNI in the kernel, an Envoy per node for L7 Comes with the CNI; identity is tied to Cilium's model

Linkerd uses its own small Rust proxy and favours simplicity; Istio uses Envoy and offers the largest feature set. Both are CNCF graduated projects. Turning a namespace on is one label:

bash
kubectl label namespace shop istio-injection=enabled          # Istio, sidecar mode
kubectl label namespace shop istio.io/dataplane-mode=ambient  # Istio, ambient mode
kubectl annotate namespace shop linkerd.io/inject=enabled     # Linkerd
kubectl rollout restart deployment -n shop                    # sidecars arrive with new Pods

Identity and mTLS

Each workload gets a short-lived X.509 certificate (Istio rotates them daily by default) whose identity comes from its ServiceAccount, written as a SPIFFE ID: spiffe://cluster.local/ns/shop/sa/api. The proxies use it for mutual TLS: both sides prove who they are, and traffic is encrypted, without a line of application code.

yaml
apiVersion: security.istio.io/v1
kind: PeerAuthentication
metadata:
  name: default
  namespace: shop
spec:
  mtls:
    mode: STRICT          # PERMISSIVE accepts plaintext too, for migrations
---
apiVersion: security.istio.io/v1
kind: AuthorizationPolicy
metadata:
  name: api-callers
  namespace: shop
spec:
  selector:
    matchLabels: {app: api}
  action: ALLOW
  rules:
    - from:
        - source:
            principals: ["cluster.local/ns/shop/sa/web"]
      to:
        - operation:
            methods: ["GET", "POST"]
            paths: ["/api/*"]

Compare this with Network Policies: those allow or block by IP and label at L3/L4, while mesh authorization checks a cryptographic identity and can look at methods and paths. They complement each other. The model decides each request in a namespace during a migration from PERMISSIVE to STRICT:

python · try it yourself
POLICY = {"api": [("spiffe://cluster.local/ns/shop/sa/web", {"GET", "POST"}, "/api/")]}

def decide(src, dst, method, path, mode):
    if src["identity"] is None:                 # no sidecar: plaintext
        if mode == "STRICT":
            return "connection reset (plaintext refused)"
        peer = "plaintext"
    else:
        peer = "mTLS"
    rules = POLICY.get(dst)
    if rules is None:
        return f"allowed via {peer} (no policy on {dst})"
    for principal, methods, prefix in rules:
        if src["identity"] == principal and method in methods and path.startswith(prefix):
            return f"allowed via {peer}"
    return f"403 RBAC: access denied ({peer})"

web = {"identity": "spiffe://cluster.local/ns/shop/sa/web"}
worker = {"identity": "spiffe://cluster.local/ns/shop/sa/worker"}
legacy = {"identity": None}

calls = [(web, "web", "api", "GET", "/api/orders"), (web, "web", "api", "DELETE", "/api/orders/7"),
         (worker, "worker", "api", "GET", "/api/orders"), (legacy, "legacy", "api", "GET", "/api/orders"),
         (legacy, "legacy", "search", "GET", "/q?x=1")]
for mode in ["PERMISSIVE", "STRICT"]:
    print(f"mode={mode}")
    for src, name, dst, method, path in calls:
        print(f"  {name:6} -> {dst:6} {method:6} {path:14} {decide(src, dst, method, path, mode)}")
mode=PERMISSIVE
  web    -> api    GET    /api/orders    allowed via mTLS
  web    -> api    DELETE /api/orders/7  403 RBAC: access denied (mTLS)
  worker -> api    GET    /api/orders    403 RBAC: access denied (mTLS)
  legacy -> api    GET    /api/orders    403 RBAC: access denied (plaintext)
  legacy -> search GET    /q?x=1         allowed via plaintext (no policy on search)
mode=STRICT
  web    -> api    GET    /api/orders    allowed via mTLS
  web    -> api    DELETE /api/orders/7  403 RBAC: access denied (mTLS)
  worker -> api    GET    /api/orders    403 RBAC: access denied (mTLS)
  legacy -> api    GET    /api/orders    connection reset (plaintext refused)
  legacy -> search GET    /q?x=1         connection reset (plaintext refused)

Note that a plaintext caller gets past PERMISSIVE mode but never matches a principals rule, because it has no identity. Watch the mesh's metrics for plaintext connections before switching a namespace to STRICT.

Timeouts and retries

Proxies can retry failed requests and cut off slow ones. With Istio's API:

yaml
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
  name: inventory
  namespace: shop
spec:
  hosts: [inventory]
  http:
    - timeout: 2s                       # total budget for the request
      retries:
        attempts: 3
        perTryTimeout: 500ms
        retryOn: 5xx,reset,connect-failure
      route:
        - destination: {host: inventory}

The same settings exist as timeouts (and, in the experimental channel, retry) on an HTTPRoute whose parentRefs names the Service, the Gateway API mesh profile (GAMMA) introduced in The Gateway API. Retries are only safe for idempotent requests, and they multiply: three layers that each make up to four attempts (the first try plus three retries) can turn one failing request into 64 calls on the bottom service, exactly when it is already struggling. The model shows a request's fate with a per-try timeout and an overall budget, and the multiplication:

python · try it yourself
def call(latencies_ms, attempts=3, per_try=500, budget=2000):
    """latencies_ms: how long each attempt would take (None = returns 503 immediately after 20 ms)."""
    elapsed, log = 0, []
    for i in range(attempts + 1):            # first try + retries
        if i >= len(latencies_ms):
            break
        if i > 0:
            elapsed += 25 * (2 ** (i - 1))   # back-off before each retry
        lat = latencies_ms[i]
        spent = 20 if lat is None else min(lat, per_try)
        if elapsed + spent > budget:
            log.append(f"try {i + 1}: cut off by the 2s budget")
            return budget, "504 timeout", log
        elapsed += spent
        if lat is None:
            log.append(f"try {i + 1}: 503 after 20ms")
        elif lat > per_try:
            log.append(f"try {i + 1}: per-try timeout at {per_try}ms")
        else:
            log.append(f"try {i + 1}: 200 in {lat}ms")
            return elapsed, "200", log
    return elapsed, "503", log

for name, lats in [("one 503 then ok", [None, 80]), ("slow pod then ok", [900, 120]),
                   ("all slow", [900, 900, 900, 900]), ("down", [None, None, None, None])]:
    total, status, log = call(lats)
    print(f"{name:17} -> {status} after {total}ms: {'; '.join(log)}")

print("retry amplification with 3 retries per layer:")
for layers in range(1, 4):
    print(f"  {layers} layer(s): up to {4 ** layers} calls reach the bottom service")
one 503 then ok   -> 200 after 125ms: try 1: 503 after 20ms; try 2: 200 in 80ms
slow pod then ok  -> 200 after 645ms: try 1: per-try timeout at 500ms; try 2: 200 in 120ms
all slow          -> 504 timeout after 2000ms: try 1: per-try timeout at 500ms; try 2: per-try timeout at 500ms; try 3: per-try timeout at 500ms; try 4: cut off by the 2s budget
down              -> 503 after 255ms: try 1: 503 after 20ms; try 2: 503 after 20ms; try 3: 503 after 20ms; try 4: 503 after 20ms
retry amplification with 3 retries per layer:
  1 layer(s): up to 4 calls reach the bottom service
  2 layer(s): up to 16 calls reach the bottom service
  3 layer(s): up to 64 calls reach the bottom service

Circuit breaking and outlier detection

Retries help with a single bad request; a single bad Pod needs a different tool. Outlier detection watches each endpoint and ejects one from the load-balancing pool for a while after a run of consecutive errors; connection pool limits cap queued requests so a slow service fails fast instead of piling up threads in its callers.

yaml
apiVersion: networking.istio.io/v1
kind: DestinationRule
metadata:
  name: inventory
  namespace: shop
spec:
  host: inventory
  trafficPolicy:
    connectionPool:
      http:
        http1MaxPendingRequests: 50
        maxRequestsPerConnection: 100
    outlierDetection:
      consecutive5xxErrors: 3
      interval: 10s
      baseEjectionTime: 30s           # doubled on each repeated ejection
      maxEjectionPercent: 50
python · try it yourself
ENDPOINTS = ["10.1.0.11", "10.1.0.12", "10.1.0.13"]
BAD_UNTIL = {"10.1.0.12": 40}            # this Pod returns 503 until t=40s
CONSECUTIVE, BASE_EJECT, MAX_PCT = 3, 30, 50

errors = {e: 0 for e in ENDPOINTS}
ejected_until, ejections = {}, {e: 0 for e in ENDPOINTS}
rr, served, failed = 0, 0, 0
for t in range(0, 70, 2):                 # one request every 2 s, round-robin
    pool = [e for e in ENDPOINTS if ejected_until.get(e, -1) <= t]
    ep = pool[rr % len(pool)]
    rr += 1
    served += 1
    ok = t >= BAD_UNTIL.get(ep, 0)
    if ok:
        errors[ep] = 0
        continue
    errors[ep] += 1
    failed += 1
    print(f"t={t:2}s {ep} -> 503 (consecutive: {errors[ep]})")
    if errors[ep] >= CONSECUTIVE and (len(ejected_until) + 1) * 100 / len(ENDPOINTS) <= MAX_PCT:
        ejections[ep] += 1
        ejected_until[ep] = t + BASE_EJECT * ejections[ep]
        errors[ep] = 0
        print(f"t={t:2}s {ep} EJECTED until t={ejected_until[ep]}s")
    ejected_until = {e: u for e, u in ejected_until.items() if u > t}
print(f"{served} requests, {failed} failed; ejections: {ejections}")
t= 2s 10.1.0.12 -> 503 (consecutive: 1)
t= 8s 10.1.0.12 -> 503 (consecutive: 2)
t=14s 10.1.0.12 -> 503 (consecutive: 3)
t=14s 10.1.0.12 EJECTED until t=44s
35 requests, 3 failed; ejections: {'10.1.0.11': 0, '10.1.0.12': 1, '10.1.0.13': 0}

Without ejection, the broken Pod would have kept receiving every third request until t=40s: 7 failures instead of 3. When it came back at t=44s it was healthy again. maxEjectionPercent is the safety valve: if half the endpoints look bad, the problem is probably not the endpoints, and ejecting more would overload the rest.

Observability for free (almost)

Because every request crosses a proxy, the mesh reports the golden signals (request rate, error rate, latency percentiles) for every service pair without instrumentation, and tools like Kiali or Linkerd's dashboard draw the live call graph. Distributed tracing still needs one thing from your code: forwarding the trace headers (traceparent) from incoming to outgoing requests, otherwise every hop starts a new trace. See Observability.

Do you need one?

A mesh adds moving parts: a control plane to upgrade, proxies to debug, extra latency per hop (well under a millisecond for a sidecar, less in ambient mode) and, in sidecar mode, memory per Pod. It pays off when you need zero-trust mTLS across many services, uniform traffic policy for polyglot teams, or per-service-pair telemetry. A handful of services with an Ingress or Gateway and Network Policies usually don't need one. If you adopt one, start with mTLS in PERMISSIVE mode and observability, then add STRICT, authorization and traffic policies service by service.

Learn more: Admission Control & Policies (sidecar injection) · TLS with cert-manager · Multi-Cluster Kubernetes

Test yourself

Where does a workload's identity in Istio or Linkerd come from?

  1. The Pod's IP address
  2. Its Kubernetes ServiceAccount, encoded in a certificate (SPIFFE ID)
  3. The node name
  4. An HTTP header set by the app

Three service layers each retry failed calls 3 times (4 attempts). How many calls can one user request cause on the bottom service?

  1. 4
  2. 12
  3. 64
  4. 3

What does outlier detection do?

  1. Retries every request twice
  2. Temporarily removes endpoints that keep failing from the load-balancing pool
  3. Encrypts traffic
  4. Scales the Deployment