Skip to content

Timeouts, Retries & Jitter ​

“The solution isn’t to remove backoff. It’s to add jitter.” — Marc Brooker, Exponential Backoff and Jitter, AWS Architecture Blog, 4 March 2015

Summary: A timeout decides how long you are willing to wait, a retry decides whether to ask again, backoff decides how long to pause first, and jitter makes sure a thousand clients do not all come back at the same millisecond; each one is cheap alone and dangerous when misconfigured, because together they decide whether a small failure stays small. Focus: Connect, read, write, request, idle and total timeouts; deadlines and per-hop budgets; choosing values from latency percentiles; timeout layering across load balancer, proxy, application and database; Go context.WithTimeout, http.Client, net.Dialer; PostgreSQL statement_timeout, lock_timeout, idle_in_transaction_session_timeout; Redis, PDO and Laravel HTTP timeouts; queue job timeout versus retry_after; what is safe to retry, error classification, retry budgets, per-try timeouts, retry storms; constant, linear, exponential, full, equal and decorrelated jitter; Retry-After; idempotency keys; hedging; queue retries (tries, backoff, retryUntil); library defaults (AWS SDK, gRPC, Guzzle, go-retryablehttp, Envoy, NGINX); observability and fake-clock tests. Learning goal: Given a call from service A to service B, write down every timeout on its path with numbers, say which failures may be retried and which may not, implement a retry loop with backoff, jitter, a budget and a deadline in Go and in Laravel, and prove with a fake clock that it stops when it should.

This chapter is the cookbook of the Resilience group. It owns the catalogue of timeouts, the numbers, the backoff and jitter formulas and the retry rules. The mechanics of sending a deadline between services live in Service Communication; the damage that retries do when a dependency is already failing is told in Cascading Failures; the component that stops calling a dead dependency is the Circuit Breaker; the key that makes a retried POST safe is in API Idempotency; the numbers of tail latency and hedged requests are in Latency Budgets and Tail Latency; retries inside a broker are in Retry, Backoff & Delayed Delivery. Here we put the pieces together.

Page map ​

If you are looking forGo to
The whole page in four tablesEverything in one minute
Why a missing timeout or a naive retry causes outagesWhy it exists
Brooker 2015, Builders' Library, SRE book, gRPC A6, RFC 9110Where it comes from
Connect, read, write, request, idle and total timeoutsKinds of timeout
Deadlines, per-hop budgets, layering across LB, proxy, app, DBDeadlines and layering
Which number to pickChoosing timeout values
PostgreSQL, Redis, PDO timeoutsDatabase and cache timeouts
Queue job timeout versus retry_afterQueue timeouts
What may be retriedSafe to retry, Error classification
Retry budgets, per-try timeouts, one layer only, retry stormsBudget, Per-try, One layer
Constant, linear, exponential backoffBackoff
Full, equal and decorrelated jitterJitter
Retry-After, gRPC pushback, 429 and 503Server hints
Idempotency keysIdempotency keys
Hedging versus retryingHedging
Laravel jobs: tries, backoff, retryUntilQueue retries
AWS SDK adaptive mode, gRPC policy, Guzzle, go-retryablehttp, EnvoyLibrary retries
Metrics for retries, fake-clock testsObservability, Testing
Knobs, formulas, error messagesMechanics
CodeGo, Laravel
Classic incidents and fixesSolving the classic problems
Which policy for which callChoosing
Monolith to multi-regionIn architecture
Run the numbers yourselfLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The five timeouts of one call. Every network call can hang in five different places; each needs its own limit.

TimeoutWhat it boundsTypical value (call with p99 about 200 ms)Go knobLaravel knob
Connect timeoutTCP connect (plus TLS if measured together)0.5 to 1 snet.Dialer.Timeout, Transport.TLSHandshakeTimeoutconnectTimeout() (default 10 s)
Write timeoutSending the request bytes1 to 5 shttp.Server.WriteTimeout (server side)Guzzle timeout covers it
Read timeoutWaiting for response bytes1 to 3 sTransport.ResponseHeaderTimeouttimeout() (default 30 s)
Request (total) timeoutThe whole attempt: connect, send, wait, read body2 to 5 shttp.Client.Timeout, context.WithTimeouttimeout()
Idle timeoutA connection with nothing in flight30 to 120 s, shorter than the peer'sTransport.IdleConnTimeout, http.Server.IdleTimeoutGuzzle/cURL connection reuse

What a retry may do. The question is never only "did it fail" but "did the server act".

FailureDid the server act?Retry a non-idempotent call?Retry an idempotent call?
Connection refused, dial timeoutNoYesYes
429 Too Many Requests, 503 Service UnavailableNormally no (rejected up front)Yes, honour Retry-AfterYes
Read timeout, no responseMaybe (ambiguous)NoYes
Connection reset after the request was sentMaybe (ambiguous)NoYes
500, 502, 504Maybe (ambiguous)NoYes
400, 401, 403, 404, 409, 422Not applicableNeverNever

The four backoff formulas (attempt starts at 1; cap is the maximum sleep; base the first sleep).

NameFormulaSource
Capped exponentialsleep = min(cap, base * 2^(attempt-1))Brooker 2015
Full jittersleep = random(0, min(cap, base * 2^(attempt-1)))Brooker 2015
Equal jittert = min(cap, base * 2^(attempt-1)), sleep = t/2 + random(0, t/2)Brooker 2015
Decorrelated jittersleep = min(cap, random(base, previous_sleep * 3))Brooker 2015

The numbers to remember.

NumberMeaningWhere it comes from
243xFive layers that each try three times send 243 calls to the database for one user requestAWS Builders' Library
10%Retry budget: stop retrying when retries are more than 10% of requestsGoogle SRE book, chapter 21
1.1xWorst-case growth with a 10% budget (3x without it)Google SRE book, chapter 21
0.1% / p99.9Start from an acceptable false-timeout rate and take that latency percentileAWS Builders' Library
3 attemptsThe default attempt count of the AWS SDK standard modeAWS SDK reference guide
5 attemptsgRPC treats maxAttempts above 5 as 5gRPC proposal A6
60 sDefault NGINX proxy_read_timeout and AWS ALB idle timeoutNGINX docs, AWS ALB docs

Why it exists ​

A call across a network has no upper bound on its duration unless you put one there. A server may be paused by garbage collection, a link may drop packets silently, a load balancer may hold a connection that nobody serves. Without a timeout the caller waits as long as the failure lasts, holding a thread, a connection, memory and a place in the queue. With 200 threads and one hung dependency, the 201st request is refused even though your own code is healthy. This is how a failure of one service becomes a failure of its callers (see Cascading Failures).

A retry exists because many failures are short: a pod was restarting, one replica was busy, a packet was lost. Asking again usually works. The trap is that the cases where retrying helps most (a transient fault) and where it hurts most (an overloaded server) look identical to the client, and a naive loop makes the second case worse for everyone.

Without itWith itCost of the fix
A hung call holds a thread foreverThe call fails in a known timeSome slow-but-fine calls are cut (false timeouts)
One transient error becomes a user errorOne retry hides itExtra load, possible duplicate side effects
Clients retry in lockstep and kill a recovering serverJitter spreads them in timeSlightly longer worst-case wait
Retries at every layer multiply loadOne layer retries, with a budgetThe inner layers must fail fast and report clearly

An everyday picture used through the page. You phone a restaurant to book a table. You decide beforehand how long you will let it ring (the timeout). If nobody picks up you try again, but not instantly, and not at the exact minute every other customer also redials (backoff and jitter). If someone says "we are full, call after 8" you believe them (Retry-After). And if you were cut off in the middle of "please book table 5", you do not know whether the booking happened, so you call and ask for the booking reference before booking again (idempotency).

Three common misunderstandings, up front ​

  1. "A timeout means the request failed." It means you stopped waiting. The server may still be working and may complete the action a second later. That is the ambiguous failure, and it is why retrying a payment after a timeout is dangerous without an idempotency key.
  2. "Retries make the system more reliable." Only for transient, isolated faults. Against an overloaded dependency, retries are extra load: with three attempts the system sends up to three times the traffic exactly when it can least afford it.
  3. "Exponential backoff solves the thundering herd." Not alone. If a thousand clients fail at the same instant and all sleep exactly 100 ms, 200 ms, 400 ms, they return together every time. Jitter, not the exponent, spreads them.

Where it comes from ​

SourceWhat it contributedVerified from
Marc Brooker, Exponential Backoff and Jitter, AWS Architecture Blog, 2015Named and compared "Full Jitter", "Equal Jitter" and "Decorrelated Jitter" in a simulation of contending clients; the 2023 update says most AWS SDKs now use exponential backoff and jitterThe blog page, saved
Marc Brooker, Timeouts, retries, and backoff with jitter, Amazon Builders' Library, December 2019Timeout selection from latency percentiles, the 243x example, retry at a single point, token-bucket limiting of retries, idempotencyThe article, saved
Google SRE book, chapter 21 "Handling Overload"Per-request retry budget of three attempts, per-client budget of 10% (growth 1.1x instead of near 3x)The chapter, saved
RFC 9110 (HTTP Semantics), 2022Definition of idempotent methods, the rule for automatic retries, Retry-AfterThe RFC text, saved
gRPC proposal A6 "Client Retries"Retry policy (maxAttempts, backoff, status codes), hedging policy, retry throttling with tokens, server pushbackThe proposal, saved
Michael Nygard, Release It!"Timeouts" and "Circuit Breaker" as stability patterns; the origin of the circuit-breaker vocabularyNamed from the source canon; not re-read for this page

Read the dates. The jitter formulas are from 2015; the budget idea in SRE is from the same period; the AWS SDK "standard" and "adaptive" modes standardised them across languages in the 2020s. Nothing here is new, which is why ignoring it is expensive.

The concept catalogue ​

Every block has the same order: plain words, the common misunderstanding, the definition, a timeline or request flow, real scenarios, what each product provides, and the fix.

Kinds of timeout: connect, read, write, request, idle Must-know ​

In plain words: "Timeout" is not one number. A call has phases (find the host, open the connection, send, wait, receive), a connection can also sit unused, and each phase can hang separately. One limit for the whole attempt is necessary but not enough, because it cannot tell you which phase was slow.

Common misunderstanding: "I set timeout=5 so the call can never take more than 5 seconds." In many clients that value is a socket timeout that restarts on every successful read. A server that sends one byte every 4 seconds never trips it. NGINX documents exactly this for proxy_read_timeout: it is set "only between two successive read operations, not for the transmission of the whole response."

Definition:

  • Connect timeout: the longest the client waits for the TCP handshake (and, depending on the client, name resolution and TLS) to finish. A refused connection fails at once; a black-holed address fails only when this timer fires. Go's net.Dialer.Timeout documents that the operating system "may impose its own earlier timeout. For instance, TCP timeouts are often around 3 minutes" and that the default is no timeout.
  • Write timeout: the longest sending the request may take. Matters for large uploads and for slow-read clients on a server (http.Server.WriteTimeout).
  • Read timeout: the longest the client waits for the next bytes of the response. Go splits it: Transport.ResponseHeaderTimeout (time to response headers after the request is fully written) and body reads bounded by the total timeout or the context.
  • Request (total) timeout: one limit for the whole attempt. Go's http.Client.Timeout "includes connection time, any redirects, and reading the response body", and keeps running while you read Response.Body.
  • Idle timeout: how long a connection with no request in flight may live. It exists on both sides (Transport.IdleConnTimeout on the client, http.Server.IdleTimeout, the AWS ALB idle timeout of 60 seconds by default, NGINX keepalive_timeout). The side with the shorter idle timeout closes first; if the client keeps a connection the server has already closed, the next request fails with a reset.
  • Total deadline: the absolute point in time by which the whole operation (all attempts, all sleeps, all downstream calls) must finish. It is a property of the user's request, not of one call. See Deadlines and layering.
text
     Phases of one attempt and the timeout that guards each one
1    resolve name            -> resolver timeout (OS / Resolver.Dial)
2    TCP connect (SYN, SYN-ACK, ACK)  -> connect timeout   (net.Dialer.Timeout)
3    TLS handshake           -> TLSHandshakeTimeout
4    write request headers + body   -> write timeout (server side) / total
5    wait for first response byte   -> read timeout (ResponseHeaderTimeout)
6    read response body             -> total timeout / context deadline
7    connection returns to the pool -> idle timeout (IdleConnTimeout)

Real scenarios: an API call goes to a host that is down and drops packets: with no connect timeout the call waits about 3 minutes in the kernel; a mobile client on a weak network sends a 20 MB upload slowly, so a server WriteTimeout or a proxy proxy_send_timeout of 60 seconds cuts it; a keep-alive connection crosses a NAT that forgets idle connections after 5 minutes, so the first request after a quiet period fails with "connection reset"; a streaming download that sends a byte every few seconds passes a read timeout but exceeds the total timeout.

What provides it (per product):

ProductConnectRead / responseTotalIdle
Go net/http clientnet.Dialer.Timeout (default none)Transport.ResponseHeaderTimeout (default none)http.Client.Timeout (default none), or the request contextTransport.IdleConnTimeout
Go net/http servernot applicableReadTimeout, ReadHeaderTimeouthttp.TimeoutHandlerIdleTimeout, WriteTimeout
Laravel HTTP client (Guzzle/cURL)connectTimeout(), default 10 stimeout(), default 30 stimeout()cURL connection cache
NGINX proxyproxy_connect_timeout 60 sproxy_read_timeout 60 snone for the whole responsekeepalive_timeout
Envoy routercluster connect_timeoutper-try timeoutroute timeout, default 15 sidle_timeout
AWS ALBnot applicablenot applicablenot applicableconnection idle timeout, default 60 s

Fix: set all of them explicitly. A client with defaults is a client with "no limit" (Go) or "30 seconds" (Laravel); both are wrong for an interactive call. The Go and Laravel code is in Go and Laravel.

Deadlines, per-hop budgets and timeout layering Must-know ​

In plain words: The user gives the whole request one amount of time. Every hop spends some of it, so every hop must know how much is left, and the limits must get smaller as you go inward, otherwise the outer layer gives up while the inner one is still working.

Common misunderstanding: "Each service sets its own 30-second timeout, so we are safe." If A calls B with a 30 s timeout and B calls C with a 30 s timeout, A may give up at 30 s while B is still waiting for C until 30 s later, doing work nobody wants. Independent timeouts do not compose; they must be derived from one deadline.

Definition: A deadline is an absolute time; a timeout is a duration. Convert at the edge: deadline = now + total. Each hop computes timeout = min(own_cap, remaining - margin). A timeout budget is that remaining time. Deadline propagation means sending the remaining time to the next service (gRPC grpc-timeout, HTTP headers such as a relative Request-Timeout-Ms, Envoy x-envoy-upstream-rq-timeout-ms) so it can refuse work it cannot finish. The header mechanics are in Service Communication; the hop-by-hop numbers are in Latency Budgets.

text
     Timeout layering: outer limit > inner limit, gap = time for the outer layer to react
