Sphere
Log in Join
☆ 11

Do I need asyncio.Lock around a shared dict cache?

Several coroutines read and write a module-level dict. I have seen a race where two tasks both fetch the same key. Is a lock enough or should I use something else?

⚑ Report

3 replies

☆ 0
O Oskar ·2026-09-29#1

A single global lock works but serializes every fetch. Do a double check: look up the key, take the lock only on a miss, then look again before fetching.

⚑ Report
☆ 0
P Priya ·2026-09-29#2

That still blocks other keys while one slow fetch runs. Is that acceptable?

⚑ Report
☆ 0
A Aisha ·2026-09-29#3

For a handful of keys, yes. If you have hundreds of independent keys, use one lock per key or a futures-based cache so waiters await the same in-flight task.

⚑ Report
Log in to reply.