What it is
Service discovery is how a service finds the network addresses of the instances of another service it wants to call. Instead of a fixed address, the caller uses a name (payments), and a service registry answers with the instances that are alive right now.
Why it exists
In a container platform or autoscaling group, instances are short-lived. Every deploy, scale-out, scale-in and host failure creates or destroys instances, and each new one gets a new address. Configuration files with IP addresses go stale within minutes. Discovery keeps an up-to-date list per service name, so callers follow the instances without being redeployed.
How it works
Registration. When an instance starts and is ready to serve, it is added to the registry with its name, address, port and often metadata (version, zone). Either the instance registers itself (self-registration, e.g. with Consul or Eureka) or the platform does it for the instance (third-party registration: Kubernetes adds a ready pod's address to the Service's EndpointSlices).
Liveness. The registry needs to know an instance is still alive. Common mechanisms are heartbeats with a TTL (the instance renews its entry every few seconds; the entry expires if renewals stop), sessions/leases in a consensus store (etcd, ZooKeeper), or active health checks run by the registry or platform (readiness probes in Kubernetes).
Deregistration. On a clean shutdown the instance removes itself (or the platform removes it) before stopping, then drains in-flight requests. A crashed instance cannot do this; its entry stays until liveness detection removes it.
Lookup. Two patterns:
- Client-side discovery: the caller queries the registry (or receives pushed updates), caches the instance list and balances across it itself. Examples: Eureka with a client library, gRPC with a name resolver and balancing policy, service-mesh sidecars configured over xDS. No extra network hop; the caller can do per-instance retries and smarter balancing; every service needs the library (or a sidecar).
- Server-side discovery: the caller sends to one stable name or virtual IP; a load balancer that follows the registry picks the instance. Examples: a Kubernetes Service (kube-proxy or an eBPF data plane), cloud internal load balancers. Clients stay simple and language-agnostic; there is an extra hop (or at least a NAT step), and the balancer must itself be highly available.
DNS-based discovery sits between the two: the registry is exposed through DNS (Consul DNS, Kubernetes CoreDNS). Simple and universal, but clients and resolvers cache answers, and many clients connect once and keep the connection, so changes propagate slowly unless TTLs are short and connections are recycled.
When to use it
- Any environment where instances are created and destroyed automatically: containers, autoscaling groups, serverless back ends behind internal endpoints.
- When several services call each other and you want them to scale and deploy independently.
- For blue/green and canary releases, where discovery metadata (version, weight) steers traffic.
When not to
- A handful of long-lived servers with stable addresses: a load balancer or DNS name maintained by hand is simpler.
- When the platform already provides it (Kubernetes Services, a managed service mesh): use that rather than running a second registry.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Client-side discovery | No extra hop, per-instance retries and balancing | A library or sidecar in every service, in every language |
| Server-side discovery | Simple clients, central control | An extra hop, a balancer to keep highly available |
| Short heartbeat interval / TTL | Smaller stale window after crashes | More registry load, healthy instances expired on short pauses |
| Push updates (watch) instead of polling | Callers learn changes within milliseconds to seconds | Long-lived connections to the registry, more complex clients |
| DNS-based discovery | Works with every client | Caching makes updates slow and uneven |
Alternatives
- Static configuration with a load balancer per service: fine for small, stable fleets.
- DNS round robin with short TTLs: no extra infrastructure, slow and uneven failover.
- Service mesh: sidecars or node proxies get endpoints from a control plane and handle balancing, retries and mTLS; discovery becomes part of the platform.
Failure modes
- Stale entries: a crashed instance keeps receiving traffic until it expires (interval × misses) and callers refresh. Requests in that window fail unless retried elsewhere.
- Expiring healthy instances: aggressive TTLs remove instances during GC pauses or brief network trouble, causing flapping.
- Registry outage: if callers cannot reach the registry, they should keep using their last known list rather than fail; a registry that is on the request path for every call is a single point of failure.
- Health that lies: an instance that heartbeats but cannot serve (its own dependency is down) stays listed. Readiness should reflect the ability to serve, without making every instance fail together when a shared dependency blips.
- Thundering refresh: thousands of clients polling the registry at the same moment; use watches, jitter and caching.
- Long-lived connections: HTTP/2 and gRPC clients keep connections to old instances, so new ones get no traffic until connections are recycled or the client balances per request.
In production
Use the platform's discovery where possible (Kubernetes Services and EndpointSlices, cloud service discovery, a mesh). Make shutdown graceful: fail readiness or deregister, wait for callers to notice, drain, then exit (Kubernetes uses a preStop hook and a termination grace period for this). Cache the last known instance list in clients. Retry connection failures on a different instance, and eject instances passively after repeated failures (outlier detection). Monitor registry health, entry churn and the number of instances per service.
Common misconceptions
- "The registry knows instantly when an instance dies." It infers death from missing heartbeats or failed checks, which always takes some time.
- "DNS is real-time discovery." Resolvers and clients cache answers, often longer than the TTL says.
- "Server-side discovery has no cost." Every call takes an extra hop through a component that must scale and stay up.
- "Discovery makes retries unnecessary." It removes dead instances eventually; retries cover the window before that.
Interview angle
When your design has more than one instance of a service, say how callers find them: "Kubernetes Service in front of the pods", or "client-side balancing with a registry". Interviewers probe what happens when an instance crashes (stale window, how long, how to shrink it), how a deploy avoids dropped requests (deregister, drain, stop), what happens if the registry is down (cached list), and client-side versus server-side trade-offs. Sizing the window ("5 s heartbeats × 3 misses + 10 s refresh ≈ 25 s worst case") shows you understand the mechanism.
Model assumptions
Traffic is simulated; the registry is not. Orders sends 200 calls per second (Poisson arrivals); each Payments instance has 4 workers and a 20 ms mean service time (lognormal), 3 ms away. Registrations, heartbeats, lookups and deregistrations are scripted packets for illustration. Their effect on routing is modelled by the engine's load balancer health checks: expiry after N missed heartbeats plus the caller's refresh is played by "eject after N failed probes", and admission of a new instance by "add after one good probe". The client-side balancer sits inside Orders (0 ms hop); the server-side balancer adds a 3 ms hop each way. Graceful deregistration is modelled by removing the instance from the balancer before it stops. Retries use exponential backoff with full jitter. Numbers show behaviour and orders of magnitude only.