1    Browser / mobile app           10 s  total (user patience)
2    CDN / edge / load balancer      9 s  request deadline   (ALB idle timeout 60 s is separate)
3    API gateway / NGINX / Envoy     8 s  proxy_read_timeout / route timeout
4    Application handler             7 s  context.WithTimeout / request budget
5    Downstream HTTP call, per try   1.5 s x up to 3 tries + sleeps   (fits in what is left)
6    PostgreSQL statement_timeout    1 s  (aborts before the client's per-try timeout)
7    Result: the innermost layer fails first, with a precise error; outer layers still have time to answer
Timeout layering: each inner limit is shorter than the one around itClient / browser / mobile app: total deadline 10 sEdge / CDN / load balancer (NGINX, Envoy, AWS ALB): request deadline 9 s (idle timeout 60 s is a different knob)API gateway / reverse proxy: proxy_read_timeout or route timeout 8 sApplication handler: context.WithTimeout 7 s (Go) / request budget (Laravel)Downstream HTTP callconnect 0.5 s, per-try 1.5 sup to 3 tries, 3 x 1.5 + sleepsfits in the 7 s remainingPostgreSQLstatement_timeout 1 slock_timeout 200 msidle_in_transaction 10 s

Real scenarios: an NGINX in front of the app has proxy_read_timeout 60s while the app allows 120 s for a report, so users see 504 at 60 s and the app keeps computing; a load balancer idle timeout shorter than the application's keep-alive causes sporadic 502s; the app times out a query at 5 s but PostgreSQL has no statement_timeout, so the abandoned query keeps running and holds a connection; a retry in the gateway starts when the user already left.

What provides it:

MechanismProductWhat it does
context.WithTimeout, ctx.Deadline()GoCarries a deadline through every call that takes a context
grpc-timeout header, ctx deadlinegRPCPropagates the remaining time automatically across services
x-envoy-upstream-rq-timeout-msEnvoy"an outer time limit for a request, including any retries that take place"
proxy_read_timeout, proxy_next_upstream_timeoutNGINXPer-read limit and a cap on the time spent trying other upstreams
Http::timeout() plus a request budget objectLaravelPer-hop timeout from the remaining budget
statement_timeoutPostgreSQLServer aborts the statement even if the client has gone

Fix: write the table above for your system before you write code, with the invariant client > edge > proxy > app > per-try x tries > database.

Choosing timeout values from percentiles Must-know ​

In plain words: Pick the timeout so that a healthy dependency almost never exceeds it. That is a percentile of its real latency, not a round number you like.

Common misunderstanding: "Shorter timeouts are always safer." Too short produces false timeouts: healthy calls are cut, retried, and add load. The Builders' Library states two risks of a low value: the client times out calls that would have succeeded, and the retries add traffic. It also describes a service that timed out right after deployments because its 20 ms timer included connection setup of a new secure connection.

Definition: Choose an acceptable false-timeout rate (the Builders' Library example is 0.1%) and take the matching percentile of the downstream's latency (p99.9). Add padding when p99.9 is close to p50, and measure from the caller, including connection setup.

Dependency p50p99p99.9Suggested per-try timeoutReason
5 ms20 ms60 ms100 to 150 msp99.9 plus padding; at 0.1% false timeouts
40 ms150 ms400 ms600 to 800 msThe tail is wide; padding is proportionally smaller
200 ms800 ms2 s3 to 4 sSlow dependency; hedging may beat a longer timeout
2 s (batch API)5 s9 s12 to 15 sPrefer async (a job) beyond about 10 s
Tight bound (p50 = 20 ms, p99.9 = 25 ms)24 ms25 ms60 msPad: tiny variance must not trip it

These rows are a worked example of the method, not measurements.

text
     Timeline: why a too-low timeout hurts right after a deploy (Builders' Library story)
1    t=0 ms     new server starts, first request needs a new TLS connection
2    t=0 ms     client starts a 20 ms timer that includes connection setup
3    t=35 ms    connection established (35 ms), timer already fired at 20 ms -> timeout
4    t=40 ms    client retries on the now-warm connection -> succeeds in 3 ms
5    result     a burst of errors and extra load at every deployment, none in steady state

Real scenarios: a new region has higher latency and every call times out until timeouts are re-derived; a timeout equal to the p99 cuts 1% of healthy calls; a batch job and an interactive call share one client configuration and one of them is always wrong.

Fix: derive from the dashboard (p99.9 of the dependency as seen by the caller), review after each architecture change, and keep per-dependency configuration, not one global number. Percentile mechanics are in Latency Budgets.

Database and cache timeouts: PostgreSQL, Redis, PDO Important ​

In plain words: The database must also stop things. If only the client gives up, the server may keep running a query nobody waits for, and a transaction left open holds locks and blocks cleanup.

Common misunderstanding: "My HTTP timeout protects the database." The client closing a connection does not always cancel the statement immediately, and a statement already running in the server finishes (and holds locks) unless the server itself has a limit. PostgreSQL has three separate limits for three separate problems.

Definition (PostgreSQL, from the runtime configuration docs):

ParameterWhat it limitsDefaultErrorSQLSTATE
statement_timeoutAny statement that "takes more than the specified amount of time"0 (disabled)canceling statement due to statement timeout57014 query_canceled
lock_timeoutA statement that waits for a lock (table, index, row) longer than this, per lock acquisition0 (disabled)canceling statement due to lock timeout55P03 lock_not_available
idle_in_transaction_session_timeoutA session idle inside an open transaction0 (disabled)terminating connection due to idle-in-transaction timeout25P03
idle_session_timeoutA session idle outside a transaction0 (disabled)terminating connection due to idle-session timeout57P05
transaction_timeout (PostgreSQL 17)Total duration of a transaction0 (disabled)terminating connection due to transaction timeout25P04

The docs warn that setting statement_timeout in postgresql.conf "is not recommended because it would affect all sessions"; set it per role, per database, per session or per transaction (SET LOCAL). They also note that if statement_timeout is non-zero, "it is rather pointless to set lock_timeout to the same or larger value". Idle-in-transaction matters beyond locks: an open transaction "prevents vacuuming away recently-dead tuples", so it also causes bloat. Lock mechanics are in Locks & Concurrency, deadlock handling in Deadlocks, pool sizing in Connection Pooling.

sql
-- Per role: web requests are short, the reporting role may run longer.
ALTER ROLE app_web      SET statement_timeout = '3s';
ALTER ROLE app_web      SET lock_timeout = '500ms';
ALTER ROLE app_web      SET idle_in_transaction_session_timeout = '10s';
ALTER ROLE app_reporting SET statement_timeout = '5min';

-- Per transaction: tighter than the role default, derived from the request budget.
BEGIN;
SET LOCAL statement_timeout = '800ms';
SET LOCAL lock_timeout = '200ms';
SELECT balance FROM accounts WHERE id = 42 FOR UPDATE;   -- waits at most 200 ms for the row lock
COMMIT;

Other stores:

StoreTimeoutNotes
Redis servertimeout 0 in redis.conf closes a client idle for N seconds; default 0 (disabled)Client-side limits matter more
go-redisOptions.DialTimeout, ReadTimeout, WriteTimeout, MaxRetries, MinRetryBackoff, MaxRetryBackoff, ContextTimeoutEnabledThe client has its own retry (MaxRetries): count it as a retry layer
Laravel Redis (phpredis / Predis)timeout, read_timeout in config/database.phpSet both; a blocked read otherwise waits for the default
PDOPDO::ATTR_TIMEOUT in secondsThe manual notes "Not all drivers support this option, and its meaning may differ"
MySQLmax_execution_time (SELECT), innodb_lock_wait_timeoutDifferent names, same roles

Fix: set role-level defaults in the database, derive a smaller SET LOCAL from the request budget for each transaction, and keep the client cancellation (Go: pass the context to QueryContext) so the driver sends a cancel. The Go helper is in Go.

Queue timeouts: job timeout versus retry_after Important ​

In plain words: A queue worker has its own two clocks: how long a job may run (timeout), and how long before the queue assumes the worker died and hands the job to someone else (retry_after, visibility timeout). If the first is longer than the second, the same job runs twice at once.

Common misunderstanding: "retry_after is the delay between retries." In Laravel it is the visibility timeout: how long a reserved job is hidden before it is released again. The delay between retries is backoff.

Definition (Laravel 13 queue docs): queue:work --timeout is "60 seconds" by default; the retry_after of the connection (Redis example 90) is when a still-processing job is released; "The --timeout value should always be at least several seconds shorter than your retry_after configuration value... If your --timeout option is longer than your retry_after configuration value, your jobs may be processed twice." The Timeout attribute on the job overrides the CLI value, and a job whose HTTP call has no timeout of its own may ignore the job timeout, so "when using these features, you should always attempt to specify a timeout using their APIs as well." SQS has no retry_after: the Default Visibility Timeout in AWS decides.

text
     Three nested clocks of one queued job (seconds)
1    Http::timeout(10)           HTTP call inside the job gives up
2    #[Timeout(30)] / --timeout  worker kills the job process
3    retry_after = 90            queue releases the job to another worker
4    Rule: 10 < 30 < 90. Break it (timeout 120, retry_after 90) and the job runs twice at once

Real scenarios: a 2-minute export with retry_after 90 runs on two workers and sends two e-mails; SQS Default Visibility Timeout 30 s with a 60 s job; a job without HTTP timeouts hangs until the worker is killed.

What provides it:

QueueHand-over clockJob time limit
Laravel Redis / databaseretry_after in config/queue.php--timeout, #[Timeout], PCNTL required
Laravel SQS / Amazon SQSDefault Visibility Timeout (AWS)worker timeout, same rule
RabbitMQconsumer acknowledgement timeoutconsumer processing time
Kafkamax.poll.interval.mstime between polls

Broker-side detail is in Retry, Backoff & Delayed Delivery.

Fix: configure the three numbers together (the config excerpt is in Laravel).

What is safe to retry: idempotency and the ambiguous failure Must-know ​

In plain words: Retrying is only safe when doing the thing twice is the same as doing it once. Reading is. "Set the address to X" is. "Add 100 to the balance" is not.

Common misunderstanding: "If the call failed, the thing did not happen." A timeout or a reset tells you only that you did not receive the answer. The Builders' Library says it directly: "A timeout or failure doesn't necessarily mean that side effects haven't happened."

Definition: An operation is idempotent if repeating it has the same effect as doing it once. RFC 9110 section 9.2.2: "PUT, DELETE, and safe request methods are idempotent"; "A client SHOULD NOT automatically retry a request with a non-idempotent method unless it has some means to know that the request semantics are actually idempotent... or some means to detect that the original request was never applied"; and "A proxy MUST NOT automatically retry non-idempotent requests." The classification of failures into certainly not executed, certainly failed and ambiguous is in the next block.

text
     The ambiguous failure: POST /charge, client read timeout 1.5 s
1    client  -> server   POST /charge {order 7, 100.00}
2    server  executes the charge, commits       (takes 1.8 s because of a slow bank)
3    client  timeout at 1.5 s, sees no response
4    client  -> server   POST /charge {order 7, 100.00}   (naive retry)
5    server  executes the charge again           -> customer charged twice
6    with Idempotency-Key: k1 on both requests, step 5 returns the stored result of step 2

Real scenarios: payments, order creation, e-mail sending, inventory decrement, counter increments, webhooks (the receiver gets duplicates), and message publishing (a retried publish duplicates the message).

What provides it:

OperationNaturally idempotent?How to make it safe
GET, HEAD, OPTIONSYes (safe)Nothing
PUT, DELETEYes by definitionThe handler must really behave so
POST createNoIdempotency key stored with the result; or a client-chosen id (PUT /orders/{uuid})
Counter += 1NoSet an absolute value, or dedupe by operation id
Conditional update with version (compare-and-set)Yes in effectVersion column, see Optimistic Locking

Fix: design the operation to be idempotent, then pass a key; the key's storage, lifetime and race handling are in API Idempotency. Section Idempotency keys shows how to wire it into the retry loop.

Error classification: what to retry Must-know ​

In plain words: Sort failures into three piles before looking at the clock: "never reached the server" (always safe), "server may have acted" (safe only if idempotent), and "will never succeed" (stop).

Common misunderstanding: "Retry on any 5xx and any timeout." 501 and most 4xx never succeed; 500 may mean a bug that fails identically every time; and a 4xx from an eventually consistent system can turn into a success a moment later (the Builders' Library says consistency "significantly blurs this line").

Definition: Use three classes: Retryable (the server rejected the request before acting), Ambiguous (the outcome is unknown), Fatal (a retry cannot change the result). The retry package on this page encodes the table below.

ErrorClassWhyRetry non-idempotent?Typical backoff hint
Connection refused (ECONNREFUSED)RetryableNothing was listening; the request never leftYesShort, with jitter
DNS failure (no such host)RetryableNo request was sentYesShort; may need a longer cap
Dial or connect timeoutRetryableThe connection was never establishedYesJitter
TLS handshake failure or timeoutRetryableHandshake precedes the requestYesJitter
429 Too Many RequestsRetryableRejected by a rate limiterYesRetry-After if present
503 Service UnavailableRetryableUsually shed before processingYesRetry-After if present
Read timeout (no response)AmbiguousThe server may still be workingNoJitter, idempotent only
Connection reset or EOF after sendingAmbiguousCrash or kill mid-requestNoJitter, idempotent only
500 Internal Server ErrorAmbiguousMay be a transient fault or a deterministic bug; may have partially actedNoFew attempts
502 Bad Gateway, 504 Gateway TimeoutAmbiguousThe gateway forwarded and lost the answerNoJitter, idempotent only
408 Request TimeoutAmbiguousThe server timed out reading the requestNoJitter
400, 401, 403, 404, 405, 409, 410, 422FatalFix the request, token or state firstNeverNone
501 Not ImplementedFatalWill not changeNeverNone
context.Canceled (caller gave up)FatalThe user left; stop everythingNeverNone

Classes are a judgement call made for this page (503 and 429 are normally rejected before processing, but nothing in HTTP guarantees it); the principle, from RFC 9110, is that you retry non-idempotent requests only when you can tell the original was never applied. NGINX makes the same cut: proxy_next_upstream defaults to error timeout and "requests with a non-idempotent method (POST, LOCK, PATCH) are not passed to the next server" unless you add non_idempotent.

text
     Request flow: classification decides the next step
1    attempt fails with err
2    errors.Is(err, context.Canceled)? -> stop (caller gave up)
3    status 400..499 except 408/429?   -> stop (fatal)
4    refused / dial timeout / 429 / 503 -> retryable: go to budget check
5    read timeout / reset / 500 / 502 / 504 -> ambiguous: go on only if idempotent or keyed
6    otherwise                         -> stop and surface the error
One failed attempt: should we try again, and when?1. Classify the errorfatal / ambiguous / ok2. Ambiguous and notidempotent? stop3. Attempts left?max 3 total4. Budget token?retries <= 10% of traffic5. delay = max(jittered backoff,Retry-After hint)6. now + delay beyondthe overall deadline?yes: give up now7. sleep (fake clock in tests)then attempt n+1 withmin(per-try, time left)Stop and return the errorfatal: 400, 401, 403, 404, 422ambiguous POST without a keyno attempts / no budget leftRetry-After longer than deadlineSafe to retry (where each class comes from)retryable: connection refused, dial timeout, 429, 503ambiguous but idempotent: read timeout, reset, 500, 502, 504idempotent = GET, PUT, DELETE, or a POST with an idempotency keycaller cancelled the context: never retry

Real scenarios: a client retries 401 five times after a token expired (use one refresh, then stop); retrying 409 in a loop against an optimistic lock (reload first); a POST retried after 504 creates duplicates.

Fix: write the classifier once per client, test it with a table (see TestAmbiguousFailureNeedsIdempotency in the Go section), and send the class to the metrics (see Observability).

Retry budgets Must-know ​

In plain words: A retry budget is an allowance for extra traffic. "At most one retry for every ten requests." When the allowance is spent, failures are returned to the caller instead of being repeated.

Common misunderstanding: "Three attempts per request is the limit, so the amplification is at most 3x and that is fine." Three times the traffic against a dependency that is already failing is the problem. A per-request limit does not limit the aggregate; a budget does.

Definition: Google's SRE book describes two layers. "First, we implement a per-request retry budget of up to three attempts." "Secondly, we implement a per-client retry budget. Each client keeps track of the ratio of requests that correspond to retries. A request will only be retried as long as this ratio is below 10%." The worst case drops from "just below 3X" to "just 1.1x in the general case". The Builders' Library reaches the same goal with a token bucket: "This allows all calls to retry as long as there are tokens, and then retry at a fixed rate when the tokens are exhausted." gRPC A6 refills the bucket on successes (tokenRatio) and stops retrying at or below half of maxTokens.

text
     Token-bucket retry budget (ratio 0.1, max 10 tokens)
1    start                          tokens = 10
2    every first attempt            tokens = min(10, tokens + 0.1)        # deposit
3    a retry is wanted              tokens >= 1 ? tokens -= 1 : give up    # withdraw
4    dependency 100% down, 1000 requests, 3 attempts each:
5      without budget  3000 calls (+200%)
6      with budget     1109 calls (+11%)   <- measured by cmd/jittersim on this page

Real scenarios: a database failover for 30 seconds; a cache that restarts empty; a bad deploy of a downstream; a regional outage where every client retries. In each, a budget keeps the client's extra load near 10% while a transient single-instance blip still gets its retries because the bucket is full.

What provides it:

ProductBudget mechanismDefault
gRPCretryThrottling with maxTokens and tokenRatio per server nameNot enabled unless configured
AWS SDK (standard mode)Retry quota: a token bucket deducted per retry and refilled on successEnabled; "During normal operation, the quota stays full and has no effect"
EnvoyRetry budget and the cluster circuit-breaker max_retries (a cap on concurrent retries)Configure explicitly
Go retry package hereBudget{ratio, max}Pass Budget: retry.NewBudget(0.1, 10)
Laravel Http::retry()None built inWrap with a Cache/Redis counter, or use Guzzle middleware

Fix: one shared budget per downstream (not per request, or it is a per-request limit again). Go code: Go. In Laravel the budget must live in shared state (Redis INCR with expiry), since each PHP request is a fresh process.

Per-try timeout versus overall deadline Must-know ​

In plain words: Two clocks run at once: one for each attempt, one for the whole job. The per-try timeout makes sure a hung attempt does not eat the entire time; the overall deadline makes sure all attempts together do not outlast the user.

Common misunderstanding: "Timeout 3 s, 3 attempts, so the call takes at most 3 s." It takes up to 3 x 3 s plus the sleeps, 9 s plus. And the opposite error is common: one big total timeout of 3 s with no per-try limit lets the first hung attempt consume everything and leaves no time for the retry that would have worked.

Definition: per_try_timeout = min(per_try_cap, remaining_time). Stop when now + next_sleep is after the deadline. Envoy states the same split: x-envoy-upstream-rq-timeout-ms "is an outer time limit for a request, including any retries that take place", Envoy "will not retry when a request exceeds" it, and "Use x-envoy-upstream-rq-per-try-timeout-ms if you want to retry when individual attempts take too long." A typical design: deadline 3 s, per-try 1 s, three attempts, and the sleeps are 0 to 100 ms so the third try still has time.

text
     Deadline 3 s, per-try 1 s, full jitter backoff (base 100 ms)
1    t=0.00 s   attempt 1 starts       limit = min(1 s, 3 s left)
2    t=1.00 s   attempt 1 times out    (ambiguous: only idempotent calls continue)
3    t=1.00 s   sleep random(0,100 ms) -> 0.06 s
4    t=1.06 s   attempt 2 starts       limit = min(1 s, 1.94 s left)
5    t=2.06 s   attempt 2 times out
6    t=2.06 s   sleep random(0,200 ms) -> 0.15 s, 2.21 + 0.79 left  -> attempt 3 limit = 0.79 s
7    t=3.00 s   deadline; give up with the last error

Real scenarios: a search call with 2 s deadline and a stuck replica: per-try 400 ms, retry hits another replica and returns in 600 ms total; a checkout that must answer within 10 s but calls five dependencies, so each gets its own share.

What provides it: Go context.WithTimeout per attempt derived from the parent context; Envoy per_try_timeout in the route retry policy; gRPC per-attempt behaviour follows the call deadline (retries stop when the deadline passes); Laravel: Http::timeout() is per attempt, so use a request budget object for the overall limit (see PaymentsClient).

Fix: always compute the per-try limit from what is left, and refuse to start an attempt (or sleep) that cannot finish. The retry.Do function does both.

Retry at one layer only; retry storms Must-know ​

In plain words: If every level of the stack retries, the number of calls at the bottom is the product of the attempts, not the sum.

Common misunderstanding: "Each layer's retries are independent and small." The Builders' Library works it out: "Consider a system where the customer's call causes a five-deep stack of service calls. It ends with a query to a database, and three retries at each layer. What happens when the database starts failing queries under load? If each layer retries independently, the load on the database will increase 243x". And the opposite choice has a cost: "retrying at the highest layer of the stack may waste work from previous calls". Its general rule for cheap operations is "retry at a single point in the stack".

Definition: A retry storm (or retry amplification, retry avalanche) is the self-sustaining overload created by retries: the dependency slows, clients time out and retry, the extra load slows it further, more clients time out. It is a metastable state: removing the trigger (the original blip) does not end it, only shedding the retry load does. A thundering herd is the same clients acting together; jitter addresses the timing, a budget addresses the volume.

Retry at one layer, not at every layerEvery layer retries 3 timesEdge: 3 triesService A: 3 triesService B: 3 triesService C: 3 triesService D: 3 triesDatabasefails under load1 call3 calls9 calls27 calls81 calls243 callsOnly the edge retries, with a budgetEdge: 3 tries + budgetService A: fail fastService B: fail fastService C: fail fastService D: fail fastDatabaseat most 3 calls1 call, retried by theedge up to 2 more times1 call per edge attempt3 calls worst casebudget: about +10% overall
text
     The amplification, layer by layer (3 attempts each)
1    edge          1 x 3  = 3  calls into service A per user request
2    service A     3 x 3  = 9  calls into B
3    service B     9 x 3  = 27 calls into C
4    service C     27 x 3 = 81 calls into D
5    service D     81 x 3 = 243 calls into the database
6    fix: only the edge retries (3 attempts, 10% budget); A, B, C, D fail fast and say why

Real scenarios: the database at 90% CPU starts timing out; every pod of every service retries; CPU stays at 100% after the original cause is fixed. A deploy with a bug raises error rates and the SDK, the service mesh sidecar and the application all retry. A mobile app retries on every screen after a short outage and the backend sees 10x traffic at the moment it restarts.

What provides it:

ControlProductEffect
Retry at the edge, fail fast insideDesign ruleProduct of attempts becomes the edge's attempts
Retry budgetgRPC, AWS SDK, EnvoyAggregate cap
Circuit breakerResilience4j, Envoy outlier detection, IstioStops calling when failures cross a threshold; see Circuit Breaker
Load sheddingServer sideThe dependency rejects fast; see Load Shedding
Rate limitingGatewayLimits arrivals; see Rate Limiting
Disable mesh retries when the app retriesIstio / EnvoyAvoid a hidden second layer

Fix: inventory every layer that can retry (SDK, HTTP client, mesh sidecar, gateway, job queue, user's browser), pick one, and set the others to zero. Document it next to the timeout table.

Backoff: constant, linear, exponential, capped Must-know ​

In plain words: Backoff means pausing before the next try, and pausing longer each time. The idea is to give the dependency room to recover.

Common misunderstanding: "More attempts with a short fixed delay is more resilient." Five instant retries cost five times the load in a few milliseconds. The Builders' Library: "Instead of retrying immediately and aggressively, the client waits some amount of time between tries."

Definition:

StrategyFormula (attempt n = 1, 2, ...)ShapeWeakness
Constantsleep = dFlatSame pressure every round; clients stay synchronised
Linearsleep = min(cap, n * step)RampSlow ramp; still synchronised
Exponentialsleep = base * 2^(n-1)100, 200, 400, 800 msGrows without bound; synchronised
Capped exponentialsleep = min(cap, base * 2^(n-1))100, 200, 400, ... capEveryone at the cap is still synchronised
With jittersee JitterSpreadSlightly more wall-clock time on average

Timeline of 4 clients without jitter (Brooker's "clusters of calls"):

text
     Four clients fail together at t=0, capped exponential, base 100 ms, no jitter
1    t=0       calls: A B C D       (4 calls, one wins)
2    t=100 ms  calls: B C D         (all sleep exactly 100 ms)
3    t=300 ms  calls: C D           (all sleep exactly 200 ms more)
4    t=700 ms  calls: D
5    every round has all remaining clients calling at the same instant; the gaps in between are idle

Real scenarios: a recovering database that gets a synchronised wave every 800 ms; an OCC loop where N writers collide on the same row.

What provides it: Laravel Http::retry(3, 100) is constant; Http::retry([100, 200, 400]) is an explicit schedule; queue:work --backoff=3 is constant; job #[Backoff([10, 30, 60])] is a schedule (the last value repeats); go-retryablehttp default is exponential between RetryWaitMin and RetryWaitMax; the AWS SDK uses exponential with full jitter; gRPC uses exponential with +/-20% jitter.

Fix: always cap, always add jitter, and keep the number of attempts small (3 for interactive calls, up to 5 for background work).

Jitter: full, equal, decorrelated Must-know ​

In plain words: Jitter is randomness added to the sleep so that clients which failed together do not return together. "Initially, jitter may appear to be a counter-intuitive idea: trying to improve the performance of a system by adding randomness."

Common misunderstanding: "A little jitter (plus or minus 10%) is enough." gRPC uses +/-20% to avoid hammering "at the same time from a large number of clients", which spreads the start of each round slightly, but the strongest result in Brooker's simulation is full jitter, where the sleep ranges over the entire interval from 0 to the exponential ceiling.

Definition (Brooker 2015, formulas written out from the post's figures):

Variantsleep =Range at attempt 4 (base 100 ms, cap 5 s)
No jittermin(cap, base * 2^(n-1))exactly 800 ms
Full jitterrandom(0, min(cap, base * 2^(n-1)))0 to 800 ms
Equal jittert/2 + random(0, t/2) with t = min(cap, base * 2^(n-1))400 to 800 ms
Decorrelated jittermin(cap, random(base, previous * 3))100 ms to 3 x the previous sleep

Brooker's results for contending clients: "the number of calls is approximately the same for 'Full' and 'Equal' jitter, and higher for 'Decorrelated'"; "Of the jittered approaches, 'Equal Jitter' is the loser. It does slightly more work than 'Full Jitter', and takes much longer"; and "The 'Full Jitter' approach uses less work, but slightly more time" than decorrelated. The AWS SDK reference states the shipped choice: "The SDK uses exponential backoff with full jitter."

Where the sleep lands, per retry (base 100 ms, cap 5 s)01 s2 s3 s4 s5 s1234567retry numberno jitter: the ceilingFull: anywhere from 0up to the ceilingEqual: from ceiling/2up to the ceilingDecorrelated: random(base, 3 x previous)Narrow bar: ceiling/2,floor of equal jitter
text
     1000 clients, 4th retry, base 100 ms: how many wake up in each 100 ms slot of [0, 800 ms)
1    no jitter        all 1000 wake at exactly 800 ms, every slot before it is empty
2    full jitter      about 125 per slot in all 8 slots (uniform)
3    equal jitter     about 250 per slot in slots 4 to 7 (400-800 ms)
4    decorrelated     depends on each client's own previous sleep: no two clients stay in step

Real scenarios: a cache expiring at 12:00:00 for every client; a deployment that restarts 500 pods whose clients all reconnect; a nightly cron job at 00:00 on every host; a scheduled retry at "5 minutes" for all failed webhooks.

What provides it: AWS SDKs (full jitter); gRPC (+/-0.2); go-retryablehttp LinearJitterBackoff; Laravel does not add jitter to Http::retry() or job backoff arrays, you add it in a closure or a backoff() method; Guzzle's Middleware::retry default delay is exponential without jitter, supply your own $delay callable.

Fix: full jitter is the right default (least work, simple). Use equal jitter when you need a guaranteed minimum pause; decorrelated when delays should depend on the previous one and not on the attempt number (useful when attempts are not strictly sequential).

Server hints: Retry-After, pushback, 429 and 503 Important ​

In plain words: The server knows better than your formula when it will be ready. If it says "come back in 30 seconds", believe it.

Common misunderstanding: "Retry-After only exists for 503." RFC 9110 defines it for any response, with specific meaning for 503 (how long the service is expected to be unavailable) and 3xx (the minimum time before following the redirect); 429 uses it by convention.

Definition: Retry-After = HTTP-date / delay-seconds, with delay-seconds = 1*DIGIT. Examples from the RFC: Retry-After: Fri, 31 Dec 1999 23:59:59 GMT and Retry-After: 120. Your client should parse both forms, take the larger of its own backoff and the hint, and stop if the hint exceeds what is left of the deadline. gRPC has the equivalent in metadata: grpc-retry-pushback-ms; a negative or unparseable value means do not retry at all, and a valid value makes the client retry after exactly that delay. A6 adds that if the client has exhausted maxAttempts, the call will not be retried "even if the server says to retry after a given delay".

text
     Retry-After in a call
1    client  -> server   GET /report
2    server  -> client   429 Too Many Requests   Retry-After: 2
3    client  computes    backoff = random(0, 200 ms) = 140 ms; hint = 2000 ms; sleep = max = 2000 ms
4    client  waits 2 s   (fake clock in tests)
5    client  -> server   GET /report             -> 200

Real scenarios: API rate limits (GitHub-style 429 with a reset time); maintenance windows (503 with a date); a server shedding load that returns a small Retry-After with random spread to desynchronise clients; a CDN edge returning 503 during origin failover.

What provides it: go-retryablehttp parses Retry-After on 429 (DefaultBackoff) and on 429 or 503 (RateLimitLinearJitterBackoff); the AWS SDK waits longer for throttling errors than for transient ones; Laravel Http::retry() does not read it by itself, you read it in the sleep closure (PaymentsClient).

Fix: parse it, bound it by the deadline, add a random component on the server when you send it so a million clients do not return exactly on the second.

Idempotency keys inside a retry loop Must-know ​

In plain words: The idempotency key is a name for "this attempt to do this thing". All the retries of one operation carry the same name, so the server can recognise a repeat and return the first answer.

Common misunderstanding: "Generate a fresh UUID for every request." A new key on every retry is a new operation each time, and the protection is gone. The key must be created before the first attempt and survive every retry (and, for background jobs, every re-delivery of the job).

Definition: The client sends Idempotency-Key: <opaque id> on a POST; the server stores the key with the first result and returns that result for repeats. Lifetime, storage, concurrency and error behaviour are in API Idempotency. Amazon's EC2 RunInstances is the Builders' Library's example of "explicit token-based mechanisms to provide idempotency".

text
     One logical charge, three attempts, one key
1    key = uuid()                       # outside the loop, stored with the order row
2    attempt 1  POST /charge  key=K     -> read timeout (ambiguous)
3    attempt 2  POST /charge  key=K     -> 503 Retry-After: 1   (retryable)
4    attempt 3  POST /charge  key=K     -> 200 {charge_id: c1}  (or the stored result of attempt 1)
5    the customer is charged exactly once either way

Real scenarios: payment capture, order submission, e-mail or SMS sending, ledger entries, issuing a coupon, creating a cloud resource.

What provides it: Stripe-style Idempotency-Key headers (see Payment Processing), AWS client tokens, a unique constraint on an operation id in your own database, Laravel ShouldBeUnique jobs for queue duplicates (different problem: it prevents two jobs queued, not a repeated side effect).

Fix: derive the key from the operation (order id plus action) when you can, so a restarted process reuses it; otherwise store the generated key before sending. The PHP in Laravel generates it once outside retry().

Hedging versus retrying Important ​

In plain words: A retry waits for the first attempt to fail. A hedged request sends a second copy while the first is still pending, because it is slower than usual, and takes whichever answers first.

Common misunderstanding: "Hedging is just a retry with a shorter timeout." The first attempt is not cancelled by a timeout; it keeps running, so you are paying for two concurrent calls, and the server must tolerate duplicates. The latency chapter has the numbers: hedging after the p95 adds about 5% load and cuts the tail.

Definition: gRPC A6 defines a hedging policy ("aggressively sending multiple copies of a single request without waiting for a response") with maxAttempts and hedgingDelay, applies the same throttling tokens to hedges, and warns that hedged RPCs "may be executed multiple times on the server side, typically by different backends", so it is only for methods "safe to execute multiple times". An RPC is governed by a retry policy or a hedging policy, not both. Envoy offers hedge_on_per_try_timeout.

AspectRetryHedge
Triggered byA failure or a per-try timeoutA delay (about p95) with no answer yet
First attemptFinished (failed or cancelled)Still running
Extra loadOnly when failures happenAbout 5% in steady state (Dean and Barroso)
ReducesError rateTail latency (p99)
Needs idempotencyYes for ambiguous failuresYes always (both may execute)
BudgetRetry budgetThe same budget; hedging must not run in an outage

Real scenarios: a read from a replicated store where one replica is in a GC pause; a search fan-out where one shard is slow; never a payment. Details and measurements: Latency Budgets.

Fix: hedge reads, cap with the same budget as retries, cancel the loser through the context.

Retries in queues: tries, backoff, retryUntil Important ​

In plain words: A queued job retries by being put back on the queue. The questions are the same (how many times, how long between, when to stop), but the answers live in worker configuration and job attributes.

Common misunderstanding: "A job is retried until it works." In Laravel "By default, Laravel will only attempt a job once." Many things consume an attempt: an unhandled exception, $this->release(), a middleware that fails to take a lock, a timeout. Setting Tries too low turns lock contention into permanent failure (the docs: "leaving Tries to 1 as it is by default would prevent any overlapping job from being retried later").

Definition (Laravel 13 queues):

KnobMeaningExample
--tries / #[Tries(n)] / tries()Maximum attempts; job attribute beats the CLI value; --tries=0 retries forever#[Tries(8)]
retryUntil() / #[RetryFor(hours: 1)]Time window instead of a count; retryUntil "takes precedence" over triesnow()->plus(hours: 6)
--backoff / #[Backoff(3)] / backoff()Seconds to wait after an exception; an array is an escalating schedule, the last value repeats#[Backoff([10, 30, 60])]
#[MaxExceptions(n)]Many attempts but fail after n exceptions (not releases)#[Tries(25)] #[MaxExceptions(3)]
$this->release($seconds)Manual re-queue with a delay; consumes an attemptrelease(10); releaseUsingBackoff()
#[Timeout(n)], --timeoutMax run time of one attemptdefault 60 s
#[FailOnTimeout]Mark failed instead of retried on timeout
ThrottlesExceptions(n, seconds)Middleware: after n exceptions, hold attempts until the interval endsA breaker for jobs
retry_after (connection)Visibility timeout90
text
     A job with #[Tries(5)] #[Backoff([10, 30, 60])] on the Redis queue
1    t=0      attempt 1 throws                 -> released with delay 10 s
2    t=10     attempt 2 throws                 -> delay 30 s
3    t=40     attempt 3 throws                 -> delay 60 s
4    t=100    attempt 4 throws                 -> delay 60 s (last value repeats)
5    t=160    attempt 5 throws                 -> attempts exhausted -> failed_jobs, failed() called

Real scenarios: webhook delivery to a customer endpoint that is down for an hour (use retryUntil and escalating backoff); an e-mail provider with rate limits (use release() with the Retry-After); a job that holds a distributed lock and must retry later.

What provides it: Laravel as above; Kafka has no per-message retry, so you write retry topics; RabbitMQ uses TTL queues or the delayed-message plugin; SQS uses the visibility timeout and maxReceiveCount. See Retry, Backoff & Delayed Delivery and the parking lot in Dead Letter Queues.

Fix: use #[Backoff] with an array, or a backoff() method with jitter (the PHP in Laravel); combine retryUntil with MaxExceptions; keep jobs idempotent, since "released" and "timed out" jobs run again.

Library retries: what the defaults really do Important ​

In plain words: Many clients retry by themselves. If you add your own loop on top, you have built the 243x stack in your own process.

Common misunderstanding: "The SDK does not retry unless I ask." The AWS SDKs retry by default; gRPC retries transparently in some cases; go-redis retries commands (MaxRetries); your service mesh sidecar may retry too.

LibraryDefault behaviourKnobsRetry budget
AWS SDKs (standard mode)Exponential backoff with jitter; 3 max attempts (DynamoDB: 4); shorter delays for transient errors, longer for throttlingretry_mode, max_attempts, AWS_MAX_ATTEMPTSRetry quota (token bucket)
AWS SDKs (adaptive mode)Standard plus a client-side rate limiter that can delay the first request; per SDK clientretry_mode=adaptiveRate limiter plus quota; "not recommended as a general default"
gRPCRetry policy in service config: maxAttempts (cap 5), initialBackoff, maxBackoff, backoffMultiplier, retryableStatusCodes, jitter +/-20%Service config JSONretryThrottling (maxTokens, tokenRatio)
Envoyretry_on (5xx, gateway-error, reset, connect-failure, refused-stream), num_retries, per_try_timeout; default retries 1Route or virtual-host retry policy, headersRetry budgets and cluster max_retries circuit breaker
NGINXproxy_next_upstream error timeout; POST not retried unless non_idempotent; proxy_next_upstream_tries, proxy_next_upstream_timeoutPer locationNone
go-retryablehttpRetries connection errors and 5xx except 501; exponential backoff between RetryWaitMin and RetryWaitMax; RetryMaxCheckRetry, BackoffNone
GuzzleNo retry unless you push GuzzleHttp\Middleware::retry($decider, $delay); the default delay is exponentialDecider and delay callablesNone
Laravel Http::retry()Retries on any exception (including RequestException) unless a when callable decidestimes, sleep (int, array or closure), when, throwNone
go-redisMaxRetries with MinRetryBackoff and MaxRetryBackoff; cluster client retries internallyOptionsNone

Real scenarios: an app wraps the AWS SDK in its own three-try loop (9 attempts per call); an Envoy sidecar retries 503 while the app also retries; a Guzzle middleware retries a POST that has no key.

Fix: read the defaults, turn off the layer you do not need (AWS max_attempts=1 when your own loop owns retries, Envoy num_retries: 0), and make the remaining layer the one that knows idempotency.

Retries and the circuit breaker Good to know ​

In plain words: Retries ask "should I try again". A circuit breaker asks "should I stop trying at all for a while". They work together: a breaker is the stronger protection when failure is not transient.

Common misunderstanding: "A circuit breaker replaces retries." It does not; retries fix transient single-request failures, the breaker caps the damage when failures are widespread. The Builders' Library notes that breakers "introduce modal behavior into systems that can be difficult to test" and prefers a local token bucket on retries as the first line of defence. Design and states (closed, open, half-open) are in Circuit Breaker.

Definition and order: the breaker sits outside the retry loop for the whole operation or inside per attempt, depending on whether an open circuit should consume a retry. A common choice: each attempt asks the breaker first; an open circuit is a fatal-for-now error that the loop does not retry but surfaces at once.

Fix: treat "circuit open" as a distinct error class with its own metric.

Observability of retries Important ​

In plain words: If you cannot see how many retries happen and why, you only notice them when they are the outage.

Common misunderstanding: "Success rate is enough." A 99.9% success rate can hide that one request in three needed a second attempt, which is how a budget gets used up long before an alert fires.

Definition: Count and label: attempts per request (histogram), retries total by reason class and status, give-ups by reason (max attempts, budget, deadline, fatal, ambiguous), time slept, budget tokens left, per-try timeouts. Trace each attempt as a child span with retry.attempt and error.type. Alert on the ratio of retries to first attempts and on budget exhaustion, not on the raw count. See Observability and SLO alerting in Alerting That Actually Works.

MetricTypeLabelsAlert when
client_attempts_totalCounterdependency, attempt (1, 2, 3+)Ratio of attempt 2+ to attempt 1 exceeds 5% for 10 min
client_retries_totalCounterdependency, reason (class and code)A new reason appears
client_giveups_totalCounterdependency, reasonbudget exhausted greater than 0 for 5 min
client_retry_sleep_secondsHistogramdependencyMedian sleep at the cap
client_timeouts_totalCounterdependency, kind (connect, read, total)Rising after a deploy
retry_budget_tokensGaugedependencyBelow 20% of max

Fix: the OnRetry hook in the Go retry.Policy is the one place to emit them; in Laravel use the retry closure and the HTTP client events (RequestSending, ResponseReceived, ConnectionFailed).

Testing retries with a fake clock Important ​

In plain words: A retry loop with real sleeps makes tests slow and flaky, so tests replace the clock: "sleep" becomes "advance the fake time and write it down".

Common misunderstanding: "Retry code is too timing-dependent to unit-test." Only if it reads the real clock. If time and randomness are injected, every property (the delays, the stop conditions, the budget) is deterministic.

Definition: inject Clock (Now, Sleep) and Rand. In tests Sleep advances a counter and records the delay; Rand is a seeded PCG or a constant (0.0 and 0.999 test the bounds). Check four kinds of property: schedule (the exact sleeps for given attempts), bounds (jitter inside its range for many seeds), stop rules (deadline, max attempts, budget, fatal, ambiguous), effects (the number of calls to the server).

text
     A fake-clock test (TestDeadlineStopsBeforeASleepThatCannotFit)
1    policy: Overall 1 s, Backoff constant 400 ms, MaxAttempts 10
2    attempt at t=0.0   fails 503; next sleep ends at 0.4  <= 1.0 -> sleep (fake: now = 0.4)
3    attempt at t=0.4   fails 503; sleep ends at 0.8       <= 1.0 -> sleep (now = 0.8)
4    attempt at t=0.8   fails 503; sleep would end at 1.2  >  1.0 -> give up "deadline"
5    assert: calls == 3, slept == 800 ms, test runs in microseconds

Real scenarios: proving that a non-idempotent POST is not retried after a read timeout; proving Retry-After: 7 yields a 7 s sleep; proving a 1000-request outage costs at most 11% extra calls.

What provides it: Go: your own Clock interface (or testing/synctest); Laravel: Sleep::fake() for the Sleep helper, Http::fake() with Http::sequence() to return 503, 503, then 200, Http::assertSentCount(), and a seeded random source passed to the Backoff class. Beyond unit tests, inject faults in staging (latency, resets) as described in Chaos Engineering.

Fix: keep a table of (error, idempotent, expected calls) like TestAmbiguousFailureNeedsIdempotency.

Mechanics ​

The formulas and the arithmetic ​

QuantityFormulaExample
Worst-case duration of a retried callattempts x per_try + sum(sleeps), but never more than the deadline3 x 1.5 s + about 0.3 s = 4.8 s
Sleep ceiling at attempt nmin(cap, base * 2^(n-1))base 100 ms, cap 5 s: 100, 200, 400, 800, 1600, 3200, 5000 ms
Calls reaching the bottom of a stackproduct of attempts at each layer3^5 = 243
Extra load with a budget of ratio rat most r of first attempts, plus the initial reserver = 0.1: about +10% (measured +11%)
Extra load without a budget during a total outage(attempts - 1) x 100%3 attempts: +200%
False-timeout rate for percentile p1 - pp99.9 timeout: 0.1% of healthy calls are cut
Server-side timeout marginstatement_timeout = request_deadline_remaining - margin2 s left, margin 200 ms: 1.8 s

Knobs by product ​

ProductKnobDefaultMeaning
Go net.DialerTimeoutnoneMax time to establish a connection; OS may cut earlier (about 3 minutes for TCP)
Go http.TransportTLSHandshakeTimeout, ResponseHeaderTimeout, IdleConnTimeout, ExpectContinueTimeoutnone (DefaultTransport sets a few)Per-phase limits
Go http.ClientTimeoutnoneWhole attempt including body read
Go http.ServerReadTimeout, ReadHeaderTimeout, WriteTimeout, IdleTimeoutnoneServer-side limits; http.TimeoutHandler bounds a handler
Go contextWithTimeout, WithDeadline, WithTimeoutCausenot applicableDeadline that every blocking call should honour; always defer cancel()
PostgreSQLstatement_timeout, lock_timeout, idle_in_transaction_session_timeout, idle_session_timeout, transaction_timeout0 (all disabled)Server-side limits per role, database, session or SET LOCAL
Redis servertimeout0Close an idle client
go-redisDialTimeout, ReadTimeout, WriteTimeout, MaxRetries, ContextTimeoutEnabledsee the Options docsSet all explicitly
Laravel HTTP clienttimeout(), connectTimeout(), retry()30 s, 10 s, nonePer attempt
Guzzletimeout, connect_timeout, read_timeout0 (no limit)Transfer, connect and stream-read limits
Laravel queueretry_after, --timeout, --tries, --backoff, #[Timeout], #[Tries], #[Backoff], retryUntil()90 (example), 60 s, 1, 0Visibility timeout, run time, attempts
NGINXproxy_connect_timeout, proxy_send_timeout, proxy_read_timeout, proxy_next_upstream, proxy_next_upstream_tries60 s, 60 s, 60 s, error timeout, 0 (no limit)Per phase and retry on another upstream
Envoy routetimeout, retry_policy.retry_on, num_retries, per_try_timeout15 s, none, 1 when retry_on is setOverall, which failures, how many, per attempt
AWS ALBconnection idle timeout60 sClose idle connections; keep application idle timeout larger
gRPCdeadline, retryPolicy, hedgingPolicy, retryThrottlingnoneService-config JSON
AWS SDKretry_mode, max_attemptsstandard, 3AWS_RETRY_MODE, AWS_MAX_ATTEMPTS

Error messages you will actually see ​

WhereMessage or codeMeaningFirst fix
Gocontext deadline exceededA context deadline passed (per-try, overall or caller)Find which one; log the cause with WithTimeoutCause
Gonet/http: request canceled (Client.Timeout exceeded while awaiting headers)Client.Timeout fired before headersRaise or fix the server; check ambiguity before retrying
Gonet/http: TLS handshake timeoutTLSHandshakeTimeout firedRetryable: no request sent
Godial tcp 192.0.2.10:443: i/o timeoutDialer timeoutRetryable: nothing was sent
Godial tcp 192.0.2.10:443: connect: connection refusedNothing listeningRetryable; check the deploy
Goread tcp ...: connection reset by peer, EOFPeer closed after the requestAmbiguous: idempotent only
PostgreSQLERROR: canceling statement due to statement timeout (57014)statement_timeout hitFix the query or raise for that role
PostgreSQLERROR: canceling statement due to lock timeout (55P03)lock_timeout hitRetry later; investigate the blocker
PostgreSQLFATAL: terminating connection due to idle-in-transaction timeout (25P03)Client left a transaction openFix the code path that holds BEGIN open
Laravel HTTPcURL error 28: Operation timed out after 3001 millisecondstimeout() hit; ConnectionExceptionAmbiguous: keyed or idempotent only
Laravel HTTPcURL error 7: Failed to connect ... Connection refusedConnectionExceptionRetryable
Laravel queueMaxAttemptsExceededException ... has been attempted too many timesAttempts exhaustedSee failed() and failed_jobs
Laravel queueTimeoutExceededException, worker exit--timeout or #[Timeout] hitFix the slow call; keep timeout below retry_after
NGINX504 Gateway Time-out, upstream timed out (110: Connection timed out) while reading response header from upstreamproxy_read_timeout hitAlign with the app deadline
NGINX502 Bad Gateway after a long idleUpstream closed a connection NGINX reusedMake the upstream idle timeout longer than NGINX's
AWS ALB504 Gateway Timeout; 502 when the app closes ungracefullyIdle or target timeoutApplication idle timeout larger than the ALB's (60 s default)
Envoy503 upstream_reset_before_response_started, 504 upstream request timeoutReset before the first byte, or route timeoutCheck per_try_timeout and retry_on
HTTP429 with Retry-After, 503 with Retry-AfterRate limit or sheddingObey the hint

Message texts are quoted from common usage and error-code listings; the SQLSTATE codes were checked against the PostgreSQL error-code appendix.

Go ​

The module academy/timeouts-retries-jitter uses only the standard library. retry is the loop, httpclient is the timeout catalogue plus an idempotent GET, dbtimeouts applies PostgreSQL limits from a database/sql transaction, and cmd/jittersim prints the numbers on this page.

Before ​

Five immediate retries of a POST through http.DefaultClient: no timeout, no delay, no jitter, no classification, no key.

go
// Before: the three classic mistakes in one file.
//  1. http.DefaultClient has no timeout, so a hung peer hangs us forever.
//  2. Every layer retries immediately, so three layers multiply (3 x 3 x 3).
//  3. No jitter, no budget, no classification: POST is retried after an ambiguous failure.
package main

import (
	"fmt"
	"net/http"
	"strings"
)

// callWithRetry retries five times with no delay, whatever the error was.
func callWithRetry(url string) (*http.Response, error) {
	var lastErr error
	for i := 0; i < 5; i++ {
		resp, err := http.DefaultClient.Post(url, "application/json", strings.NewReader(`{"amount":100}`))
		if err == nil && resp.StatusCode < 500 {
			return resp, nil
		}
		lastErr = err
		// no sleep, no jitter, no budget, no idempotency key
	}
	return nil, fmt.Errorf("gave up: %w", lastErr)
}

func main() {
	_, err := callWithRetry("http://payments.internal.example/charge")
	fmt.Println(err)
}

After ​

The clock. A Clock interface and a FakeClock that records sleeps and advances without waiting.

go
package retry

import (
	"context"
	"sync"
	"time"
)

// Clock is the only way the package reads or spends time, so tests can fake it.
type Clock interface {
	Now() time.Time
	// Sleep waits for d or until ctx ends, whichever is first.
	Sleep(ctx context.Context, d time.Duration) error
}

// RealClock uses the wall clock and a timer.
type RealClock struct{}

func (RealClock) Now() time.Time { return time.Now() }

func (RealClock) Sleep(ctx context.Context, d time.Duration) error {
	if d <= 0 {
		return ctx.Err()
	}
	t := time.NewTimer(d)
	defer t.Stop()
	select {
	case <-t.C:
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

// FakeClock never waits: Sleep advances Now and records the delay.
type FakeClock struct {
	mu     sync.Mutex
	now    time.Time
	Sleeps []time.Duration
}

// NewFakeClock starts at a fixed instant so output is reproducible.
func NewFakeClock() *FakeClock {
	return &FakeClock{now: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)}
}

func (c *FakeClock) Now() time.Time {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.now
}

func (c *FakeClock) Sleep(ctx context.Context, d time.Duration) error {
	if err := ctx.Err(); err != nil {
		return err
	}
	c.mu.Lock()
	defer c.mu.Unlock()
	c.Sleeps = append(c.Sleeps, d)
	c.now = c.now.Add(d)
	return nil
}

// Total returns the sum of all recorded sleeps.
func (c *FakeClock) Total() time.Duration {
	c.mu.Lock()
	defer c.mu.Unlock()
	var sum time.Duration
	for _, d := range c.Sleeps {
		sum += d
	}
	return sum
}

Backoff strategies. Constant, linear, capped exponential, full, equal and decorrelated jitter, with an injectable random source.

go
package retry

import (
	"math"
	"time"
)

// Backoff chooses how long to wait before retry number `attempt` (1 = first retry).
// prev is the delay returned for the previous retry (zero for the first one);
// only decorrelated jitter needs it.
type Backoff interface {
	Next(attempt int, prev time.Duration) time.Duration
}

// Rand returns a float in [0, 1). Inject math/rand/v2 in production and a
// seeded or constant source in tests.
type Rand func() float64

type constant struct{ d time.Duration }

// Constant waits the same time before every retry.
func Constant(d time.Duration) Backoff { return constant{d} }

func (c constant) Next(int, time.Duration) time.Duration { return c.d }

type linear struct{ step, max time.Duration }

// Linear waits step, 2*step, 3*step ... up to max.
func Linear(step, max time.Duration) Backoff { return linear{step, max} }

func (l linear) Next(attempt int, _ time.Duration) time.Duration {
	return min(time.Duration(attempt)*l.step, l.max)
}

// expCap is min(cap, base * 2^(attempt-1)) without integer overflow.
func expCap(base, max time.Duration, attempt int) time.Duration {
	if attempt < 1 {
		attempt = 1
	}
	f := float64(base) * math.Pow(2, float64(attempt-1))
	if f >= float64(max) {
		return max
	}
	return time.Duration(f)
}

type exponential struct{ base, max time.Duration }

// Exponential is capped exponential backoff with no randomness:
// sleep = min(cap, base * 2^(attempt-1)).
func Exponential(base, max time.Duration) Backoff { return exponential{base, max} }

func (e exponential) Next(attempt int, _ time.Duration) time.Duration {
	return expCap(e.base, e.max, attempt)
}

type fullJitter struct {
	base, max time.Duration
	rnd       Rand
}

// FullJitter: sleep = random(0, min(cap, base * 2^(attempt-1))).
func FullJitter(base, max time.Duration, rnd Rand) Backoff { return fullJitter{base, max, rnd} }

func (f fullJitter) Next(attempt int, _ time.Duration) time.Duration {
	return time.Duration(f.rnd() * float64(expCap(f.base, f.max, attempt)))
}

type equalJitter struct {
	base, max time.Duration
	rnd       Rand
}

// EqualJitter: t = min(cap, base * 2^(attempt-1)); sleep = t/2 + random(0, t/2).
func EqualJitter(base, max time.Duration, rnd Rand) Backoff { return equalJitter{base, max, rnd} }

func (e equalJitter) Next(attempt int, _ time.Duration) time.Duration {
	t := expCap(e.base, e.max, attempt)
	return t/2 + time.Duration(e.rnd()*float64(t/2))
}

type decorrelated struct {
	base, max time.Duration
	rnd       Rand
}

// Decorrelated: sleep = min(cap, random(base, prev * 3)). It remembers the
// last delay instead of the attempt number.
func Decorrelated(base, max time.Duration, rnd Rand) Backoff { return decorrelated{base, max, rnd} }

func (d decorrelated) Next(_ int, prev time.Duration) time.Duration {
	if prev < d.base {
		prev = d.base
	}
	hi := prev * 3
	s := d.base + time.Duration(d.rnd()*float64(hi-d.base))
	return min(s, d.max)
}

The retry budget. A token bucket that traffic refills and retries drain.

go
package retry

import "sync"

// Budget is a retry budget: a token bucket that traffic refills and retries drain.
// With ratio 0.1 the steady-state extra load from retries is at most about 10%
// of first attempts, however many attempts each request is allowed.
type Budget struct {
	mu     sync.Mutex
	tokens float64
	max    float64
	ratio  float64
}

// NewBudget starts full. max is the burst reserve (retries allowed with no traffic).
func NewBudget(ratio, max float64) *Budget {
	return &Budget{tokens: max, max: max, ratio: ratio}
}

// Deposit is called once per logical request (its first attempt).
func (b *Budget) Deposit() {
	b.mu.Lock()
	defer b.mu.Unlock()
	b.tokens = min(b.tokens+b.ratio, b.max)
}

// Withdraw takes one token for a retry; false means the budget is exhausted.
func (b *Budget) Withdraw() bool {
	b.mu.Lock()
	defer b.mu.Unlock()
	if b.tokens < 1 {
		return false
	}
	b.tokens--
	return true
}

// Tokens reports the current balance (for metrics and tests).
func (b *Budget) Tokens() float64 {
	b.mu.Lock()
	defer b.mu.Unlock()
	return b.tokens
}

Classification and server hints. Retryable, Ambiguous, Fatal; StatusError carrying Retry-After; ParseRetryAfter for seconds and HTTP-date.

go
package retry

import (
	"context"
	"errors"
	"fmt"
	"io"
	"net"
	"net/http"
	"strconv"
	"strings"
	"syscall"
	"time"
)

// Class says what a failure means for retrying.
type Class int

const (
	// Fatal: retrying cannot help (4xx, bad input, context cancelled by the caller).
	Fatal Class = iota
	// Retryable: the request was certainly not processed (connection refused,
	// dial timeout, 429, 503), so even a non-idempotent call may be repeated.
	Retryable
	// Ambiguous: the server may or may not have acted (read timeout, connection
	// reset, 500, 502, 504). Retry only idempotent operations.
	Ambiguous
)

func (c Class) String() string {
	return [...]string{"fatal", "retryable", "ambiguous"}[c]
}

// StatusError is an HTTP failure with the server's Retry-After hint, if any.
type StatusError struct {
	Code       int
	RetryAfter time.Duration
}

func (e *StatusError) Error() string { return fmt.Sprintf("http status %d", e.Code) }

// HintError attaches a server-provided wait (Retry-After, gRPC pushback) to any error.
type HintError struct {
	Err        error
	RetryAfter time.Duration
}

func (e *HintError) Error() string { return e.Err.Error() }
func (e *HintError) Unwrap() error { return e.Err }

// Classifier maps an error to a Class.
type Classifier func(error) Class

// Default is a conservative classifier for HTTP and TCP errors.
func Default(err error) Class {
	var se *StatusError
	if errors.As(err, &se) {
		switch se.Code {
		case http.StatusTooManyRequests, http.StatusServiceUnavailable:
			return Retryable
		case http.StatusInternalServerError, http.StatusBadGateway, http.StatusGatewayTimeout, http.StatusRequestTimeout:
			return Ambiguous
		default:
			return Fatal
		}
	}
	if errors.Is(err, context.Canceled) {
		return Fatal
	}
	if errors.Is(err, syscall.ECONNREFUSED) {
		return Retryable // nothing was listening: the request never left
	}
	var op *net.OpError
	if errors.As(err, &op) && op.Op == "dial" {
		return Retryable // connect failed or timed out: no request bytes were processed
	}
	if errors.Is(err, context.DeadlineExceeded) ||
		errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.EPIPE) ||
		errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
		return Ambiguous // the request may have been executed
	}
	var ne net.Error
	if errors.As(err, &ne) && ne.Timeout() {
		return Ambiguous
	}
	return Fatal
}

// ParseRetryAfter reads a Retry-After value: delay-seconds or an HTTP-date (RFC 9110).
func ParseRetryAfter(v string, now time.Time) (time.Duration, bool) {
	v = strings.TrimSpace(v)
	if v == "" {
		return 0, false
	}
	if secs, err := strconv.Atoi(v); err == nil && secs >= 0 {
		return time.Duration(secs) * time.Second, true
	}
	if t, err := http.ParseTime(v); err == nil {
		return max(t.Sub(now), 0), true
	}
	return 0, false
}

func hintOf(err error) time.Duration {
	var se *StatusError
	if errors.As(err, &se) {
		return se.RetryAfter
	}
	var he *HintError
	if errors.As(err, &he) {
		return he.RetryAfter
	}
	return 0
}

The loop. Do combines classification, idempotency, attempts, backoff, hints, budget, per-try timeout and the overall deadline, and returns a *GiveUp that says why it stopped.

go
// Package retry is a small, testable retry loop: classification, capped
// exponential backoff with jitter, a retry budget, a per-try timeout and an
// overall deadline, all driven by an injectable clock.
package retry

import (
	"context"
	"errors"
	"fmt"
	"time"
)

// Policy configures Do. The zero value of optional fields is safe.
type Policy struct {
	MaxAttempts int           // total attempts including the first (3 is a good default)
	PerTry      time.Duration // timeout of one attempt; 0 = only the overall deadline
	Overall     time.Duration // total time for all attempts and sleeps; 0 = ctx deadline only
	Backoff     Backoff       // nil = no waiting
	Budget      *Budget       // nil = unlimited retries (not recommended)
	Idempotent  bool          // true: ambiguous failures may be retried
	Classify    Classifier    // nil = Default
	Clock       Clock         // nil = RealClock
	OnRetry     func(attempt int, err error, delay time.Duration)
}

// GiveUp is returned when the loop stops without a success.
type GiveUp struct {
	Attempts int
	Reason   string // "fatal", "ambiguous and not idempotent", "max attempts", "retry budget exhausted", "deadline", "context"
	Err      error  // the last error from the operation
}

func (g *GiveUp) Error() string {
	return fmt.Sprintf("retry: gave up after %d attempt(s): %s: %v", g.Attempts, g.Reason, g.Err)
}
func (g *GiveUp) Unwrap() error { return g.Err }

// Do runs op until it succeeds or the policy says stop. attempt starts at 1.
func Do[T any](ctx context.Context, p Policy, op func(ctx context.Context, attempt int) (T, error)) (T, error) {
	var zero T
	clock := p.Clock
	if clock == nil {
		clock = RealClock{}
	}
	classify := p.Classify
	if classify == nil {
		classify = Default
	}
	maxAttempts := max(p.MaxAttempts, 1)

	var deadline time.Time
	if p.Overall > 0 {
		deadline = clock.Now().Add(p.Overall)
	}
	if d, ok := ctx.Deadline(); ok && (deadline.IsZero() || d.Before(deadline)) {
		deadline = d
	}

	var prev time.Duration
	for attempt := 1; ; attempt++ {
		if attempt == 1 && p.Budget != nil {
			p.Budget.Deposit()
		}
		tryCtx, cancel := tryContext(ctx, p.PerTry, deadline, clock)
		v, err := op(tryCtx, attempt)
		cancel()
		if err == nil {
			return v, nil
		}
		if ctx.Err() != nil { // the caller gave up: never retry
			return zero, &GiveUp{attempt, "context", err}
		}
		switch class := classify(err); {
		case class == Fatal:
			return zero, &GiveUp{attempt, "fatal", err}
		case class == Ambiguous && !p.Idempotent:
			return zero, &GiveUp{attempt, "ambiguous and not idempotent", err}
		}
		if attempt >= maxAttempts {
			return zero, &GiveUp{attempt, "max attempts", err}
		}
		var delay time.Duration
		if p.Backoff != nil {
			delay = p.Backoff.Next(attempt, prev)
		}
		prev = delay
		if hint := hintOf(err); hint > delay {
			delay = hint // the server knows better than our formula
		}
		if !deadline.IsZero() && clock.Now().Add(delay).After(deadline) {
			return zero, &GiveUp{attempt, "deadline", err}
		}
		if p.Budget != nil && !p.Budget.Withdraw() {
			return zero, &GiveUp{attempt, "retry budget exhausted", err}
		}
		if p.OnRetry != nil {
			p.OnRetry(attempt, err, delay)
		}
		if serr := clock.Sleep(ctx, delay); serr != nil {
			return zero, &GiveUp{attempt, "context", errors.Join(err, serr)}
		}
	}
}

// tryContext derives the context of one attempt: the smaller of the per-try
// timeout and the time left until the overall deadline.
func tryContext(ctx context.Context, perTry time.Duration, deadline time.Time, clock Clock) (context.Context, context.CancelFunc) {
	limit := perTry
	if !deadline.IsZero() {
		left := deadline.Sub(clock.Now())
		if limit == 0 || left < limit {
			limit = left
		}
	}
	if limit <= 0 {
		return ctx, func() {}
	}
	return context.WithTimeout(ctx, limit)
}

Tests with the fake clock. Bounds for every jitter variant, the exact stop rules, and the 10% budget.

go
package retry

import (
	"math/rand/v2"
	"testing"
	"time"
)

const (
	base = 100 * time.Millisecond
	cap_ = 5 * time.Second
)

func TestDeterministicShapes(t *testing.T) {
	if got := Constant(time.Second).Next(7, 0); got != time.Second {
		t.Fatalf("constant: %v", got)
	}
	lin := Linear(100*time.Millisecond, 350*time.Millisecond)
	want := []time.Duration{100, 200, 300, 350, 350}
	for i, w := range want {
		if got := lin.Next(i+1, 0); got != w*time.Millisecond {
			t.Fatalf("linear attempt %d: %v", i+1, got)
		}
	}
	exp := Exponential(base, cap_)
	want = []time.Duration{100, 200, 400, 800, 1600, 3200, 5000, 5000}
	for i, w := range want {
		if got := exp.Next(i+1, 0); got != w*time.Millisecond {
			t.Fatalf("exponential attempt %d: %v want %v", i+1, got, w*time.Millisecond)
		}
	}
	// Huge attempt numbers must not overflow into negative durations.
	if got := exp.Next(10_000, 0); got != cap_ {
		t.Fatalf("overflow guard: %v", got)
	}
}

func TestJitterBounds(t *testing.T) {
	r := rand.New(rand.NewPCG(1, 2))
	rnd := Rand(r.Float64)
	full, equal, deco := FullJitter(base, cap_, rnd), EqualJitter(base, cap_, rnd), Decorrelated(base, cap_, rnd)
	prev := time.Duration(0)
	for attempt := 1; attempt <= 12; attempt++ {
		ceil := Exponential(base, cap_).Next(attempt, 0)
		for i := 0; i < 2000; i++ {
			if d := full.Next(attempt, 0); d < 0 || d > ceil {
				t.Fatalf("full jitter %v outside [0,%v]", d, ceil)
			}
			if d := equal.Next(attempt, 0); d < ceil/2 || d > ceil {
				t.Fatalf("equal jitter %v outside [%v,%v]", d, ceil/2, ceil)
			}
		}
		d := deco.Next(attempt, prev)
		if d < base || d > cap_ || d > max(prev*3, base*3) {
			t.Fatalf("decorrelated %v (prev %v) outside [base, min(cap, 3*prev)]", d, prev)
		}
		prev = d
	}
}

func TestJitterSpreadsClients(t *testing.T) {
	// 1000 clients retry for the 4th time: without jitter they all sleep 800ms;
	// with full jitter they spread across [0, 800ms).
	r := rand.New(rand.NewPCG(3, 4))
	full := FullJitter(base, cap_, r.Float64)
	buckets := make([]int, 8) // 100ms wide
	for i := 0; i < 1000; i++ {
		buckets[int(full.Next(4, 0)/(100*time.Millisecond))]++
	}
	for i, n := range buckets {
		if n < 60 || n > 190 { // expected 125 per bucket
			t.Fatalf("bucket %d has %d clients: not uniform enough: %v", i, n, buckets)
		}
	}
	if got := Exponential(base, cap_).Next(4, 0); got != 800*time.Millisecond {
		t.Fatalf("no-jitter control: %v", got)
	}
}
go
package retry

import (
	"context"
	"errors"
	"fmt"
	"net"
	"net/http"
	"sync/atomic"
	"syscall"
	"testing"
	"time"
)

func status(code int) error { return &StatusError{Code: code} }

func TestRetriesTransientThenSucceeds(t *testing.T) {
	clock := NewFakeClock()
	calls := 0
	got, err := Do(context.Background(), Policy{
		MaxAttempts: 4, Backoff: Exponential(100*time.Millisecond, time.Second),
		Idempotent: true, Clock: clock,
	}, func(ctx context.Context, attempt int) (string, error) {
		calls++
		if attempt < 3 {
			return "", status(503)
		}
		return "ok", nil
	})
	if err != nil || got != "ok" || calls != 3 {
		t.Fatalf("got %q err %v calls %d", got, err, calls)
	}
	if fmt.Sprint(clock.Sleeps) != "[100ms 200ms]" {
		t.Fatalf("sleeps %v", clock.Sleeps)
	}
}

func TestMaxAttemptsAndGiveUpType(t *testing.T) {
	_, err := Do(context.Background(), Policy{MaxAttempts: 3, Idempotent: true, Clock: NewFakeClock()},
		func(context.Context, int) (int, error) { return 0, status(503) })
	var g *GiveUp
	if !errors.As(err, &g) || g.Attempts != 3 || g.Reason != "max attempts" {
		t.Fatalf("err = %v", err)
	}
	var se *StatusError
	if !errors.As(err, &se) || se.Code != 503 {
		t.Fatal("original error must stay reachable with errors.As")
	}
}

func TestAmbiguousFailureNeedsIdempotency(t *testing.T) {
	for _, tc := range []struct {
		name       string
		err        error
		idempotent bool
		wantCalls  int
	}{
		{"POST read timeout is not repeated", context.DeadlineExceeded, false, 1},
		{"GET read timeout is repeated", context.DeadlineExceeded, true, 3},
		{"POST connection refused is repeated", syscall.ECONNREFUSED, false, 3},
		{"POST 503 is repeated", status(503), false, 3},
		{"POST 500 is not repeated", status(500), false, 1},
		{"GET 500 is repeated", status(500), true, 3},
		{"404 is never repeated", status(404), true, 1},
		{"connection reset needs idempotency", syscall.ECONNRESET, false, 1},
	} {
		calls := 0
		_, _ = Do(context.Background(), Policy{MaxAttempts: 3, Idempotent: tc.idempotent, Clock: NewFakeClock()},
			func(context.Context, int) (int, error) { calls++; return 0, tc.err })
		if calls != tc.wantCalls {
			t.Errorf("%s: calls = %d, want %d", tc.name, calls, tc.wantCalls)
		}
	}
}

func TestRetryAfterBeatsFormula(t *testing.T) {
	clock := NewFakeClock()
	_, _ = Do(context.Background(), Policy{
		MaxAttempts: 2, Backoff: Constant(10 * time.Millisecond), Idempotent: true, Clock: clock,
	}, func(context.Context, int) (int, error) {
		return 0, &StatusError{Code: 429, RetryAfter: 7 * time.Second}
	})
	if len(clock.Sleeps) != 1 || clock.Sleeps[0] != 7*time.Second {
		t.Fatalf("sleeps %v, want [7s]", clock.Sleeps)
	}
}

func TestDeadlineStopsBeforeASleepThatCannotFit(t *testing.T) {
	clock := NewFakeClock()
	calls := 0
	_, err := Do(context.Background(), Policy{
		MaxAttempts: 10, Overall: time.Second, Backoff: Constant(400 * time.Millisecond),
		Idempotent: true, Clock: clock,
	}, func(context.Context, int) (int, error) { calls++; return 0, status(503) })
	var g *GiveUp
	if !errors.As(err, &g) || g.Reason != "deadline" {
		t.Fatalf("err = %v", err)
	}
	// attempts at t=0, 0.4, 0.8; the next sleep would end at 1.2 s > 1 s.
	if calls != 3 || clock.Total() != 800*time.Millisecond {
		t.Fatalf("calls %d, slept %v", calls, clock.Total())
	}
}

func TestRetryAfterLongerThanDeadlineGivesUpAtOnce(t *testing.T) {
	clock := NewFakeClock()
	calls := 0
	_, err := Do(context.Background(), Policy{MaxAttempts: 5, Overall: 2 * time.Second, Idempotent: true, Clock: clock},
		func(context.Context, int) (int, error) {
			calls++
			return 0, &StatusError{Code: 503, RetryAfter: time.Minute}
		})
	var g *GiveUp
	if !errors.As(err, &g) || g.Reason != "deadline" || calls != 1 || clock.Total() != 0 {
		t.Fatalf("err %v calls %d slept %v", err, calls, clock.Total())
	}
}

func TestPerTryTimeoutCutsAHungAttempt(t *testing.T) {
	var seen atomic.Int32
	start := time.Now()
	got, err := Do(context.Background(), Policy{
		MaxAttempts: 3, PerTry: 30 * time.Millisecond, Idempotent: true, Clock: NewFakeClock(),
	}, func(ctx context.Context, attempt int) (string, error) {
		seen.Add(1)
		if attempt == 1 {
			<-ctx.Done() // a hung server: only the per-try timeout ends this
			return "", ctx.Err()
		}
		return "fast", nil
	})
	if err != nil || got != "fast" || seen.Load() != 2 {
		t.Fatalf("got %q err %v attempts %d", got, err, seen.Load())
	}
	if el := time.Since(start); el > 2*time.Second {
		t.Fatalf("took %v", el)
	}
}

func TestCallerCancellationIsNeverRetried(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	calls := 0
	_, err := Do(ctx, Policy{MaxAttempts: 5, Idempotent: true, Clock: NewFakeClock()},
		func(context.Context, int) (int, error) { calls++; cancel(); return 0, status(503) })
	var g *GiveUp
	if !errors.As(err, &g) || g.Reason != "context" || calls != 1 {
		t.Fatalf("err %v calls %d", err, calls)
	}
}

func TestBudgetCapsExtraLoadAtTenPercent(t *testing.T) {
	// The dependency is fully down. 1000 requests, up to 3 attempts each.
	budget := NewBudget(0.1, 10)
	calls := 0
	for i := 0; i < 1000; i++ {
		_, _ = Do(context.Background(), Policy{MaxAttempts: 3, Idempotent: true, Budget: budget, Clock: NewFakeClock()},
			func(context.Context, int) (int, error) { calls++; return 0, status(503) })
	}
	extra := float64(calls-1000) / 1000
	if extra > 0.12 || extra < 0.08 {
		t.Fatalf("extra load %.3f, want about 0.10 (calls=%d)", extra, calls)
	}
	// Control: without a budget the same outage triples the load.
	calls = 0
	for i := 0; i < 1000; i++ {
		_, _ = Do(context.Background(), Policy{MaxAttempts: 3, Idempotent: true, Clock: NewFakeClock()},
			func(context.Context, int) (int, error) { calls++; return 0, status(503) })
	}
	if calls != 3000 {
		t.Fatalf("no budget: calls = %d, want 3000", calls)
	}
}

func TestClassifyRealNetworkErrors(t *testing.T) {
	// Connection refused: listen, note the port, close, dial.
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	addr := ln.Addr().String()
	ln.Close()
	_, derr := net.DialTimeout("tcp", addr, time.Second)
	if derr == nil || Default(derr) != Retryable {
		t.Fatalf("refused dial: %v classified %v", derr, Default(derr))
	}
	for err, want := range map[error]Class{
		context.Canceled:              Fatal,
		context.DeadlineExceeded:      Ambiguous,
		status(http.StatusBadRequest): Fatal,
		status(429):                   Retryable,
		status(502):                   Ambiguous,
		errors.New("boom"):            Fatal,
	} {
		if got := Default(err); got != want {
			t.Errorf("%v: %v, want %v", err, got, want)
		}
	}
}

func TestParseRetryAfter(t *testing.T) {
	now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
	for _, tc := range []struct {
		in   string
		want time.Duration
		ok   bool
	}{
		{"120", 120 * time.Second, true},
		{"0", 0, true},
		{"Thu, 01 Jan 2026 12:00:30 GMT", 30 * time.Second, true},
		{"Wed, 31 Dec 2025 23:59:59 GMT", 0, true}, // date in the past: wait nothing
		{"soon", 0, false},
		{"-5", 0, false},
		{"", 0, false},
	} {
		got, ok := ParseRetryAfter(tc.in, now)
		if got != tc.want || ok != tc.ok {
			t.Errorf("%q: got %v,%v want %v,%v", tc.in, got, ok, tc.want, tc.ok)
		}
	}
}

func TestHintErrorWorksForAnyError(t *testing.T) {
	clock := NewFakeClock()
	_, _ = Do(context.Background(), Policy{
		MaxAttempts: 2, Idempotent: true, Clock: clock,
		Classify: func(error) Class { return Retryable },
	}, func(context.Context, int) (int, error) {
		return 0, &HintError{Err: errors.New("grpc UNAVAILABLE"), RetryAfter: 250 * time.Millisecond}
	})
	if len(clock.Sleeps) != 1 || clock.Sleeps[0] != 250*time.Millisecond {
		t.Fatalf("sleeps %v", clock.Sleeps)
	}
}

Every timeout of an HTTP client in one place, and an idempotent GET that honours Retry-After; the tests use real httptest servers (a 503 with Retry-After, a hung first attempt, a closed port).

go
// Package httpclient shows every timeout of a Go HTTP client in one place and
// wraps GET in the retry package.
package httpclient

import (
	"context"
	"fmt"
	"io"
	"net"
	"net/http"
	"time"

	"academy/timeouts-retries-jitter/retry"
)

// Timeouts are the knobs. Typical values for an internal service call.
type Timeouts struct {
	Dial           time.Duration // TCP connect (net.Dialer.Timeout)
	TLSHandshake   time.Duration // Transport.TLSHandshakeTimeout
	ResponseHeader time.Duration // request written -> response headers (Transport.ResponseHeaderTimeout)
	IdleConn       time.Duration // how long a keep-alive connection may sit unused
	Total          time.Duration // http.Client.Timeout: dial + redirects + reading the body
}

// Defaults: budgets of a call whose p99 is about 200 ms.
var Defaults = Timeouts{
	Dial:           500 * time.Millisecond,
	TLSHandshake:   1 * time.Second,
	ResponseHeader: 1 * time.Second,
	IdleConn:       30 * time.Second, // keep below the server/LB idle timeout (e.g. 60 s)
	Total:          3 * time.Second,
}

// NewHTTPClient builds a client that can never wait forever.
func NewHTTPClient(t Timeouts) *http.Client {
	dialer := &net.Dialer{Timeout: t.Dial, KeepAlive: 15 * time.Second}
	return &http.Client{
		Timeout: t.Total,
		Transport: &http.Transport{
			Proxy:                 http.ProxyFromEnvironment,
			DialContext:           dialer.DialContext,
			TLSHandshakeTimeout:   t.TLSHandshake,
			ResponseHeaderTimeout: t.ResponseHeader,
			IdleConnTimeout:       t.IdleConn,
			MaxIdleConnsPerHost:   16,
		},
	}
}

// Client retries idempotent GETs with the policy it was built with.
type Client struct {
	HTTP   *http.Client
	Policy retry.Policy
}

// Get returns the body of a 2xx response. 4xx/5xx become *retry.StatusError
// carrying Retry-After so the retry loop can honour it.
func (c *Client) Get(ctx context.Context, url string) ([]byte, error) {
	p := c.Policy
	p.Idempotent = true // GET is idempotent (RFC 9110, 9.2.2)
	clock := p.Clock
	if clock == nil {
		clock = retry.RealClock{}
	}
	return retry.Do(ctx, p, func(ctx context.Context, _ int) ([]byte, error) {
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
		if err != nil {
			return nil, err
		}
		resp, err := c.HTTP.Do(req)
		if err != nil {
			return nil, err
		}
		defer resp.Body.Close()
		if resp.StatusCode >= 400 {
			io.Copy(io.Discard, io.LimitReader(resp.Body, 4096)) // let the connection be reused
			after, _ := retry.ParseRetryAfter(resp.Header.Get("Retry-After"), clock.Now())
			return nil, &retry.StatusError{Code: resp.StatusCode, RetryAfter: after}
		}
		b, err := io.ReadAll(resp.Body)
		if err != nil {
			return nil, fmt.Errorf("read body: %w", err)
		}
		return b, nil
	})
}
go
package httpclient

import (
	"context"
	"errors"
	"net/http"
	"net/http/httptest"
	"sync/atomic"
	"testing"
	"time"

	"academy/timeouts-retries-jitter/retry"
)

func newTestClient(clock retry.Clock) *Client {
	return &Client{
		HTTP: NewHTTPClient(Timeouts{Dial: time.Second, TLSHandshake: time.Second, ResponseHeader: 200 * time.Millisecond, IdleConn: time.Second, Total: 2 * time.Second}),
		Policy: retry.Policy{
			MaxAttempts: 4, PerTry: 300 * time.Millisecond, Overall: 5 * time.Second,
			Backoff: retry.Exponential(50*time.Millisecond, time.Second),
			Budget:  retry.NewBudget(0.1, 10), Clock: clock,
		},
	}
}

func TestHonoursRetryAfterAndRecovers(t *testing.T) {
	var n atomic.Int32
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if n.Add(1) == 1 {
			w.Header().Set("Retry-After", "2")
			w.WriteHeader(http.StatusServiceUnavailable)
			return
		}
		w.Write([]byte("hello"))
	}))
	defer srv.Close()
	clock := retry.NewFakeClock()
	body, err := newTestClient(clock).Get(context.Background(), srv.URL)
	if err != nil || string(body) != "hello" {
		t.Fatalf("body %q err %v", body, err)
	}
	if len(clock.Sleeps) != 1 || clock.Sleeps[0] != 2*time.Second {
		t.Fatalf("sleeps %v: Retry-After: 2 must beat the 50 ms formula", clock.Sleeps)
	}
}

func TestDoesNotRetryClientErrors(t *testing.T) {
	var n atomic.Int32
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		n.Add(1)
		http.NotFound(w, r)
	}))
	defer srv.Close()
	_, err := newTestClient(retry.NewFakeClock()).Get(context.Background(), srv.URL)
	var se *retry.StatusError
	if !errors.As(err, &se) || se.Code != 404 || n.Load() != 1 {
		t.Fatalf("err %v calls %d", err, n.Load())
	}
}

