Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 20 min · revision 1

Service discovery, health checks, draining and sticky sessions

Wire service discovery, active and passive health checks, connection draining and session affinity so that instances can join, fail or be redeployed without users seeing errors.

Contentsand lesson path

What you will learn

  • Wire service discovery, health checks, connection draining and session affinity so instances can join, fail or be deployed without user-visible errors.

Prerequisites: Scalability Fundamentals

01. Why it matters

The set of instances behind a balancer changes all the time: autoscaling adds and removes them, deployments replace them and some crash. For each change the balancer has to answer four questions:

  1. Who exists? That is service discovery.
  2. Who can take traffic right now? That is health checking.
  3. How does an instance leave without dropping requests? That is draining.
  4. Must a user come back to the same instance? That is session affinity, also called sticky sessions.

Many errors that users see during deployments come from getting one of these wrong, or from doing the steps in the wrong order.

02. Service discovery: who exists?

A static list in a configuration file breaks as soon as instances come and go on their own. Two dynamic approaches are common:

  • DNS-based: a name such as orders.internal resolves to the current instance addresses. Every language can use it, but resolvers, operating systems and sometimes the application cache the answers, so removals reach callers slowly (see lesson 5).
  • Registry-based: instances are recorded in a registry such as Consul, etcd, the Kubernetes API (EndpointSlices) or a cloud target group, by the instance itself or by the platform that started it. Balancers watch the registry and receive changes within seconds.

The second choice is where the lookup happens. With server-side discovery, the caller sends every request to a balancer (a cloud load balancer, a Kubernetes Service or a proxy), and only the balancer reads the registry. With client-side discovery, the caller's library or sidecar proxy reads the registry and balances by itself. Client-side saves a hop and allows per-request balancing for internal calls, but every client needs the logic, and each client only knows its own outstanding requests.

Registries are eventually consistent: readers can briefly see different lists. Envoy copes by combining discovery with its own health checks: a discovered host that fails its checks gets no traffic, while a host that has vanished from discovery but still passes keeps getting traffic until it fails too, so a brief registry hiccup cannot empty the pool.

03. Health checks: who can take traffic now?

An active health check is a probe the balancer sends on a timer, for example GET /health every 10 s. The instance is marked down after several failures in a row and up again after several passes, so one slow response does not remove it and a flapping instance does not rejoin too early.

A passive health check, which Envoy calls outlier detection, watches real responses instead: after, say, five errors in a row, the instance is ejected for a while. It needs real traffic, so it learns nothing about an idle instance, and its speed depends on how fast errors come back, as the script below shows. Most setups use both kinds.

What should /health check? It should answer "would removing this instance help?". Check what the instance controls: the process is up, its configuration is loaded, its warm-up is finished, it has free worker capacity. Avoid deep checks on shared dependencies: when a shared database slows down, every instance fails together and the balancer has nothing left.

Many balancers guard against that case by failing open: an AWS Application Load Balancer routes to all targets when every target is unhealthy, and Envoy ignores health status when fewer than 50% of hosts are healthy (its default panic threshold). Kubernetes splits the question into a readiness probe (send me traffic?) and a liveness probe (restart me?), as in the Kubernetes probes lab.

The settings decide how long a failed instance keeps receiving requests. The script below estimates that window when one balancer sends an instance 150 requests per second.

Python 3.12 · detection_window.py
"""How many requests hit a dead instance before the balancer stops sending?"""

RPS = 150  # requests per second that one balancer sends to this instance


def active(interval: float, fails: int, timeout: float) -> tuple[float, float]:
    """Seconds from failure to removal by active checks: (best, worst) case."""
    best = (fails - 1) * interval + timeout  # failure just before a check
    worst = fails * interval + timeout  # failure just after a passing check
    return best, worst


def passive(errors: int, request_timeout: float) -> float:
    """Seconds until `errors` failures in a row are seen on real requests.

    A refused connection or a quick 5xx fails at once (timeout 0). A request
    to an instance that hangs fails only when its own timeout fires.
    """
    return request_timeout + errors / RPS


print(f"{'active checks':<32}{'window (s)':<14}failed requests")
for label, interval, fails, timeout in [
    ("30 s interval, 2 fails, hang", 30, 2, 5),
    ("10 s interval, 2 fails, hang", 10, 2, 2),
    ("5 s interval, 2 fails, refused", 5, 2, 0),
]:
    lo, hi = active(interval, fails, timeout)
    print(f"{label:<32}{lo:>2.0f} to {hi:<8.0f}{lo * RPS:>5,.0f} to {hi * RPS:,.0f}")

print(f"\n{'passive, eject after 5 errors':<32}{'window (s)':<14}failed requests")
for label, request_timeout in [
    ("refused or quick 5xx", 0),
    ("hang, 5 s request timeout", 5),
    ("hang, 1 s request timeout", 1),
]:
    w = passive(5, request_timeout)
    print(f"{label:<32}{w:>8.3f}{'':6}{w * RPS:>7,.0f}")
Expected output (deterministic)
active checks                   window (s)    failed requests
30 s interval, 2 fails, hang    35 to 65      5,250 to 9,750
10 s interval, 2 fails, hang    12 to 22      1,800 to 3,300
5 s interval, 2 fails, refused   5 to 10        750 to 1,500

passive, eject after 5 errors   window (s)    failed requests
refused or quick 5xx               0.033            5
hang, 5 s request timeout          5.033          755
hang, 1 s request timeout          1.033          155

