Course contents

11. Microservices Lesson 3 of 10

Service Discovery

How services find each other: registries, heartbeats, client-side vs server-side discovery, and why stale entries route traffic to dead instances.

15 minIntermediate9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A registry maps a service name to its live instances; instances register, heartbeat and deregister.
  • Client-side discovery: the caller picks an instance (no extra hop). Server-side: a platform balancer picks (simple clients).
  • Crashed instances cannot deregister; their stale entries receive traffic until heartbeats expire them.
  • The stale window ≈ heartbeat interval × allowed misses + caller refresh time.
  • Graceful shutdown (deregister, drain, stop) and retries on refused calls keep failures near zero.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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.

The lesson as textEvery step of the simulation, written out.
  1. 1. A fixed address breaks on the first redeploy

    Orders calls Payments at an address written in its configuration: payments = 10.0.1.17. That works while the instance lives.

    At 1 s the platform replaces the instance, as it does on every deploy, autoscaling event or host failure. The new instance is running at a different address, but Orders still calls the old one: every payment call fails while a healthy Payments sits idle.

    Scene: Orders calls one Payments instance at a fixed address. The instance is replaced at 1 second; the new one runs at another address, and every call from Orders now fails.

    Key idea: In a dynamic environment instance addresses change all the time; callers must look them up, not hard-code them.

  2. 2. Instances register, callers look them up

    A service registry keeps the current list of instances per service name. Each Payments instance registers when it starts (name, address, port) and then sends a heartbeat every second. Orders looks up payments, caches the list and refreshes it.

    Here Orders balances over the list itself (client-side discovery: a library inside Orders, so no extra hop). The 200 calls per second spread evenly over the three instances. *(The registry messages are a scripted illustration; the traffic is simulated.)*

    Scene: Three Payments instances register with the service registry and send heartbeats. Orders looks up the list once and its built-in balancer spreads calls evenly over the three instances.

    Key idea: A registry maps a service name to its live instances: instances register and heartbeat, callers look up and cache.

  3. 3. A new instance joins without a config change

    At 1 s a fourth instance starts and registers itself. Nobody edits a configuration file or restarts Orders.

    Orders picks it up on its next refresh of the list, here within a second, and from then on a quarter of the calls go to it. That delay is the propagation time of discovery: a new instance takes a moment to receive traffic, which is usually harmless.

    Scene: A fourth Payments instance starts at 1 second and registers. Within about a second Orders refreshes its list and starts sending a quarter of its calls to the new instance.

    Key idea: Instances announce themselves; callers find new capacity on their next refresh, with no deploy of the caller.

  4. 4. Graceful shutdown: deregister first

    Payments 1 is being retired. Before stopping, it deregisters: the registry removes it and pushes the new list to Orders, which stops sending it calls.

    Only then, at 1 s, does the process stop. Nothing was in flight and nothing was routed to it, so no call fails. Deploy tools do this on every rollout: remove from discovery, drain in-flight requests, then stop.

    Scene: Payments 1 deregisters, the registry tells Orders, and Orders stops calling it. When Payments 1 stops at 1 second, no call fails.

    Key idea: Deregister, drain, then stop: a planned shutdown should never cost a single request.

  5. 5. A crash leaves a stale entry

    At 1 s Payments 2 crashes. A crashed process cannot deregister, so the registry still lists it: the entry is stale. Orders keeps sending it a third of the calls, and each one fails with *connection refused*.

    The registry only notices when heartbeats stop arriving. It expires the instance after three missed heartbeats (3 s here), Orders refreshes, and the errors stop. Until then, a stale entry routes real traffic to a dead instance.

    Scene: Payments 2 crashes. The registry still lists it, so a third of the calls fail for about three seconds, until the missed heartbeats expire the entry and Orders stops calling it.

    Key idea: Discovery learns about crashes only through missing heartbeats; until the entry expires, callers send traffic to a dead instance.

  6. 6. Shorter heartbeats, shorter window

    Payments 2 is restarted and crashes again at 1 s, but now instances send a heartbeat every 250 ms and the registry expires them after two misses. The stale window shrinks from about 3 s to about half a second, and far fewer calls fail.

    The price: four times the heartbeat traffic to the registry, and a higher risk of expiring a healthy instance during a short GC pause or network blip. Many systems also let callers mark an instance bad on their own after a few refused connections (*passive* health checking).

    Scene: With 250 ms heartbeats and expiry after two misses, Payments 2’s crash causes errors for only about half a second before it is removed.

    Key idea: The stale window is roughly heartbeat interval × allowed misses (plus the caller’s refresh); shorten it, at the cost of chatter and false alarms.

  7. 7. Retry on another instance

    One more layer: when a call is refused, Orders retries it (up to twice) after a short random backoff. The balancer hands each retry to the next instance in its list, which is almost always a healthy one, so the crash of Payments 2 at 1 s costs almost no failed orders, only a few milliseconds on the retried ones.

    Retrying on *connection refused* is safe because the request never reached the service. Retrying after a timeout is different: the first attempt may have charged the card, so the call must be idempotent (see the circuit breaker and rate limiting lessons for retry storms).

    Scene: Payments 2 crashes again. Calls that hit it are retried on another instance, so almost no order fails.

    Key idea: Discovery is eventually right; retries on a different instance cover the gap while it catches up.

  8. 8. Server-side discovery

    The alternative is server-side discovery: Orders calls one stable name, and a load balancer run by the platform watches the registry and picks the instance. This is how a Kubernetes Service or a cloud internal load balancer works.

    Orders gets simpler: no discovery library, any language works. The cost is an extra network hop on every call (here about 6 ms per round trip) and one more component that must be highly available. Client-side discovery avoids the hop but needs a discovery library in every service.

    Scene: Orders now calls a platform load balancer by one stable name; the balancer watches the registry and picks an instance. Every call takes a few milliseconds longer because of the extra hop.

    Key idea: Client-side: callers choose the instance (no extra hop, smarter clients). Server-side: a balancer chooses (simple clients, one more hop).

  9. 9. Discovery in one picture

    Instances register on start, heartbeat while alive and deregister on a clean shutdown. Callers look up a name and cache the result, either in a client library (client-side) or through a platform balancer (server-side).

    Crashes are the hard case: the registry learns of them only by missing heartbeats, so there is always a stale window. Size it (interval × misses + refresh), keep it short, and let callers retry refused calls on another instance.

    Scene: Orders calls Payments through a platform load balancer that follows the service registry. Three Payments instances are healthy and heartbeating.

    Key idea: Register, heartbeat, deregister, look up; and plan for the stale window after a crash.