Pidoku

Backpressure, Timeouts, and Retries

Module 20 Lesson 20.e 1h 15m Difficulty 4/5

Prerequisites 1.c, 12.p, 20.c


Before you start: words you need#

WordPlain meaning
BackpressureA full component telling the one upstream of it to slow down or stop sending.
TimeoutGiving up on an operation after a fixed time.
RetrySending a failed request again.
Exponential backoff with jitterWaiting longer after each failure (1 s, 2 s, 4 s …), plus a random amount, so that many clients do not retry at the same instant.
Retry budgetA cap on retries as a share of all traffic, such as “retries may add at most 10%”.
CancellationStopping work on the server because the client no longer wants the answer, and freeing what it held.
IdempotentSafe to repeat: sending it twice has the same effect as once. A generation request is not, once tokens have been streamed.
Metastable failureAn overload that sustains itself after its cause has gone (20.c).

1. What is it?#

The three mechanisms that decide whether a service slows down gracefully under overload or collapses:

BACKPRESSURE  telling upstream "I'm full", so it slows down
TIMEOUTS      giving up on work that has taken too long
RETRIES       trying again after a failure, and the discipline not to

LLM serving needs different settings and different reasoning for all three than ordinary web services do, because its requests are long (seconds to minutes), expensive (each holds a slot and KV cache memory), and not idempotent once streaming has begun.


2. Why does it exist?#

Because a naive system under overload does not get “slower”. It collapses, often in a way it cannot recover from:

overload → queue grows → latency grows → clients time out → clients retry
        → more load → queue grows more → …

and in LLM serving specifically:
  the ORIGINAL request is still running, holding a KV slot, generating
  tokens that nobody will read.

The system now does three times the work for none of the value. Arrival rate going back to normal does not help, because the server is busy with abandoned work. That is a metastable failure.

Retries are not only something your own code does. The official openai Python SDK retries connection errors, 408, 409, 429 and 5xx responses twice by default, with a short exponential backoff. Every client of an OpenAI-compatible service is a retrying client unless someone turned it off.


3. Simple analogy#

A ticket office with a queue out of the door.

Without backpressure: everyone joins the queue. After an hour, people at the back give up and join again from the start (retry), making the queue longer. The clerks serve people who left twenty minutes ago.

With backpressure: a sign at the door says “queue full, come back at 3 pm”. The queue stays short, the people served are happy, and the people turned away know to come back rather than wait three hours for nothing.

Cancellation is the clerk noticing that the person at the window has walked off, and calling the next one instead of finishing the paperwork.


4. Tiny example: the retry storm#

An overloaded server: 32 slots, requests arriving at 12 per second, service times averaging about 3.7 s (so capacity is about 8.6 per second). Clients give up after 30 s and, in two of the runs, retry up to twice. In the third run the server also notices when a client has gone and stops work on its request.

Go
// retries.go — an overloaded server, with and without retries and cancellation.
package main

import (
	"container/heap"
	"fmt"
	"math"
	"math/rand"
)

type event struct {
	t       float64
	attempt int
}
type events []event

func (h events) Len() int           { return len(h) }
func (h events) Less(i, j int) bool { return h[i].t < h[j].t }
func (h events) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *events) Push(x any)        { *h = append(*h, x.(event)) }
func (h *events) Pop() any          { old := *h; x := old[len(old)-1]; *h = old[:len(old)-1]; return x }

type floats []float64

func (h floats) Len() int           { return len(h) }
func (h floats) Less(i, j int) bool { return h[i] < h[j] }
func (h floats) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *floats) Push(x any)        { *h = append(*h, x.(float64)) }
func (h *floats) Pop() any          { old := *h; x := old[len(old)-1]; *h = old[:len(old)-1]; return x }

func simulate(arrivalRate float64, retries, cancellation bool, simTime float64) (completed int, wasted float64) {
	rng := rand.New(rand.NewSource(1))
	slots := make(floats, 32) // when each of 32 slots becomes free
	var q events
	for t := rng.ExpFloat64() / arrivalRate; t < simTime; t += rng.ExpFloat64() / arrivalRate {
		heap.Push(&q, event{t, 0}) // the original requests
	}
	for q.Len() > 0 {
		ev := heap.Pop(&q).(event)
		if ev.t >= simTime {
			break
		}
		deadline := ev.t + 30 // the client gives up after 30 s
		start := math.Max(ev.t, slots[0])
		service := math.Exp(1.0 + 0.8*rng.NormFloat64())

		var busyUntil float64
		switch {
		case start+service <= deadline: // finished while the client was still listening
			busyUntil = start + service
			completed++
		case cancellation: // server notices the client left and aborts early
			busyUntil = math.Max(start, deadline)
			wasted += busyUntil - start
		default: // server runs to completion for nobody
			busyUntil = start + service
			wasted += service
		}
		slots[0] = busyUntil
		heap.Fix(&slots, 0)

		if start+service > deadline && retries && ev.attempt < 2 {
			heap.Push(&q, event{deadline, ev.attempt + 1}) // the client tries again
		}
	}
	return completed, wasted
}

