Implux Field GuideAGENTIC AI · FORWARD DEPLOYED ENGINEERING

A practical reference for designing agents, delivering software, and proving outcomes.

THE PRACTITIONER'S REFERENCE
Questions · Patterns · Practice

Runnable coding lab / Python standard library

Idempotent write tool

A minimal idempotency ledger that prevents repeated requests from re-running a completed operation. The exercise is deliberately small: focus on the invariant and tests, then explain what production hardening it would need.

No external packagesSolution and unittest cases includedCopy, run, then extend

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.

  1. Before looking at the solution

    Write down the invariant the code must preserve and one failure case that could violate it.

  2. Run the reference implementation

    Download the single-file lab and run python idempotent-tools.py. It uses Python's built-in unittest and needs no network or API key.

  3. Read each test as a requirement

    Identify what the test proves, what it does not prove, and which production boundary remains trusted.

  4. 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

01InvariantWhat must always remain true?
02BoundaryWhich decision belongs in trusted code?
03FailureWhat happens when the result is unknown?
04EvidenceWhich test demonstrates the property?
05ProductionWhat concurrency, persistence, or policy layer is missing?
A concise implementation answer names both the working code path and the assumptions the toy example leaves behind.

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?