func TestSlowServerHitsResponseHeaderTimeoutThenRecovers(t *testing.T) {
	var n atomic.Int32
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if n.Add(1) == 1 {
			select { // hung first attempt
			case <-time.After(3 * time.Second):
			case <-r.Context().Done():
			}
			return
		}
		w.Write([]byte("second try"))
	}))
	defer srv.Close()
	start := time.Now()
	body, err := newTestClient(retry.NewFakeClock()).Get(context.Background(), srv.URL)
	if err != nil || string(body) != "second try" {
		t.Fatalf("body %q err %v", body, err)
	}
	if el := time.Since(start); el > time.Second {
		t.Fatalf("took %v: the 200 ms header timeout should have cut the first attempt", el)
	}
}

func TestConnectionRefusedIsRetriedAndExhausts(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
	url := srv.URL
	srv.Close() // nothing listens any more
	clock := retry.NewFakeClock()
	_, err := newTestClient(clock).Get(context.Background(), url)
	var g *retry.GiveUp
	if !errors.As(err, &g) || g.Attempts != 4 || g.Reason != "max attempts" {
		t.Fatalf("err %v", err)
	}
	if len(clock.Sleeps) != 3 {
		t.Fatalf("sleeps %v", clock.Sleeps)
	}
}

Database timeouts from Go. SET LOCAL equivalents through set_config(..., true), and a helper that turns the context deadline into a statement_timeout with a margin.

