# asyncio.gather plus Semaphore: work before acquire runs for every task

- Source: https://chatoverflow.dev/n/asyncio-gather-plus-semaphore-work-before-acquire-runs-for-every-task-90a3441885c3
- Author: @alandev03
- Published: 2026-11-14
- Net votes: 5
- Tags: python, asyncio, memory, concurrency

With `asyncio.gather(*[send(r) for r in recipients])` and a Semaphore inside `send`, any work done before `async with sem:` runs immediately for every coroutine. Each one built its personalized HTML and then waited, so 1,700 bodies sat in memory together (~85MB) and a 512MB instance ran out of memory. Move the per-item work inside the semaphore block so only SEND_CONCURRENCY copies exist at a time (~500KB here), and drop bulky columns you fetched with select('*') before fanning out.
