Sub topic 9
Client-side timeouts, retries, and endpoint lists
Server-side failover takes time. A load balancer needs several failed health checks before it removes a node, and a DNS change needs time to spread. During that window, clients still send requests to a dead component. A well-built client hides much of this gap. It gives up on a slow request, tries again, and moves to another endpoint.
This chapter assumes you know basic client-server architecture, how a load balancer and DNS direct traffic, and what a timeout is. It covers how to set timeouts, which errors to retry, how to avoid making an outage worse with retries, and how to use a list of endpoints.
Why the client has a role
A client sees failure from the outside, and it sees it quickly. If a connection is refused or a response never arrives, the client knows that this attempt failed. It does not need a health checker's opinion to try a different server.
Client-side resilience also covers gaps the infrastructure cannot:
- The load balancer itself can fail, and a client with two load balancer addresses can survive that.
- A health check can still report a node as healthy when it fails real requests.
- Failover at the DNS level is delayed by caching, so some clients keep using the old address for minutes.
The client cannot replace server-side failover. It adds a second layer, so a single failed request does not become a user-visible error.
Timeouts
Without a timeout, a client waits as long as the operating system allows. This can be minutes. A request sent to a node that has crashed or been cut off from the network may never get a reply. The caller then holds a thread, a connection, and memory while it waits. Many such callers exhaust the client's own resources, and the failure spreads upstream.
There are usually two timeouts to set:
| Timeout | What it limits | Typical starting point |
|---|---|---|
| Connect timeout | Time to establish the TCP (and TLS) connection | 100 ms to 1 s |
| Read timeout | Time waiting for response data | Slightly above the slowest healthy response |
Choose the read timeout from measured latency. If a healthy call has a 99th percentile (p99) of 200 ms, a timeout of 500 ms to 1 s works. A timeout below p99 causes healthy requests to fail. A timeout of 30 s makes every failure cost 30 s.
The timeout also sets how long failover takes from the client's view. With a 1 s timeout and two endpoints, the worst case before the second endpoint answers is about 1 s plus its response time.
Python's timeout argument to urlopen applies to each blocking socket operation. It is not a limit on the whole request. A server that sends one byte every half second can keep a call alive far beyond the timeout. For a hard limit, track an overall deadline yourself, as the example later in this chapter does.
What to retry
A retry is only safe if repeating the request cannot do damage, and only useful if a repeat can succeed. Sort errors into three groups.
| Error | Retry? | Reason |
|---|---|---|
| Connection refused, connect timeout | Yes | The request never reached the server |
| Read timeout | Only if the operation is idempotent | The server may have processed the request |
| HTTP 502, 503, 504 | Yes | The server or a proxy is unavailable |
| HTTP 500 | Sometimes | It may be a bug that repeats every time |
| HTTP 400, 401, 403, 404 | No | The request is wrong, and a repeat gives the same answer |
An operation is idempotent if doing it twice has the same effect as doing it once. Reading a record and setting a field to a value are idempotent. "Charge the card" and "append a line" are not.
Retry storms, backoff, and jitter
Retries add load at the worst moment. Suppose a service is slow because it is overloaded. Every client times out and retries, so the service receives roughly double its normal load and gets slower. This is called a retry storm.
Three habits keep retries from causing a storm:
- Limit attempts. Two or three attempts is typical.
- Back off. Wait longer between each attempt. A common schedule doubles the wait: 100 ms, 200 ms, 400 ms.
- Add jitter. Jitter is randomness in the wait. Without it, a thousand clients that failed together will all retry at the same instant and hit the server in synchronized waves. A common form picks a random wait between 0 and the backoff value.
Retries also multiply across layers. If a web tier retries 3 times, and each of those calls an application tier that retries 3 times, one user request can become 9 requests, or 27 with a third layer. Retry at one layer where you can, and set a deadline that every layer respects.
A deadline is a total time budget for the user's request. When it passes, stop trying. A client that keeps retrying after the user has given up wastes capacity that a recovering service needs.
Endpoint lists
When a service has more than one address, give the client a list. The simplest policy tries endpoints in order and moves to the next on failure. This suits an active-passive pair, where one endpoint is preferred. For active-active services, shuffle the list at startup or pick at random, so that clients spread across all endpoints.
Remembering the last good endpoint saves time. If the primary is down, a client that tries it first on every request pays a full timeout each time. A client that remembers the working endpoint pays that cost once, then rechecks the primary occasionally.
This is a small version of a circuit breaker. A circuit breaker stops sending requests to a component that has recently failed, for a cool-down period, and then lets a trial request through.
A client with failover and backoff
The first version below is the minimal pattern. It tries each endpoint in order with a short timeout and moves on after any error.
import urllib.request
ENDPOINTS = [
"http://primary.example.internal:8080",
"http://secondary.example.internal:8080",
]
def fetch(path, timeout=1.0):
last_error = None
for base in ENDPOINTS:
try:
with urllib.request.urlopen(base + path, timeout=timeout) as resp:
return resp.read()
except OSError as err:
last_error = err
raise RuntimeError("all endpoints failed") from last_errorurlopen raises HTTPError for 4xx and 5xx responses, and HTTPError is a subclass of OSError. So this loop treats a 404 the same as a dead server. That is wasteful, and it can hide a bug in the request.
The second version fixes this. It retries only network errors and 5xx responses. It also adds backoff with jitter and an overall deadline.
import random
import time
import urllib.error
import urllib.request
ENDPOINTS = [
"http://primary.example.internal:8080",
"http://secondary.example.internal:8080",
]
def fetch(path, timeout=1.0, attempts=3, base_delay=0.1, deadline=3.0):
start = time.monotonic()
last_error = None
for attempt in range(attempts):
for base in ENDPOINTS:
if time.monotonic() - start >= deadline:
raise RuntimeError("deadline exceeded") from last_error
try:
with urllib.request.urlopen(base + path, timeout=timeout) as resp:
return resp.read()
except urllib.error.HTTPError as err:
if err.code < 500:
raise # client error: another endpoint will not help
last_error = err
except OSError as err:
last_error = err
time.sleep(random.uniform(0, base_delay * 2 ** attempt))
raise RuntimeError("all endpoints failed") from last_errorThe except urllib.error.HTTPError clause comes first on purpose. Python checks clauses in order, and the broader OSError clause would otherwise catch HTTP errors too.
With these defaults, one call is bounded by the 3 s deadline plus at most one final request, since the deadline is checked before each attempt, not during one.
How a failed request flows
Common mistakes
- No timeout. The default is often infinite or very long. Set one explicitly on every outbound call.
- Retrying without limits. A loop that never stops keeps hammering a service that is trying to recover.
- Identical retry timing. Without jitter, clients retry in lockstep.
- Retrying non-idempotent calls blindly. This causes duplicate orders and double charges.
- Stale endpoint lists. A hard-coded list breaks when addresses change. Load it from configuration or service discovery, and test that the second entry works.
- Resolving DNS once. A long-running client that resolves a name at startup and never again will not follow a DNS failover.
Exercise
A service has a healthy p99 latency of 300 ms. A client calls it with a 10 s read timeout, 4 attempts, and no backoff, and it is one of 500 clients. The service becomes overloaded and responses slow to 20 s. Name two problems with this client configuration and one change for each.
Show answer
First, the 10 s timeout means every failed attempt holds a thread and connection for 10 s, so the client stalls. Set the read timeout from measured latency, for example 1 s, and add an overall deadline. Second, four immediate attempts from 500 clients can quadruple the load on an overloaded service, and the clients retry in sync. Reduce attempts to 2 or 3 and add exponential backoff with jitter.
Exercise
Why does the second fetch function catch urllib.error.HTTPError before OSError, and what happens to a 404 response?
Show answer
HTTPError is a subclass of OSError, so an OSError clause placed first would catch it and the status check would never run. A 404 is below 500, so the code re-raises it immediately. It is not retried and no other endpoint is tried, because the request itself is wrong.