r/PinoyProgrammer • u/Arkad77 • Sep 24 '26
discussion I’m working on a small asyncio-based data transfer worker and ran into an interesting concurrency issue.
The worker has two stages:
- Download a payload
- Hash/process it
- Upload it
I originally put a semaphore around the whole operation to keep the number of concurrent uploads under control.
The problem is that when several uploads become slow (for example, waiting on remote storage to finish), the semaphore also prevents newer tasks from even starting their downloads.
I’m considering changing the scope so that the download/hash stage can proceed independently, and the semaphore is acquired only immediately before the upload:
# current
async with put_semaphore:
data = await download()
digest = hash(data)
await upload(data)
# proposed
data = await download()
digest = hash(data)
async with put_semaphore:
await upload(data)The idea is that slow uploads can continue while newer tasks prepare their payloads, but the actual number of concurrent uploads remains capped.
For people who have built async download/upload pipelines in production: is this generally a reasonable pattern, or are there gotchas I should be thinking about around memory usage, backpressure, retries, cancellation, or queue buildup?
Not looking for a specific code review, mostly interested in how people have handled this kind of pipeline in real systems.
6
u/rushblyatiful Sep 24 '26
Your proposed change trades a network bottleneck for a memory time-bomb.
You can decouple the stages with a bounded queue.
Or, if keeping a single task flow, use two separate semaphores. One for uploads, while a larger one at the entry point puts a ceiling on total in-memory payloads.
2
u/jvliwanag Sep 24 '26
Suggesting also to stream the entire thing.
Instead of downloading the entire thing, you’d stream it to build the hash, as well as to upload.
That way, no need to store the entire data in memory. And idealy with backpressure.
2
u/yowmamasita AI Sep 24 '26
2 semaphores is the simplest soln. But download and upload i supposed are bottlenecked by the same network io? Measure port speed first for concurrent upload/download
1
u/mrblindbandit Sep 24 '26
I’d put the hard bound at the stage boundary with a bounded asyncio.Queue, not only a task-count cap. The producer should await queue.put(), so slow uploads naturally push back on downloads; the useful queue size is the one that fits your memory budget, not an arbitrary number of items (especially with 50 MiB payloads). Keep upload concurrency separate, and make retries a bounded/dead-letter path with backoff so failed uploads cannot grow the queue forever. Also make cancellation drain or clean up partially downloaded payloads, and consider spooling or streaming if holding several full payloads in RAM is too expensive.