Service discovery
medium 30 minService discovery turns a service name into the address of a running, healthy copy of that service.
See it run
From registering to calling, what a crash does to the list, and how to leave without a failed request.
Operations
Register, discover, call
Client-side discovery from the start of an instance to the answer.
Step 1 of 6
Instances register
Registry: healthy
10.0.0.1 · 10.0.0.2
User A and user B tell the registry their name and address, and their first checks pass.
Step 1: Instances register
registry.register("user-service", host, port)def call(path): instances = cache.get("user-service") # asks every 30 s chosen = instances[turn() % len(instances)] return http.get(chosen.address + path, timeout=3)- Extra hop
- None
- List can be old by
- Cache time
- Server-side
- one hop more, simpler caller
Stress that the registry is not on the path of each call. Only the list comes from it.
In the real world
The same service discovery doing real jobs. Pick one and step through it.
What still works, and what does not.
Step 1 of 4
Normal
Registry: healthy
10.0.0.1 · 10.0.0.2
Caller's list
10.0.0.1 · 10.0.0.2
The caller refreshes its list every 30 seconds.
Step 1: Normal
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A lookup on every call
majorThe registry becomes a bottleneck and a single point of failure for every request.
Wronginst = registry.lookup("user") # each callRightinst = choose(cache.get("user")) # refreshed in the backgroundA shared dependency in the liveness check
criticalWhen it fails, every instance is restarted or removed together.
Wrongdef live(): return db.ping() and cache.ping()Rightdef live(): return event_loop_responds()Stopping without leaving the list
criticalCallers send to a closed port until their lists are fresh.
Wrongon_sigterm = exitRightdef on_sigterm(): deregister(); drain(35); exit()Round robin from the clock
minorA hash of the current time is a poor random choice, not turn by turn.
Wrongidx = hash(datetime.now()) % len(instances)Rightidx = next(counter) % len(instances)
Interview tips
How to explain it
- A name becomes the address of a healthy instance.
- Register, check, discover, choose.
- The registry gives directions, it does not carry traffic.
Memory trick: RDHL
- Register: the service joins.
- Discover: the client finds it.
- Health: check the status. Load balance: select one.
Always say
- How old the list can be.
- Retry on a different instance.
- Deregister, drain, stop.
Watch out for
- DNS answers that are kept too long.
- Checks that test shared dependencies.
- Long connections that stay on one instance.