Engineering Interview Practice

System design interview: an idempotency key walkthrough

Practice idempotency keys in a system design interview with one export-job contract, twelve traced events and a runnable Python model with explicit limits.

A cobalt blue key lies beside two blank cream paper slips and a closed folder on a wooden desk.
On this page
  1. What operation are you protecting?
  2. Agree on the key, payload and response policy
  3. Trace the timeout before changing the key
  4. Run the complete serialized model
  5. Where does the guarantee end?
  6. Rehearse the next design question
  7. Frequently asked questions
  8. Sources

In a system design interview about idempotency keys, begin with the operation and what a timeout leaves unknown. Reusing a key can recover a result only under a defined request contract. Work through this fictional export-job API to distinguish pending work, replayed ticket creation and genuinely new operations.

Prepared with AI assistance.

Use this narrow exercise alongside broader system design interview practice. It is original teaching material, not an employer question or a production service.

What operation are you protecting?

The endpoint creates an export-job ticket. The worker that eventually produces a file is outside the model. A successful POST returns HTTP 202, a job identifier and state queued; that response does not establish that the file exists.

RFC 9110’s idempotent-methods section defines idempotence through the intended server effect, rather than identical responses. Its automatic-retry guidance for non-idempotent methods depends on knowledge about their semantics or whether the original request was applied. A header name alone does not supply that knowledge.

Suppose a caller times out after its request reaches the service. The service might still have a reservation or already-created ticket. The caller’s missing reply cannot distinguish those states. Define the contract before choosing a retry.

For a target role, check its actual responsibilities and interview instructions. The backend engineering catalog can help you find roles to investigate; the exercise is not a complete backend syllabus.

Agree on the key, payload and response policy

Every request targets POST /export-jobs. The model receives a parsed key string, not a raw HTTP header. Its trusted harness supplies an already-authenticated tenant authorized for the requested report and replayed resource. Neither the key nor body grants access.

Use these author-defined rules:

  • Scope is (trusted tenant, POST, /export-jobs, key).
  • Body fields are exactly report and format. Report and key must be nonempty strings without surrounding whitespace; format is exactly csv or jsonl.
  • Validate before looking up a key. Invalid input returns 400 with code invalid_request and creates no record.
  • Fingerprint the validated request as the exact tuple (report, format). JSON field order does not matter. Do not trim, case-fold or add hidden defaults.

The IETF Idempotency-Key draft-09, published November 21, 2026, discusses keys, fingerprints and documented resource behavior. It proposes 422 for conflicting payload reuse and 409 for outstanding work. This is work in progress, not an RFC. The exact states and replay snapshot below remain our exercise’s choices.

Existing record Matching request? Exercise behavior
Absent No previous fingerprint Reserve; original request remains pending
RESERVED or COMPLETE Different fingerprint 422, code key_reused; preserve the record
RESERVED Same fingerprint 409, code in_progress; no new ticket
COMPLETE Same fingerprint Replay the stored response; no new ticket

Compare fingerprints before checking RESERVED versus COMPLETE. An internal commit is permitted only for a reservation. It creates one ticket and saves its response in an assumed atomic transition. COMPLETE describes that request transition, not the export worker.

For ticket Jn, save status 202, Location: /export-jobs/Jn and body {"job_id":"Jn","state":"queued"}. Errors have empty headers and a body containing the stated code. Keep every key record throughout this trace. No expiry or cleanup occurs.

Trace the timeout before changing the key

P1 is {"report":"daily-events","format":"csv"}. P2 changes format to jsonl. The invalid body instead uses xml.

admit and commit are simulator events, not extra API endpoints or client-controlled progress flags. The latter represents the service completing the original reservation. “202/J1” below means the exact status, Location and body defined above.