func main() {
	for _, c := range []struct {
		label           string
		retries, cancel bool
	}{{"no retries, no cancel", false, false}, {"retries, no cancel", true, false}, {"retries + cancel", true, true}} {
		done, wasted := simulate(12, c.retries, c.cancel, 300)
		fmt.Printf("%-25s completed=%5d wasted_gpu_sec=%8.0f\n", c.label, done, wasted)
	}
}

Output (five simulated minutes):

no retries, no cancel     completed=  645 wasted_gpu_sec=   11599
retries, no cancel        completed=  639 wasted_gpu_sec=   30218
retries + cancel          completed= 1906 wasted_gpu_sec=    6684

How to read it:

  • Retries without cancellation make things worse: slightly fewer answers delivered, and nearly three times the GPU time wasted on answers nobody received.
  • Retries with cancellation deliver three times as many answers, because abandoned work stops at the client’s deadline and the slot goes to someone still waiting.
  • Most systems implement retries and forget cancellation. The combination is what matters.

5. Technical explanation#

Backpressure: the mechanisms#

1. REJECT (503 + Retry-After)
   The main mechanism. Fast, explicit, honest (20.c).

2. BOUNDED QUEUES at every layer
   Router, API server, engine. Each one bounded.

3. FLOW CONTROL ON STREAMS
   If a client is not reading, stop generating for it.

4. RATE LIMITS (token bucket, per tenant)
   Stop one client consuming the fleet (23.j).

5. CONCURRENCY LIMITS per tenant
   Simpler than rate limits, and they bound slot use directly.

Mechanism 3 is LLM-specific and often missed. If a client stops reading the stream, the socket buffer fills and writes block. If the server does not notice, it either blocks its event loop or buffers tokens in memory without limit, while the request keeps its slot. Treat a client that has not read for a long time like a disconnected one.

Timeouts: you need several#

TIMEOUT               TYPICAL VALUE          PURPOSE
connect               1–5 s                  network reachability
TLS handshake         2–5 s
queue wait            5–30 s                 do not queue forever
time to first token   30–60 s                catch prefill problems
inter-token stall     10–30 s                catch engine hangs     ← LLM-specific
total generation      5–15 min               absolute bound
idle connection       > longest generation   do not kill live streams

The inter-token stall timeout is the important one. A 10-minute total timeout is useless for detecting a wedged engine; a “no token for 30 seconds” timeout catches it in 30 seconds.

Watch the defaults of everything between client and engine. The openai SDK waits 10 minutes by default; many load balancers and proxies cut idle connections at 60 seconds, which kills any stream that pauses for long reasoning (9.a).

The stall timeout in Go: the timer resets on every token, so a long answer is fine and a silent engine is not.

Go
var ErrEngineStalled = errors.New("engine stalled")

// streamWithStallTimeout forwards tokens, but fails if the engine goes quiet.
// The timeout is per TOKEN, not per request: a long answer is fine, a silent engine is not.
func streamWithStallTimeout(ctx context.Context, in <-chan string, out chan<- string, stall time.Duration) error {
	timer := time.NewTimer(stall)
	defer timer.Stop()
	for {
		select {
		case tok, ok := <-in:
			if !ok {
				return nil // generation finished normally
			}
			out <- tok
			timer.Reset(stall)
		case <-timer.C:
			return fmt.Errorf("%w: no token in %v", ErrEngineStalled, stall)
		case <-ctx.Done():
			return ctx.Err() // client went away
		}
	}
}

Reasoning models can think silently for a long time if the server hides reasoning tokens. Count reasoning tokens as “progress” for the stall timer, or the timer will fire on a healthy request.

Retries: the discipline#

RULE 1  Never retry a request that may still be running.
        Cancel it first, then retry.

RULE 2  Never retry after streaming has started.
        The client already has part of the answer; a retry duplicates or contradicts it.

RULE 3  Retry only failures that did no work:
        connection refused, 503 with Retry-After, 429 after the wait.
        NOT a timeout (the work may still be in flight) or a mid-stream 500.

RULE 4  Budget retries.
        Cap them at about 10% of total requests. A retry budget stops a partial
        outage becoming a total one.

RULE 5  Exponential backoff WITH jitter. Without jitter, retries synchronize into waves.

RULE 6  Respect Retry-After.

A retry budget is a few lines:

Go
// RetryBudget allows retries only while they are a small fraction of total traffic.
type RetryBudget struct {
	mu                sync.Mutex
	ratio             float64       // e.g. 0.1: retries may add at most 10% load
	window            time.Duration // e.g. one minute
	requests, retries []time.Time
}

func (b *RetryBudget) RecordRequest(now time.Time) {
	b.mu.Lock()
	defer b.mu.Unlock()
	b.requests = append(b.requests, now)
}