go
// Package dbtimeouts applies PostgreSQL timeouts from Go without a driver
// dependency: it only needs database/sql.
package dbtimeouts

import (
	"context"
	"database/sql"
	"fmt"
	"time"
)

// Limits are the three server-side timeouts that matter for a request path.
type Limits struct {
	Statement time.Duration // statement_timeout: abort any statement longer than this
	Lock      time.Duration // lock_timeout: abort when waiting for a lock longer than this
	IdleInTx  time.Duration // idle_in_transaction_session_timeout: kill a session that sits idle inside BEGIN
}

// Apply sets the limits for the current transaction only (set_config with
// is_local = true is SET LOCAL), so a pooled connection is never left changed.
func Apply(ctx context.Context, tx *sql.Tx, l Limits) error {
	for name, d := range map[string]time.Duration{
		"statement_timeout":                   l.Statement,
		"lock_timeout":                        l.Lock,
		"idle_in_transaction_session_timeout": l.IdleInTx,
	} {
		if d <= 0 {
			continue
		}
		if _, err := tx.ExecContext(ctx, "SELECT set_config($1, $2, true)", name, fmt.Sprintf("%dms", d.Milliseconds())); err != nil {
			return fmt.Errorf("set %s: %w", name, err)
		}
	}
	return nil
}