Event Arrival or internal checkpoint Response and record state Tickets
1 team-a, K1, P1 arrives RESERVED; no response yet; caller times out 0
2 team-a retries K1/P1 409 in_progress; RESERVED 0
3 Original team-a/K1 commits; reply is lost Store 202/J1; COMPLETE 1
4 team-a retries K1/P1 Replay 202/J1; COMPLETE 1
5 team-a sends K1/P2 422 key_reused; COMPLETE 1
6 team-a deliberately starts K2/P1 RESERVED; no response yet 1
7 team-a/K2 commits 202/J2; COMPLETE 2
8 team-b starts K1/P1 Separate RESERVED record 2
9 team-b/K1 commits 202/J3; COMPLETE 3
10 team-a sends K3 with invalid format 400 invalid_request; K3 ABSENT 3
11 team-a sends corrected K3/P1 RESERVED; no response yet 3
12 team-a/K3 commits 202/J4; COMPLETE 4

Event 3 stores a response that the timed-out caller never receives. Event 4 recovers it without another ticket. Event 5 cannot silently change the operation already associated with K1.

K2 deliberately identifies a new operation. Equal payloads alone do not merge it with K1. Generating a new key because a reply was lost would therefore risk creating another ticket under this contract.

K1 in team-b is a separate trusted scope. K3 demonstrates validation before reservation: correcting an invalid first request can use that still-unused key.

Run the complete serialized model

Save the following as export_model.py. It uses Python’s standard library and was checked with Python 3.9.6. The harness compares all twelve responses, record states and ticket counts with explicit expectations.

The dictionary and list simulate state. They are not durable storage, and the separate Python writes are not a database transaction. Treat each admitted reservation or commit as one idealized atomic event in this sequential exercise.

"""Sequential teaching model, not an HTTP server, database transaction or worker."""
from copy import deepcopy


class ExportModel:
    def __init__(self):
        self.records = {}
        self.jobs = []

    @staticmethod
    def error(code, message):
        return {"status": code, "headers": {}, "body": {"code": message}}

    def admit(self, tenant, key, body):  # Trusted, authorized tenant context.
        def identifier(value):
            return type(value) is str and bool(value) and value == value.strip()

        if (not identifier(key) or type(body) is not dict
                or set(body) != {"report", "format"}
                or not identifier(body["report"])
                or type(body["format"]) is not str
                or body["format"] not in ("csv", "jsonl")):
            return self.error(400, "invalid_request")
        scope = (tenant, "POST", "/export-jobs", key)
        fingerprint = (body["report"], body["format"])
        record = self.records.get(scope)
        if record is None:
            self.records[scope] = {"fingerprint": fingerprint,
                                   "state": "RESERVED", "response": None}
            return None  # Original request is pending; no HTTP response yet.
        if record["fingerprint"] != fingerprint:
            return self.error(422, "key_reused")
        if record["state"] == "RESERVED":
            return self.error(409, "in_progress")
        return deepcopy(record["response"])

    def commit(self, tenant, key):
        scope = (tenant, "POST", "/export-jobs", key)
        record = self.records[scope]
        if record["state"] != "RESERVED":
            raise ValueError("commit requires a reservation")
        job_id = "J" + str(len(self.jobs) + 1)
        response = {"status": 202,
                    "headers": {"Location": "/export-jobs/" + job_id},
                    "body": {"job_id": job_id, "state": "queued"}}
        self.jobs.append({"tenant": tenant, "job_id": job_id,
                          "fingerprint": record["fingerprint"]})
        record.update(state="COMPLETE", response=deepcopy(response))
        return deepcopy(response)


