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
IN_PROGRESS, remember a hash of the payload, and return "<key>: START".payload: return "<key>: 422 PAYLOAD_MISMATCH" (this is a 422, meaningfully different from an auth or lock failure).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.DONE: return the cached response: "<key>: 200 CACHED <response>".complete(key: string, response: string): string
DONE, stores the response, and returns "<key>: 201 DONE <response>".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
IN_PROGRESS must never return a cached response — only DONE records may be replayed.