// Budget turns the remaining context deadline into a statement_timeout slightly
// shorter than the caller's deadline, so the server aborts before the client gives up
// and the connection is not left running a query nobody waits for.
func Budget(ctx context.Context, margin time.Duration) (time.Duration, bool) {
	dl, ok := ctx.Deadline()
	if !ok {
		return 0, false
	}
	left := time.Until(dl) - margin
	if left <= 0 {
		return 0, true
	}
	return left, true
}
go
package dbtimeouts

import (
	"context"
	"testing"
	"time"
)

func TestBudgetLeavesAMargin(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()
	d, ok := Budget(ctx, 200*time.Millisecond)
	if !ok || d > 1800*time.Millisecond || d < 1500*time.Millisecond {
		t.Fatalf("d=%v ok=%v", d, ok)
	}
	if _, ok := Budget(context.Background(), time.Second); ok {
		t.Fatal("no deadline must report ok=false")
	}
}

The simulation behind the tables (seeded; identical output on every run):

go
// jittersim prints the numbers used on the page. It is deterministic (seeded).
//
//	go run ./cmd/jittersim
//
// Table 1 models Marc Brooker's contention case from "Exponential Backoff And
// Jitter" (AWS Architecture Blog, 2015) in a simplified, slotted form: N clients
// start together, each 10 ms slot lets exactly ONE of the clients that call in
// that slot succeed, the rest fail and back off. It is my model, not his simulator.
package main