func (b *RetryBudget) AllowRetry(now time.Time) bool {
	b.mu.Lock()
	defer b.mu.Unlock()
	cutoff := now.Add(-b.window)
	expire := func(ts []time.Time) []time.Time {
		for len(ts) > 0 && ts[0].Before(cutoff) {
			ts = ts[1:]
		}
		return ts
	}
	b.requests, b.retries = expire(b.requests), expire(b.retries)
	if float64(len(b.retries)) >= b.ratio*float64(max(len(b.requests), 10)) {
		return false // budget spent: fail now rather than add load
	}
	b.retries = append(b.retries, now)
	return true
}

This one type prevents most retry storms, and few teams have it. Service meshes offer the same idea as configuration (Envoy’s retry budgets, Linkerd’s retry budgets); use theirs if you run one.

Retries between your own services are the router’s business too: a router that sees a replica fail can retry on another replica, but only if no token has been sent to the client yet.

Cancellation: the whole chain#

client disconnects (or a timeout fires)
   → the web server cancels the request's task
   → the streaming handler sees the cancellation
   → the API server sends abort(request_id) to the engine
   → the scheduler removes the request from the running batch
   → the KV cache manager frees its blocks
   → the slot is free for the next request in the queue

Every link must exist. If one is missing, capacity leaks. vLLM’s OpenAI server does the whole chain for you: a cancelled task becomes an ABORT message that the engine core handles between steps (16.f). Lesson 12.p shows the disconnect check in a hand-written server. The links you add around the engine are the ones that break: a gateway that keeps the upstream connection open after the client leaves, or a retry wrapper that never cancels the first attempt.

Test it: start a long generation, kill the client, and check that vllm:num_requests_running drops within a step or two.


6. Under the hood: measuring abandonment#

vllm:request_success{finished_reason="abort"}   requests ended by an abort
vllm:num_requests_running                        should drop at once after a disconnect
your gateway: client-closed (499) count          how many users gave up
your gateway: time from disconnect to abort      should be milliseconds
tokens generated after disconnect                pure waste; should be ~0

In chat products, 10–30% of requests commonly end with the client disconnecting. A rising share of abort in vLLM’s finished_reason label usually means latency is driving users away (19.c).


7. Performance implications#

The capacity value of cancellation:

20% of requests abandoned halfway through their answer
→ 10% of all generated tokens are wasted without cancellation
→ fixing it gives back about 10–11% of capacity, for a day of work

Under overload the effect is far larger: section 4 shows three times as many delivered answers.

Retries cost the reverse. A client that retries twice on every 503 can triple offered load exactly when the service is already full. A 10% retry budget caps that at 1.1×.


8. Production implications#

  • Get cancellation right first. It is the highest return on effort in this lesson.
  • Set a stall timeout, not only a total timeout.
  • Use a retry budget in every client and router you control, and configure the SDK’s max_retries deliberately.
  • Return Retry-After on 429 and 503, and honour it in your own clients.
  • Bound every queue (20.c).
  • Check every proxy’s idle timeout against your longest pause in a stream.
  • Test the overload path. Load-test past capacity and check that you reject cleanly instead of collapsing, and that you recover when load drops. Most teams never do this.
  • Alert on rejection rate as well as latency. Rejections are the healthy failure mode; you want to know how often you use it.

Failure handling beyond overload (dead GPUs, NCCL hangs, circuit breakers) is lesson 23.e.


9. Common mistakes#

  1. Retries without cancellation. Actively harmful.
  2. Retrying on a timeout while the original is still running.
  3. Retrying after streaming has started.
  4. No jitter. Retries arrive in synchronized waves.
  5. No retry budget. A partial outage becomes a total one.
  6. Forgetting the SDK retries too. Three attempts in your code, each with the SDK’s three, is up to nine requests for one user action.
  7. Idle timeout shorter than a generation. Streams die at 60 seconds.
  8. No stall timeout. A wedged engine holds slots forever.
  9. Never testing the overload path.

10. Hands-on exercise#

A. Reproduce the storm. Run retries.go. Lower the arrival rate until the server is no longer overloaded (try 8, then 6). At what rate do retries stop hurting?

B. Add a budget. Give the simulator a retry budget of 10% and re-run the “retries, no cancel” case. How much wasted GPU time does it save?

C. Cancellation end to end. Against a real vLLM server, start 20 long streaming requests, kill the clients after 5 seconds, and watch vllm:num_requests_running and vllm:kv_cache_usage_perc. Put an nginx or Envoy proxy in between and repeat. Does the abort still arrive?

D. Stall timeout. Wire streamWithStallTimeout into a small proxy. Simulate an engine hang (stop the engine process with kill -STOP) and check the timer fires in 30 seconds.

E. Overload test. Load-test your service at twice its capacity. Does it reject cleanly? What is the p99 latency of the requests it serves? Does it recover when load drops?


11. Interview questions#

  1. What is a metastable failure, and how do retries cause one?
  2. Why are retries harmful without cancellation in LLM serving?
  3. Which timeouts does an LLM service need? Why is a stall timeout necessary?
  4. What is a retry budget, and why does it matter?
  5. Why should you never retry after streaming has started?
  6. Trace cancellation from a disconnected client to freed KV blocks. Where does it usually break?
  7. What is the healthy failure mode under overload, and how do you check you have it?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in