AlgoViz

Service discovery

medium 30 min

Service discovery turns a service name into the address of a running, healthy copy of that service.

Video lesson · Chapter 1 of 5

Find a kitchen after its address changes

0:00 / 3:43

How services find each other, in 80 seconds

1:20Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A service usually runs as several identical copies, called instances, each with its own address and port. Service discovery is the part of a system that answers one question: where can I reach a healthy instance of this service right now?

It has two sides. On one side instances become known and are removed again: registration and health checks. On the other side callers look them up and choose one: discovery and load balancing. Between the two sits a service registry, a list from names to addresses.

Why it exists

When servers were bought and named, an address could stand in a configuration file for years. Today instances are created by autoscalers, replaced at every release and moved when a machine fails. A written-down address is wrong within hours.

A name that always leads to a healthy instance makes growth, failover and releases routine. The hard part is time: the list is always a little behind reality, so good callers expect some addresses to be wrong.

A short history

  1. November 1983

    RFC 882 introduces domain names. It explains that the central table of hosts, the file HOSTS.TXT, was close to the limit of what could be managed.

  2. November 1987

    RFC 1035 specifies the domain name system in the form still used, including how long an answer may be cached.

  3. February 2000

    RFC 2782 defines the SRV record, which gives the host, the port, a priority and a weight for a named service.

  4. 17 April 2014

    The first release of Consul, 0.1.0: a registry with health checks and a DNS interface.

  5. 6 June 2014

    The first commit of Kubernetes reaches GitHub. Its Services give a changing set of containers one stable name and address.

  6. 24 May 2017

    Istio 0.1 is announced. In a service mesh, proxies receive the addresses and the application only knows names.

Words to know

Instance
One running copy of a service, with an address and a port.
Service registry
The list from service names to instances and their health.
Heartbeat
A message an instance sends regularly to say that it is alive.
Lease
A registration that ends by itself unless it is renewed.
TTL
Time to live: how long an answer may be kept before asking again.
Readiness
Whether an instance should receive traffic now.
Liveness
Whether a process should be restarted.

How it works

Step through the idea, or press Play.

Step 1 of 3

Register. An instance tells the registry its name, address and health check

Understand it

Start here

The street market

Traders at a market take a different pitch each day. Imagine you want cheese. Nobody can tell you the pitch in advance, but there is a board at the entrance.

Finding the cheese
WHO IS WHERECheese: 2Bread: 3235Traders sign in

Sign in, ask, walk, check, and keep a note. Every discovery system does these five things.

The idea

Register, discover, call

The registry between both sides

Two machines run the user service at 10.0.0.1 port 8080 and 10.0.0.2 port 8080. Both register with and send heartbeats to the service registry. The registry tells the order service where the user service is.
Step 1 fills the registry, step 2 reads it. The calls themselves go from service to service.

From start to call

  1. 1

    The service starts

    An instance comes up and checks that it can work.

  2. 2

    It registers

    Name, address, port and health check go to the registry.

  3. 3

    The registry keeps watch

    It renews or removes the entry.

  4. 4

    A caller discovers

    It asks for the name and gets healthy addresses.

  5. 5

    The caller calls

    It picks one and sends the request.

What you gain

  • Services are found while addresses change.
  • Failover without a person.
  • Load balancing over all healthy instances.
  • Elastic scaling: new instances get traffic by themselves.
  • Simpler releases.

Without it

  • Addresses in configuration files.
  • A release of the caller when the other service moves.
  • Traffic to dead machines.
  • New instances that nobody uses.

What a registry stores

FieldExampleUsed for
Service nameuser-serviceThe question callers ask
Instance iduser-service-7f3aReplace or remove exactly this entry
Host and port10.0.0.1:8080Where to connect
Health checkGET /health every 10 sKeep or remove
Metadataversion 2, zone b, weight 3Same-zone routing, gradual releases

Getting in

Registration

  • Self-registration

    The service registers itself at start and deregisters at stop. Simple, but every language needs the code, and a crash deregisters nothing.

  • Third-party registration

    A separate registrar, such as a platform, watches instances and writes the entries. The service knows nothing about it. Kubernetes and Docker Swarm work like this.

The life of an entry

Heartbeats renew the lease of a healthy entry. A new entry should not get traffic until its first check has passed.

Way 1

Client-side discovery

The caller asks the registry, keeps the list and chooses an instance itself. Netflix's Eureka with a client library is the well-known example.

The caller chooses

The service registry gives the order service a list of addresses. The order service chooses itself, calls user service A at 10.0.0.1 directly and sends the next call to user service B at 10.0.0.2.
No extra hop on the way, but the logic lives in every caller.

Way 2

Server-side discovery

The caller uses one fixed name or address. A load balancer behind it knows the instances and passes the request on.

The load balancer chooses

The order service calls user at one fixed name. A load balancer, which gets addresses from the service registry, forwards the call to user service A and the next call to user service B.
Callers stay simple in any language. The balancer is one more hop and must itself run in several copies.

Way 3

DNS

Every language can look up a name. The registry answers DNS queries with the addresses of healthy instances. An address record holds no port. An SRV record does, with a priority and a weight, but many client libraries never ask for it.

A DNS answer that is out of date

The caller cannot learn about the change before its kept answer ends. Some runtimes keep answers longer than they should, and an open connection never asks again.

Way 4

Service mesh

A proxy beside each service receives the addresses from a control plane and makes the calls. The application only uses names. More about meshes is in microservice communication.

The proxy chooses

In the order pod the order service asks its proxy for user. A control plane that watches all instances sends addresses to the proxy. The proxy calls user service A, and the next call goes to user service B.
The control plane sends changes to the proxy. If it is down, the proxy goes on with the last addresses it had.

Compare

Four ways side by side

