# Why Your Python Cache Does the Same Work Twice (P.S: GIL Won't Save You)

DevFeed: [Why Your Python Cache Does the Same Work Twice (P.S: GIL Won't Save You)](<https://devfeed.tech/articles/why-your-python-cache-does-the-same-work-twice-p-s-gil-won-t-save-you-110843.md>)

Original publisher: [Read original article](<https://hackernoon.com/why-your-python-cache-does-the-same-work-twice-ps-gil-wont-save-you?source=rss>)

Author: Sohel Alam

Published: 2026-11-01T15:18:56Z

Content type: tutorial

Language: en

Sources: [HackerNoon](<https://devfeed.tech/sources/hackernoon.md>)

Topics: [Python](<https://devfeed.tech/topics/python.md>), [Cache](<https://devfeed.tech/topics/cache.md>), [scheduling](<https://devfeed.tech/topics/scheduling.md>), [cache-invalidation](<https://devfeed.tech/topics/cache-invalidation.md>)

Tags: [cache](<https://devfeed.tech/tags/cache.md>), [gil](<https://devfeed.tech/tags/gil.md>), [gotcha](<https://devfeed.tech/tags/gotcha.md>), [hackernoon-top-story](<https://devfeed.tech/tags/hackernoon-top-story.md>), [locks](<https://devfeed.tech/tags/locks.md>), [lru](<https://devfeed.tech/tags/lru.md>), [python](<https://devfeed.tech/tags/python.md>), [python-concurrency](<https://devfeed.tech/tags/python-concurrency.md>), [python-gil](<https://devfeed.tech/tags/python-gil.md>), [python-programming](<https://devfeed.tech/tags/python-programming.md>), [python-threading](<https://devfeed.tech/tags/python-threading.md>), [race-conditions](<https://devfeed.tech/tags/race-conditions.md>), [thread-safety](<https://devfeed.tech/tags/thread-safety.md>)

## AI overview

A cache can return correct values yet run expensive work repeatedly because its check-then-act sequence is not atomic, even on standard CPython with the GIL. A single lock around both steps prevents duplicate computations but makes threads wait even when they request different keys. Per-key locks let different keys proceed independently; recheck the cache after acquiring the key lock. The example's fast path assumes entries are not removed or replaced, its lock map grows with the key set, and thread locks coordinate only within one process. `functools.lru_cache` keeps its internal state consistent but may call the wrapped function more than once during concurrent misses; `cached_property` can also run its getter repeatedly. For side effects, the article recommends idempotency keys and persistent deduplication because in-process locking does not guarantee exactly-once execution. The author tested on CPython 3.12.3 and says they did not test the examples on a free-threaded build.

## Source excerpt

Your Python cache can run the same work twice, even with the GIL. See the check-then-act race, the lru_cache gotcha, and how locks fix it.