Service Discovery & Heartbeats
How services find each other when addresses keep changing, and how the system knows who's still alive.
Service discovery in 30 seconds
- Problem: in the cloud, service instances come and go and their addresses change — so how does one service find another?
- Answer: a registry (Consul, etcd, Eureka) where instances register themselves and callers look up healthy addresses.
- Heartbeats: each instance periodically says 'still alive'; miss a few and the registry drops it so nobody routes to a dead node.
- Two styles: client-side (caller asks the registry, then picks) vs server-side (a load balancer does the lookup for you).
- Health checks are the glue — discovery is only useful if 'registered' means 'actually working'.
Calling a friend whose number keeps changing
Imagine a friend who switches phone numbers every few days. If you'd scribbled their old number inside a book, you'd call it and reach a stranger — or nobody. The fix isn't to memorize numbers; it's to keep one contact entry that always holds their current number, and to have them update that entry whenever it changes. You look up the contact, not the number.
Service discovery is that shared contact list for a running system. Services are the friends with ever-changing numbers (network addresses), and the registry is the contact book that each service keeps up to date. Nobody hardcodes a number; everybody looks up the name. The rest of this page is really just two questions: how does the contact book stay current, and how does it know when a friend has gone silent for good?
Why we even need this — hardcoded addresses rot
In the old days you knew exactly where a service lived — a fixed server with a fixed address you could hardcode in a config file. That worked because the address never changed. Understanding why that's gone is the whole motivation for this topic.
- Autoscaling spins instances up when traffic rises and kills them when it falls — each with a fresh address.
- Containers get rescheduled onto different hosts when a node dies or is drained, landing on a new address.
- Deployments replace every old instance with a brand-new one — new process, new address.
- The result: the address you hardcoded yesterday points at nothing today. A static config file is out of date the moment you save it.
So services need a living, always-current directory of 'who's running and where,' kept honest by the things themselves rather than by a human editing a file. That directory is service discovery.
The registry: a phone book that updates itself
- Register: when an instance starts, it tells the registry 'I'm the Orders service, reachable at this address.'
- Look up: when a caller needs Orders, it asks the registry for the current healthy addresses.
- Deregister: when an instance shuts down (or dies), it's removed, so traffic stops going there.
- Stay current: the registry constantly reflects reality, not a config file someone forgot to update.
// On boot, announce 'I'm the Orders service, reachable here'
void onStartup() {
Instance self = new Instance(
"orders", // service name callers look up
InetAddress.getLocalHost(), // current, not-hardcoded address
8080);
registry.register(self);
// Cleanly leave the directory when we shut down
Runtime.getRuntime().addShutdownHook(
new Thread(() -> registry.deregister(self)));
}Heartbeats: how the system knows you're alive
A registry is only trustworthy if it drops dead instances quickly. That's the job of heartbeats:
- Each instance sends a small 'I'm alive' signal every few seconds.
- The registry expects these on a schedule.
- Miss a few in a row and the instance is marked unhealthy and pulled from the directory.
- No more traffic gets routed to it — automatically, without a human noticing first.
// Each instance pings the registry on a fixed schedule
scheduler.scheduleAtFixedRate(
() -> registry.heartbeat(self.id()), // 'still alive'
0, 3, TimeUnit.SECONDS);
// Client-side discovery: ask for live addresses, then pick one
List<Instance> healthy = registry.lookup("orders");
if (healthy.isEmpty()) {
throw new NoHealthyInstanceException("orders");
}
Instance target = loadBalancer.choose(healthy); // e.g. round-robin
response = httpClient.get(target.url() + "/orders/42");Heartbeats vs health checks — 'alive' isn't 'working'
A heartbeat proves an instance's process is running and can reach the registry. But running isn't the same as working. An instance can happily send heartbeats while its database connection is dead, its disk is full, or it's stuck in a loop returning errors. If 'registered' only meant 'the process is up,' callers would still be routed to a box that fails every request.
That's why real discovery pairs heartbeats with a health check: the instance (or the registry) actually exercises the thing — 'can you serve a real request right now?' — before declaring it healthy. The heartbeat is the pulse; the health check is the full physical.
// The registry calls GET /health on each instance periodically.
// Return 200 only if we can ACTUALLY do our job right now.
@GetMapping("/health")
public ResponseEntity<String> health() {
if (!database.canConnect()) // dependency we need to serve
return status(503).body("db down"); // unhealthy -> pull from pool
if (diskUsage() > 0.95) // no room to write
return status(503).body("disk full");
return ok("healthy"); // only now: safe to route traffic here
}
// A heartbeat alone would have said 'alive' in all three cases.The gap plain DNS can't fill
A fair question: DNS already maps names to addresses, and you've probably used it forever. Why not just put your services in DNS and be done? DNS is the oldest form of discovery, and for slow-changing things it's fine. But in a fast-churning cluster it has two gaps that bite hard:
- Caching makes it stale. DNS answers are cached all over the network with a TTL (time-to-live). When an instance dies, resolvers keep handing out its dead address until the TTL expires — so traffic flows to a corpse for seconds or minutes.
- It carries no health. Classic DNS returns addresses whether or not the thing behind them is actually working. It has no concept of 'this one is sick, skip it.'
- It's awkward to update fast. Registering and de-registering instances many times a minute isn't what DNS was built for.
A purpose-built registry closes exactly those gaps: near-instant updates, and — the crucial part — a notion of health so 'listed' means 'actually working.' That's why systems reach for Consul/etcd/Eureka instead of leaning on raw DNS for internal, fast-moving services.
# DNS hands out an address with a TTL, then everyone caches it.
orders.internal -> 10.0.0.7 (TTL 60s)
# t=0s instance 10.0.0.7 dies
# t=5s client resolves 'orders.internal' -> STILL 10.0.0.7 (cached!)
# -> connection refused, user sees an error
# t=60s TTL finally expires, cache refreshes, dead address drops out
# A registry with heartbeats would have evicted 10.0.0.7 in ~seconds,
# because it knows HEALTH, not just a name->address mapping.Client-side vs server-side discovery
Once you have a registry, there's one more design choice: who actually does the lookup before a call? There are two styles, and they trade simplicity against control.
| Style | Who does the lookup | Pros | Cons |
|---|---|---|---|
| Client-side | The calling service queries the registry and picks an instance. | Fewer hops; client controls the choice. | Every client needs discovery logic baked in. |
| Server-side | A load balancer / gateway does the lookup; clients just call it. | Clients stay dumb and simple. | The balancer is an extra hop and must be highly available. |
Choosing how to do discovery
Putting it together, here's a quick guide to which mechanism fits which situation:
| Your situation | Reach for | Why |
|---|---|---|
| Slow-changing, external-facing hosts | Plain DNS | Simple, universal; staleness doesn't bite when addresses rarely change. |
| Fast-churning internal microservices | A registry (Consul/etcd/Eureka) + heartbeats | Near-instant updates and real health checks keep the directory honest. |
| Many client languages / external callers | Server-side discovery (load balancer) | Clients stay dumb — they just hit one stable address. |
| One-language shop, latency-sensitive | Client-side discovery (shared library) | Fewer hops; the caller picks the instance itself. |
| Large, polyglot fleet, zero-trust | Service mesh (sidecar proxies) | Gets server-side simplicity with client-side locality, plus mTLS. |
Service discovery is the piece that makes the whole 'cloud is elastic' promise actually usable — without a living directory of who's running and where, nothing could find anything once addresses stopped being fixed.
Why it matters
- It's what lets instances scale up, scale down, and get rescheduled without anyone hand-editing a config file.
- Paired with heartbeats, it keeps traffic flowing only to instances that are genuinely alive and healthy.
- It's the quiet foundation under load balancing, deployments, and failover in any dynamic environment.
If ignored
- Requests get routed to dead or drained instances, so users hit errors while everything 'looks' deployed.
- Hardcoded addresses rot the instant autoscaling or a container reschedule moves a service.
- Deploys turn fragile and manual, because adding or removing a node means touching configuration by hand.
Where it fits
- Sits in the routing layer, between a caller and the pool of instances it's trying to reach.
- Lives in a registry (Consul, etcd, Eureka) plus the health-checking that keeps it honest.
- Shows up the moment instances become ephemeral — which in the cloud is essentially always.
Related topics
- Load balancing: server-side discovery hides the registry behind a balancer
- DNS: the oldest form of discovery — mapping a name to current addresses
- Circuit breaker: discovery drops dead nodes; the breaker handles the dying ones
- Availability & reliability: the heartbeat window is the same fast-detection-vs-false-alarm trade
Interview lens
Questions it unlocks
- How do microservices find each other when instances keep changing?
- How does the system know an instance has died?
- Client-side or server-side discovery — what's the difference?
60-second answer
In the cloud, instances and addresses change constantly, so services find each other through a registry — Consul, etcd, Eureka — where instances register and callers look up current healthy addresses. Heartbeats keep it honest: each instance signals it's alive, and missing a few gets it dropped so no traffic goes to a dead node. I'd tune the heartbeat window to balance fast detection against false evictions. For the lookup, client-side means the caller queries the registry directly; server-side hides it behind a load balancer so clients stay simple. Health checks are what make 'registered' actually mean 'working'.
Common traps
- Hardcoding addresses in a world where instances are ephemeral.
- Setting heartbeat thresholds that either flap or keep routing to dead nodes.
- Treating 'registered' as 'healthy' without real health checks.