Service Discovery and Service Mesh: How Services Find and Talk to Each Other
The checkout service calls the pricing service over gRPC. Pricing runs 12 pods behind a Kubernetes Service. During a traffic spike the autoscaler adds 12 more pods, and the dashboards show something strange: the 12 new pods sit at 3% CPU while the original 12 are pinned at 95% and p99 latency has tripled. Nothing is broken. Checkout’s gRPC client opened one long-lived HTTP/2 connection to the Service’s virtual IP at startup, the kernel picked one backend for that connection, and every request since has followed it. New pods never receive traffic until checkout restarts.
An hour later a node fails. Its pricing pods are gone, but a Java service that resolved their addresses earlier keeps sending to them until its own DNS cache expires. A few hundred requests hang on connect timeouts before anyone notices.
Both incidents are service discovery problems: how a caller learns which instances exist, which are healthy, and how to spread requests across them while that set changes every minute. A service mesh is the most complete, and most expensive, answer.
What it is
Service discovery is the mechanism that maps a logical name (pricing) to the current set of network endpoints (10.4.7.21:8080, 10.4.9.3:8080, …) and keeps that mapping fresh as instances start, stop, fail and move. It has three parts: registration (how instances get into the list), lookup (how callers read it), and health (how dead instances get out of it).
A service mesh moves service-to-service networking concerns, such as discovery, load balancing, retries, timeouts, mutual TLS and telemetry, out of application code into a layer of proxies (the data plane) configured centrally (the control plane). Every call between services passes through that layer.
You need discovery the moment you have more than one instance of anything. You need a mesh only when you have enough services, teams and security requirements that implementing those concerns consistently in every codebase has become the harder problem.
How discovery works
Client-side versus server-side discovery
flowchart LR
subgraph CS["Client-side discovery"]
A1["Checkout<br/>(client library)"] -->|"1 lookup"| R1[("Registry")]
A1 -->|"2 direct call, picks instance"| P1["Pricing pod 1"]
A1 --> P2["Pricing pod 2"]
end
subgraph SS["Server-side discovery"]
A2["Checkout"] -->|"call pricing VIP"| LB["Load balancer or proxy"]
LB -->|"watches"| R2[("Registry")]
LB --> P3["Pricing pod 1"]
LB --> P4["Pricing pod 2"]
end
style R1 fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style R2 fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style LB fill:#FAEEDA,stroke:#854F0B,color:#633806
style A1 fill:#E1F5EE,stroke:#0F6E56,color:#085041
style A2 fill:#E1F5EE,stroke:#0F6E56,color:#085041
In client-side discovery the caller reads the endpoint list itself and chooses an instance per request. There is no extra hop, and the client can use smart policies (least outstanding requests, zone affinity, consistent hashing on a key). The cost is a discovery-aware library in every language you run, and every library has to be upgraded when the policy changes. gRPC’s built-in resolvers and balancers, and the older Netflix Eureka plus Ribbon stack, work this way.
In server-side discovery the caller sends to one stable address, and something in the middle (a cloud load balancer, kube-proxy rules, a proxy) knows the instances. Clients stay simple and language-agnostic; you pay an extra hop or a layer of kernel rules, and the middle box’s balancing policy is usually simpler. The load balancing article covers the algorithms both sides can use.
A sidecar mesh is client-side discovery implemented out of process: the proxy next to each client does the lookup and the balancing, so the application sees a simple local call.
DNS-based discovery and Kubernetes Services
DNS is the universal discovery API: every language can resolve a name. Kubernetes builds on it.
- A ClusterIP Service gets a stable virtual IP and a DNS name such as
pricing.shop.svc.cluster.local. The control plane tracks ready pods in EndpointSlices, and kube-proxy (or an eBPF replacement such as Cilium) programs iptables, IPVS or nftables rules on every node so that connections to the virtual IP are spread across ready pods. Balancing happens per connection, not per request. - A headless Service (
clusterIP: None) has no virtual IP. DNS returns the pod IPs directly as multiple A records, so the client sees every instance and can balance itself. StatefulSets use headless Services to give each pod a stable name such askafka-0.kafka.
The basics of pods and Services are in containers and Kubernetes, later in the course.
DNS has well-known limits as a discovery protocol:
- TTL and caching. CoreDNS serves Kubernetes records with a short TTL (a few seconds by default), but clients and runtimes cache on their own terms. Some HTTP clients resolve once at startup and never again; the JVM caches successful lookups for 30 seconds by default when no security manager is installed. Removed pods keep receiving traffic until every cache along the path expires.
- No health or weight. DNS returns addresses, not “this one is slow” or “send 10% here”. Readiness probes remove pods from EndpointSlices, but a caller’s cached answer still contains them.
- Long-lived connections ignore DNS. HTTP/2 and gRPC hold a connection for minutes or hours. Through a ClusterIP, that connection is pinned to whichever pod the kernel picked, which is the opening incident.
- Lookup amplification. The default pod resolver setting
ndots:5makes a name likeapi.example.comtry several cluster search domains before the real query. Use fully qualified names with a trailing dot for external hosts in hot paths.
Registries
When you need richer data than DNS gives you, or you run outside Kubernetes, you use a registry: a strongly or eventually consistent store of instances with health, metadata and a watch API so clients hear about changes in seconds instead of polling.
| Registry | Consistency and model | Typical use in 2026 |
|---|---|---|
| Consul | Raft servers, gossip among agents, health checks, DNS and HTTP APIs | Multi-platform discovery across VMs and Kubernetes, also a mesh |
| etcd | Raft key-value store with leases and watches | Kubernetes’ own backing store; building blocks for custom discovery |
| ZooKeeper | ZAB consensus, ephemeral znodes, watches | Legacy Hadoop, older Kafka and JVM ecosystems |
| Eureka | AP, client heartbeats, self-preservation mode | Legacy Spring Cloud estates; rarely chosen for new systems |
| Kubernetes API | EndpointSlices watched by kube-proxy, CoreDNS and meshes | The default inside a cluster |
The consistency choice matters. A CP registry (etcd, ZooKeeper, Consul servers) refuses writes when it loses quorum, so new instances cannot register during a partition, but no one reads a split-brain view. An AP registry such as Eureka keeps answering with possibly stale data, which is usually what you want for discovery: a slightly stale list of mostly live instances beats no list. Clients should cache the last good list and keep using it if the registry is unreachable. The consensus protocols underneath are covered in distributed consensus and membership protocols in gossip and failure detection.
Health: active checks and outlier detection
Registries and Kubernetes rely on active health checks: probes on /healthz or a TCP port every few seconds. They answer “is the process up” but miss “is it returning errors to real traffic” and “is it 10 times slower than its peers”.
Outlier detection is passive: the caller’s proxy or library watches real responses per host and temporarily ejects hosts that misbehave. Envoy, for example, ejects a host after 5 consecutive 5xx responses by default, for a base ejection time of 30 seconds that grows with repeated ejections, and by default never ejects more than 10% of hosts at once so a fleet-wide problem does not eject everything. It is a per-host circuit breaker: move the failure-rate slider below to see the same closed, open and half-open cycle that an ejected host goes through. Circuit breakers in depth are in circuit breaker, later in the course.
xDS: the discovery API meshes speak
Envoy introduced a family of gRPC streaming APIs, collectively called xDS, through which a control plane pushes configuration to proxies:
- LDS (listeners): which ports to listen on and with which filters.
- RDS (routes): how to match requests to clusters, including retries, timeouts and traffic splits.
- CDS (clusters): the upstream services and their policies (load balancing, outlier detection, circuit breakers).
- EDS (endpoints): the current healthy instances of each cluster, with weights and zones.
- SDS (secrets): certificates and keys for mTLS, rotated without restarts.
Because xDS became the common language, many control planes (Istio’s istiod, Envoy Gateway, Consul, cloud mesh products) drive Envoy, and gRPC libraries can consume xDS directly. That last option is proxyless gRPC: the gRPC client itself receives endpoints, routes and certificates over xDS and balances per request, with no sidecar.
gRPC client-side load balancing
gRPC over HTTP/2 multiplexes all requests on a few long-lived connections, which defeats connection-level balancing. Your options, from least to most infrastructure:
- Headless Service plus the client’s round-robin policy. The gRPC
dnsresolver returns all pod IPs;round_robinopens a connection to each and spreads requests. Re-resolution happens when connections break and periodically, so set a server-sidemax_connection_age(for example 5 minutes) to force clients to reconnect and pick up new pods. - An L7 proxy that balances per request (a mesh sidecar, a waypoint, or a standalone Envoy).
- Proxyless gRPC with xDS, where the client gets live endpoint updates and policies from a control plane.
The protocol trade-offs of gRPC itself are in REST vs GraphQL vs gRPC.
How a service mesh works
flowchart TB CP["Control plane<br/>(istiod, Linkerd destination,<br/>Consul servers)"] subgraph PodA["Pod: checkout"] APP1["checkout app"] --> SC1["sidecar proxy"] end subgraph PodB["Pod: pricing"] SC2["sidecar proxy"] --> APP2["pricing app"] end SC1 -->|"mTLS, retries,<br/>per-request LB"| SC2 CP -.->|"xDS: routes, endpoints,<br/>certificates"| SC1 CP -.->|"xDS"| SC2 SC1 -.->|"metrics, traces"| OBS["Telemetry backend"] SC2 -.->|"metrics, traces"| OBS style CP fill:#EEEDFE,stroke:#534AB7,color:#3C3489 style SC1 fill:#FAEEDA,stroke:#854F0B,color:#633806 style SC2 fill:#FAEEDA,stroke:#854F0B,color:#633806 style APP1 fill:#E1F5EE,stroke:#0F6E56,color:#085041 style APP2 fill:#E1F5EE,stroke:#0F6E56,color:#085041 style OBS fill:#F1EFE8,stroke:#888780,color:#444441
The data plane is the set of proxies that carry traffic. The control plane watches the Kubernetes API (or a registry), compiles policy into proxy configuration, issues workload certificates, and pushes everything over xDS or an equivalent API. If the control plane goes down, proxies keep running on their last configuration; you lose the ability to change things, not the traffic.
What a mesh buys you, uniformly and without code changes:
- Mutual TLS everywhere with automatically issued and rotated workload identities, plus authorization policy by identity (“only checkout may call pricing”). The identity side is covered in mTLS and workload identity, later in the course.
- Per-request load balancing for HTTP/2 and gRPC, zone-aware routing, and outlier ejection.
- Retries, timeouts and budgets defined in one place, which is also the danger: a retry policy in the mesh multiplies with retries in the app. Agree on one layer, as explained in timeouts, retries and backoff.
- Traffic splitting by weight or header for canaries and blue-green releases, covered in deployment strategies.
- Golden-signal telemetry (request rate, errors, latency per route and per caller) and trace propagation, provided the app forwards trace headers. See logs, metrics and traces.
What it costs:
- Latency per hop. In a sidecar mesh each call passes through two proxies, the caller’s and the callee’s. Each adds a fraction of a millisecond at the median and more at the tail. A request that fans out through 6 services crosses 12 proxies.
- Resources. One proxy per pod, each with its own memory and CPU, multiplied across thousands of pods.
- Operational complexity. Another control plane to upgrade, certificate authorities to run, new failure modes (a misconfigured route that blackholes traffic everywhere at once), and engineers who must debug iptables redirection and proxy config dumps.
Data plane models
Sidecars. A proxy container in every pod, with traffic redirected through it. Istio’s classic mode uses Envoy; Linkerd uses its own lightweight proxy written in Rust. Full L7 features for every workload, at full per-pod cost.
Istio ambient mode. Generally available since Istio 1.24 (November 2024). It splits the data plane in two. A per-node ztunnel (written in Rust) handles L4: it captures pod traffic, provides mTLS and L4 authorization, and tunnels traffic between nodes. Optional waypoint proxies (Envoy, deployed per namespace or per service) are added only where you need L7 features such as HTTP routing, retries or header-based policy. Workloads that need only encryption and identity pay for a shared per-node proxy instead of one per pod. Istio continues to support sidecar mode alongside it.
Linkerd. A sidecar mesh focused on simplicity and a small, fast Rust proxy, with automatic mTLS, per-request load balancing, retries, timeouts and Gateway API based routing. Since February 2024 the open-source project publishes edge releases, and stable release artifacts come from vendors, primarily Buoyant. Linkerd 2.20 shipped in June 2026.
Cilium service mesh. Cilium is a CNI that uses eBPF in the kernel for L3 and L4 processing (service load balancing, network policy, observability via Hubble) and runs Envoy, typically one per node, for L7 features. It implements Gateway API, including the GAMMA profile for mesh routing. Its mutual authentication feature is still marked beta in the Cilium documentation, so teams that require mTLS everywhere often pair Cilium networking with Istio.
Proxyless. gRPC clients speak xDS directly. No proxy hop or sidecar cost, but only for gRPC traffic, and only with features the gRPC library implements.
Where it breaks
- Retry amplification. App retries 3 times, the mesh retries 3 times, and a downstream that slows down receives up to 16 attempts per user request. Pick one layer for retries and enforce retry budgets.
- Stale endpoints. Long DNS caches, clients that resolve once, and connections that outlive pods send traffic to instances that no longer exist. Respect TTLs, cap connection age, and drain pods gracefully: fail readiness first, keep serving in-flight requests, then exit.
- Registry as a single point of failure. If callers block on the registry for every request, a registry outage becomes a full outage. Cache endpoint lists locally and keep using the last good set.
- Health checks that lie. A
/healthzthat returns 200 while the database pool is exhausted keeps a broken pod in rotation. Combine shallow liveness, meaningful readiness and passive outlier detection. - Mesh-wide blast radius. One bad route or authorization policy is pushed to every proxy within seconds. Roll policy changes out progressively and test them in a staging mesh.
- Sidecar startup and shutdown races. An app that starts before its sidecar cannot reach anything, and a sidecar that exits before the app drops in-flight requests. Kubernetes native sidecar containers (init containers with a restart policy of Always) fix ordering; use them where your mesh supports them.
- Mesh as a substitute for design. A mesh does not fix chatty service boundaries or missing idempotency. It makes calls observable and encrypted, not fewer.
Real-world systems
Kubernetes gives every cluster DNS-based server-side discovery through Services, EndpointSlices, CoreDNS and kube-proxy, plus headless Services for client-side patterns.
Consul provides discovery across VMs and Kubernetes with health checks, a DNS interface and a service mesh built on Envoy.
Envoy is the most widely used L7 proxy for meshes and gateways and defined the xDS APIs that many control planes and gRPC libraries implement.
Istio offers both sidecar and ambient data planes, with ambient GA since version 1.24.
Linkerd remains the lightweight sidecar option, with weekly edge releases from the open-source project and stable distributions from vendors.
Cilium combines an eBPF networking datapath with per-node Envoy for L7 and Gateway API support.
gRPC ships resolvers and load-balancing policies, including xDS support for proxyless meshes.
How to apply it
| Situation | Recommendation |
|---|---|
| One cluster, a handful of HTTP services | Kubernetes Services and DNS. No mesh. |
| gRPC services with skewed load | Headless Service with round_robin and max connection age, or an L7 proxy |
| VMs and containers across environments | A registry such as Consul with local caching in clients |
| Compliance requires mTLS for all internal traffic | A mesh; consider an L4-first model such as Istio ambient to limit cost |
| Many teams, many languages, inconsistent retries and telemetry | A mesh with one owning platform team and progressive rollout |
| Latency-critical gRPC paths | Proxyless gRPC with xDS, or exclude those paths from L7 proxies |
Before adopting a mesh, check:
- Who owns it? A mesh without a platform team becomes everyone’s mystery.
- Which features do you actually need on day one: mTLS, telemetry, traffic splitting? Start with those and turn on L7 policy per service later.
- Have you removed duplicate retries from application code, or set budgets in both layers?
- Is there a tested path to roll back a bad mesh config, and is the mesh upgrade cadence realistic for your team?
Interview angle
Interview questions
Q1: New gRPC pods receive no traffic after a scale-out. Why, and how do you fix it?
gRPC multiplexes requests over long-lived HTTP/2 connections. Through a ClusterIP Service, kube-proxy balances connections, not requests, so each client’s connection stays pinned to the pod chosen when it connected, and new pods are only used by new connections. Fixes: use a headless Service so DNS returns all pod IPs and configure the gRPC client with the round_robin policy; set max_connection_age on servers so clients periodically reconnect and re-resolve; or put an L7 proxy (sidecar, waypoint, Envoy) in the path to balance per request; or use proxyless gRPC with xDS for live endpoint updates.
Q2: Compare client-side and server-side discovery.
Client-side discovery has the caller read the registry and pick an instance, which avoids an extra hop and allows rich policies such as least outstanding requests or zone affinity, but needs a maintained library per language and couples clients to the registry. Server-side discovery sends traffic to a stable address and lets a load balancer or proxy pick, which keeps clients simple and polyglot at the cost of a hop and usually simpler policies. A sidecar mesh is client-side discovery moved into a local proxy, so you get rich policy without per-language libraries, paid for in proxy resources and latency.
Q3: What does a service mesh give you, and when is it not worth it?
It gives uniform mTLS with workload identity and identity-based authorization, per-request load balancing with outlier ejection, centrally defined timeouts and retries, traffic splitting for canaries, and consistent telemetry without changing application code. It costs extra latency per hop (two proxies per call with sidecars), CPU and memory per pod or per node, and a control plane and CA to operate, with a large blast radius for bad config. It is not worth it for a small number of services owned by one team, where Kubernetes Services, a good client library and TLS at the edge are enough, or for ultra-low-latency paths unless you use proxyless gRPC or an L4-only mode.
✅ Key takeaways
- Discovery is registration, lookup and health. Client-side discovery balances in the caller; server-side discovery balances in a middle box.
- Kubernetes ClusterIP Services balance per connection; headless Services return pod IPs for client-side balancing. DNS caches and long-lived connections cause stale and skewed traffic.
- Registries (Consul, etcd, ZooKeeper, legacy Eureka) add health and watches; clients must cache the last good list.
- Passive outlier detection catches hosts that pass health checks but fail real traffic. xDS is the common API for pushing endpoints, routes and certificates.
- A mesh buys mTLS, per-request balancing, retries, traffic splitting and telemetry, and costs per-hop latency, resources and operations. Istio ambient (GA in 1.24) cuts cost with per-node ztunnels and optional waypoints.
- Put retries in exactly one layer, and use headless round robin, an L7 proxy or proxyless gRPC for gRPC balancing.
🧠 Check your understanding
0 / 4-
1A gRPC client talks to a ClusterIP Service with 20 pods, yet one pod gets almost all its traffic. Why?
ClusterIP balancing happens when a connection is opened. gRPC multiplexes all requests on that connection, so they all follow it. A ClusterIP name resolves to one virtual IP, not to pods, and headless Services would actually help by returning all pod IPs.
-
2What does Istio ambient mode's ztunnel do?
Ambient splits the data plane: a per-node ztunnel for L4 security and optional Envoy waypoints for L7 features. The tempting wrong answer describes classic sidecar mode, which ambient exists to avoid.
-
3Which is the best reason to prefer an AP registry or cached endpoint lists for discovery?
Discovery tolerates staleness well, especially with outlier detection to skip dead hosts, but cannot tolerate callers blocking when the registry is unavailable. AP does not remove staleness; it trades it for availability.
-
4An app retries 3 times and the mesh also retries 3 times on failure. A dependency slows down. How many attempts can one user request cause at that dependency?
Each of the 4 app attempts (1 plus 3 retries) can become 4 mesh attempts, so 4 x 4 = 16. Adding the counts gives 6, which underestimates how layered retries multiply load. Keep retries in one layer with a budget.
Where to go next
- API gateway patterns: the north-south front door, and how it differs from the east-west mesh.
- mTLS and workload identity: how the certificates a mesh hands out prove who a service is.
- Circuit breaker: the per-dependency version of outlier ejection, and how it interacts with retries.
- Containers and Kubernetes: pods, Services and probes, the substrate most meshes run on.
Finished this lesson?
Mark it complete to track your progress across the roadmap.