Distributed patterns and operations
Service discovery
Explain how services find each other when instances change every few minutes, compare client-side, server-side, DNS and mesh approaches, and plan for stale data.
The problem
An orders service needs to call a payments service. On a small, static fleet the answer sits in a configuration file: payments.host = 10.0.3.17. There are three payments machines, and they keep their addresses for years. When one is replaced, someone edits the file and redeploys.
Then the fleet moves to containers and autoscaling. Payments runs as 12 instances at night and 60 at the midday peak. Each deploy replaces every instance, and each new instance gets a new IP address. A spot instance on AWS can be reclaimed with two minutes’ notice. An address is now valid for hours or minutes, and the configuration file is wrong before it has finished rolling out.
Teams tried to patch the old model. Configuration management pushed a fresh host list every half hour, which left a half-hour window of calls to machines that had gone. Others put a load balancer with a fixed name in front of every service. That works and is still common, but it moves the question: now the load balancer has to learn which instances exist.
Service discovery answers “where is payments right now?” automatically. It has three parts: a registry of live instances, a way for instances to get into and out of it, and a way for callers to use it.
The registry
A service registry maps a service name to the instances currently able to serve it: address, port, and often metadata such as zone and version. Consul, etcd, ZooKeeper and Netflix’s Eureka are used as registries, and Kubernetes has one built into its control plane.
Instances get into the registry in one of two ways:
- Self-registration. The instance registers when it starts, sends heartbeats, and deregisters when it shuts down. Every service needs the code, and a crashed instance cannot deregister itself.
- Third-party registration. The platform that started the instance registers it. Kubernetes works this way: it launched the pod, so it knows the pod’s address and state.
Every call path now depends on the registry, so it runs as a replicated cluster. Consul, etcd and ZooKeeper use consensus and prefer consistency: nodes cut off from the majority refuse writes. Eureka makes the opposite choice and keeps answering from data that may be stale, since an old list of addresses is more useful than none.
Health checks
An entry is only useful if the instance behind it can serve. There are two ways to find out:
- Heartbeats. The instance tells the registry that it is alive every few seconds, and the entry expires after several missed beats. Eureka’s defaults are a heartbeat every 30 seconds and removal after 90 seconds without one.
- Active checks. The registry, the platform or the load balancer calls a health endpoint on the instance. Kubernetes readiness probes work this way: a pod that fails its readiness probe is taken out of the Service’s endpoints without being restarted.
What the check tests matters. A check that only proves the process is running keeps sending traffic to an instance that cannot do its job. A check that tests every dependency fails in a worse way: when a shared database slows down, every instance fails its check at once and the registry empties, turning a partial problem into a total outage. A sensible middle is to check what is local to the instance, and to let callers’ timeouts and circuit breakers deal with shared dependencies.
Client-side and server-side discovery
In client-side discovery the caller asks the registry for the instances, caches the list, and chooses one itself.
Step 1 of 8
The payments service runs as two instances. When each one started, it registered its address with the registry. Instance C does not exist yet.
Read the steps as text
- The payments service runs as two instances. When each one started, it registered its address with the registry. Instance C does not exist yet.
- Each instance sends the registry a heartbeat every few seconds. The registry keeps an entry only while its heartbeats keep arriving.
- The orders service needs to call payments. It asks the registry for the name and gets back both addresses, which it caches so that it does not have to ask before every call.
- Orders picks an instance from its list and calls it directly, then picks the other one for the next call. No load balancer sits in the path. This is client-side discovery.
- Traffic grows and the autoscaler starts instance C. It registers itself, and orders learns about it at its next refresh. Nobody edited a configuration file.
- Instance A is killed without warning, so it never deregisters. The registry still lists it, and will keep listing it until enough heartbeats have been missed.
- Orders still has A in its cached list and sends it a request. The connection fails. Orders retries on B, which succeeds, and stops choosing A for now.
- The registry expires A after the missed heartbeats, and the next refresh removes it from the cached list. Discovery data is always slightly out of date, so callers need timeouts and a retry on a different instance.
There is no extra hop and no shared load balancer to scale, and the caller can balance intelligently: prefer its own zone, avoid an instance that has just failed, pick the one with the fewest requests outstanding. The cost is discovery logic in every service, in every language you use, all kept up to date. Netflix’s Eureka with its Ribbon client library is the classic example, and gRPC’s built-in load balancing follows the same pattern.
In server-side discovery the caller sends requests to one stable address, and a load balancer behind that address knows the instances. Callers stay simple and can be written in anything. The cost is usually an extra network hop, and a component that must itself be scaled and highly available. An AWS Application Load Balancer with a target group is this pattern.
| Client-side | Server-side | |
|---|---|---|
| Who picks the instance | The caller | A load balancer or proxy |
| Extra hop | No | Usually |
| Caller needs | A discovery library | One stable address |
| Choose it when | High-volume internal calls on one technology stack | Mixed languages, external callers, a small platform team |
DNS as discovery
DNS is the registry everyone already has. Publish an A record per instance, or SRV records when ports differ, and every language can look the name up. Consul and Kubernetes both expose their registries through DNS for this reason.
Its weakness is caching. A DNS answer carries a time to live (TTL), and every layer may cache the answer for that long or longer:
- A TTL of 60 seconds means up to 60 seconds of calls to an address that has gone. A TTL of 5 seconds multiplies the query load on your DNS servers.
- Some clients do not honour the TTL. The JVM keeps its own cache: OpenJDK holds successful lookups for 30 seconds by default, and for ever when a security manager was installed, which caught out many older deployments.
- Connection pools make the TTL irrelevant. A caller that holds long-lived connections never looks the name up again, so it never sees new instances.
DNS suits names that change slowly, such as a load balancer’s address. It is a poor way to track instances that come and go every few minutes.
Kubernetes Services
Kubernetes combines several of these ideas. A Service gives a set of pods a stable virtual IP and a DNS name such as payments.shop.svc.cluster.local. The control plane watches pod readiness and keeps the addresses of ready pods in EndpointSlice objects. On every node, kube-proxy turns that list into packet-forwarding rules in the kernel, so that a connection to the virtual IP is rewritten to one of the pod IPs.
To the caller this is server-side discovery behind a stable name. The rewriting happens on the caller’s own node, so no separate load balancer sits in the path.
The catch is that the choice is made per connection and not per request. A gRPC or HTTP/2 client that keeps one long-lived connection sends everything to one pod, however many replicas exist. The usual fixes are a headless Service, which makes DNS return the pod IPs so that the client can balance for itself, or a service mesh.
Service mesh sidecars
A service mesh places a proxy, commonly Envoy, beside every instance. The application calls the destination by name. The sidecar intercepts the call, chooses a healthy instance from a list pushed to it by the mesh’s control plane, and balances per request. Retries, timeouts, mutual TLS and metrics are applied in the same place.
This gives the smart balancing of client-side discovery with no library in the application. You pay with added latency (a call usually passes through a proxy on each side), memory and CPU for every sidecar, and a control plane to operate.
Failure modes
- Stale entries. An instance dies and stays listed until its heartbeats time out, and callers hit a dead address. Use short connection timeouts, retry on a different instance (see retries and timeouts), and eject an instance that keeps failing without waiting for the registry.
- Deploys. An instance that exits the moment it is told to stop drops requests from callers that have not yet heard. Deregister first, wait for the change to spread, finish the requests in flight, and then exit.
- Registry outage. If callers ask the registry before every call, its outage is everyone’s outage. Callers should keep the last list they received and carry on using it. Existing traffic continues, although new instances cannot register until the registry returns.
- Mass expiry. A network fault between the registry and the fleet looks, from the registry, like every instance dying together. Deleting them all would turn a monitoring problem into an outage. Eureka’s self-preservation mode stops expiring entries when too many heartbeats go missing at once.
In the interview
Any design with several services and autoscaling must answer “how does A find B?”. Usually one sentence is enough: “services run on Kubernetes and call each other through Services”, or “each service sits behind an internal load balancer that tracks healthy targets”.
Go deeper when the interviewer asks about failure. A strong answer names the registry and how instances enter and leave it, says whether the caller or a proxy picks the instance and why, and then deals with staleness: the list is always a little out of date, so callers use timeouts, retry on another instance, and keep a cached list if the registry is down. Mention the per-connection balancing trap if you have proposed gRPC over Kubernetes Services.
Key takeaways
- With autoscaling and frequent deploys an instance address lives for minutes, so addresses cannot sit in configuration files.
- A registry maps a service name to the instances that are currently healthy, kept up to date by registration and health checks.
- Client-side discovery has no extra hop and needs a library in every caller. Server-side discovery keeps callers simple and adds a load balancer to run.
- DNS works everywhere and goes stale through TTL caching, clients that ignore TTLs and long-lived connections.
- A Kubernetes Service gives a stable virtual IP and name, and balances per connection, which misleads gRPC and HTTP/2 clients.
- Discovery data is always slightly out of date, so callers need timeouts, retries on a different instance and a cached list that survives a registry outage.
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
What three parts make up service discovery?
A registry of live instances, a way for instances to enter and leave it (registration and health checks), and a way for callers to look up and choose an instance.
Client-side and server-side discovery: who chooses the instance?
In client-side discovery the caller reads the registry and chooses. In server-side discovery the caller uses one stable address, and a load balancer or proxy chooses.
Why is DNS a weak way to track individual instances?
Results are cached for the TTL or longer, some clients ignore the TTL, and long-lived connections never look the name up again. DNS also carries no load information.
What does a Kubernetes Service provide?
A stable virtual IP and DNS name for a set of pods. The control plane tracks ready pods, and kube-proxy on each node rewrites connections to the virtual IP so that they reach one of them.
What does a service mesh sidecar add to discovery?
A proxy beside each instance that receives the instance list from a control plane and balances per request, with retries, timeouts and mutual TLS, and no discovery library in the application.
How should callers cope with a stale registry entry?
Short connection timeouts, a retry on a different instance, and temporarily ejecting an instance that keeps failing. On a registry outage, keep using the last known list.