SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
  • Service Discovery
  • API Gateway Pattern
  • Backend for Frontend (BFF)
  • Sidecar Pattern
  • Circuit Breaker
  • Bulkhead
  • Strangler Fig
  • Service Mesh
  • Database per Service
  • Timeouts and Deadlines
  • API Composition
  • Anti-Corruption Layer
  • Ambassador Pattern
  • Idempotent Consumer and Inbox Pattern
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Architecture/Microservices Patterns

Service Discovery

How services find each other when machines and addresses keep changing.

⏱ 13 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Service discovery is how one service finds the current address (IP and port) of another service, when those addresses keep changing.

  • In the cloud, instances start, stop, crash and scale all day. Their addresses are not fixed.
  • Each instance registers itself in a service registry and sends regular "I am alive" heartbeats.
  • A caller asks the registry (or a load balancer that uses it) for the healthy instances, instead of using a hard-coded list.

02Concept: What is it?

In a monolith, one part calls another by a normal function call. In microservices, the Orders service must call the Payments service over the network. To do that it needs an address, such as 10.0.3.17:8080.

You could write that address in a config file. But in the cloud there may be ten Payments instances today and thirty tomorrow. Containers get new IP addresses each time they restart. Autoscaling adds and removes machines. A fixed list is wrong within minutes.

The fix is a service registry: a small, fast database of "service name β†’ list of live instances". Instances register when they start, send heartbeats while they run, and are removed when the heartbeats stop (or when they shut down cleanly). Callers use the name ("payments"), and discovery turns it into a real address.

The registry flow
πŸ’³Payments instancesstart and stop often
→↓1. register + heartbeat
πŸ“’Service registrypayments β†’ 3 addresses
←2. who is payments?
πŸ“¦Orders servicethe caller
↓3. call one of the addresses directly
Three steps: register, ask, call. The registry is only a phone book. The real traffic goes straight to the service.
🧠Names, not addresses
Code should say "call payments", never "call 10.0.3.17". Discovery is the layer that turns the name into a live address.

03Real-Life Example

🍡The Phone Book of a Busy Restaurant Chain
A restaurant chain opens and closes branches all the time. A delivery rider cannot memorise every address. So the chain keeps one live directory at head office. When a new branch opens it calls head office to be added. Every few minutes it sends a short message, "still open". If the messages stop, head office removes the branch. A rider who needs "a pizza branch near me" asks head office and gets only the branches that are open now.
Restaurant chain
Service discovery
Head office directory
Service registry (Consul, Eureka, etcd, ZooKeeper)
A new branch calls to be listed
Instance registers itself on start-up
β€œStill open” message every few minutes
Heartbeat
No message for a long time, branch removed
Heartbeat timeout (TTL) removes the instance
Rider asks head office for open branches
Client queries the registry
Rider picks any open branch
Client-side load balancing
A branch that closed but is still listed
A stale registry entry
The life of an instance
πŸš€Startget IP and port
→↓
πŸ“Registername + address
→↓
πŸ’“Heartbeatevery few seconds
→↓
πŸ‘‹Stopderegister, or timeout

04Why Do We Need It?

πŸ”„Addresses change
Containers and VMs get new IPs on every restart or deploy. A fixed list goes out of date quickly.
πŸ“ˆAutoscaling works
New instances join the pool by themselves and get traffic. Removed ones leave without breaking callers.
🩺Skip dead instances
Failed health checks or missing heartbeats take an instance out of the list, so fewer requests hit a dead target.
🚫No hard-coded config
No more editing config files and redeploying every caller when a service moves.
βš–οΈSpread the load
With a list of live instances, a client or proxy can share requests between them.
🌍Many places
The same name can point to different instances in different zones or regions.
In a system where machines come and go, you need a live directory. Service discovery is that directory.

05Where Do We Use It?

🧩Microservices
Service-to-service calls inside the same system. This is the main use.
☸️Kubernetes
A Service object plus built-in DNS gives each service a stable name (like payments.default.svc), and tracks the Pods behind it.
☁️Cloud load balancers
Target groups register and remove instances, using health checks.
πŸ•ΈοΈService meshes
The mesh control plane knows every instance and tells the proxies where to send traffic.
πŸ—„οΈDatabases and caches
Finding the current primary or the nodes of a cluster after a failover.
🌐Public DNS
The oldest form of discovery: a name turns into addresses. Useful, but slow to change because of caching.

06Types / Parts / How It Works

Client-side vs server-side discovery

