In the cloud, service instances come and go constantly: autoscaling adds them, deploys replace them, crashes remove them, and each gets a fresh IP address. Service discovery is how a caller finds a healthy instance of a service at the moment it needs one. A service mesh goes further, moving discovery, load balancing, retries, mutual TLS and telemetry out of application code and into a proxy that runs next to every instance.
Think of it like
A hotel front desk
Guests check in and out all day and rooms are reassigned constantly, so memorizing room numbers is useless. You ask the front desk, which knows who is staying where and who has already left. With client-side discovery the desk hands you the guest list and you walk to the room yourself; with server-side discovery a concierge takes your message and delivers it for you.
The problem: addresses keep changing
A config file listing payments: 10.0.1.7:8080 works for exactly as long as that machine lives. In a modern deployment the set of instances is a moving target, so callers need a live, health-aware view of where each service runs.
- Autoscaling adds and removes instances every few minutes as load changes.
- Rolling deploys replace every instance, often several times a day.
- Failures and spot-instance reclaims remove instances without warning.
- Container schedulers place workloads on any node with dynamic IPs and sometimes dynamic ports.
- Service registry
- A database of the network locations of service instances, plus their health. The source of truth for discovery.
- Registration
- Adding an instance to the registry on startup and removing it on shutdown.
- Health check
- How the registry or load balancer learns an instance can no longer serve traffic: probes, heartbeats or leases with a TTL.
- Discovery
- Querying the registry (directly or through a router) to turn a service name into a healthy address.
Client-side discovery
The caller queries the registry, gets the list of healthy instances, and load-balances itself, connecting directly to the chosen instance. Netflix's Eureka with the Ribbon client library popularized this pattern; gRPC clients do the same with name resolvers.
Strengths
- No extra hop: lowest latency
- Client can use smart, application-aware balancing (zone affinity, request hedging)
- No central load balancer to scale or fail
Weaknesses
- Discovery logic in every client, for every language you use
- Clients are coupled to the registry's API
- Library upgrades must roll out across every service
Server-side discovery
The caller sends requests to a stable address, a load balancer or router, which knows the current instances and forwards each request. AWS Elastic Load Balancing with target groups and Kubernetes Services both work this way. Clients stay simple: they only need DNS and HTTP.
| Client-side | Server-side | |
|---|---|---|
| Who picks the instance | The calling service (library) | A load balancer or router |
| Network hops | Direct: one | Via router: two |
| Client complexity | High: per-language library | Low: DNS + HTTP |
| Balancing intelligence | Rich, app-aware | Generic (round robin, least connections) |
| Extra infrastructure | Registry only | Registry + highly available routers |
| Examples | Eureka + Ribbon, gRPC xDS clients, Finagle | AWS ALB/NLB, Kubernetes Services, NGINX |
Service registries
| Registry | Consistency | Liveness mechanism | Notes |
|---|---|---|---|
| Consul (HashiCorp) | CP: Raft per data center | Agent-run checks (HTTP, TCP, script, TTL); gossip for membership | DNS and HTTP APIs, KV store, built-in mesh (Consul Connect) |
| etcd | CP: Raft | Leases with TTL plus keepalives | Watch API; the backing store of Kubernetes |
| Apache ZooKeeper | CP: ZAB consensus | Ephemeral znodes vanish when the session dies | Watches; classic in Hadoop, HBase and pre-KRaft Kafka |
| Netflix Eureka | AP: peer-to-peer replication | Client heartbeats every 30 s; lease expires after 90 s | Self-preservation mode stops expiring instances during network trouble |
Self-registration vs third-party registration
Self-registration
- The instance registers itself on startup, heartbeats, and deregisters on shutdown
- Simple, and the instance knows best when it is ready
- Couples every service to the registry client library
- A crashed instance can't deregister: rely on TTL expiry
Third-party registration
- A registrar watches the platform and registers instances on their behalf
- Kubernetes' EndpointSlice controller, AWS target groups, Consul agents with service definitions
- No discovery code in the application
- The registrar is one more component that must be highly available
Health checks
- Active checks: the registry or load balancer polls an endpoint such as
GET /healthzevery few seconds and removes the instance after N consecutive failures. - Passive checks (heartbeats, leases): the instance proves it's alive by renewing a TTL; silence means death. See Heartbeats & Gossip Protocols.
- Outlier detection: proxies eject an instance from the pool after, say, five consecutive 5xx responses, even if its health endpoint says it's fine.
- Liveness vs readiness: liveness means "restart me, I'm stuck"; readiness means "don't send me traffic yet" (warming caches, draining before shutdown). Discovery should follow readiness.
DNS-based discovery and Kubernetes
DNS is the oldest registry of all (Domain Name System (DNS)). It works with every client, but plain DNS has sharp edges: records are cached according to TTLs (and some runtimes, notably older JVM defaults, cache longer than the TTL), A records carry no port (SRV records do), and a vanilla DNS server knows nothing about health.
Kubernetes sidesteps the caching problem. Each Service gets a stable virtual IP (the ClusterIP) and a DNS name such as payments.default.svc.cluster.local. Because the virtual IP never changes, caching it is harmless. The real routing to pod IPs happens below DNS, in rules that kube-proxy programs on every node from the Service's EndpointSlices, which list only ready pods.
apiVersion: v1
kind: Service
metadata:
name: payments
spec:
selector:
app: payments # pods with this label (and passing readiness) become endpoints
ports:
- port: 80 # the port callers use on the ClusterIP
targetPort: 8080 # the container port
---
# Headless variant: DNS returns the individual pod IPs instead of one virtual IP.
# Used for client-side balancing (gRPC) and StatefulSets (db-0, db-1, ...).
apiVersion: v1
kind: Service
metadata:
name: payments-headless
spec:
clusterIP: None
selector:
app: payments
ports:
- port: 8080Service mesh
As fleets grow, every service needs the same networking features: discovery, balancing, retries, timeouts, encryption, identity, metrics. Rather than reimplementing them in every language, a service mesh deploys a proxy (usually Envoy) as a sidecar next to each instance and transparently routes all traffic through it.
Data plane
- The sidecar proxies that carry every request
- Discovery and load balancing from their local endpoint list
- mTLS, retries, timeouts, outlier detection, traffic splitting
- Emit metrics, access logs and trace spans
Control plane
- Never touches requests; it configures the proxies
- Watches the platform (Kubernetes) for services and endpoints
- Pushes routes, policies and endpoints via the xDS APIs
- Acts as certificate authority, issuing and rotating workload certificates
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
name: payments
spec:
hosts:
- payments
http:
- timeout: 2s # overall deadline for the request
retries:
attempts: 3
perTryTimeout: 500ms
retryOn: 5xx,reset,connect-failure
route:
- destination:
host: payments
subset: v1
weight: 90
- destination:
host: payments
subset: v2
weight: 10 # canary
---
apiVersion: networking.istio.io/v1
kind: DestinationRule
metadata:
name: payments
spec:
host: payments
subsets:
- name: v1
labels:
version: v1
- name: v2
labels:
version: v2
trafficPolicy:
outlierDetection: # passive health checking
consecutive5xxErrors: 5
interval: 10s
baseEjectionTime: 30s
maxEjectionPercent: 50| Mesh | Proxy | Character |
|---|---|---|
| Istio | Envoy sidecars, or sidecar-less ambient mode (per-node ztunnel + optional waypoint proxies) | Most features: rich traffic management, policy, multi-cluster; more moving parts |
| Linkerd | linkerd2-proxy, a small Rust micro-proxy | Simplicity and low overhead; mTLS on by default; fewer knobs |
| Consul service mesh | Envoy | Spans Kubernetes and VMs; integrates with Consul's registry |
| Cilium | eBPF in the kernel, Envoy for L7 | Sidecar-less networking and security at the kernel level |
Implementation
Fetch healthy instances from Consul's health API, cache them briefly, fall back to the last known list if the registry is down, and round-robin across them.
import itertools
import time
import requests
class ServiceResolver:
def __init__(self, consul_url: str = "http://localhost:8500", ttl_s: float = 5.0):
self.consul_url = consul_url
self.ttl_s = ttl_s
self._cache: dict[str, tuple[float, list[tuple[str, int]]]] = {}
self._counter = itertools.count()
def _healthy(self, service: str) -> list[tuple[str, int]]:
hit = self._cache.get(service)
if hit and time.monotonic() - hit[0] < self.ttl_s:
return hit[1]
try:
resp = requests.get(
f"{self.consul_url}/v1/health/service/{service}",
params={"passing": "true"}, # only instances whose checks pass
timeout=1.0,
)
resp.raise_for_status()
instances = [
(e["Service"]["Address"] or e["Node"]["Address"], e["Service"]["Port"])
for e in resp.json()
]
self._cache[service] = (time.monotonic(), instances)
return instances
except requests.RequestException:
if hit: # registry unavailable: fall back to the last known list
return hit[1]
raise
def pick(self, service: str) -> tuple[str, int]:
instances = self._healthy(service)
if not instances:
raise RuntimeError(f"no healthy instances of {service}")
return instances[next(self._counter) % len(instances)]
resolver = ServiceResolver()
host, port = resolver.pick("payments")
requests.post(f"http://{host}:{port}/charges", timeout=2.0)Key takeaways
- Instances are ephemeral, so callers need a live, health-aware registry rather than static addresses.
- Client-side discovery avoids an extra hop but puts logic in every client; server-side discovery keeps clients simple behind a stable router.
- Registries (Consul, etcd, ZooKeeper, Eureka) differ in CP vs AP behavior; clients should cache the last known list either way.
- Kubernetes combines DNS with stable virtual IPs: EndpointSlices track ready pods and kube-proxy rules route to them.
- A service mesh moves discovery, retries, mTLS and telemetry into sidecar proxies (data plane) configured by a control plane.
Common pitfalls
- Hard-coding IPs or long-lived DNS caches that keep sending traffic to replaced instances.
- Deep health checks that fail the whole fleet when a shared dependency blips.
- Routing traffic on liveness instead of readiness, so cold or draining instances receive requests.
- Making the registry a hard dependency on every request instead of caching results.
- Adopting a service mesh for a handful of services and paying its latency and operational cost for little benefit.
Interview tips
- Name the mechanism explicitly (Kubernetes Service DNS, Consul, or a load balancer) whenever services call each other in your design.
- Explain client-side vs server-side discovery as a trade-off between hops and client complexity.
- If security comes up, mention mesh-provided mTLS and workload identity as the zero-trust answer for service-to-service calls.
Real-world applications
- Kubernetes Services and CoreDNS in virtually every containerized platform.
- Netflix's Eureka-based discovery for thousands of JVM service instances.
- Istio and Linkerd meshes providing mTLS and canary routing in large Kubernetes estates.
Test yourself
What is the defining feature of client-side discovery?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.