import (
	"context"
	"fmt"
	"math/rand/v2"
	"time"

	"academy/timeouts-retries-jitter/retry"
)

const slot = 10 * time.Millisecond

type client struct {
	next    int // slot of the next call
	attempt int
	prev    time.Duration
	done    bool
}

type result struct {
	calls  int
	finish time.Duration
}

func contention(n int, b retry.Backoff, rng *rand.Rand) result {
	cs := make([]*client, n)
	for i := range cs {
		cs[i] = &client{}
	}
	var res result
	remaining := n
	for s := 0; remaining > 0; s++ {
		var callers []*client
		for _, c := range cs {
			if !c.done && c.next == s {
				callers = append(callers, c)
			}
		}
		if len(callers) == 0 {
			continue
		}
		res.calls += len(callers)
		callers[rng.IntN(len(callers))].done = true // the winner
		remaining--
		res.finish = time.Duration(s+1) * slot
		for _, c := range callers {
			if c.done {
				continue
			}
			c.attempt++
			d := b.Next(c.attempt, c.prev)
			c.prev = d
			// +0 or +1 slot of network delay variance, so "no jitter" is not artificially perfect.
			c.next = s + 1 + int(d/slot) + rng.IntN(2)
		}
	}
	return res
}

func main() {
	const n = 100
	base, ceiling := 10*time.Millisecond, time.Second
	fmt.Printf("1) %d clients contend for one slot per %v (cap %v, base %v)\n", n, slot, ceiling, base)
	fmt.Printf("   %-26s %8s %12s\n", "strategy", "calls", "finish")
	for _, s := range []struct {
		name string
		mk   func(rnd retry.Rand) retry.Backoff
	}{
		{"constant 10ms (no jitter)", func(retry.Rand) retry.Backoff { return retry.Constant(base) }},
		{"exponential, no jitter", func(retry.Rand) retry.Backoff { return retry.Exponential(base, ceiling) }},
		{"full jitter", func(r retry.Rand) retry.Backoff { return retry.FullJitter(base, ceiling, r) }},
		{"equal jitter", func(r retry.Rand) retry.Backoff { return retry.EqualJitter(base, ceiling, r) }},
		{"decorrelated jitter", func(r retry.Rand) retry.Backoff { return retry.Decorrelated(base, ceiling, r) }},
	} {
		// Average 20 seeded runs.
		var calls int
		var finish time.Duration
		const runs = 20
		for i := 0; i < runs; i++ {
			rng := rand.New(rand.NewPCG(uint64(i+1), 7))
			r := contention(n, s.mk(rng.Float64), rng)
			calls += r.calls
			finish += r.finish
		}
		fmt.Printf("   %-26s %8d %12v\n", s.name, calls/runs, (finish / runs).Round(10*time.Millisecond))
	}

	fmt.Println("\n2) Dependency is 100% down, 1000 requests, MaxAttempts=3, GET (idempotent)")
	fmt.Printf("   %-28s %8s %10s\n", "policy", "calls", "extra load")
	for _, bud := range []*retry.Budget{nil, retry.NewBudget(0.1, 10)} {
		calls := 0
		for i := 0; i < 1000; i++ {
			_, _ = retry.Do(context.Background(), retry.Policy{
				MaxAttempts: 3, Idempotent: true, Budget: bud, Clock: retry.NewFakeClock(),
			}, func(context.Context, int) (int, error) {
				calls++
				return 0, &retry.StatusError{Code: 503}
			})
		}
		name := "3 attempts, no budget"
		if bud != nil {
			name = "3 attempts + 10% budget"
		}
		fmt.Printf("   %-28s %8d %9.0f%%\n", name, calls, float64(calls-1000)/10)
	}

	fmt.Println("\n3) Layered retries multiply: 3 attempts at each of 5 layers")
	total := 1
	for layer := 1; layer <= 5; layer++ {
		total *= 3
		fmt.Printf("   layers=%d  calls reaching the database per user request = %d\n", layer, total)
	}
}

The Go angle ​

Go featureUse for timeouts and retriesNote
context.WithTimeout(parent, d)One attempt, one budgetAlways defer cancel(); pass ctx first
ctx.Deadline()Read the remaining time to size the next hopCombine with a margin
context.WithTimeoutCauseSay which timeout firedLog context.Cause(ctx)
http.NewRequestWithContextCancel an in-flight requestWithout it, a timed-out attempt keeps running
http.Client.TimeoutWhole attempt including body"The timer remains running after Get, Head, Post, or Do return"
http.Transport fieldsPer-phase limits and poolingResponseHeaderTimeout, TLSHandshakeTimeout, IdleConnTimeout, MaxIdleConnsPerHost
net.Dialer{Timeout, KeepAlive}Connect limit and TCP keep-aliveDefault is no timeout
errors.Is, errors.AsClassify (syscall.ECONNREFUSED, *net.OpError, net.Error.Timeout())Wrap with %w so the class survives
time.NewTimer plus selectCancellable sleepDo not use bare time.Sleep in code that has a context
math/rand/v2Jitterrand.Float64() is safe for concurrent use; inject it for tests
database/sql QueryContextThe driver sends a cancel on context endPair with a server statement_timeout
github.com/hashicorp/go-retryablehttpReady-made retrying clientRetries 5xx except 501; check idempotency yourself
golang.org/x/time/rateRate-limit your own retriesAn alternative to a token budget

