How to Implement Service Discovery
Let services find each other: use DNS or a registry, resolve at call time, cache with a TTL, and handle the instance that has gone away.
On this page
Introduction
In a dynamic environment, the instances of a service change: a deploy replaces them, an autoscaler adds them, a crash removes them. A client that hardcodes an address or resolves a name once at startup keeps sending traffic to instances that no longer exist. Service discovery is the mechanism that lets a client find the current instances at the time of the call, whether by DNS or by a registry.
This tutorial covers choosing discovery by DNS or a registry, resolving at call time, caching with a TTL and failing over, and testing the instance churn. The examples use HTTP clients and a DNS resolution, and the design applies to any dynamic service.
Choose DNS or a registry
DNS gives a service a stable name that resolves to its current instances. It is universal and needs no extra infrastructure, but the resolution is cached with a TTL, so a change takes up to the TTL to propagate. A registry, such as Consul or the Kubernetes service API, tracks the live instances, often with a health check, and can be queried for the healthy set, which reflects the churn faster.
Choose by the dynamism. A service with a stable set of instances can use DNS and a moderate TTL. A service whose instances change often, or that needs to know the healthy instances, benefits from a registry. The registry adds infrastructure and a dependency, so use it when the churn or the health-awareness justifies it, not by default.
Resolve at call time, not at startup
Resolve the service name to the current instances when the call is made, not once at startup. A resolution cached forever or held in a static variable becomes wrong as the fleet changes, and the client sends traffic to instances that are gone. Resolve at the call, or cache with a short TTL and refresh, so the current set is used.
The client should hold a small, refreshed set of instances rather than a single address. When an instance is removed, the client learns on the next refresh or when a call to it fails, and it uses the others. This is the client-side discovery: the client resolves, picks an instance, and fails over, which distributes the load and tolerates the churn.
import { lookup } from 'node:dns/promises';
async function callService(name, port) {
const addresses = await lookup(name, { all: true }); // resolve at call time
for (const { address } of addresses) {
try {
return await fetch('http://' + address + ':' + port + '/api');
} catch {
// this instance failed: try the next one
}
}
throw new Error('no instance of ' + name + ' responded');
}
Cache with a TTL and fail over
Resolving on every call adds latency and resolver load, so cache the resolution with a TTL that balances freshness against the cost. The TTL should be short enough that a removed instance is dropped within a bounded time, and long enough that the resolution is not repeated on every call. A negative result, such as a name that does not resolve, is cached briefly too, so a misconfiguration does not hammer the resolver.
Failover across the resolved instances: when a call to one fails, try the next, so a dead instance is skipped. Combined with the refresh, this handles both the instance that was removed and the one that is briefly unhealthy. The client’s instance list is the current, healthy-ish set, and the failover makes a stale entry cheap to handle.
let cache = { addresses: [], expires: 0 };
async function resolveCached(name, ttlMs = 5000) {
if (Date.now() < cache.expires) return cache.addresses;
const addresses = (await lookup(name, { all: true })).map((a) => a.address);
cache = { addresses, expires: Date.now() + ttlMs }; // short TTL: churn is picked up
return addresses;
}
Let the registry track health
A registry tracks the instances and their health, so a client can query the healthy set rather than the whole set. An instance registers on startup, health-checks, and deregisters on shutdown, and the registry removes an instance that fails its health check. The client queries the healthy instances, so a failed instance is not in the set and no call is sent to it.
The deregistration on shutdown is what makes a graceful shutdown clean: the instance removes itself from the registry before it stops, so the client stops sending traffic before the instance closes. This pairs the discovery with the shutdown drain, so a rolling deploy does not send requests to an instance that is leaving.
Test the churn and the failover
Test that adding an instance makes it appear in the resolution and removing one makes it disappear within the TTL, by changing the set and asserting the client sees the change. Test that a call to a dead instance fails over to a live one, by making one instance refuse and asserting the call succeeds on another. Test that a shutdown deregisters the instance so no new traffic is sent, by draining an instance and asserting the client stops using it.
# remove one instance and assert the client stops sending to it within the TTL
# make one instance fail and assert the call fails over to a healthy one
node scripts/simulate-churn.mjs --remove one
node scripts/assert-client-uses-live-instances.mjs
Common pitfalls
Hardcoding an address or resolving once at startup, a TTL so long that a removed instance keeps receiving traffic, no failover so one dead instance fails the call, not deregistering on shutdown so traffic is sent to a leaving instance, and resolving on every call without a cache so the resolver is hammered are the recurring mistakes. Call-time resolution, a short TTL, failover across the instances, a deregistration on shutdown, and a TTL cache address them.
Conclusion
Service discovery lets a client find the current instances of a service. Choose DNS or a registry by the churn, resolve at call time, cache with a short TTL, fail over across the instances, and let the registry track the health with a deregistration on shutdown. Self-check by changing the instance set and asserting the client sees it within the TTL, and by failing an instance and asserting the call fails over. Then the client always talks to a live instance.
Sources: Microservices.io: Service discovery, Kubernetes: Service and DNS, Consul: Service discovery.
FAQ
- DNS or a service registry?
- DNS is simple and universal but has a TTL and may not reflect churn quickly. A registry, such as Consul or a Kubernetes service, tracks the live instances and can be queried for health, which suits a highly dynamic environment. Choose by how often the instances change.
- Why resolve at call time?
- An instance can be replaced, scaled, or moved between the startup and a later call. Resolving at the call finds the current set, while resolving once at startup keeps a static set that becomes wrong as the fleet changes, sending traffic to instances that are gone.
Report a problem with this articleOpens a pre-filled issue on GitHub.