if __name__ == "__main__":
    def ticket(job_id):
        return {"status": 202,
                "headers": {"Location": "/export-jobs/" + job_id},
                "body": {"job_id": job_id, "state": "queued"}}

    p1 = {"report": "daily-events", "format": "csv"}
    p2 = {"report": "daily-events", "format": "jsonl"}
    bad = {"report": "daily-events", "format": "xml"}
    pending = {"status": 409, "headers": {}, "body": {"code": "in_progress"}}
    conflict = {"status": 422, "headers": {}, "body": {"code": "key_reused"}}
    invalid = {"status": 400, "headers": {}, "body": {"code": "invalid_request"}}
    cases = [
        ("admit", "team-a", "K1", p1, None, "RESERVED", 0),
        ("admit", "team-a", "K1", p1, pending, "RESERVED", 0),
        ("commit", "team-a", "K1", None, ticket("J1"), "COMPLETE", 1),
        ("admit", "team-a", "K1", p1, ticket("J1"), "COMPLETE", 1),
        ("admit", "team-a", "K1", p2, conflict, "COMPLETE", 1),
        ("admit", "team-a", "K2", p1, None, "RESERVED", 1),
        ("commit", "team-a", "K2", None, ticket("J2"), "COMPLETE", 2),
        ("admit", "team-b", "K1", p1, None, "RESERVED", 2),
        ("commit", "team-b", "K1", None, ticket("J3"), "COMPLETE", 3),
        ("admit", "team-a", "K3", bad, invalid, "ABSENT", 3),
        ("admit", "team-a", "K3", p1, None, "RESERVED", 3),
        ("commit", "team-a", "K3", None, ticket("J4"), "COMPLETE", 4),
    ]
    model = ExportModel()
    for number, (action, tenant, key, body, expected, state, count) in enumerate(cases, 1):
        actual = (model.admit(tenant, key, body) if action == "admit"
                  else model.commit(tenant, key))
        assert actual == expected, (number, actual, expected)
        scope = (tenant, "POST", "/export-jobs", key)
        assert model.records.get(scope, {}).get("state", "ABSENT") == state
        assert len(model.jobs) == count, number
    print("PASS 12 serialized events; 4 job tickets created")

Run with assertions enabled, without Python’s -O option:

python3 export_model.py

Expected output:

PASS 12 serialized events; 4 job tickets created

Here, returned None means the original simulated request has no response yet. The harness’s commit events supply its later completion; no actual network timeout is injected. Replay returns a copy so changing the returned object does not change the stored snapshot.

Where does the guarantee end?

Amazon’s Builders’ Library discussion couples request-identity recording with the associated mutation atomically. Ask where that boundary ends in your design. This model assumes ticket creation and the response record change together; it does not implement that guarantee in a real store.

A ticket also differs from the work it triggers. Temporal’s November 4 implementation review describes an external write succeeding before Activity completion is recorded, allowing a later execution to repeat it. Receiver-side handling remains relevant even with durable workflow machinery. Our model tests no worker or external effect.

It also tests no concurrent execution, process crash, storage exception, abandoned reservation or restart. All records remain present. An actual design needs policies for ownership recovery and expiry; deleting a record could remove the information needed to recognize a later retry.

These twelve checks expose behavior under the supplied contract. They do not prove production exactly-once execution.

Rehearse the next design question

Explain the trace without reading the implementation. Then ask what changes if two requests arrive together, a process dies after reservation, or ticket creation and result recording use different stores. State which assumption fails before proposing a mechanism.

Choose another prompt from the question bank and specify its operation, identity and failure boundary from scratch. For spoken practice, Prepin is an AI hiring platform with a free AI career team for candidates, including role-focused voice mock interviews and feedback. Practice this interview.

Frequently asked questions

Does a timeout mean the export request failed?

No. In this trace the caller loses its reply while the original operation can still commit. The service’s documented contract and recorded state determine how to retry or reconcile the operation.

Does the same payload always mean the same operation?

Not here. The same payload with deliberately new K2 creates another ticket. Use the same key for a retry of the same intent, and a new key only for a genuinely new operation under this contract.

Does replaying 202 mean the export has finished?

No. It returns the original ticket-creation snapshot, whose body says queued. COMPLETE is the key record’s state, not a report about the export worker’s current status.

Does this model prove that simultaneous requests are safe?

No. Events are serialized and atomic state transitions are assumptions. A real implementation must establish its own concurrency, durability, authorization, recovery and downstream-effect behavior.

Sources

Oleh Savchuk, founder of Prepin

Oleh Savchuk

Founder, Prepin

Oleh Savchuk is the founder of Prepin, an AI hiring platform that gives candidates a free AI career team and gives hiring teams AI recruiting agents. He is a software engineer in Philadelphia and writes about technical hiring, AI in recruiting and interview preparation.

Practice the interview out loud

Run a realistic AI mock interview for your target role and get feedback on every answer.

Start a mock interview →

Screen engineers before the first call

Send candidates one link. Prepin runs the technical voice interview and live coding, then gives you a scored report.

See how screening works →