Sphere
Log in Join
☆ 3

asyncio.wait_for cancels my task but the cleanup hangs for 8 seconds

Python 3.12. I use await asyncio.wait_for(do_stuff(), timeout=5). When it times out I get the TimeoutError as expected, but my finally block in do_stuff has an await cleanup() that itself takes about 8 seconds, and wait_for doesn't return until that finishes. So my 5 second timeout actually takes 13 seconds. Is there a way to give up without waiting for cleanup? I don't think I want to shield it but I'm not sure.

⚑ Report

4 replies

☆ 0
Y yaml ·2026-10-07#1

That's wait_for's documented behavior — it waits for cancellation to complete before it raises. If cleanup can't be cancelled because it's shielded or blocking, you wait along with it. What's actually inside cleanup()? If it's a synchronous blocking call, that's a completely different problem and no amount of asyncio configuration will help you.

⚑ Report
☆ 0
G glitch ·2026-10-14#2

cleanup() closes an aiohttp ClientSession and does a final POST to a logging endpoint. The POST is the slow part, it's sitting there waiting on the network. Closing the session is instant. So the timeout is being eaten almost entirely by that one log call.

⚑ Report
☆ 0
G ghost29 ·2026-10-14#3

Then give the POST its own short timeout inside cleanup, or fire-and-forget it with asyncio.create_task. You're in a cancelled context at that point, so awaiting network I/O in a cancellation handler is asking for trouble. Wrap the part you must keep in asyncio.shield() with a small timeout of its own, and accept that it might get dropped.

⚑ Report
☆ 0
G ghost ·2026-10-23#4

We hit this exact thing in a scraper. Our solution: in the finally, do the session close, then t = asyncio.create_task(log_flush()) with a done callback that swallows exceptions, and don't await it. Ugly but the timeout is now real. If the log must survive process exit you need a different mechanism — a queue consumed by a separate worker, for example.

⚑ Report
Log in to reply.