Skip to content

Lesson 8 of 9 · 23m

Backpressure, Timeouts, and Retries

Network systems fail by accumulation — control queue growth, bound every operation, and retry only when the protocol makes it safe.

Most network services do not collapse because one operation is slow. They collapse because slow operations accumulate: sockets pile up, buffers grow, queues deepen, memory climbs, and latency feeds more retries. Backpressure is the discipline of saying "stop" early enough for the system to remain useful.

Every operation needs a deadline

async def fetch_line(reader):
    return await asyncio.wait_for(reader.readline(), timeout=5)

A connect timeout does not cover reads. A read timeout does not cover writes. A request timeout does not control queue time. Production systems layer deadlines deliberately: connect timeout, per-read/write timeout, overall request deadline, and maximum connection lifetime. If they are all the same number copied from a blog post, they are not design.

Writers must respect slow readers

TCP applies backpressure naturally by filling kernel buffers. Your application can defeat it by accepting unlimited data into user-space queues. asyncio exposes the pressure through drain():

writer.write(payload)
await writer.drain()

When drain pauses, the correct behavior is usually to slow producers or drop low-priority messages — not allocate a bigger queue. Metrics queues, broadcast fan-out, and proxy pipelines all need explicit maximum queue sizes and a policy for overflow: block, shed, or degrade.

Retry only safe operations

Retries amplify failure. Three retry attempts at one hundred clients can turn a small server hiccup into a self-inflicted denial-of-service event. Retry idempotent operations, use exponential backoff, and add jitter so clients do not synchronize.

delay = 0.2
for attempt in range(4):
    try:
        return await operation()
    except TransientError:
        await asyncio.sleep(delay + random.uniform(0, delay))
        delay *= 2

Non-idempotent operations need an idempotency key or a reconciliation path. A timeout means the outcome is unknown, not necessarily failed.

Timeouts need close semantics

After a read timeout, can the parser resume on the same stream? Usually no: you do not know whether the missing bytes will arrive later and corrupt the next frame. Closing the connection is often the only safe recovery. Document this in the protocol. It is better to reconnect cleanly than to preserve a poisoned stream because the socket object is expensive.

Load shedding is a feature

When saturated, reject cheaply and quickly. Return overloaded, close new low-priority connections, shorten expensive responses, or stop optional work. A health check that keeps returning success while the queue grows is worse than no health check. Measure queue depth, oldest queued item, write-buffer bytes, and connection counts.

Field notes

  • Retry storms often look like traffic growth in graphs until you annotate deploys and outages.
  • Include jitter even in internal systems; synchronized cron jobs are enough to align retries.
  • Deadlines should be end-to-end, not restarted independently at every proxy hop.
  • Test slow clients by writing a client that reads one byte per second.
  • Queue length is a leading indicator; CPU is often the lagging corpse.

Was this lesson helpful?

Sign in to rate