Sub topic 7
Deadlines and not doing work nobody is waiting for
This chapter assumes you know how queues grow under overload (see the earlier chapters on unbounded queues) and can read short Python async examples.
The problem: wasted work
When a queue is long, a request can wait seconds before a worker picks it up. The client may have given up by then. If the worker processes the request anyway, the result goes nowhere. The work still uses CPU, memory, and database connections that live requests need.
This is how a service stays busy and still serves almost no one. Every worker is occupied with abandoned requests, and the live ones wait behind them.
Timeouts versus deadlines
A timeout is a duration: "give up after 2 seconds." A deadline is a point in time: "this answer is useless after 12:00:02.500."
Timeouts do not compose well across a call chain. If service A calls B with a 2 second timeout, and B calls C with its own 2 second timeout, B may spend 1.9 seconds waiting in its queue and then start a fresh 2 second call. A has already given up.
A deadline travels with the request. Each hop computes how much time is left and passes that on. Every service then knows whether the answer can still matter.
Checking the deadline before working
The key habit is to check the deadline when a request leaves the queue, before starting any expensive work.
import asyncio
import time
class DeadlineExceeded(Exception):
pass
async def worker(queue: asyncio.Queue) -> None:
while True:
deadline, payload = await queue.get()
if time.monotonic() >= deadline:
# The caller has given up. Skip the work.
print(f"dropped expired request {payload}")
continue
await asyncio.sleep(0.05) # simulate real work
print(f"served {payload}")
async def main() -> None:
queue: asyncio.Queue = asyncio.Queue()
now = time.monotonic()
for i in range(10):
await queue.put((now + 0.2, i)) # 200 ms budget each
task = asyncio.create_task(worker(queue))
await asyncio.sleep(1)
task.cancel()
asyncio.run(main())Ten requests arrive at once with a 200 ms budget, and each takes 50 ms. The first few are served. The rest have expired by the time the worker reaches them and are dropped in microseconds. Without the check, the worker would spend half a second on answers nobody wants.
Use time.monotonic() for deadlines inside one process, because wall-clock time can jump. Between machines, send the remaining budget (for example, "350 ms left") instead of an absolute timestamp, since clocks differ.
Cancel downstream work too
Dropping a request at the queue is not enough. If a request is already running when its deadline passes, stop it. In asyncio, asyncio.timeout() (Python 3.11 and later) cancels the work when time runs out:
import asyncio
async def call_backend(remaining: float) -> str:
async with asyncio.timeout(remaining):
await asyncio.sleep(1) # stand-in for a slow backend call
return "ok"
async def main() -> None:
try:
print(await call_backend(0.3))
except TimeoutError:
print("deadline exceeded, work cancelled")
asyncio.run(main())Common errors
- Checking only at the edge. A request that passed at arrival can expire in a queue. Check again at dequeue.
- Fresh timeouts at each hop. The total time can then exceed what the original caller allowed.
- Deadlines longer than the client's patience. If the server allows 30 seconds and the client gives up at 5, the last 25 seconds are wasted.
- Ignoring cancellation. Code that swallows
CancelledErrorkeeps running after its caller is gone.
Exercise
A service has a 2 second timeout on every outgoing call. A request spends 1.8 seconds in the queue and then makes two sequential calls. What goes wrong, and what would you change?
Show answer
The caller has probably given up already, and each outgoing call can still take up to 2 seconds, so the service may work for several more seconds on an abandoned request. Carry a deadline with the request. Check it when the request leaves the queue, drop it if it has expired, and give each outgoing call only the remaining time as its timeout.