Python async cache: choose who owns cancellation
Share unfinished lookups without handing their lifetime to whichever request arrived first.
Quick answer
Python's ordinary `lru_cache` stores the object returned by a function call. An `async def` call returns a coroutine object, so decorating it directly can preserve a coroutine that has already been consumed. Sharing a Task fixes that object mismatch, but you must also decide who may cancel the shared operation and when its owner shuts down.
On this page
Python's ordinary lru_cache stores the object returned by a function call. An async def call returns a coroutine object, so decorating it directly can preserve a coroutine that has already been consumed. Sharing a Task fixes that object mismatch, but you must also decide who may cancel the shared operation and when its owner shuts down. [1][3][6]
Why does the second await fail?#
The cached object is the coroutine, rather than its eventual result. The distinction matters even when every call runs on the same event loop and the arguments are identical. Cache thread safety cannot turn a consumed coroutine into a reusable result. Python explicitly rejects awaiting the same coroutine object again. [1][6]
Scenario: a fictional service looks up a tenant's immutable pricing revision before calculating an estimate. Concurrent requests for the same tenant and revision should share the lookup. A request that disconnects should stop waiting, while another request still needs the answer. The example is about read-only lookup ownership, not deduplicating a payment or another durable business action.
import asyncio
from functools import lru_cache
@lru_cache(maxsize=16)
async def revision(tenant, version):
return (tenant, version)
async def main():
print(await revision('acme', 'r7'))
print(await revision('acme', 'r7')) # Reuses the coroutine object.
asyncio.run(main())The first await runs the coroutine. The next call finds the same cached object; it does not create another invocation of the body. Removing the decorator is the smallest correct repair if repeat lookups are cheap. It is also a useful baseline: establish that the underlying operation works before introducing shared work. [1][6]
Before choosing a decorator, decide which work should be reused. You may want simultaneous callers to share an unfinished lookup, completed callers to reuse a value until expiry, or requests across multiple processes to consult a distributed cache. Write those requirements separately. Otherwise a fix for the coroutine exception can accidentally become an unbounded repository of Tasks and their exceptions.
What should a shared lookup own?#
For this service, the lookup component owns in-flight Tasks; individual HTTP requests own only their waits. A timed-out request may abandon its wait without deciding whether the service's shared work should continue. Python's shield supports that separation, but the caller still receives cancellation. It does not turn cancellation into a successful response. [2]
The proposed contract is deliberately narrow. A component instance belongs to a single running event loop. It retains a bounded set of in-flight lookups, accepts explicit keys, removes completed work, and rejects new calls after close begins. It never promises a TTL, cross-process reuse, background refresh or distributed exclusion. These are design choices for the example, not guarantees supplied by a cache decorator.
Use a key containing everything that changes the answer. In the pricing example, that means tenant identity, pricing revision and any permission scope that changes the returned data. A tenant stored only in request-local context is not visibly part of the key. Passing the same explicit arguments from different request contexts should never return information belonging to the wrong tenant.
Make the shared result immutable, or copy it at the boundary where callers receive it. If the result is a mutable dictionary and one caller edits it, another caller can observe that edit. Sharing a Task does not define ownership of the value it returns. A tuple of immutable revision fields is easier to reason about than a live database connection or response stream.
A service-scoped implementation#
This component coalesces unfinished lookups and forgets them when they finish. It therefore demonstrates the ownership layer an async cache needs, without pretending to implement completed-result retention. A request for an already-finished key may trigger another load once the completion callback removes the old Task. That behavior is intentional.
import asyncio
class SharedLookup:
"""One event loop; in-flight sharing only; no result cache."""
def __init__(self, load, limit=64):
self.load = load
self.limit = limit
self.tasks = {}
self.closed = False
async def get(self, key):
if self.closed:
raise RuntimeError('lookup is closed')
task = self.tasks.get(key)
if task is None:
if len(self.tasks) >= self.limit:
raise RuntimeError('lookup capacity reached')
task = asyncio.create_task(self.load(key))
self.tasks[key] = task
task.add_done_callback(lambda done: self._finished(key, done))
return await asyncio.shield(task)
def _finished(self, key, task):
if self.tasks.get(key) is task:
del self.tasks[key]
if not task.cancelled():
task.exception()
async def close(self):
self.closed = True
pending = tuple(self.tasks.values())
for task in pending:
task.cancel()
await asyncio.gather(*pending, return_exceptions=True)
self.tasks.clear()The lookup function must be an async function returning the agreed immutable value. Creating a Task schedules its coroutine, and the registry keeps a strong reference while it is running. The completion callback checks object identity before removing an entry, so a stale callback cannot erase a different Task that later occupies the same key. [2][3]
No await separates registry inspection from registration under the ordinary single-loop execution model. That is the scope in which this small component is intended to be used. Do not share the instance between event loops or threads. If your application configures a custom task factory or other execution hooks, include that configuration in its tests rather than assuming the default scheduling behavior.
The capacity limit applies to distinct registered keys, not to the number of callers waiting on each key. A busy tenant can still accumulate many HTTP requests. Keep request admission limits and upstream deadlines elsewhere in the service. Rejecting a new distinct lookup is clearer than silently evicting a Task that existing callers still await.
What happens when the first caller leaves?#
The request that arrives first does not acquire the right to cancel everyone’s lookup. Test that rule using an event-controlled loader, so the experiment cannot accidentally pass because the loader finished before cancellation arrived. Start callers with the same explicit key, wait for the loader to announce entry, then cancel only the first caller.
async def cancellation_case():
entered = asyncio.Event()
release = asyncio.Event()
calls = []
async def load(key):
calls.append(key)
entered.set()
await release.wait()
return ('revision', key)
lookup = SharedLookup(load)
first = asyncio.create_task(lookup.get(('acme', 'r7')))
await entered.wait()
second = asyncio.create_task(lookup.get(('acme', 'r7')))
await asyncio.sleep(0)
first.cancel()
try:
await first
except asyncio.CancelledError:
pass
release.set()
assert await second == ('revision', ('acme', 'r7'))
assert calls == [('acme', 'r7')]
await lookup.close()This experiment establishes a specific property: cancellation of a waiter does not cancel the service-owned lookup, and another waiter can receive its result. It does not establish that a database driver stops network activity on cancellation, that a remote server abandons its query, or that the service has a complete deadline policy. Those require tests at their respective boundaries.
Now cancel every waiter. Under this contract, the loader still continues until it finishes, its own deadline expires, or the service closes it. That consumes resources after the original demand disappears. The trade-off is defensible for a small, bounded read; it may be wrong for an expensive query with no remaining consumer. A reference-counted alternative needs explicit race tests around the last waiter leaving and a new waiter arriving.
Keep caller timeout budgets separate from the upstream lookup budget. A caller may have less time remaining than the loader is allowed. Conversely, a shared loader that never finishes can occupy capacity indefinitely. Place the actual I/O deadline inside load, using the driver's supported timeout semantics, and verify that its cleanup completes. Our thread timeout article explains why a timeout alone may not end underlying work.
How are failure and shutdown handled?#
A failed Task carries an exception, so retaining it as a cache entry can make every later caller receive the same failure. The example removes terminal Tasks instead of retaining failed answers. Observing the exception in the completion callback also handles the case in which all callers abandoned their waits before failure occurred. Existing waiters can still receive the same exception. [2][3]
Failure eviction does not itself provide sensible retry behavior. If an upstream service is unavailable, newly arriving requests can immediately start another lookup after each failure. Add an explicit backoff or circuit policy at the appropriate layer if that is part of the service contract. Do not disguise every failure as a valid empty pricing revision merely to obtain a cacheable value.
Close the lookup before closing the database pool or HTTP client used by its loader. The service first stops admitting new lookups, cancels registered Tasks, awaits their completion, and then closes those dependencies. If a loader suppresses cancellation and never returns, close can wait indefinitely. Require cooperative cleanup and test it; a shutdown deadline is an operational policy, not proof that arbitrary work has stopped. [2]
Do not create a fresh asyncio.run call for every cached lookup or keep the component in a process-global object that outlives successive loops. The runner manages an event loop and closes it after its work. A service-owned object should be constructed and closed inside the application's existing async lifecycle, rather than crossing that loop boundary. [4]
Test equal keys together, then change the tenant, cancel a waiter and let every waiter leave. Fail the loader, retry it, fill the registry and close it while a load is unfinished. Record the observed loader calls and completion events. A passing sequential example cannot establish the behavior of concurrent callers.
### Keep the loader independent of the first request
The explicit key is necessary, but inspect what the loader actually reads. If it fetches tenant identity, authorization or locale from the first request's ambient context, the registered Task can still depend on inputs that other callers never supplied. Make the loader a function of the approved key and service-owned dependencies. The async-lru project also warns that results depending on inputs outside the key can cross tenant boundaries. [5]
Scenario: both requests pass the same tenant and revision, but the first request carries a narrower permission scope in request-local state. A loader that consults that hidden state may return a restricted answer to everyone sharing the Task. Reversing arrival order could produce a broader answer. The right repair is to include the relevant scope in the contract, not to hope that a more complete cache key compensates for a loader that ignores it.
When reviewing the implementation, trace each loader input to its source. A database client owned by the service is different from a request-scoped session that closes when its request leaves. Keeping the Task alive after that request ends cannot keep an already-closed session usable. Our async generator cleanup guide follows the related problem of closing a dependent operation before its pool.
The local checks for this example cover cancellation, eviction, key separation and close behavior with event-controlled loaders. They do not use a real pricing database or authenticate requests. Before adoption, repeat the same event-order cases with the actual driver and lifecycle hooks. The demonstration establishes the small component's behavior; the integration must establish that its dependencies satisfy the same contract.
When should you use a maintained cache instead?#
Use a maintained async cache when you actually need completed-result caching, TTL expiry, targeted invalidation and eviction policy. The async-lru project exposes these features and an explicit close API. Its documented invalidation result also distinguishes removing an existing entry from finding nothing to remove. Pin and test the version you adopt. [5]
Replacing the small example with a package does not remove the ownership questions. Test its behavior when a waiter is cancelled, when all waiters disappear, when an entry expires during a load and when the service shuts down. Also test whether the chosen cache key includes every tenant and authorization input. Package defaults may serve a different workload from yours.
- Choose no caching when the underlying read is cheap and simplicity matters more than reuse.
- Choose in-flight sharing when simultaneous requests should share a read but later requests should load fresh data.
- Choose completed-result caching when the domain defines a tolerable freshness interval and invalidation policy.
- Choose a shared external cache when process-local reuse cannot meet the service's requirements; define its consistency and failure behavior separately.
What else should you check?#
- Does an async cache work across application workers?
- A process-local cache shares work only within its own process and lifecycle. Separate workers can still run the same lookup. If the requirement spans workers, design a shared cache or coordination layer explicitly, including its failure and consistency behavior.
- Should a not-found lookup be cached?
- Decide whether absence is a valid domain result or an operational failure. A valid absence may have a short freshness policy; a transient upstream failure should not silently become a permanent empty result. Test invalidation when the missing record is later created.
- Can the key include an authenticated user object?
- Prefer a stable, explicit identity and the permission inputs that determine the returned data. Avoid retaining a request object with unrelated state. Check that equivalent keys mean equivalent answers, and that different tenant or authorization scopes cannot share an answer accidentally.
- Where should the component be constructed?
- Create it inside the async service lifecycle that owns its loader dependencies. Close it before those dependencies. Do not retain Tasks across successive event loops or nest a fresh runner inside an already running async application. [4]