Service Discovery
How services find healthy instances of each other when IPs change constantly.
What is it?
In a modern backend, services run as many instances that come and go: autoscaling adds them, deploys replace them, crashes remove them. Their IP addresses change all the time. Hard-coding "orders service is at 10.0.3.17" doesn't work.
Service discovery answers "where are the healthy instances of service X right now?" It has three parts:
- A service registry: a database of available instances and their addresses (Consul, etcd, ZooKeeper, Eureka, or Kubernetes' own API). - Registration: instances (or the platform) add themselves when they start and are removed when they stop or fail. - Health checks: so unhealthy instances are taken out of rotation.
There are two styles: client-side discovery, where the caller queries the registry and picks an instance, and server-side discovery, where the caller talks to a stable address (a load balancer or proxy) that does the lookup for it.
Explain like I'm 10
Service discovery is a hotel's front desk. Guests change rooms all the time, so instead of memorizing room numbers you ask the desk 'where's Ms. Lee?' Client-side discovery is getting the room number and walking there yourself; server-side discovery is the desk transferring your call.
Examples
Kubernetes: a stable DNS name for changing pods
apiVersion: v1
kind: Service
metadata:
name: orders
namespace: shop
spec:
selector:
app: orders # any pod with this label is a backend
ports:
- port: 80
targetPort: 8080
---
# Other pods call it by name; DNS resolves to the Service's virtual IP,
# and traffic is spread across Ready pods matching the selector:
# http://orders.shop.svc.cluster.local
# http://orders (from inside the same namespace)Kubernetes is a built-in registry. The Service gets a stable name and virtual IP, and only pods passing their readiness probe receive traffic. This is server-side discovery from the caller's point of view.
Client-side discovery (pseudo-code)
async function callOrders(path) {
// Registry returns only instances passing health checks.
const instances = await registry.getHealthyInstances("orders"); // cached, refreshed via watch
if (instances.length === 0) throw new Error("No healthy orders instances");
const instance = pickRoundRobin(instances); // client does the load balancing
return http.get("http://" + instance.host + ":" + instance.port + path);
}The caller asks the registry (for example, Consul) and balances load itself. No extra network hop, but every client needs this logic, in every language.
How it works
Registration happens in one of two ways:
- Self-registration: the instance calls the registry on startup and sends heartbeats; if they stop, its entry expires. - Third-party registration: the platform (Kubernetes, a Consul agent, ECS) watches instances and registers them. Application code stays unaware.
Health checks keep the registry honest. A registry or agent probes an HTTP endpoint, TCP port or script, or expects heartbeats. Kubernetes separates liveness probes (restart the container if it fails) from readiness probes (stop sending traffic until it passes). Readiness should reflect whether the instance can serve now; liveness should only fail if a restart would actually help.
Client-side discovery: the client queries the registry (usually caching results and watching for changes) and load-balances itself. Fewer hops and smarter balancing, but discovery logic must exist in every client library. Netflix's Eureka with the Ribbon client is the classic example.
Server-side discovery: the client calls a stable address; a load balancer, proxy or the platform resolves instances. Kubernetes Services, AWS load balancers and service meshes work this way. Clients stay simple; you add a hop and a component to operate.
DNS-based discovery (Consul's DNS interface, Kubernetes DNS) is universal because every language can resolve names. But DNS answers are cached (by TTL, and sometimes by runtimes for longer than the TTL), so changes propagate slowly, and DNS has no notion of load or health beyond what the server filters.
Registries need strong consistency, so Consul and etcd use the Raft consensus algorithm across 3 or 5 servers; etcd is also where Kubernetes stores its cluster state.
Client-side discovery Server-side discovery
Client --1. lookup "orders"--> Registry Client --request--> Load balancer / proxy
Client <--[10.0.1.4, 10.0.2.9]-- (stable address) |
Client --2. request--> 10.0.2.9 lookup ---> Registry
|
LB --forward--> 10.0.2.9
Registration and health
Instance --register + heartbeat--> Registry <--probe /health-- Health checker
(Raft cluster: 3 or 5 nodes)Why does it exist?
Static configuration breaks as soon as instances become ephemeral. Without discovery, every scale-up, deploy or crash would need someone to update config files, and traffic would be sent to dead instances in the meantime.
When to use it
Any system with more than a handful of services, autoscaling, or frequent deploys needs some form of discovery. On Kubernetes, use its built-in Services and DNS first. Outside Kubernetes, or across clusters and VMs, a registry like Consul fits. Choose client-side discovery when you need smart client load balancing and control every client; server-side when clients are diverse or should stay simple.
When not to use it
A small system with a few long-lived servers can use a load balancer with a fixed DNS name. Don't run a separate Consul cluster inside Kubernetes just for discovery the platform already provides, unless you need cross-cluster or cross-platform discovery.
Common mistakes
Making the readiness or liveness check depend on downstream services, so one database blip marks every instance unhealthy at once.
Treating liveness and readiness as the same check, causing restart loops for instances that were only temporarily busy.
Ignoring client-side DNS caching, so callers keep using IPs of instances that no longer exist.
Running a registry as a single node, making discovery itself a single point of failure.
Not draining connections on shutdown, so in-flight requests fail during every deploy before the registry catches up.
Practice exercises
- Easy:
Explain the difference between a Kubernetes liveness probe and a readiness probe, with an example where only one should fail.
- Medium:
Compare client-side and server-side discovery for a company with services in Go, Java, Python and Node.js. Which would you choose and why?
- Hard:
Design discovery for services spread across two Kubernetes clusters and a fleet of legacy VMs, including how health is checked and how failover works.
Interview questions
What problem does service discovery solve?
Finding the current network locations of healthy instances of a service when instances are created, moved and destroyed dynamically, so callers don't depend on hard-coded addresses.
Client-side vs server-side discovery?
Client-side: the caller queries the registry and chooses an instance itself. Fewer hops and smarter balancing, but logic in every client. Server-side: the caller hits a stable load balancer or proxy that resolves and routes. Simpler clients, at the cost of an extra hop and component.
What is a service registry, and give examples?
A database of available service instances and their addresses, usually with health status. Examples: Consul, etcd, ZooKeeper, Netflix Eureka, and the Kubernetes API (Endpoints/EndpointSlices).
Self-registration vs third-party registration?
With self-registration, each instance registers and heartbeats itself. With third-party registration, a platform or agent watches instances and registers them, so application code stays unaware of the registry.
How does service discovery work in Kubernetes?
A Service selects pods by label and gets a stable virtual IP and a DNS name like name.namespace.svc.cluster.local. The control plane tracks Ready pods in EndpointSlices, and kube-proxy (or a CNI equivalent) routes traffic to them. Headless Services return pod IPs directly via DNS.
What's the difference between liveness and readiness probes?
Liveness asks 'is this process stuck and in need of a restart?' Readiness asks 'should this instance receive traffic right now?' A starting or temporarily overloaded instance should fail readiness, not liveness.
What are the downsides of DNS-based discovery?
Caching: clients and runtimes may hold stale records past the TTL, so traffic keeps going to dead instances. DNS also doesn't carry load information, and clients often pin to one resolved IP for long-lived connections.
Why do Consul and etcd use consensus?
The registry must give a consistent view and survive node failures. Raft replicates the data across a majority of servers, so a 3-node cluster tolerates 1 failure and a 5-node cluster tolerates 2.
Why shouldn't a health check call the database?
If the database has a brief issue, every instance fails its check at once and gets pulled from rotation (or restarted), turning a partial degradation into a full outage. Health checks should mostly reflect the instance itself; handle dependency failures with timeouts and circuit breakers.
How does a service mesh change discovery?
A sidecar proxy next to each instance gets endpoint lists from the mesh's control plane and does load balancing, retries and mTLS. The application calls a simple name; discovery becomes client-side in the proxy but invisible to app code.