Idempotency Key Store For Duplicate Requests

An idempotency key store that replays the recorded response for duplicate keys and rejects reuse with a different payload.

PythonData Fetching

Code

py
60 lines
import hashlib
import time
from dataclasses import dataclass
from typing import Any, Dict, Optional


class IdempotencyConflictError(ValueError):
    """Raised when a key is reused with a different payload."""


@dataclass(frozen=True)
class Entry:
    payload_hash: str
    response: Any
    stored_at: float


def payload_fingerprint(payload: str) -> str:
    """Return a stable fingerprint for a request payload."""
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


class IdempotencyStore:
    """Replay recorded responses for duplicate keys; reject payload conflicts."""

    def __init__(self, ttl_s: float = 3600.0, clock: Any = time.monotonic) -> None:
        if ttl_s <= 0:
            raise ValueError("ttl_s must be positive")
        self._ttl_s = ttl_s
        self._clock = clock
        self._entries: Dict[str, Entry] = {}

    def execute(self, key: str, payload: str, produce: Any) -> Any:
        """Return the recorded response, or run produce and record it."""
        if not key:
            raise ValueError("idempotency key must be non-empty")
        fingerprint = payload_fingerprint(payload)
        existing = self._get_live(key)
        if existing is not None:
            if existing.payload_hash != fingerprint:
                raise IdempotencyConflictError(
                    f"key {key!r} was already used with a different payload"
                )
            return existing.response
        response = produce()
        self._entries[key] = Entry(
            payload_hash=fingerprint,
            response=response,
            stored_at=self._clock(),
        )
        return response

    def _get_live(self, key: str) -> Optional[Entry]:
        entry = self._entries.get(key)
        if entry is None:
            return None
        if self._clock() - entry.stored_at > self._ttl_s:
            del self._entries[key]
            return None
        return entry

A client retry after a timeout can execute a charge twice because the server cannot tell a retry from a new request.

Use case: engineers building payment or write APIs where clients retry on timeout

Inputs / outputs

  • Input: an idempotency key, a request payload fingerprint, a response to record
  • Output: the recorded response on replay, a conflict error on payload mismatch, or None on first execution

Error conditions

  • same key with a different payload (conflict)
  • key expired beyond the retention window

Approach

store key to entry with payload hash and response; on repeat, compare payload hash and either replay the response or raise a conflict; TTL entries are dropped lazily.

Implementation

import hashlib
import time
from dataclasses import dataclass
from typing import Any, Dict, Optional


class IdempotencyConflictError(ValueError):
    """Raised when a key is reused with a different payload."""


@dataclass(frozen=True)
class Entry:
    payload_hash: str
    response: Any
    stored_at: float


def payload_fingerprint(payload: str) -> str:
    """Return a stable fingerprint for a request payload."""
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


class IdempotencyStore:
    """Replay recorded responses for duplicate keys; reject payload conflicts."""

    def __init__(self, ttl_s: float = 3600.0, clock: Any = time.monotonic) -> None:
        if ttl_s <= 0:
            raise ValueError("ttl_s must be positive")
        self._ttl_s = ttl_s
        self._clock = clock
        self._entries: Dict[str, Entry] = {}

    def execute(self, key: str, payload: str, produce: Any) -> Any:
        """Return the recorded response, or run produce and record it."""
        if not key:
            raise ValueError("idempotency key must be non-empty")
        fingerprint = payload_fingerprint(payload)
        existing = self._get_live(key)
        if existing is not None:
            if existing.payload_hash != fingerprint:
                raise IdempotencyConflictError(
                    f"key {key!r} was already used with a different payload"
                )
            return existing.response
        response = produce()
        self._entries[key] = Entry(
            payload_hash=fingerprint,
            response=response,
            stored_at=self._clock(),
        )
        return response

    def _get_live(self, key: str) -> Optional[Entry]:
        entry = self._entries.get(key)
        if entry is None:
            return None
        if self._clock() - entry.stored_at > self._ttl_s:
            del self._entries[key]
            return None
        return entry

Verification tests

import unittest

from example import IdempotencyConflictError, IdempotencyStore, payload_fingerprint


class FakeClock:
    def __init__(self):
        self.t = 0.0

    def __call__(self):
        return self.t


class IdempotencyStoreTests(unittest.TestCase):
    def test_records_then_replays_the_response(self):
        store = IdempotencyStore(ttl_s=1000)
        calls = []

        def produce():
            calls.append(1)
            return {"status": "charged"}

        first = store.execute("key-1", '{"amount": 10}', produce)
        second = store.execute("key-1", '{"amount": 10}', produce)
        self.assertEqual(first, {"status": "charged"})
        self.assertEqual(second, {"status": "charged"})
        self.assertEqual(len(calls), 1)

    def test_raises_conflict_on_payload_mismatch(self):
        store = IdempotencyStore(ttl_s=1000)
        store.execute("key-1", '{"amount": 10}', lambda: "ok")
        with self.assertRaises(IdempotencyConflictError):
            store.execute("key-1", '{"amount": 20}', lambda: "ok")

    def test_expires_entries_after_ttl(self):
        clock = FakeClock()
        store = IdempotencyStore(ttl_s=10, clock=clock)
        calls = []

        def produce():
            calls.append(1)
            return "fresh"

        store.execute("key-1", "payload", produce)
        clock.t = 20
        store.execute("key-1", "payload", produce)
        self.assertEqual(len(calls), 2)

    def test_rejects_empty_key(self):
        store = IdempotencyStore(ttl_s=10)
        with self.assertRaises(ValueError):
            store.execute("", "payload", lambda: "ok")


if __name__ == "__main__":
    unittest.main()

Dependencies and running

No external dependencies (standard library only).

Runtime: python >= 3.9 Entry point: python example.py

Limitations and error handling

in-memory only; no cross-process sharing; TTL checked lazily on access.

Verification boundary

execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox

Interactive Tools for This Topic