The first row uses a 30 s interval, a 5 s timeout and two failures, the documented defaults of an AWS Application Load Balancer for instance targets: an instance that hangs keeps receiving traffic for 35 to 65 s, and without retries all of those requests fail. Shorter intervals shrink the window but add probe traffic and false alarms, for example during a garbage-collection pause. An exited process is quicker to spot, because its connections are refused at once.

Passive checks are fast only when errors come back fast. A refused connection or a quick 5xx gets the instance ejected after five requests, about 33 ms here. An instance that hangs sends nothing back until each request's own timeout fires, so ejection waits for that timeout and every request sent meanwhile fails: about 755 with a 5 s timeout. With several balancers, each sees only part of the traffic and needs longer to collect five errors. Use active checks for idle instances and to decide when an ejected instance may return; use passive checks, with tight request timeouts, to stop the bleeding.

04. Draining: leaving without dropping requests

Health checks find failures after they happen. A planned removal, such as a deployment or a scale-in, can avoid user-visible errors if it happens in the right order. It usually starts with SIGTERM, the signal a platform sends to ask a process to stop. The Google SRE book calls an instance in this phase a lame duck: it still serves, but asks clients to stop sending new work.

Removing one instance cleanly
t0      SIGTERM arrives. Readiness flips to "not ready";
        the instance keeps serving everything it receives.
t0..t1  Balancers notice: deregistration, failed readiness checks,
        or a registry update. New requests stop arriving.
t1..t2  In-flight requests finish. Keep-alive connections get
        "Connection: close"; HTTP/2 connections get a GOAWAY frame.
t2      The process exits. A hard deadline (SIGKILL) ends anything left.

Two details cause most draining bugs. First, step t0 to t1 takes time, and the instance must not exit during it. In Kubernetes, the control plane marks a terminating Pod's endpoints as not ready at the same time as the kubelet starts shutting the Pod down, so proxies that see the update a little later can still send requests to it. A short preStop delay keeps the process alive while they catch up, and terminationGracePeriodSeconds (30 s by default) must cover the delay plus the time to finish in-flight work. Managed balancers expose the same idea as a setting: AWS calls it the deregistration delay, 300 s by default, and finishes early when a target has no requests or connections left.

Second, long-lived connections do not drain on their own. HTTP/1.1 keep-alive connections close after the next response if the server sends Connection: close. HTTP/2 has a GOAWAY frame (RFC 9113) that names the last stream the server will still process: streams up to it may still complete, and the client may retry any later stream on a new connection, because the server will not process it. A WebSocket cannot be moved to another instance; the server closes it and the client reconnects, ideally after a random delay so that thousands of clients do not reconnect in the same second. Joining is the mirror image: some balancers offer a slow start that ramps traffic to a new instance while its caches warm up.

05. Sticky sessions: when the same instance must answer

Session affinity sends all requests of one user, or one session, to the same instance. Balancers implement it in a few ways: a cookie the balancer sets (AWS uses AWSALB, Caddy uses lb), a cookie the application sets, a hash of the client IP address, or a hash of a header such as a user ID. IP-based affinity is the most fragile: users behind one NAT share an address, and a phone that moves from Wi-Fi to mobile data gets a new one.

Teams usually add stickiness because something lives in one instance's memory: a login session, a cart, a half-finished upload or a warm local cache. It works, but it has costs:

  • Uneven load. A heavy user stays on one instance, and least-request balancing cannot move them.
  • Lost state. When the instance dies or is drained, the data in its memory is gone. The balancer picks a new instance and the user starts again.
  • Harder deployments. Draining has to choose between waiting for sessions to end and breaking them.

The durable fix is to make instances stateless: keep sessions in a shared store such as a database or Redis, or in a signed token the client carries, so that any instance can answer. Then stickiness becomes an optional optimisation, for example to reuse a warm cache, rather than something correctness depends on.

06. Check your understanding

Practice check · 3 questions

Discovery, health, draining and affinity

Three scenarios about a hung instance, HTTP/2 draining and IP-based affinity.

Q1. A proxy sends 400 requests per second to each instance. It ejects an instance after 5 failed requests in a row, and it counts a request that reaches its 10 s timeout as failed. One instance hangs: it accepts connections but never answers. Roughly how long until it is ejected, and how many requests fail?
Q2. While draining, a server sends an HTTP/2 GOAWAY frame that names stream 41 as the last one it will process. The client had just sent a POST on stream 43 over that connection. What may the client do with that POST?
Q3. A file service uses source-IP affinity, because each half-finished upload lives in one instance's memory. Users on phones say large uploads restart from zero when they walk out of the office. What is the likely cause?
Practice only: not graded, not saved, not evidence.

07. Apply it

For a service you run, or the shop from the first lesson, write a one-page "instance lifecycle" note:

  1. How a new instance is discovered, and how long until it receives traffic.
  2. What /health checks, and what it deliberately does not check.
  3. The active check interval, timeout and thresholds, plus any passive ejection rule, and the detection window they give (adapt the script above).
  4. The shutdown order, with the delay before exit and the hard deadline.
  5. Whether anything depends on stickiness, and how you would remove that dependency.

The next lesson, a lab, kills an instance under load with and without health checks and draining, as the skill's practice task asks.

08. Review prompt

Without notes, list the four questions a balancer must answer when instances change, and the mechanism that answers each. Explain why an instance should keep serving for a few seconds after it starts failing its readiness check, and describe two costs of sticky sessions that remain even when the balancer handles failures correctly.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check