Budget time across dependent services
Set a deadline for the whole operation and allocate it intentionally.
Start from user latency
If a request must respond in four seconds, three downstream calls each with a four-second timeout do not fit the budget when called sequentially. Reserve time for validation, retries, rendering, and a graceful error. Measure actual latency distributions rather than choosing identical default timeouts everywhere.
Propagate the remaining deadline
Pass cancellation through each async layer. A child operation should see how much time remains and avoid starting a call that cannot finish usefully. Retry loops must consume the same total budget; resetting a full timeout on every attempt can multiply user wait time.
remaining = deadline - loop.time()
if remaining <= 0:
raise TimeoutError('request budget exhausted')
result = await asyncio.wait_for(call(), timeout=remaining)
Plan partial failure
Choose whether a missing recommendation can be omitted while the main account result succeeds, or whether the entire response must fail. Label partial data honestly. Test a slow dependency, cancellation, and a late response after the request has ended. Monitor budget exhaustion separately from permanent validation errors.
Check your understanding
Why must retries share one overall deadline?
Show explanation
Giving every attempt a fresh full timeout can make total latency far exceed the user's request budget.
You can read for free. Create an account to save your progress.
← Previous lesson: Backfill data without overwhelming productionTry it at senior level
Allocate a 900 ms deadline across three dependent calls, one optional. Show what happens when the first call uses 500 ms.
Check your work
The total stays within 900 ms, later calls receive the remaining budget, and the optional result can fail without falsifying core success.
Self-guided practice. This does not record assessed mastery.
Put this lesson into practice
A related activity in this module at mid level.
Try: Add exponential backoff with jitterFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.