Idempotency Key Processor

Guarantee that retried network calls (client timeouts, proxy retries, double-clicks) never produce duplicate side effects, such as charging a card twice.

Clients that time out waiting for a response often retry the exact same request. Without protection, a payment API might charge the customer twice for one intent. Idempotency keys let the server recognize "I've seen this exact operation before" and return the original result instead of repeating it — while also protecting against key reuse with a different payload, which usually indicates a client bug or an attacker replaying a stolen key with new data.

Implement an IdempotencyProcessor with:

  • begin(key: string, payload: string): string
    • If the key has never been seen: create a record with status IN_PROGRESS, remember a hash of the payload, and return "<key>: START".
    • If the key exists and the stored payload hash does not match the hash of the new payload: return "<key>: 422 PAYLOAD_MISMATCH" (this is a 422, meaningfully different from an auth or lock failure).
    • If the key exists, the payload matches, and the record is still IN_PROGRESS (the original request hasn't finished): return "<key>: 409 IN_PROGRESS" — this is the in-flight lock that prevents two concurrent workers from double-processing the same key.
    • If the key exists, the payload matches, and the record is DONE: return the cached response: "<key>: 200 CACHED <response>".
  • complete(key: string, response: string): string
    • Marks the record DONE, stores the response, and returns "<key>: 201 DONE <response>".
    • If complete is called for a key with no prior begin, return "<key>: 500 NO_RECORD".

Input arrives as ##-separated commands: BEGIN:<key>,<payload> and COMPLETE:<key>,<response>.

Input:  BEGIN:k1,payloadA##COMPLETE:k1,resultA##BEGIN:k1,payloadA##BEGIN:k1,payloadB
Output: k1: START
        k1: 201 DONE resultA
        k1: 200 CACHED resultA
        k1: 422 PAYLOAD_MISMATCH

Constraints

  • Payload comparison must be based on a hash of the payload content, not identity/reference.
  • A key that is still IN_PROGRESS must never return a cached response — only DONE records may be replayed.
  • Keys are independent: state for one key must never leak into another.
Ad SpaceGoogle AdSense active for guests & free-tier learners.