KatInterview

Thread-Safe Idempotency Key Processor

Data Structure DesignModel answer
HardModel answerData Structure Designconcurrencycachingdesign

Last 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

  1. execute(key: str, task: Callable[[], Any]) -> Any:
    • If key has not been seen (or has expired), execute task() and store its result.
    • If key is currently being executed by another thread, subsequent callers must block until execution finishes and return the stored result.
    • If key was already completed within its valid lifetime, return the cached result without executing task() again.
  2. Concurrency: The class must be fully thread-safe. Multiple threads invoking execute with the same key simultaneously must guarantee that task() runs at most once.
  3. 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.
  4. 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.