Who does the lookup?
Client-side discovery
πŸ“¦Callerasks, then picks one
↑list
↓call
πŸ“’Registry
πŸ’³Servicedirect call
Server-side discovery
πŸ“¦Callerknows only one name
↓call the name
βš–οΈLoad balancer / proxyasks the registry, picks one
↓forward
πŸ’³Service
Caller Registry / proxy Service instance
Both use a registry. The difference is who asks it and who picks the instance.
StyleHow it worksGoodBad
Client-sideThe caller queries the registry and chooses an instance (Netflix Eureka with Ribbon, gRPC client-side balancing)One less hop. Smart choices are possible.Every language needs discovery code. Clients must be kept up to date.
Server-sideThe caller sends to a fixed address. A load balancer or proxy looks up the instances (AWS ALB, Kubernetes Service, NGINX)Callers stay simple and language-free.An extra hop, and the proxy must be highly available.

How instances get into the registry

PatternWho registersExample
Self-registrationThe service registers and sends heartbeats itselfA Spring Boot app with Eureka client
Third-party registrationA separate agent watches the platform and updates the registryKubernetes (the control plane tracks Pods), Registrator for Docker

Common registry tools

ToolNotes
ConsulRegistry with health checks, key-value store and DNS interface
EurekaNetflix registry. Favours availability, so it can show stale data during a network split.
etcd / ZooKeeperStrongly consistent stores. Often used under the hood (Kubernetes uses etcd) or for leader election.
Kubernetes DNSBuilt in. A Service name resolves to a stable virtual IP or to the Pod addresses.
Cloud Map / DNS-basedManaged services from cloud providers, or plain DNS with a short TTL.
VisualizerFixed address list vs service registryCrash an instance, then send requests with each mode. Add a new instance and see who uses it. Turn the heartbeat timeout up and watch stale entries last longer.
How does the client find the payments service?
Clock: 0 s
πŸ“±Clientasks the registry
πŸ“’ Service registry
payments-1beating
payments-2beating
payments-3beating
🟒payments-1running
in registry
in config
client uses it
🟒payments-2running
in registry
in config
client uses it
🟒payments-3running
in registry
in config
client uses it
In registry
3
3 really running
Client targets
3
from registry
Succeeded
0
requests
Failed
0
requests
Three payment instances are running. Try crashing one, adding a new one, or sending requests. Press Play to let the clock run so the registry can notice a crash.

A simplified model. Running instances send heartbeats all the time. A crashed one stops, and the registry removes it after the timeout. The client rotates through its targets in order (round-robin). A real client may also retry on another instance, which hides most of the stale window.

07How to Use It / Steps / Implementation

Setting up discovery

  1. 1
    Give each service a name
    Use stable logical names such as payments or orders. These are what code refers to.
  2. 2
    Pick a registry or use the platform
    On Kubernetes, use Services and cluster DNS. Elsewhere use Consul, Eureka or a cloud service.
  3. 3
    Register on start, deregister on stop
    Register only when the instance is truly ready to take traffic. On a clean shutdown, remove it first, then finish in-flight requests.
  4. 4
    Add health checks
    Heartbeats prove the process is alive. A health endpoint proves it can do work (database reachable, caches warm).
  5. 5
    Choose the lookup style
    Client-side for small, single-language systems. Server-side or a mesh when many languages share the platform.
  6. 6
    Handle stale data
    Clients should use short timeouts, retry on another instance, and cache the list for a short time, so a registry outage does not stop traffic.
  7. 7
    Keep the registry highly available
    Run it as a cluster (3 or 5 nodes). If it is a single machine, you have created a new single point of failure.
πŸ’‘Keep a last-known list
A good client caches the last answer. If the registry is briefly unreachable, the client keeps using the cached list instead of failing every call.
⚠️Not ready is not the same as alive
A process can be running while its database connection is still opening. If it registers too early, it gets traffic it cannot serve. Use a readiness check, separate from a liveness check.

08Key Terms to Know

TermMeaning in easy words
Service registryA database of service names and their live instance addresses
RegistrationAn instance adds its name and address to the registry
DeregistrationRemoving an instance from the registry, on shutdown or after it fails
HeartbeatA small, regular message that says the instance is still alive
TTL (time to live)How long the registry waits without a heartbeat before it removes an instance
Health checkA test that shows whether an instance can do real work, not just that it runs
Client-side discoveryThe caller queries the registry and picks an instance itself
Server-side discoveryA load balancer or proxy queries the registry for the caller
Service nameA stable logical name (payments) that callers use instead of an IP address
Stale entryA registry record for an instance that is already gone
Readiness vs livenessReady: can take traffic now. Live: the process is running and not stuck.

