DevPath
Mid lesson · 12 min

Let async service work stop cleanly

Propagate cancellation and release resources on every exit path.

Give the request a budget

An async operation should not continue indefinitely after its caller leaves. Apply an overall deadline to the service request and smaller limits to individual dependencies where useful. A timed-out call must return a meaningful failure; silently returning partial data as complete is misleading.

Do not swallow cancellation

Cancellation can arrive during an await. Let it propagate after cleanup rather than converting it into a generic success or retry. Use finally for resources and avoid broad exception handlers that hide the cancellation signal. A semaphore permit acquired with an async context manager is released when the block exits.

async with limit:
    try:
        return await fetch(item)
    finally:
        record_completion(item)

Test unfinished work

Start a task with a dependency that waits, cancel it, and assert that no later side effect occurs. Verify that another task can acquire the semaphore afterward. Test a timeout at the whole-request level as well as a single slow item. Avoid tests that depend on long real sleeps.

Check your understanding

What should an async worker do when its caller cancels it?

Show explanation

Clean up resources and propagate cancellation, rather than silently treating unfinished work as success.

Put this lesson into practice

A practice activity at this level in the same module.

Try: Add exponential backoff with jitter

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.