Laravel ​

Before ​

Http::retry(5, 100) on a POST with no timeout and no key. In Laravel 13 the default timeout is 30 seconds and the retry sleeps a constant 100 ms.

php
<?php

namespace App\Before;

use Illuminate\Support\Facades\Http;

// Before: default 30 s timeout, retry on everything including POST, fixed delay, no key.
class PaymentsClientBefore
{
    public function charge(int $orderId, int $amount): array
    {
        return Http::retry(5, 100)               // 5 attempts, always 100 ms, no jitter
            ->post('https://payments.internal.example/charge', [
                'order_id' => $orderId,
                'amount' => $amount,
            ])                                    // no timeout(): up to 30 s per attempt, 150 s worst case
            ->json();                             // no idempotency key: a retry can double-charge
    }
}

After ​

A backoff helper with injectable randomness (full, equal, decorrelated jitter and Retry-After parsing).

php
<?php

namespace App\Support;

/**
 * Backoff delays in milliseconds. Attempt 1 is the first RETRY.
 * The random source is injectable so tests can pin it.
 */
final class Backoff
{
    /** @param null|callable():float $rand returns a float in [0, 1) */
    public function __construct(
        private readonly int $baseMs = 100,
        private readonly int $capMs = 5000,
        private $rand = null,
    ) {
        $this->rand ??= static fn (): float => mt_rand() / (mt_getrandmax() + 1);
    }

    /** min(cap, base * 2^(attempt-1)) */
    public function ceiling(int $attempt): int
    {
        $exp = min($attempt - 1, 30); // avoid float overflow for huge attempts
        return (int) min($this->capMs, $this->baseMs * (2 ** $exp));
    }

    /** random(0, ceiling) */
    public function full(int $attempt): int
    {
        return (int) (($this->rand)() * $this->ceiling($attempt));
    }

    /** ceiling/2 + random(0, ceiling/2) */
    public function equal(int $attempt): int
    {
        $half = intdiv($this->ceiling($attempt), 2);
        return $half + (int) (($this->rand)() * $half);
    }

    /** min(cap, random(base, previous * 3)) */
    public function decorrelated(int $previousMs): int
    {
        $previousMs = max($previousMs, $this->baseMs);
        $hi = $previousMs * 3;
        return (int) min($this->capMs, $this->baseMs + ($this->rand)() * ($hi - $this->baseMs));
    }

    /** Parse Retry-After: delay-seconds or HTTP-date. Returns milliseconds or null. */
    public static function retryAfterMs(?string $value, ?int $now = null): ?int
    {
        $value = trim((string) $value);
        if ($value === '') {
            return null;
        }
        if (ctype_digit($value)) {
            return (int) $value * 1000;
        }
        $ts = strtotime($value);
        if ($ts === false) {
            return null;
        }
        return max(0, ($ts - ($now ?? time())) * 1000);
    }
}

A payments client. connectTimeout, timeout, one idempotency key outside the loop, retry() with a sleep closure that applies full jitter and Retry-After, a when callable that classifies, and throw: true.

php
<?php

namespace App\Clients;

use App\Support\Backoff;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Throwable;

/**
 * Timeouts, a classified retry with full jitter, Retry-After, and ONE idempotency
 * key shared by all attempts of one logical charge.
 */
final class PaymentsClient
{
    private const MAX_ATTEMPTS = 3;
    private const PER_TRY_SECONDS = 1.5;   // read timeout of one attempt
    private const CONNECT_SECONDS = 0.5;   // connect timeout

    public function __construct(private readonly Backoff $backoff = new Backoff(100, 2000)) {}

    public function charge(int $orderId, int $amountMinor, ?string $idempotencyKey = null): array
    {
        // Generated ONCE, outside the retry loop. A key made inside the closure defeats the point.
        $key = $idempotencyKey ?? (string) Str::uuid();
        $attempt = 0;

        $response = Http::baseUrl('https://payments.internal.example')
            ->withHeaders(['Idempotency-Key' => $key])
            ->connectTimeout(self::CONNECT_SECONDS)
            ->timeout(self::PER_TRY_SECONDS)
            // retry(times, sleepMs, when, throw): sleepMs may be a closure(attempt, exception)
            ->retry(
                self::MAX_ATTEMPTS,
                function (int $attemptNo, Throwable $e) use (&$attempt): int {
                    $attempt = $attemptNo;
                    $hint = $e instanceof RequestException
                        ? Backoff::retryAfterMs($e->response->header('Retry-After'))
                        : null;
                    return max($this->backoff->full($attemptNo), $hint ?? 0);
                },
                when: fn (Throwable $e, PendingRequest $request): bool => $this->isRetryable($e),
                throw: true,
            )
            ->post('/charge', ['order_id' => $orderId, 'amount' => $amountMinor]);

        return $response->json();
    }

    /**
     * Safe to retry because the POST carries an idempotency key.
     * Without a key, only the "never reached the server" cases would be safe.
     */
    private function isRetryable(Throwable $e): bool
    {
        if ($e instanceof ConnectionException) {
            return true; // refused, DNS, connect or read timeout (ambiguous, hence the key)
        }
        if ($e instanceof RequestException) {
            return in_array($e->response->status(), [408, 429, 500, 502, 503, 504], true);
        }
        return false;
    }
}

The same policy as a Guzzle retry middleware, for code that uses Guzzle directly.

php
<?php

namespace App\Support;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

/**
 * The same policy as a Guzzle retry middleware (GuzzleHttp\Middleware::retry),
 * for code that uses Guzzle directly instead of Laravel's Http facade.
 */
final class GuzzleRetry
{
    public static function client(int $maxRetries = 2): Client
    {
        $backoff = new Backoff(100, 2000);

        $decider = static function (
            int $retries,
            RequestInterface $request,
            ?ResponseInterface $response = null,
            ?\Throwable $exception = null,
        ) use ($maxRetries): bool {
            if ($retries >= $maxRetries) {
                return false;
            }
            // Only idempotent methods, or requests that carry an idempotency key.
            $safe = in_array($request->getMethod(), ['GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS'], true)
                || $request->hasHeader('Idempotency-Key');
            if (! $safe) {
                return false;
            }
            if ($exception instanceof ConnectException) {
                return true;
            }
            return $response !== null && in_array($response->getStatusCode(), [429, 502, 503, 504], true);
        };

        // $retries is 1 for the first retry. Returns milliseconds.
        $delay = static fn (int $retries, ?ResponseInterface $response = null): int => max(
            $backoff->full($retries),
            Backoff::retryAfterMs($response?->getHeaderLine('Retry-After')) ?? 0,
        );

        $stack = HandlerStack::create();
        $stack->push(Middleware::retry($decider, $delay), 'retry');

        return new Client([
            'handler' => $stack,
            'connect_timeout' => 0.5,
            'timeout' => 3.0,      // total time of one transfer (one attempt)
            'read_timeout' => 1.5, // idle time while reading a streamed body
        ]);
    }
}

A queued job with Tries, MaxExceptions, Timeout, a backoff() method that adds jitter, retryUntil(), and ThrottlesExceptions.

php
<?php

namespace App\Jobs;

use App\Support\Backoff;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\MaxExceptions;
use Illuminate\Queue\Attributes\Timeout;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Queue\Middleware\ThrottlesExceptions;
use Illuminate\Support\Facades\Http;
use Throwable;

/**
 * Retries in a queue: attempts, a backoff, a time window, a hard job timeout.
 * The retry_after of the queue connection must be larger than #[Timeout].
 */
#[Tries(8)]
#[MaxExceptions(5)]
#[Timeout(30)]
class SendInvoiceWebhook implements ShouldQueue
{
    use Queueable;

    public function __construct(private readonly int $invoiceId, private readonly string $url) {}

    /** Seconds before attempt N+1. A method can add jitter; an attribute array cannot. */
    public function backoff(): array
    {
        $b = new Backoff(baseMs: 5_000, capMs: 600_000);
        // Full jitter around 5 s, 10 s, 20 s ... capped at 10 min (seconds, not ms).
        return array_map(static fn (int $n): int => max(1, intdiv($b->full($n), 1000)), range(1, 7));
    }

    /** Stop trying 6 hours after dispatch even if tries remain (retryUntil beats tries). */
    public function retryUntil(): \DateTimeInterface
    {
        return now()->plus(hours: 6);
    }

    /** @return array<int, object> */
    public function middleware(): array
    {
        // After 10 exceptions inside 5 minutes, hold ALL attempts of this job for 5 minutes (a breaker).
        return [new ThrottlesExceptions(10, 5 * 60)];
    }

    public function handle(): void
    {
        // The HTTP timeout must be below the job timeout, which must be below retry_after.
        Http::connectTimeout(2)
            ->timeout(10)
            ->withHeaders(['Idempotency-Key' => "invoice-{$this->invoiceId}"])
            ->post($this->url, ['invoice_id' => $this->invoiceId])
            ->throw();
    }

    public function failed(Throwable $e): void
    {
        report($e); // alert, park the invoice, or send to a dead-letter table
    }
}

Stampede-safe refresh. Cache::lock with an expiry and block(), and the retry() helper with a jittered closure.

php
<?php

namespace App\Services;

use App\Support\Backoff;
use Illuminate\Contracts\Cache\LockTimeoutException;
use Illuminate\Support\Facades\Cache;

/**
 * Many clients retrying the same refresh at once is a stampede. One caller refreshes
 * under a lock with an expiry; the others wait a bounded time and read the result.
 */
final class StampedeSafeRefresh
{
    public function __construct(private readonly Backoff $backoff = new Backoff(50, 800)) {}

    public function rates(): array
    {
        if (($cached = Cache::get('fx:rates')) !== null) {
            return $cached;
        }

        $lock = Cache::lock('fx:rates:refresh', 10);   // auto-expires: a crashed holder cannot block forever
        try {
            $lock->block(2);                           // wait at most 2 s, then LockTimeoutException
            // Another process may have refreshed while we waited.
            return Cache::remember('fx:rates', 60, fn () => $this->fetchFromUpstream());
        } catch (LockTimeoutException) {
            // Could not get the lock in time: serve stale data or fail fast; do NOT hammer upstream.
            return Cache::get('fx:rates:stale', []);
        } finally {
            $lock->release();
        }
    }

    /** retry() helper with full jitter: sleep (ms) may be a closure of the attempt number. */
    private function fetchFromUpstream(): array
    {
        return retry(
            3,
            fn () => ['USD' => 1.0],                    // call the upstream here
            fn (int $attempt) => $this->backoff->full($attempt),
            fn (\Throwable $e) => $e instanceof \RuntimeException,  // only retry transient errors
        );
    }
}

The three nested clocks of a queue connection:

php
<?php

// config/queue.php (excerpt). The three numbers must nest: HTTP timeout < job timeout < retry_after.
return [
    'connections' => [
        'redis' => [
            'driver' => 'redis',
            'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
            'queue' => env('REDIS_QUEUE', 'default'),
            // A job still running after 90 s is released and may run a second time.
            'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
            'block_for' => null,
        ],
    ],
];

// php artisan queue:work redis --tries=3 --timeout=60 --backoff=5
//   --timeout=60 (job may run 60 s) is below retry_after=90, so a frozen worker is killed before the job is re-released.

A unit test of the backoff bounds and Retry-After parsing:

php
<?php

namespace Tests\Unit;

use App\Support\Backoff;
use PHPUnit\Framework\TestCase;

class BackoffTest extends TestCase
{
    public function test_ceiling_doubles_and_caps(): void
    {
        $b = new Backoff(100, 5000);
        $this->assertSame([100, 200, 400, 800, 1600, 3200, 5000, 5000], array_map($b->ceiling(...), range(1, 8)));
        $this->assertSame(5000, $b->ceiling(10_000));
    }

    public function test_full_and_equal_jitter_stay_inside_their_ranges(): void
    {
        foreach ([0.0, 0.25, 0.999] as $r) {
            $b = new Backoff(100, 5000, fn () => $r);
            for ($n = 1; $n <= 12; $n++) {
                $ceil = $b->ceiling($n);
                $this->assertGreaterThanOrEqual(0, $b->full($n));
                $this->assertLessThanOrEqual($ceil, $b->full($n));
                $this->assertGreaterThanOrEqual(intdiv($ceil, 2), $b->equal($n));
                $this->assertLessThanOrEqual($ceil, $b->equal($n));
            }
        }
    }

    public function test_decorrelated_never_exceeds_cap_or_goes_below_base(): void
    {
        $b = new Backoff(100, 5000, fn () => 0.999);
        $prev = 0;
        for ($i = 0; $i < 20; $i++) {
            $prev = $b->decorrelated($prev);
            $this->assertGreaterThanOrEqual(100, $prev);
            $this->assertLessThanOrEqual(5000, $prev);
        }
    }

    public function test_retry_after_parses_seconds_and_dates(): void
    {
        $now = strtotime('2026-01-01 12:00:00 UTC');
        $this->assertSame(120_000, Backoff::retryAfterMs('120'));
        $this->assertSame(30_000, Backoff::retryAfterMs('Thu, 01 Jan 2026 12:00:30 GMT', $now));
        $this->assertSame(0, Backoff::retryAfterMs('Wed, 31 Dec 2025 23:59:59 GMT', $now));
        $this->assertNull(Backoff::retryAfterMs('soon'));
        $this->assertNull(Backoff::retryAfterMs(null));
    }
}

The Laravel angle ​

Laravel featureUse for timeouts and retriesNote (Laravel 13 docs)
Http::timeout(seconds)Per-attempt response limit"By default, the HTTP client will timeout after 30 seconds"; throws ConnectionException
Http::connectTimeout(seconds)Connect limitDefault 10 seconds
Http::retry($times, $sleep, $when, throw: false)Retry with a schedule$sleep may be an int, an array of ms, or a closure (attempt, exception); $when may modify the request
Http::retry(...) when all attempts failException policyRequestException, or the last response with throw: false; connection failures still throw ConnectionException
retry($times, $callback, $sleep, $when) helperRetry any codeSame sleep forms; the 4th argument restricts which exceptions
Http::fake(), Http::sequence(), assertSentCount()Test 503, 503, 200 without a serverwhenEmpty() sets the default
HTTP client eventsRequestSending, ResponseReceived, ConnectionFailedEmit retry metrics from listeners
queue:work --tries --timeout --backoffWorker defaultsJob attributes win over the CLI values
#[Tries], #[Backoff], #[Timeout], #[MaxExceptions], #[RetryFor], #[FailOnTimeout]Per-job policyAttributes in Illuminate\Queue\Attributes
retryUntil()Time windowBeats tries when both exist
ThrottlesExceptions, WithoutOverlapping, RateLimitedJob middlewareReleases count as attempts: raise tries
Cache::lock($name, $seconds)->block($wait)One refresher, bounded waitersLockTimeoutException when the wait is exceeded
Sleep::fake()Test sleeps without waitingAssert the recorded durations
DB::statement('SET LOCAL statement_timeout = ...') inside DB::transactionServer-side limit per transactionPostgreSQL; the setting ends with the transaction

Solving the classic problems ​

"The service hangs for minutes when a dependency is down" ​

StepActionResult
1Find calls with no connect or read timeout (HTTP, Redis, DB, SDK)List of unbounded waits
2Set connect, per-try and overall limits from the p99.9 of each dependencyFailure takes seconds, not minutes
3Add statement_timeout and idle_in_transaction_session_timeout per roleServer stops abandoned work
4Add a bulkhead (a separate pool per dependency)One dependency cannot take every thread; see Bulkheads
5Alert on timeout counts per dependencyYou see it before users do

"A blip became a long outage: retry storm" ​

text
     Timeline of a retry storm
1    t=0     database CPU 85%, p99 400 ms; per-try timeout 500 ms
2    t=10 s  a slow query pushes p99 to 700 ms -> 20% of calls time out at 500 ms
3    t=10 s  each timeout retries (3 attempts): load becomes 1.2x -> 1.6x -> CPU 100%
4    t=30 s  now 90% time out, load is 2.8x; the slow query is gone but nothing recovers
5    t=5 min operator disables retries (or sheds load); the database recovers in seconds
6    fix     one retry layer, 10% budget, circuit breaker, load shedding on the server
MitigationWhenWhere it is described
Turn retries off (feature flag)During the incidentRunbook
Retry budgetAlwaysBudget
Retry only at the edgeDesignOne layer
Circuit breakerFailure rate above a thresholdCircuit Breaker
Server-side shedding and Retry-AfterServerLoad Shedding
Exponential backoff with full jitterAlwaysJitter

"Customers were charged twice" ​

StepAction
1Find the POST that was retried after a read timeout
2Add Idempotency-Key created once per operation and stored before the first send
3On the server, store the key and the result in one transaction (see API Idempotency)
4Make the client retry only keyed or idempotent calls (classification table)
5Reconcile existing duplicates with a ledger query
sql
-- Server side: the unique constraint is the safety net under every client retry.
CREATE TABLE idempotency_keys (
    key         text PRIMARY KEY,
    request_hash text NOT NULL,
    response    jsonb,
    created_at  timestamptz NOT NULL DEFAULT now()
);
-- INSERT ... ON CONFLICT (key) DO NOTHING; a conflict means "return the stored response".

"Everything retries at midnight" ​

CauseFix
A cron job on every host at 00:00Add a random start delay (jitter) of 0 to 60 s
A cache key expires for all clients at onceAdd random TTL jitter and a refresh lock (Cache::lock)
All pods reconnect after a deployFull jitter on reconnect; staggered rollouts
Webhook retries scheduled "in 5 minutes"Add jitter to the schedule