09Pros, Cons and Trade-offs

βœ… Pros
  • Callers never need hard-coded addresses
  • Scaling out and in works automatically
  • Dead instances are removed from traffic
  • Enables load balancing and zero-downtime deploys
  • Works across zones and regions
⚠️ Cons
  • Another critical system to run and keep available
  • Stale entries cause failed calls for a short time
  • Client-side discovery adds code to every language
  • Debugging is harder when addresses keep changing
  • Wrong health checks can remove healthy instances

Trade-offs

ChoiceWe gainWe lose
Short heartbeat timeoutDead instances disappear quicklyHealthy instances can be removed by a short network glitch
Long heartbeat timeoutStable list, few false removalsCallers hit dead instances for longer
Client-side discoveryNo extra hop, smart routingLibrary code in every service
Server-side discoverySimple clientsAn extra network hop and a proxy to maintain
Consistent registry (etcd, ZooKeeper)Everyone sees the same listMay refuse requests during a network split
Available registry (Eureka style)Always answers, even if the data is oldCallers may see outdated instances

10Common Problems and Mistakes

Common mistakes

  1. Hard-coding addresses "just for now". It stays for years, and breaks at the first scale-up.
  2. One registry node. If it fails, new lookups fail and the whole system can stall.
  3. Registering before ready. The new instance receives traffic while it is still warming up.
  4. Heartbeat only, no real health check. A stuck process can still send heartbeats while serving errors.
  5. No client retries. One stale entry then becomes a user-visible error.
  6. Relying on DNS with long TTLs. Clients and libraries cache answers, so changes spread slowly.
  7. Ignoring shutdown. If an instance stops without deregistering, callers still send it requests until the timeout.

Things to watch

πŸ‘»Stale entries
Dead instances remain listed for the TTL. Use retries, short timeouts and passive health checking.
🌩️Registry outage
Cache the last good list in clients and run the registry as a cluster.
🐘Thundering herd
After a restart every service re-registers and re-queries at once. Add jitter and backoff.
βœ‚οΈNetwork split
Part of the fleet cannot reach the registry and may be removed even though it is fine. Some tools have a self-preservation mode for this.

11Real-World Examples

🎬Netflix
Built Eureka for its AWS microservices, with client-side load balancing in the caller.
☸️Kubernetes
Every cluster has built-in discovery: Services, endpoints and cluster DNS, backed by etcd.
🏒HashiCorp Consul
A popular registry with health checks, used across data centres and for service meshes.
☁️AWS
Load balancer target groups and AWS Cloud Map track instances and run health checks for you.
πŸ•ΈοΈService meshes
Istio and Linkerd give every proxy a live list of endpoints from the platform.
🌐DNS itself
The first and most widespread discovery system, still used with short TTLs and SRV records.
πŸ“Note
Tool details change between versions. Check the current documentation before choosing timeouts and modes.
Mini case: Kubernetes, server-side discovery
πŸ“¦orders Podcalls http://payments
→↓DNS name
🧭payments Servicestable virtual address
→↓live Pods only
πŸ’³3 payments Podsready ones only
The caller only knows the name. The platform keeps the list of live Pods and spreads the requests.

12Related Topics to Read Next

Microservices→

The main reason discovery is needed.

What are Load Balancers?β†’

Server-side discovery is often a load balancer with a live target list.

DNS→

The original discovery system, and the base of many modern ones.

Service Mesh→

Makes discovery, routing and retries part of the platform.

Circuit Breaker→

Protects callers when a discovered instance keeps failing.

API Gateway Pattern→

Uses discovery to route outside requests to inner services.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: a live directory that turns a service name into healthy instance addresses.
  • βœ”Why: in the cloud, instances and IPs change all the time. Hard-coded lists break.
  • βœ”Flow: register β†’ heartbeat β†’ query β†’ call. No heartbeats means removal.
  • βœ”Client-side: the caller picks the instance. Server-side: a proxy or load balancer picks it.
  • βœ”Tools: Kubernetes Services and DNS, Consul, Eureka, etcd, ZooKeeper, cloud load balancers.
  • βœ”Health: use readiness (can serve now) and liveness (not stuck). Do not register before ready.
  • βœ”Risks: stale entries, registry outage, thundering herd. Use retries, caching and a clustered registry.
  • βœ”One line: β€œCall the name, not the address, and let a live directory find the instance.”
← Previous
Cloud Basics: Regions, Zones and Edge
Next β†’
API Gateway Pattern