ホーム 車・バイク For Intermediate Python Developers | Designing Cancellation with asyncio.timeout and shield

For Intermediate Python Developers | Designing Cancellation with asyncio.timeout and shield

篠原 沙世 篠原 沙世 • 更新: • 公開: • 読了約 15 分
目次

Introduction

nc95b6269f251

Asynchronous timeout handling is not just about measuring time. The core of the design lies in how to cancel tasks that exceed their deadline and how to ensure proper cleanup. We will organize this using asyncio.timeout() and asyncio.shield() available in Python 3.11 and later.

Basics of timeout

import asyncio

async def request() -> str:
    await asyncio.sleep(2)
    return "ok"

async def main() -> None:
    try:
        async with asyncio.timeout(0.1):
            print(await request())
    except TimeoutError:
        print("期限切れ")

asyncio.run(main())

This shield example detects a timeout at 0.05 seconds, but because it awaits the task afterward, main() finishes after about 0.2 seconds. This design prioritizes consistency by waiting for completion, rather than returning to the caller at 0.05 seconds.

When the deadline is exceeded, the current task within the context is cancelled, and an embedded TimeoutError is raised externally. If you swallow the CancelledError internally, the timeout will not function correctly.

Scope protected by shield

Protect only processes that must complete even if the caller is cancelled, such as audit logs after a payment.

import asyncio

async def write_audit() -> None:
    await asyncio.sleep(0.2)
    print("audit saved")

async def main() -> None:
    task = asyncio.create_task(write_audit())
    try:
        async with asyncio.timeout(0.05):
            await asyncio.shield(task)
    except TimeoutError:
        print("caller timed out")
        await task

asyncio.run(main())

shield is not a feature that automatically continues to manage internal tasks. You must maintain a reference to the task and collect its completion or exceptions.

Common mistakes

Shielding everything

If you protect everything, stop requests will not take effect, leading to delayed shutdowns. Limit protection to short, consistency-critical operations.

Thinking that CancelledError can be handled with except Exception

The current CancelledError inherits from BaseException. Place necessary cleanup in finally blocks and, as a rule, allow cancellation to be re-raised.

Leaving tasks abandoned after a timeout

For tasks you create explicitly, keep a reference and await them to collect results or exceptions.

Operational boundaries and adoption decisions

The examples assume Python 3.11 or later. Since timeout converts to TimeoutError when exiting the context, place your catch blocks outside. If cancelled externally, it is generally a CancelledError. Use timeout for entire HTTP requests and limited shield for short audit records. Test for normal completion, expiration, external cancellation, and failure of the protected object itself.

Failure examples and corrected versions

A bad example is except asyncio.CancelledError: return. This causes the timeout to be treated as a success, and the stop request is not propagated. The corrected version places cleanup in finally and propagates the cancellation.

async def worker():
    try: await asyncio.sleep(10)
    finally: print("resource closed")

Another example is using shield(create_task(...)) while discarding the reference. This prevents you from collecting internal exceptions. The corrected version keeps the task variable and awaits it. If immediate response is required, add it to a tracking set and record exceptions via a done callback. In tests, use an Event to verify the sequence of start, cancellation, finally, and completion of the protected object.

Supplementary Verification

We also confirm that there are zero incomplete tasks at the end of the test to prevent resource leaks.

We will also include the wait limit for termination processing and the method for recording remaining tasks in the operational procedures.

This allows us to track the causes of abnormal terminations.

In production monitoring, do not aggregate timeouts; record them separately by stage: connection, waiting for response, and post-processing. Limit retries to idempotent operations only and add random wait times. Since retrying a shielded update can lead to duplicate registrations, design for deduplication using operation IDs.

Step-by-Step Verification

First, use a small function with only sleep to verify completion within the deadline and expiration separately. Next, set a flag in finally to assert that resources are released even during cancellation. Finally, swap the shielded target with successful and failed versions to ensure that exceptions are always caught.

A bad design is to shield an entire DB transaction or an infinite loop. The termination signal will not reach it, and the process will not stop during deployment. The corrected version protects only short, atomic operations, such as committing a single update or saving a single audit row, and sets a deadline inside that as well.

async def protected_audit():
    async with asyncio.timeout(1.0):
        await write_audit()

Do not guess timeout values; determine them from latency distributions during normal and peak times. In monitoring, count expired counts, external cancellation counts, and protected task failure counts separately. If you group them all under the same TimeoutError, you cannot distinguish between delays and explicit stops.

When the application terminates, wait for the tasks in the tracking set for a certain period, cancel the rest, and collect them using gather(..., return_exceptions=True). This prevents the warning 'Task was destroyed but it is pending'.

Summary

timeout is for processing deadlines, and shield is for limited cancellation protection. By deciding the responsibilities for deadlines, cancellation propagation, and cleanup separately, you can avoid asynchronous programs that cannot be stopped.

同じカテゴリの記事

篠原 沙世

アニメとゲームの新作情報を担当。制作会社・配信元の公式告知と登壇情報を照合して記事化します。

おすすめの関連記事