The exercise
Implement a small idempotency ledger for a write operation. Demonstrate how repeated requests return the original result instead of duplicating the side effect.
- Before looking at the solution
Write down the invariant the code must preserve and one failure case that could violate it.
- Run the reference implementation
Download the single-file lab and run
python idempotent-tools.py. It uses Python's built-inunittestand needs no network or API key. - Read each test as a requirement
Identify what the test proves, what it does not prove, and which production boundary remains trusted.
- Modify one condition
Add a test for cancellation, concurrent requests, revocation, or a corrupted evaluation case. Explain how the design changes.
Download runnable lab and tests ↗
Reference solution
Show the complete solution and tests
from typing import Callable, TypeVar
T = TypeVar("T")
def apply_once(key: str, operation: Callable[[], T], ledger: dict[str, T]) -> T:
if not key:
raise ValueError("idempotency key is required")
if key in ledger:
return ledger[key]
result = operation()
ledger[key] = result
return result
if __name__ == "__main__":
import unittest
class IdempotencyTests(unittest.TestCase):
def test_duplicate_returns_original_result(self):
ledger = {}; calls = []
def charge(): calls.append("charge"); return "receipt-1"
self.assertEqual(apply_once("run-7", charge, ledger), "receipt-1")
self.assertEqual(apply_once("run-7", charge, ledger), "receipt-1")
self.assertEqual(calls, ["charge"])
def test_key_is_required(self):
with self.assertRaisesRegex(ValueError, "required"):
apply_once("", lambda: 1, {})
def test_failed_operation_is_not_marked_complete(self):
ledger = {}
def fail(): raise TimeoutError()
with self.assertRaises(TimeoutError): apply_once("run-8", fail, ledger)
self.assertNotIn("run-8", ledger)
unittest.main()The mental model
A caller can time out after the downstream system commits. Retrying with the same stable operation key should return the prior outcome instead of applying the effect again.
Limits and production extensions
An in-memory dictionary is not a durable distributed ledger and has races across workers. In production, make the key and result transactional with the system of record, scope it to the principal and operation, and reconcile unknown outcomes.
Explain it in an interview
Follow-up prompts
- What race or failure does this example still permit?
- How would you make the result observable without logging secrets?
- Which property belongs in a unit test, integration test, or production alert?