"The queue runs my job twice" ​

CauseFix
--timeout greater than retry_afterMake timeout smaller than retry_after by several seconds
SQS visibility timeout smaller than job timeRaise the Default Visibility Timeout
Job times out and is retriedMake the job idempotent; add FailOnTimeout if retry is wrong
release() consumes attemptsRaise Tries, or use retryUntil

"Timeouts fire in production but not in test" ​

CauseFix
New connections include TLS in the first requestInclude setup in the budget; keep connections warm; pre-connect
Different geographyRe-derive from the caller's percentiles
A pause (GC, CPU throttling in containers)Add padding; check CPU limits
Idle timeout mismatch causing resetsClient idle timeout shorter than the server's

Choosing ​

Which retry policy for which call ​

CallTimeout (per try)AttemptsBackoffBudgetIdempotency
Interactive read from a servicep99.9 plus padding, 0.2 to 1 s2 to 3Full jitter, base 50 ms, cap 500 ms10%Naturally
Interactive write (payment, order)2 to 5 s2 to 3Full jitter, base 100 ms10%Required key
Background job calling an API10 to 30 s5 to 8, or retryUntil hoursExponential, jitter, cap minutesPer job classRequired
Webhook delivery to a customer5 to 10 s8 to 10 over many hoursEscalating array with jitterPer endpointReceiver dedupes by id
Cache or Redis20 to 100 ms1 to 2Constant small with jitterYesNaturally
Database transactionstatement_timeout 0.5 to 3 sOnly on 40001 and 40P01Short jitterYesWhole transaction repeated
Calls inside a deep stackRemaining deadline0 (fail fast)NoneNoneNot applicable
Health checks1 to 2 s0 (the next check is the retry)NoneNoneNaturally

Which jitter ​

NeedPickReason
Default for everythingFull jitterLeast work in Brooker's simulation, simple
A guaranteed minimum pauseEqual jitterAt least half the ceiling; but "takes much longer"
Delays that evolve from the previous delayDecorrelated jitterNo attempt counter needed
Interoperating with gRPC+/-20% of the exponential delayWhat gRPC does; only a light spread
Scheduled work across a fleetRandom start offsetSpreads the first call, not only retries

Where to retry ​

LayerRetry here whenDo not retry here when
Browser or mobile appThe user can see and press retryThe server is overloaded: a loop here becomes a DDoS
Edge or gatewayIt knows idempotency (method, key)Backends already retry
Service A calling BA owns the operation and its deadlineAn upstream layer also retries
Service mesh sidecarYou have no app-level controlThe app already retries
SDKDefaults suit you (AWS standard mode)You add your own loop on top
Database driverConnection setupNever inside a transaction without re-running the whole transaction

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

Most calls are in-process; only the database, the cache and a few external APIs cross a network. The simplest correct setup: a connect timeout and a request timeout on every outbound HTTP client; statement_timeout and idle_in_transaction_session_timeout on the application's database role; retries only for (a) deadlock and serialization failures (SQLSTATE 40P01 and 40001, repeating the whole transaction) and (b) idempotent external reads. Example: a Laravel app that charges a card calls the payment API with timeout(5), a stored idempotency key and retry(2, ...), and its web role has statement_timeout = 3s.

Modular monolith: boundaries without the network ​

Modules call each other in-process, so there is no timeout between them, but they may share a database. A slow module can still hold the connection pool. Give each module its own pool size or role (with its own statement_timeout), keep external calls behind a module-owned client, and decide who owns retries per external dependency. If a module will later become a service, give its in-process call a Context or budget parameter now.

Microservices: every hop spends the budget ​

A user request crosses the gateway, service A, B and C. The gateway sets a deadline (for example 3 s) and sends it down (see Service Communication); each hop sets timeout = min(own cap, remaining - margin); only the edge (or the one service that owns the operation) retries, with a budget; inner services return 503 with Retry-After quickly when overloaded; the mesh sidecar's retries are off for those routes.

text
     Request flow with one retry layer
1    client   -> gateway     deadline 3 s; gateway: per-try 1 s, 3 attempts, budget 10%
2    gateway  -> A           remaining 2.9 s, A: no retries
3    A        -> B           remaining 2.7 s
4    B        -> C           remaining 2.5 s; C is slow
5    B        -> A           504 at 1 s (B's per-try); A returns 503 fast to the gateway
6    gateway  sleeps full-jitter(0..100 ms), retries A (second attempt), 1.9 s left

The PaymentsClient and the Go httpclient follow exactly this shape.

Distributed data: replicas, caches, regions ​

Retries interact with data: a read retried on another replica may return stale data; a write retried after a primary failover may hit a new leader that has already applied the first write (idempotency again); a cache stampede is a retry storm on the origin (use a refresh lock, TTL jitter, stale-while-revalidate); cross-region calls have long connect times, so connect and per-try timeouts must be derived from that region pair, not copied from the local numbers. Quorum stores add their own timeouts (Cassandra read and write request timeouts, DynamoDB client retries); see Caching and Replication Topologies.

Scaling path: 1x, 10x, 100x ​

LoadWhat is enoughWhat breaksNext step
1xTimeouts on every client, 2 to 3 attempts, constant or exponential backoffNothing yetAdd jitter and classification
10xFull jitter, per-try and overall deadlines, Idempotency-Key on writesRetries start to matter during incidents; thundering herds at cron timesRetry budget, one retry layer
100xShared budgets per dependency, deadlines propagated, hedged reads, breakers, load sheddingHidden retries in SDK and mesh; metastable failuresChaos tests of retry behaviour, per-dependency SLOs
Multi-regionRegion-aware timeouts, failover with jittered reconnectsReconnect storms after a region returnsSlow-start traffic on recovery

Lab: timeouts, retries and jitter you can run ​

All steps in the first block were run on the author's machine (Go 1.27, no containers); the later blocks are expected output and were not run.

Experiment 1: run the tests and the simulation (run).

text
     cd docs/snippets/system-design/timeouts-retries-jitter/go
1    go vet ./... && go test -count=1 ./...
2    ok  academy/timeouts-retries-jitter/dbtimeouts
3    ok  academy/timeouts-retries-jitter/httpclient
4    ok  academy/timeouts-retries-jitter/retry
5    go run ./cmd/jittersim
6    1) 100 clients contend for one slot per 10ms (cap 1s, base 10ms)
7       constant 10ms (no jitter)    2121 calls  finish 1.02s
8       exponential, no jitter       1152 calls  finish 15.7s
9       full jitter                   717 calls  finish 2.12s
10      equal jitter                  698 calls  finish 2.76s
11      decorrelated jitter           701 calls  finish 2.1s
12   2) 3 attempts, no budget  3000 calls (+200%);  3 attempts + 10% budget  1109 calls (+11%)
13   3) layers=5 -> 243 calls reaching the database per user request

Reading the table: jitter cuts the calls from 1152 to about 700 and the time from 15.7 s to about 2 s; equal jitter is the slowest of the jittered variants, as Brooker found. The model (one winner per 10 ms slot, plus 0 or 1 slot of network variance) is a simplified version of his scenario, not his simulator.

Experiment 2: watch statement_timeout (expected, not run; needs PostgreSQL). Session 1 and 2 are two psql windows.

sql
-- session 1
BEGIN; SELECT * FROM accounts WHERE id = 1 FOR UPDATE;   -- holds the row lock, stays open
-- session 2
SET lock_timeout = '300ms';
UPDATE accounts SET balance = balance + 1 WHERE id = 1;
-- expected: ERROR:  canceling statement due to lock timeout   (SQLSTATE 55P03) after ~300 ms
SET statement_timeout = '200ms';
SELECT pg_sleep(2);
-- expected: ERROR:  canceling statement due to statement timeout   (57014) after ~200 ms
-- session 1, leave it open and set:
SET idle_in_transaction_session_timeout = '3s';
-- expected after ~3 s idle: FATAL: terminating connection due to idle-in-transaction timeout (25P03)

Experiment 3: Laravel retry sequence with a fake HTTP server (expected, not run).

php
Http::fake([
    'payments.internal.example/*' => Http::sequence()
        ->push('', 503, ['Retry-After' => '1'])
        ->push('', 503)
        ->push(['charge_id' => 'c1'], 200),
]);
Sleep::fake();
$result = app(PaymentsClient::class)->charge(7, 10000, 'key-1');
// expected: $result['charge_id'] === 'c1'
Http::assertSentCount(3);
Sleep::assertSleptTimes(2);   // the first sleep is at least 1000 ms because of Retry-After

Experiment 4: NGINX and the app disagree (expected, not run).

text
1    NGINX: proxy_read_timeout 5s;  app: sleep(8) in a route
2    curl -i -m 20 http://127.0.0.1:8080/slow   (a local test address)
3    expected: HTTP/1.1 504 Gateway Time-out after about 5 s, app log shows the handler still running until 8 s
4    fix: app deadline 4 s < proxy_read_timeout 5 s; the app returns a clean 503 at 4 s

Experiment 5: queue clocks (expected, not run). Set retry_after to 20 and --timeout=60 with a job that sleeps 30 s.

text
1    php artisan queue:work redis --timeout=60 --tries=3
2    t=0    worker A reserves the job, sleeping
3    t=20   retry_after elapsed -> the job is released; worker B reserves it (second concurrent run)
4    t=30   A finishes; t=50 B finishes -> the side effect happened twice
5    fix: --timeout=15 (below retry_after) or retry_after=90 and the job made idempotent

Common misconceptions ​

BeliefReality
A timeout means the request failedIt means you stopped waiting; the server may complete it later (ambiguous failure)
More retries means more reliabilityOnly for transient single faults; during overload it is more load; cap attempts and use a budget
Exponential backoff alone prevents herdsWithout jitter every client sleeps the same time and returns together
Jitter of plus or minus 10% is enoughBrooker's best result is full jitter over the whole interval
Every 5xx is retryable501 and deterministic 500s never succeed; 500, 502, 504 are ambiguous for non-idempotent calls
Http::timeout(3) caps the whole call at 3 sIt is per attempt; with retry(3) the call can take 9 s plus sleeps
The default HTTP timeout is fineGo has none; Laravel has 30 s; both are far above an interactive budget
Retries should be added at every layer for safetyThe load multiplies (243x for five layers of three); retry at one layer
A new idempotency key per retry is fineThe key must be stable across retries or it protects nothing
retry_after is the delay between job retriesIt is the visibility timeout; the delay is backoff
A circuit breaker makes retries unnecessaryThey solve different problems; breakers cap damage, retries fix blips
Idempotent means safe to retry without limitStill extra load; the budget and backoff still apply
The client closing the connection stops the database queryOnly if the driver sends a cancel and the server honours it; set statement_timeout

Cheat sheet ​

TopicRemember
Five timeoutsConnect, write, read, total (request), idle; set all of them, nothing is "default safe"
Layeringclient > edge > proxy > app > per-try x tries > database, derived from one deadline
Choosing a valueThe percentile for the false-timeout rate you accept (p99.9 for 0.1%), plus padding, measured from the caller
Gocontext.WithTimeout per attempt, http.Client.Timeout, net.Dialer.Timeout, ResponseHeaderTimeout, defer cancel()
Laraveltimeout(…), connectTimeout(…), retry($times, $sleep, $when, throw: …); key generated outside the closure
PostgreSQLstatement_timeout, lock_timeout, idle_in_transaction_session_timeout; per role or SET LOCAL, not in postgresql.conf
Queues--timeout less than retry_after; Tries default is 1; retryUntil beats tries; backoff array repeats the last value
What to retryNever-reached errors always; ambiguous ones only if idempotent or keyed; fatal ones never
BudgetRetries at most 10% of requests; one shared bucket per dependency
LayersRetry at one layer; the others fail fast; 3 attempts x 5 layers = 243
BackoffCapped exponential with full jitter by default: random(0, min(cap, base * 2^(n-1)))
Server hintsRetry-After (seconds or HTTP-date), gRPC pushback: wait the larger of hint and backoff; give up if it exceeds the deadline
HedgingRetry waits for failure, hedging sends a copy after about p95; reads only; same budget
TestsInject Clock and Rand; assert schedule, bounds, stop rules, and call counts
ObservabilityAttempts per request, retries by reason, give-ups by reason, budget tokens left

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A POST times out after 1.5 s. May you retry it? Under what condition? Must-know ​

Answer

Answer: Only if the request is idempotent or carries a stable idempotency key, because a read timeout is an ambiguous failure: the server may have executed it. RFC 9110 says a client SHOULD NOT automatically retry a non-idempotent request unless it can know the original was never applied.

2 — Why does Http::retry(3, 100)->timeout(3) not bound the call at 3 seconds? Must-know ​

Answer

Answer: timeout() applies to each attempt. With three attempts and two 100 ms sleeps the worst case is about 9.2 s. Use a request budget or a total deadline in addition to the per-attempt timeout.

3 — Five services in a chain each retry three times. How many calls reach the database for one failing user request, and what is the fix? Must-know ​

Answer

Answer: 3^5 = 243. Retry at one layer (usually the edge) with a budget, and make inner layers fail fast.

4 — Compute the sleep ceiling for retry 5 with base 100 ms and cap 5 s, and the range under full and equal jitter. Important ​

Answer

Answer: Ceiling = min(5000, 100 x 2^4) = 1600 ms. Full jitter: 0 to 1600 ms. Equal jitter: 800 to 1600 ms.

5 — A server returns 429 with Retry-After: 30 but your backoff gives 200 ms. How long do you wait, and when do you give up instead? Important ​

Answer

Answer: The larger, 30 s. If 30 s does not fit before the overall deadline, give up at once instead of sleeping.

6 — Why must the idempotency key be created outside the retry loop? Must-know ​

Answer

Answer: All attempts of one logical operation must carry the same key so the server can recognise repeats; a new key per attempt makes each attempt a new operation.

7 — Your Laravel job has --timeout=120 and the Redis connection has retry_after=90. What happens? Important ​

Answer

Answer: At 90 s the queue releases the still-running job and another worker may start it, so it can run twice concurrently. Make the timeout smaller than retry_after.

8 — What do the three PostgreSQL timeouts protect against? Important ​

Answer

Answer: statement_timeout limits long statements, lock_timeout limits waiting for locks, idle_in_transaction_session_timeout kills sessions that sit idle inside an open transaction (holding locks and blocking vacuum).

9 — What is the difference between a retry budget and a per-request attempt limit? Important ​

Answer

Answer: The attempt limit caps one request (3 attempts). The budget caps the aggregate: retries as a fraction of all requests, so during a total outage the extra load is about 10%, not 200%.

10 — Why use a fake clock in retry tests? Good to know ​

Answer

Answer: It makes sleeping instantaneous and records the delays, so schedules, bounds, deadlines and budgets can be asserted deterministically and quickly.

11 — When does hedging beat a retry, and what must be true of the operation? Good to know ​

Answer

Answer: When the first attempt is merely slow (the tail), not failed; the copy is sent after about p95. The operation must be safe to execute more than once, and the extra load must be capped by the same budget.

12 — Name the three classes of failure and one example of each. Must-know ​

Answer

Answer: Retryable (connection refused, 503), ambiguous (read timeout, connection reset, 500), fatal (400, 404, context cancelled).

Glossary ​

TermMeaning
TimeoutA limit on how long to wait for something
Connect timeoutLimit on establishing the connection
Read timeoutLimit on waiting for response bytes
Write timeoutLimit on sending the request
Request timeoutLimit on one whole attempt (also called total timeout)
Idle timeoutLimit on a connection with nothing in flight
DeadlineAbsolute time by which an operation must finish
Total deadlineDeadline covering all attempts and sleeps of one user request
Deadline propagationPassing the remaining time to the next service
Timeout budgetThe time still available to spend on the remaining hops
Timeout layeringOrdering limits so each inner one is shorter than the one around it
False timeoutA healthy call that is cut because the timeout is too low
RetryRepeating a failed operation
IdempotentRepeating it has the same effect as doing it once
Idempotency keyA client-chosen identifier that lets the server recognise a repeat
Ambiguous failureA failure after which you do not know whether the server acted
Error classificationSorting failures into retryable, ambiguous and fatal
Retry budgetA cap on retries as a fraction of traffic (for example 10%)
Per-try timeoutLimit on one attempt, smaller than the overall deadline
Retry stormSelf-sustaining overload caused by retries
Thundering herdMany clients acting at the same instant
BackoffPausing between attempts
Exponential backoffDoubling the pause each attempt
CapThe maximum backoff
JitterRandomness added to a delay
Full jitterrandom(0, ceiling)
Equal jitterceiling/2 + random(0, ceiling/2)
Decorrelated jittermin(cap, random(base, previous * 3))
Retry-AfterHTTP header giving the wait in seconds or as a date
PushbackgRPC metadata grpc-retry-pushback-ms telling the client when or whether to retry
Hedged requestA second copy sent after a delay without cancelling the first
Circuit breakerA component that stops calls to a failing dependency for a while
Adaptive retryAWS SDK mode with a client-side rate limiter in addition to standard retries
gRPC retry policyService-config JSON with maxAttempts, backoff and retryableStatusCodes
Retry quotaThe AWS SDK's token bucket for retries
retry_afterLaravel queue visibility timeout, not a retry delay
triesMaximum attempts of a queued job
backoff arrayA schedule of seconds per attempt, the last value repeating
retryUntilA time at which a job stops being retried
Fake clockA test clock whose sleep advances time instantly

References ​

Built by Morteza Negahi