Sub topic 7
Deadlines and not doing work nobody is waiting for
This chapter assumes you have read the earlier chapters on unbounded queues and bounded queues. You should also be comfortable with Python asyncio basics and with HTTP request latency. A bounded queue limits how much work waits, but it does not tell you whether the waiting work is still worth doing. Deadlines answer that question.
The problem: work that no one wants
Suppose a client gives up after 1 second. Your server has a queue, and a request waits 3 seconds before a worker picks it up. The worker runs the full request, writes the response, and the connection is already closed. The server spent capacity and produced nothing of value.
Under overload this gets worse. Queues grow, so wait times grow, so more requests are already abandoned by the time they reach a worker. The server stays busy at 100% utilization, yet almost every response is discarded. Engineers separate two numbers:
- Throughput is the number of responses the server completes per second.
- Goodput is the number of responses that reach a client that was still waiting.
Under overload with no deadline handling, throughput can stay high while goodput falls toward zero. Retries from impatient clients add new requests on top of the abandoned ones, which makes the queue longer still.
Timeout versus deadline
A timeout is a duration: "give up after 2 seconds". A deadline is a point in time: "this result is useless after 10:28:04.500". They describe the same intent, but they behave differently when a request crosses several steps.
| Row | Timeout | Deadline |
|---|---|---|
| Form | Duration, such as 2 s | Absolute moment, or the remaining time at the current hop |
| Per-step use | Each step restarts its own clock | All steps share one budget |
| Worst-case total | Sum of all step timeouts | The original deadline |
| Time spent queued | Not counted unless you measure it | Counted automatically |
Consider three services in a chain that each use a 2-second timeout. The caller of the first service can wait up to 6 seconds in total, and the outermost client probably gave up long ago. With a deadline, each service asks "how much of the original budget is left?" and the whole chain stops when the budget is gone.
Where to check the deadline
A deadline only helps if code looks at it. There are three useful places:
- At admission. If the request arrives already expired, reject it before it enters the queue.
- At dequeue. This is the most valuable check. Time in the queue has been consumed, so the request may now be dead. Drop it and take the next one. A dropped request costs microseconds instead of the full service time.
- Before each expensive step. Check before a database query or a downstream call. Also compare the remaining time with the minimum time the step needs. If a query takes at least 50 ms and 10 ms remain, skip it.
The following example puts 100 requests into a queue at once. Each has a 1-second deadline, and each takes 50 ms to process, so one worker can finish only about 20 of them in time.
import asyncio
import time
from dataclasses import dataclass
@dataclass
class Request:
payload: str
deadline: float # a time.monotonic() value
def remaining(self) -> float:
return self.deadline - time.monotonic()
async def worker(queue: asyncio.Queue, stats: dict) -> None:
while True:
req = await queue.get()
try:
if req.remaining() <= 0:
stats["expired"] += 1 # dropped at dequeue, costs almost nothing
continue
await asyncio.sleep(0.05) # simulate 50 ms of real work
stats["served"] += 1
finally:
queue.task_done()
async def main() -> None:
queue: asyncio.Queue = asyncio.Queue()
stats = {"served": 0, "expired": 0}
start = time.monotonic()
for i in range(100):
await queue.put(Request(f"job-{i}", deadline=start + 1.0))
task = asyncio.create_task(worker(queue, stats))
await queue.join()
task.cancel()
print(stats, f"finished in {time.monotonic() - start:.2f}s")
asyncio.run(main())You should see about 20 requests served and about 80 expired, finishing in roughly 1 second. Without the remaining() check, the worker would spend 5 seconds producing 80 responses that nobody can use. During those 5 seconds, newer requests would sit behind them.
The example uses time.monotonic() on purpose. The wall clock (time.time()) can jump when the system clock is adjusted, which would make deadlines fire early or never.
Passing the budget to downstream calls
Inside a request, every call to another service should use the time that is left, not a fresh fixed timeout. Python 3.11 and later provides asyncio.timeout for this.
import asyncio
import time
class DeadlineExceeded(Exception):
pass
async def step(name: str, seconds: float, deadline: float) -> str:
budget = deadline - time.monotonic()
if budget <= 0:
raise DeadlineExceeded(f"{name}: no time left before start")
try:
async with asyncio.timeout(budget):
await asyncio.sleep(seconds) # stands in for a downstream call
except TimeoutError:
raise DeadlineExceeded(f"{name}: ran out of time") from None
return name
async def handle(deadline: float) -> str:
await step("auth", 0.1, deadline)
await step("database", 0.2, deadline)
return "ok"
async def main() -> None:
deadline = time.monotonic() + 0.25
try:
print(await handle(deadline))
except DeadlineExceeded as exc:
print("failed:", exc)
asyncio.run(main())The first step uses 0.1 s of the 0.25 s budget. The second step needs 0.2 s but gets only about 0.15 s, so it is cancelled at the budget boundary. The output is failed: database: ran out of time. The database call stops as soon as the deadline passes, so the connection and the downstream worker are released sooner.
Sending deadlines across the network
A deadline must travel with the request, or the next service cannot honor it. Two practical rules:
- Send the remaining duration, not an absolute timestamp. Clocks on different machines disagree by milliseconds or more, and a monotonic clock value means nothing on another host. gRPC does this with its
grpc-timeoutheader. For plain HTTP you can use a header such asX-Request-Timeout-Ms, which is a convention you define, not a standard. Each hop converts the received duration into a local monotonic deadline on arrival. - Subtract a margin. Network transit and response serialization take time. If 500 ms remain, pass on 450 ms so the caller still has time to receive the answer.
Also set a ceiling. A client might send no deadline, or a very large one. Apply a server-side default and a maximum, so that a missing or absurd value cannot keep a worker busy indefinitely.
Edge cases and failure modes
- Uncancellable work. A thread running a blocking call, or a CPU-bound loop, ignores
asynciocancellation. Check the deadline between units of work, and keep each unit short. - Server timeout longer than the client's. If the client waits 1 s and the server allows 5 s, the server keeps working for 4 s after the client leaves. Server limits should be equal to or shorter than what clients actually wait. Propagated deadlines fix this automatically.
- Deadlines that are too tight. If the budget is shorter than the normal latency, almost everything fails and clients retry. Base deadlines on measured latency percentiles, such as a value somewhat above p99, not on a guess.
- Expiry hides inside a retry loop. A retry should check the same deadline. Retrying a request with 20 ms left only adds load. The retry chapter covers retry policy in detail.
- Expired responses still count. A request that expires at dequeue should be counted as shed work in your metrics, and the client should receive an error such as a 503 or 504 where the connection is still open. Silent drops make debugging harder.
Summary of the practice
- Give every request a deadline when it enters the system, using a default if the client sends none.
- Store it as a local monotonic time and pass the remaining duration downstream, minus a margin.
- Check it at admission, at dequeue, and before each costly step.
- Cancel in-progress work when it expires, and count each expiry in your metrics.
Exercise
A service has one worker, a queue holding 30 requests, and each request takes 100 ms to process. Every request has a 1-second deadline and all 30 arrive at the same instant. (a) Roughly how many are served in time if the worker checks the deadline at dequeue? (b) What happens if it does not check, and what is the total busy time?
Show answer
(a) The worker can start a new request every 100 ms, so about 10 requests finish within the 1-second deadline. The other 20 are found expired at dequeue and dropped in almost no time, so the queue is empty after about 1 second. (b) Without the check, the worker processes all 30 requests and is busy for 3 seconds. Only the first 10 responses reach a waiting client, so goodput is the same 10 requests, but the worker wasted 2 seconds on 20 useless responses. During that time any newly arriving request waits behind them and is likely to expire as well.