CODING CHALLENGE · N°58

Idempotency Key Handler

Easy FDEIntegrationsReliability

Networks retry. A customer’s webhook fires twice; a payment request is re-sent after a timeout. Without idempotency you double-charge or double-write. The fix: dedupe by a client-supplied key and always return the first result. Solve it in Python or TypeScript, with hidden tests.

The problem

Implement process(requests). Each request is [key, value]. The first time you see a key, record its value as the result. Any later request with the same key must return that first recorded result — the new value is ignored (the operation already happened). Return the list of results, one per request, in order.

EXAMPLE 1
Input requests = [["k1","a"],["k1","b"],["k2","c"],["k1","d"]]
Output ["a", "a", "c", "a"]
every k1 returns the first value "a"; the retries are no-ops
CONSTRAINTS
  • The result for a key is fixed by its first occurrence; later values for that key are discarded.
  • Return one result per request, preserving order.
  • This is exactly how an idempotency-key store makes a retried POST safe.
SOLVE IT YOURSELF

Your turn — write it

Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.

YOUR TASK

Implement process(requests): keep a map of key → first result. For each request, if the key is new, store its value; then append the stored result for that key.

HINTS — 3 IDEAS
  1. Use a dict/Map from key to the first value seen.
  2. On each request: if the key isn’t stored yet, store the value.
  3. Always append the stored value for the key (which is the first one) to the output.
CPython · WebAssembly
Approach, complexity & discussion — open after you solve

The approach

On a request carrying an idempotency key, look it up. If the key has been seen, return the stored response without re-executing. If it is new, execute the operation, store key → response, and return. Guard concurrent duplicates (an atomic insert or a lock on the key) so two in-flight copies of the same request cannot both execute.

Complexity

Time O(1) for the lookup and store.

Common mistakes

  • Storing the response only after executing, with no atomicity — a concurrent retry then double-executes.
  • No expiry on stored keys, so the store grows without bound.
  • Keying on the wrong thing (the whole payload, or a value that changes between retries).

Where this shows up

Idempotency keys are what make payment and order APIs safe to retry: the network will make a client resend after a timeout, and this handler guarantees “charge once” even when the request arrives twice. Stripe-style idempotency keys are the reference implementation of this pattern.

Finished this one? 0 / 75 Challenges done

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Challenges