Async Request Deduplicator
Description
When a popular key expires, hundreds of requests for it arrive at once and each one hits the backend. Build a deduplicator (often called "single flight") so that concurrent requests for the same key share one backend call.
class AsyncRequestDeduplicator:
def __init__(self): ...
async def get(self, key, fetch_fn, timeout: float | None = None) -> object: ...fetch_fn(key) returns a coroutine that does the real backend call.
Rules
- If no fetch for
keyis in flight, startfetch_fn(key)and await it. If one is already in flight, await that one instead. Concurrent callers for the same key cause exactly onefetch_fncall. - Different keys are independent and fetch concurrently.
- No caching. Once a fetch finishes, successfully or not, the next
getfor that key starts a new fetch. - If the shared fetch raises, every caller waiting on it gets that exception.
timeoutapplies to one caller only and starts when that caller callsget. On timeout that caller getsTimeoutError. The shared fetch keeps running for everyone else.- Cancelling a caller only cancels that caller. The shared fetch keeps running, even if every caller has timed out or been cancelled, and a later
getfor the same key joins it while it is still in flight. getraisesValueErrorwhentimeoutis given and<= 0, without starting a fetch.
Example
d = AsyncRequestDeduplicator()
calls = 0
async def fetch(key):
global calls
calls += 1
await asyncio.sleep(0.05)
return key.upper()
await asyncio.gather(
d.get("a", fetch, timeout=0.01), # TimeoutError
d.get("a", fetch), # "A"
d.get("a", fetch), # "A"
return_exceptions=True,
)
calls # 1
await d.get("a", fetch) # "A", and calls is now 2Constraints
- Keys are hashable.
- Memory must not grow with keys that have no fetch in flight. That includes a fetch that finishes after all its callers timed out or were cancelled, when no caller is left to clean it up.
Solution
Reference solution and explanationTry it first. The explanation covers the approach, complexity, pitfalls and follow-ups.Reveal solution
Approach
Keep a map from key to the Task running that key's fetch. get reuses the task if one is in flight, otherwise it creates one. Every caller then awaits asyncio.wait_for(asyncio.shield(task), timeout).
The fetch runs in its own task, not in the first caller's coroutine. That is what lets it outlive any caller. shield gives each caller a private wrapper future, so a timeout or a cancellation cancels the wrapper and leaves the shared task alone. wait_for starts its clock when this caller calls it, which is exactly "timeout from when the caller joins".
A done callback removes the key when the task finishes, so there is no caching and no growth. Two details make that safe. The callback checks the map still points at this task before deleting. And get treats a finished task still in the map as absent, because the callback runs one loop step after the task completes. The callback also calls task.exception(), so a failure that nobody was waiting for doesn't get logged as "exception was never retrieved".
Complexity
O(1) per get. Memory is O(k) for k keys with a fetch in flight.
Pitfalls
- Running the fetch inline in the first caller (
await fetch_fn(key)and stashing a future for others). If that caller times out or is cancelled, the fetch dies for everyone. - Awaiting the task without
shield.wait_forcancels what it waits on, so one impatient caller cancels the shared fetch. - Removing the key inside the caller's code path instead of when the task finishes. If every caller times out, the key is never cleaned up, or it is cleaned up while the fetch is still running and a second fetch starts.
- Cleaning up with
self._inflight.pop(key)without checking the entry is still this task. A newer fetch for the same key may have replaced it, and the stale cleanup drops it, so the next caller starts a duplicate. Delete only ifself._inflight.get(key) is task. - Checking
timeout <= 0after creating the task. - Keeping finished results in the map. That turns the deduplicator into a cache that never expires.
Follow-ups interviewers ask
- Add a short TTL cache on top, so a burst just after completion also collapses. Store
(result, expires_at)next to the in-flight map. - Should a fetch be cancelled once every caller has gone? Track a waiter count and cancel the task when it hits zero, if the backend call is expensive and nobody wants the answer.
- Make it work across processes. A distributed lock or a lease in Redis gives single flight per key across a fleet.
- How do you stop one slow key from piling up callers forever? Give the fetch itself an upper bound, separate from caller timeouts.
Reference solution
import asyncio
class AsyncRequestDeduplicator:
def __init__(self):
self._inflight = {} # key -> Task running fetch_fn(key)
async def get(self, key, fetch_fn, timeout: float | None = None):
if timeout is not None and timeout <= 0:
raise ValueError("timeout must be > 0")
task = self._inflight.get(key)
# A done task can still be in the map until its callback runs; never hand out a stale result.
if task is None or task.done():
task = asyncio.create_task(fetch_fn(key))
self._inflight[key] = task
task.add_done_callback(lambda t: self._forget(key, t))
# shield: a caller's timeout or cancellation cancels only its own wait, not the shared task.
return await asyncio.wait_for(asyncio.shield(task), timeout)
def _forget(self, key, task):
if self._inflight.get(key) is task:
del self._inflight[key]
if not task.cancelled():
task.exception() # mark retrieved so a failure nobody awaited is not logged as lostNotes
import asyncio
class AsyncRequestDeduplicator:
def __init__(self):
pass
async def get(self, key, fetch_fn, timeout: float | None = None):
"""
Join the in-flight fetch for key, or start fetch_fn(key) if none is running.
timeout is per caller, starts when this caller arrives, and never cancels the shared fetch.
Raise ValueError if timeout is given and <= 0.
"""
raise NotImplementedErrorRun checks the 2 example tests. Submit runs all 15 and marks the problem solved when they pass.