WayWho choosesGoodCosts
Client-sideThe callerNo extra hop, the caller can choose cleverlyA library per language, logic in every caller
Server-sideA load balancerSimple callers in any languageExtra hop, the balancer must be redundant
DNSThe caller, from the answerStandard, works everywhereKept answers, little metadata
Service meshA local proxyFull control and measuring, no codeComplexity, extra memory and CPU per proxy

Common tools

ToolWhat it isHow callers use it
ConsulRegistry with health checks, by HashiCorpDNS, HTTP API or mesh
etcdConsistent key-value store, first made at CoreOSBuilding block: you write the registry on top, with leases and watches
EurekaRegistry by NetflixClient library, REST
Kubernetes Services and DNSBuilt into the platformA name with one stable virtual address
AWS Cloud MapManaged registryAPI calls or DNS

Which way?

Use what your platform already has, until a concrete need says otherwise.

Staying in

Health checks

KindWho startsExampleFinds
Active checkThe registry or balancer asksGET /health gives 200 OKInstances that run but do not answer
HeartbeatThe instance reportsPUT /heartbeat every 10 sInstances that stopped or lost the network
Watching real trafficCaller or proxy counts errors5 failures in a rowInstances that look fine but fail real requests
An active check proves that the checker can reach the instance, not that your caller can. The third kind is often called a passive check.
JSON
{  "status": "healthy",  "checks": { "database": "ok", "cache": "ok", "disk": "ok" }}
A detailed answer helps people. The status code is what machines decide on. Do not show internal details to the public.

Liveness: restart me?

  • Is this process stuck?
  • Keep it shallow: no database, no other service.
  • Failing means the process is restarted.

Readiness: send me traffic?

  • Is start-up finished and is there capacity?
  • May check what only this instance needs.
  • Failing means no traffic, but no restart.

Numbers

How old can the list be?

Worst time to a dead instance being forgotten

t=10 s×3⏟missed heartbeats+30 s⏟caller’s cache=60 secondst = \underbrace{10\text{ s} \times 3}_{\text{missed heartbeats}} + \underbrace{30\text{ s}}_{\text{caller's cache}} = 60 \text{ seconds}
A crash right after a heartbeat, three missed ones, then a caller that had just refreshed its list. Times are example settings.

What callers feel, and what a retry does

failing calls=15=20%⟶one try on a different instance: 0%\text{failing calls} = \frac{1}{5} = 20\% \quad\longrightarrow\quad \text{one try on a different instance: } 0\%
One of five instances is dead and choices are even. A second try on another instance hides it, as long as only one is dead and the request may be repeated.

Why callers keep a cache

50,000 calls/s→50,000 lookups/s2,000 callers×20 names30 s≈1,333 lookups/s50{,}000 \text{ calls/s} \to 50{,}000 \text{ lookups/s} \qquad \frac{2{,}000 \text{ callers} \times 20 \text{ names}}{30\text{ s}} \approx 1{,}333 \text{ lookups/s}
Assumed numbers. Better still, the registry can notify callers of changes: a long poll or watch. See push and pull.

Choosing

Pick one instance

StrategyHowFits
Round robinIn turn, one after the otherEqual machines, similar requests
RandomAny healthy oneMany callers, no shared counter
WeightedMore to the strongerDifferent machine sizes, gradual releases
Least connectionsThe one with the fewest active requestsRequests of very different length
Details are in load balancing. Prefer the same zone, if it has healthy instances.

One call, step by step

45 ms is an example. The next call uses index 1, without asking the registry again.

Failure

When the registry is down

  1. 1

    Callers use their cached list

    Old addresses are nearly always better than none. Log that the list is old, and keep retrying the registry with backoff.

  2. 2

    The registry runs in several copies

    Three or five servers that agree, or copies in each zone that replicate.

  3. 3

    It prefers old answers to no answers

    When many instances vanish at once, the cause is often the network and not the instances. Eureka has a self-preservation mode that stops removing entries in that case.

  4. 4

    New instances wait

    While the registry is down nothing new can join, so autoscaling and releases stop.

Leaving

Graceful shutdown

Leave before you stop

The wait must be longer than callers' caches. On Kubernetes, removal from the endpoint list and the stop signal run in parallel, so a short pause before stopping is common.

Platform

Kubernetes in one picture

A Service has a stable name and, normally, a stable virtual address. The platform keeps the list of ready pods in EndpointSlices and updates it whenever the set changes. Cluster DNS turns the name into the virtual address, and rules on each node pass connections on to a pod.

From name to pod

Because the virtual address does not change, kept DNS answers do no harm. A headless Service returns the pod addresses themselves instead.

Practice

Good habits

  • Cache results

    Less load on the registry and faster calls. Refresh in the background, with jitter.

  • Shut down gracefully

    Deregister first, serve a little longer, then stop.

  • Meaningful health checks

    Check that real work is possible, but do not let a shared dependency remove everyone.

  • Survive without the registry

    Use the last known list, with a retry on another instance.

  • Protect registration

    Only a proven service may register under a name. Otherwise anyone on the network can receive its traffic.

Summary

The whole topic in one minute.

Service discovery maps a name to healthy addresses. Instances register or are registered, leases and health checks remove the dead, and callers find them by a client library, a load balancer, DNS or a sidecar proxy.

The list is always slightly old. Add the detection time and the cache time to know how old, and cover the gap with retries on another instance, graceful shutdown and a cache that still works when the registry does not.

  • Service discovery turns a name into healthy addresses.
  • Instances register, leases and checks remove the dead.
  • The caller, a load balancer, DNS or a proxy makes the choice.
  • The list is always old by the detection time plus the cache time, so retry on another instance.
  • Deregister before stopping, and keep working when the registry is down.

Sources