Thread-Safe Idempotency Key Processor
Data Structure DesignModel answerLast updated
Design a thread-safe idempotency manager that executes tasks at most once per key, blocks concurrent callers, caches results with TTL, and cleans up expired records efficiently.
In high-throughput transactional services (such as payment processing), clients include a unique idempotency key with mutating requests. If a request is retried—due to network timeouts or concurrent client attempts—the service must process the action exactly once and return the identical result to all duplicate callers.
Design and implement a thread-safe class IdempotencyManager that acts as an in-memory execution guard and result store.
Requirements
execute(key: str, task: Callable[[], Any]) -> Any:- If
keyhas not been seen (or has expired), executetask()and store its result. - If
keyis currently being executed by another thread, subsequent callers must block until execution finishes and return the stored result. - If
keywas already completed within its valid lifetime, return the cached result without executingtask()again.
- If
- Concurrency: The class must be fully thread-safe. Multiple threads invoking
executewith the same key simultaneously must guarantee thattask()runs at most once. - Expiration (TTL): Results expire after a configurable duration (
ttl_seconds). Expired entries must be treated as unseen. Memory overhead for expired keys must be reclaimed efficiently. - Exception Handling: If
task()raises an exception, the failure must be broadcast to all currently waiting threads for that key, but the key itself must be removed so subsequent calls can retry the execution.
Interface
class IdempotencyManager:
def __init__(self, ttl_seconds: int):
"""Initialize the manager with a uniform key expiration period."""
pass
def execute(self, key: str, task: Callable[[], Any]) -> Any:
"""Execute task at most once per key per TTL window."""
pass
Example Usage
import time
manager = IdempotencyManager(ttl_seconds=300)
def charge_account():
time.sleep(1) # simulate work
return {"status": "SUCCESS", "tx_id": 9876}
# First call executes the callable
res1 = manager.execute("key_abc", charge_account)
# Second call returns cached result immediately without executing charge_account
res2 = manager.execute("key_abc", charge_account)
assert res1 == res2
Hints
Hint 1
Do not hold a global lock while calling `task()`. Doing so serializes calls across totally distinct idempotency keys.
Hint 2
Use a two-tier synchronization mechanism: a fast global lock for dictionary state transitions and per-key primitives (like `threading.Event`) to synchronize concurrent callers on the same key.
Hint 3
Because every entry shares the exact same TTL, tasks complete in chronological order of their expiration. Consider a FIFO queue for O(1) lazy eviction.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
To build an efficient, thread-safe idempotency engine, we must separate dictionary updates (bookkeeping) from task execution (business logic). Holding a single global lock during the execution of task() would cause massive bottlenecking by serializing requests across completely different keys.
Instead, we use a two-tiered synchronization model:
- Global Registry Guard (
threading.Lock): Held exclusively for short $O(1)$ state checks and modifications (inserting placeholder entries, setting results, and evicting expired keys). - Per-Entry Signal (
threading.Event): Each active entry contains a one-shotEvent. The first thread to request an unseen key claims leadership, inserts an incomplete_Entryobject into the registry, and releases the global lock before runningtask(). Concurrent callers for the exact same key discover the existing entry under the global lock, immediately release the lock, and wait onentry.done.wait().
Key Lifecycle State Machine
- Unseen / Expired: A thread creates a new
_Entry, marks itself as the execution owner, places the entry intoself._entries, and unlocks the global mutex. - In-Flight (Pending): Other threads seeing this key wait on
entry.done. - Completed: The owner computes the result, stores it in the entry alongside an expiration timestamp (
now + ttl), appends(expires_at, key, entry)to an eviction queue, callsentry.done.set(), and unlocks. - Failed: If
task()throws an exception, the owner stores the exception object inentry.error, deletes the key fromself._entriesso future calls can retry, callsentry.done.set(), and re-raises the exception.
Amortized $O(1)$ Cleanup
Since the TTL duration is fixed for every key, entries complete in chronological order of their expiration. We can maintain a FIFO collections.deque containing (expires_at, key, entry) tuples. Lazy cleanup checks the front of the deque: if the top entry's expires_at is $\le \text{current_time}$, it is popped and removed from self._entries.
Python 3 Implementation
import threading
import time
from collections import deque
from typing import Any, Callable, Deque, Dict, Optional, Tuple
class _Entry:
__slots__ = ("done", "result", "error", "expires_at")
def __init__(self) -> None:
self.done = threading.Event()
self.result: Any = None
self.error: Optional[BaseException] = None
self.expires_at: Optional[float] = None
class IdempotencyManager:
def __init__(self, ttl_seconds: int, clock: Callable[[], float] = time.monotonic) -> None:
if ttl_seconds <= 0:
raise ValueError("ttl_seconds must be strictly positive")
self._ttl = ttl_seconds
self._clock = clock
self._lock = threading.Lock()
self._entries: Dict[str, _Entry] = {}
# Stores (expires_at, key, entry_instance) in order of completion
self._expiry_queue: Deque[Tuple[float, str, _Entry]] = deque()
def _evict_expired(self, now: float) -> None:
"""Removes expired entries from the dictionary and queue.
Caller MUST hold self._lock.
"""
while self._expiry_queue and self._expiry_queue[0][0] <= now:
exp_time, key, entry = self._expiry_queue.popleft()
# Verify the entry in dict matches this exact object instance
if self._entries.get(key) is entry:
del self._entries[key]
def cleanup(self) -> None:
"""Public eviction interface for periodic background tasks."""
with self._lock:
self._evict_expired(self._clock())
def execute(self, key: str, task: Callable[[], Any]) -> Any:
now = self._clock()
with self._lock:
self._evict_expired(now)
entry = self._entries.get(key)
is_leader = entry is None
if is_leader:
entry = _Entry()
self._entries[key] = entry
# Follower threads wait on the leader's completion signal
if not is_leader:
entry.done.wait()
if entry.error is not None:
raise entry.error
return entry.result
# Leader thread performs the actual execution outside the global lock
try:
res = task()
except BaseException as exc:
with self._lock:
entry.error = exc
# Remove entry so future requests can retry execution
if self._entries.get(key) is entry:
del self._entries[key]
entry.done.set()
raise exc
# Success path
completion_time = self._clock()
with self._lock:
entry.result = res
entry.expires_at = completion_time + self._ttl
self._expiry_queue.append((entry.expires_at, key, entry))
entry.done.set()
return res
Complexity Analysis
- Time Complexity:
- Overhead: Amortized $O(1)$ time per call. Inserting, looking up keys, and popping from
dequetake $O(1)$ operations under lock. - Execution: Overall duration equals the time taken by
task()for the leader thread, while follower threads block for that same duration.
- Overhead: Amortized $O(1)$ time per call. Inserting, looking up keys, and popping from
- Space Complexity: $O(K)$, where $K$ is the number of active in-flight keys plus completed keys within the active TTL window. The FIFO queue holds at most one element per completed key.
Common Pitfalls & Edge Cases
- Holding Locks Across Network/IO Boundaries: Executing
task()insidewith self._lock:guarantees safety but destroys concurrency, turning your multithreaded application into a single-threaded bottleneck. - Clock Drift: Using
time.time()(wall-clock time) can lead to subtle bugs if NTP server updates adjust system time backward. Usingtime.monotonic()ensures strictly increasing timestamps. - Ghost Entries on Failure: If a task fails with an exception, caching the failure permanently prevents transient error recovery. Removing the key from
self._entrieswhile settingentry.errorallows waiters to receive the exception while giving future requests a clean slate to retry. - Re-created Key Invalidation: If a key expires and is later recreated, an old record for that key might still exist in
_expiry_queue. Checkingself._entries.get(key) is entryby object identity ensures we never accidentally delete a newly created entry for the same key string.