Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 30 min · revision 4

Safe Retries, Long-Running Operations, Concurrent Updates and Versioning

Design the parts of an API that keep working when things go wrong: idempotency keys for retries, 202 Accepted with a status resource for slow work, ETags and If-Match for concurrent edits, and a versioning policy that does not break clients.

Contentsand lesson path

What you will learn

  • Make unsafe operations safe to retry with idempotency keys, model long-running operations as 202 Accepted with a status resource, and protect concurrent updates with ETags and conditional requests, within a backward-compatible versioning and deprecation policy.

Prerequisites: HTTP & APIs

01. Why it matters

One uncomfortable fact drives this lesson: after a request times out, the client does not know whether the server never received it, processed it and lost the reply, or is still working on it. You met the vocabulary for this in the idempotency lesson: repeating a GET or DELETE is harmless, repeating a POST may not be. This lesson is the designer's half of that bargain: four mechanisms that let clients survive failures without duplicating work, namely idempotency keys, status resources for slow operations, conditional requests for concurrent editors, and versioning for change over time.

All four run in one small FastAPI app, printed in full below. Save every block captioned demo03_reliability.py into that one file, in the order shown, and run it. The client calls go through httpx.ASGITransport, which hands each request straight to the app inside the same process, so no server or port is needed.

Terminal · Python 3.12, in a fresh virtual environment
uv venv --python 3.12 .venv && source .venv/bin/activate
uv pip install fastapi==0.163.1 pydantic==2.14.3 httpx==0.28.1
python demo03_reliability.py
Python · demo03_reliability.py (1 of 8): app, stores and helpers
"""Idempotency keys, 202 + status resource, and ETag/If-Match on one small app."""
import asyncio
import hashlib
import itertools

import httpx
from fastapi import FastAPI, Header
from fastapi.responses import JSONResponse, Response
from pydantic import BaseModel

app = FastAPI()
TASKS = {"k101": {"id": "k101", "team": "t7", "title": "Write API guide",
                  "version": 1}}
NEXT_ID = itertools.count(102)
IDEMPOTENT: dict[tuple[str, str], dict] = {}  # (team, key) -> stored outcome
IN_FLIGHT: set[tuple[str, str]] = set()       # keys whose first request runs


class TaskIn(BaseModel):
    title: str


def problem(status: int, slug: str, detail: str) -> JSONResponse:
    """An RFC 9457 Problem Details response, as in the errors lesson."""
    body = {"type": f"https://example.com/problems/{slug}", "status": status,
            "title": slug.replace("-", " "), "detail": detail}
    return JSONResponse(body, status, media_type="application/problem+json")


def created(task: dict) -> JSONResponse:
    location = f"/teams/{task['team']}/tasks/{task['id']}"
    return JSONResponse(task, 201, headers={"Location": location})


async def insert_task(team_id: str, task_in: TaskIn) -> dict:
    await asyncio.sleep(0.05)  # stands in for a slow database write
    task = {"id": f"k{next(NEXT_ID)}", "team": team_id,
            "title": task_in.title, "version": 1}
    TASKS[task["id"]] = task
    return task

02. Idempotency keys: making POST safe to repeat

The pattern: before sending a create, the client generates a key — a UUID minted once per logical operation, not per attempt — and sends it in an Idempotency-Key header on every attempt. The server keeps the key, a fingerprint of the request body, and the response it produced. When a request arrives with a key it has seen, it does not run the operation again: it replays the stored response. When a request arrives with a key that is still being processed, the honest answer is 409 Conflict with Retry-After — "someone is already doing this, ask again shortly". And a key reused with a different body is a client bug, answered 422: the key names one operation, not one URL.

The IETF draft for this header and Stripe's idempotent requests describe the same contract. One syntax detail differs: draft 09 makes the value a Structured Field string, so it is quoted (Idempotency-Key: "8e03978e-…"), while Stripe and this demo send the bare key. The draft leaves retention to you but says to publish an expiry policy; Stripe, for example, may remove keys once they are at least 24 hours old. Store the response headers with the body, so a replay returns the same Location.

Python · demo03_reliability.py (2 of 8): the idempotent create
@app.post("/teams/{team_id}/tasks", status_code=201)
async def create_task(team_id: str, task_in: TaskIn,
                      idempotency_key: str | None = Header(None)):
    if idempotency_key is None:  # no key: a plain, non-idempotent create
        return created(await insert_task(team_id, task_in))
    key = (team_id, idempotency_key)  # scope keys to the caller and path
    body_hash = hashlib.sha256(task_in.model_dump_json().encode()).hexdigest()
    if key in IDEMPOTENT:
        stored = IDEMPOTENT[key]
        if stored["body_hash"] != body_hash:
            return problem(422, "idempotency-key-reuse",
                           "this key was already used with a different body")
        replay = created(stored["task"])
        replay.headers["Idempotent-Replayed"] = "true"
        return replay
    if key in IN_FLIGHT:
        busy = problem(409, "request-in-flight",
                       "the first request with this key is still running")
        busy.headers["Retry-After"] = "1"
        return busy
    IN_FLIGHT.add(key)  # no await between the checks and here
    try:
        task = await insert_task(team_id, task_in)
        IDEMPOTENT[key] = {"body_hash": body_hash, "task": dict(task)}
        return created(task)
    finally:
        IN_FLIGHT.discard(key)
Python · demo03_reliability.py (3 of 8): client calls for this section
def replayed(r: httpx.Response) -> str:
    return r.headers.get("Idempotent-Replayed", "-")


async def show_idempotency(c: httpx.AsyncClient) -> None:
    guide, key = {"title": "Review guide"}, {"Idempotency-Key": "a1f3-review"}
    first = await c.post("/teams/t7/tasks", json=guide, headers=key)
    print("first  ->", first.status_code, first.headers["Location"])
    retry = await c.post("/teams/t7/tasks", json=guide, headers=key)
    print("retry  ->", retry.status_code, retry.headers["Location"],
          "replayed:", replayed(retry))
    other = await c.post("/teams/t7/tasks", json={"title": "Other"}, headers=key)
    print("reused ->", other.status_code, other.json()["type"].split("/")[-1])
    twin = {"Idempotency-Key": "c9d2-twin"}
    pair = await asyncio.gather(  # two attempts racing with one key
        c.post("/teams/t7/tasks", json=guide, headers=twin),
        c.post("/teams/t7/tasks", json=guide, headers=twin))
    for label, r in zip(("first ", "second"), pair):
        print(label, "->", r.status_code,
              "retry-after:", r.headers.get("Retry-After", "-"))
    plain = await asyncio.gather(c.post("/teams/t7/tasks", json=guide),
                                 c.post("/teams/t7/tasks", json=guide))
    print("no key, concurrent ->", *(r.status_code for r in plain))
    t8 = await c.post("/teams/t8/tasks", json=guide, headers=key)
    print("same key, team t8 ->", t8.status_code, t8.headers["Location"],
          "replayed:", replayed(t8))
Expected output (first part of the run)
== idempotency ==
first  -> 201 /teams/t7/tasks/k102
retry  -> 201 /teams/t7/tasks/k102 replayed: true
reused -> 422 idempotency-key-reuse
first  -> 201 retry-after: -
second -> 409 retry-after: 1
no key, concurrent -> 201 201
same key, team t8 -> 201 /teams/t8/tasks/k106 replayed: -

The retried create and the racing pair each produced one task, although each was sent twice. The Idempotent-Replayed: true header is borrowed from Stripe, not from the draft; it lets a client tell a replay from a fresh result. Note what the client owes back: generate the key with the operation (a button press), not per network attempt; persist it until the operation is settled; and never reuse it for a different payload. Document the 409-on-in-flight case: a client seeing 409 on a first attempt will suspect a bug, not a race.

Three details in the code are easy to get wrong. The header is optional, so a request without it must skip the bookkeeping; otherwise every key-less create shares the key None and concurrent ones answer 409 to each other. The store is keyed by (team_id, key), so the same key sent to team t8 creates a new task instead of replaying t7's response; a production API scopes keys by the authenticated client as well. And the check-then-add on IN_FLIGHT is safe only because one process runs it with no await in between. With several server processes the store must be shared, claiming a key must be one atomic step (for example an insert into a table with a unique key), and stored outcomes need a published expiry.

03. Long-running operations: 202 and a status resource

Some operations cannot finish inside a request: an export that takes minutes, a report over last quarter, a video transcode. Holding the connection open fails in three places at once — client timeouts, proxy timeouts, and any retry that starts the work twice. The resource-oriented answer from lesson one applies: the operation is a noun. POST /teams/t7/exports answers 202 Accepted — the request was accepted, not completed — with a Location header naming a status resource and a Retry-After hint of how long to wait before polling. GET on the status resource reports progress and, when the work is done, links to the result. A failed job reports its failure there too, as a Problem Details document describing why.

Python · demo03_reliability.py (4 of 8): the export and its status resource
EXPORTS: dict[str, dict] = {}
JOBS: set[asyncio.Task] = set()  # keep references to running jobs


async def run_export(export_id: str, chunks: int = 6) -> None:
    job = EXPORTS[export_id]
    for done in range(1, chunks + 1):
        await asyncio.sleep(0.3)  # write one chunk of rows
        job["progress"] = round(100 * done / chunks)
    job.update(state="succeeded", result=f"/exports/{export_id}/result.csv")


@app.post("/teams/{team_id}/exports", status_code=202)
async def start_export(team_id: str):
    export_id = f"e{len(EXPORTS) + 1}"
    EXPORTS[export_id] = {"id": export_id, "team": team_id,
                          "state": "running", "progress": 0}
    job = asyncio.create_task(run_export(export_id))
    JOBS.add(job)
    job.add_done_callback(JOBS.discard)
    headers = {"Location": f"/exports/{export_id}", "Retry-After": "1"}
    return JSONResponse(EXPORTS[export_id], 202, headers=headers)


@app.get("/exports/{export_id}")
async def export_status(export_id: str):
    job = EXPORTS.get(export_id)
    if job is None:
        return problem(404, "not-found", f"no export {export_id}")
    running = job["state"] == "running"
    return JSONResponse(job, headers={"Retry-After": "1"} if running else {})
Python · demo03_reliability.py (5 of 8): a client that polls politely
async def show_export(c: httpx.AsyncClient) -> None:
    start = await c.post("/teams/t7/exports")
    print("POST /teams/t7/exports ->", start.status_code,
          "Location:", start.headers["Location"],
          "Retry-After:", start.headers["Retry-After"])
    while True:
        r = await c.get(start.headers["Location"])
        job, wait = r.json(), r.headers.get("Retry-After")
        print("GET ", start.headers["Location"], "->", r.status_code,
              "state:", job["state"], f"progress: {job['progress']}%",
              "retry-after:", wait or "-")
        if wait is None:
            print("     result:", job["result"])
            break
        await asyncio.sleep(int(wait))  # poll when the server suggests
Expected output (the export takes about two seconds)
== export ==
POST /teams/t7/exports -> 202 Location: /exports/e1 Retry-After: 1
GET  /exports/e1 -> 200 state: running progress: 0% retry-after: 1
GET  /exports/e1 -> 200 state: running progress: 50% retry-after: 1
GET  /exports/e1 -> 200 state: succeeded progress: 100% retry-after: -
     result: /exports/e1/result.csv

asyncio.create_task keeps the demo short; a real service hands the job to a queue and a worker and stores its state in the database, so a restart does not lose it. The state machine is small (running, succeeded, failed); a fuller design also lets a client cancel the job with DELETE. Poll on the schedule the server suggests (Retry-After), not a fixed timer. And when the client can receive callbacks, accept a callback_url when the job is created and POST the finished status resource to it when done — the webhook saves the polling entirely, but keep the status resource anyway, because webhooks get lost and the client needs a way to reconcile.

04. Concurrent updates: ETags and If-Match

Two people open the same task, both edit, both save. Without protection, the second save silently overwrites the first — the lost update problem. HTTP's answer is the entity tag: every representation of a task carries an ETag header, a short value that changes whenever the resource changes. A client that read the task at "v1" sends its update with If-Match: "v1". The server applies it only if the tag still matches; if the task has moved on, the update fails with 412 Precondition Failed, and that client must reload and merge.

The same header pair also serves caches: a conditional GET with If-None-Match answers 304 Not Modified and no body when nothing changed.

Python · demo03_reliability.py (6 of 8): ETag, If-None-Match and If-Match
def etag(task: dict) -> str:
    return f'"v{task["version"]}"'


@app.get("/teams/{team_id}/tasks/{task_id}")
async def read_task(team_id: str, task_id: str,
                    if_none_match: str | None = Header(None)):
    task = TASKS.get(task_id)
    if task is None or task["team"] != team_id:
        return problem(404, "not-found", f"no task {task_id}")
    if if_none_match == etag(task):  # the client's copy is still current
        return Response(status_code=304, headers={"ETag": etag(task)})
    return JSONResponse(task, headers={"ETag": etag(task)})


@app.patch("/teams/{team_id}/tasks/{task_id}")
async def update_task(team_id: str, task_id: str, task_in: TaskIn,
                      if_match: str | None = Header(None)):
    task = TASKS.get(task_id)
    if task is None or task["team"] != team_id:
        return problem(404, "not-found", f"no task {task_id}")
    if if_match is not None and if_match != etag(task):
        return problem(412, "version-conflict",
                       f"task is at {etag(task)}, you sent {if_match}")
    task.update(title=task_in.title, version=task["version"] + 1)
    return JSONResponse(task, headers={"ETag": etag(task)})
Python · demo03_reliability.py (7 of 8): two editors, one task
async def show_etags(c: httpx.AsyncClient) -> None:
    url = "/teams/t7/tasks/k101"
    ana, bo = await c.get(url), await c.get(url)
    print("Ana   GET  ->", ana.status_code, "ETag:", ana.headers["ETag"])
    print("Bo    GET  ->", bo.status_code, "ETag:", bo.headers["ETag"])
    tag = ana.headers["ETag"]
    a = await c.patch(url, json={"title": "Ana's edit"}, headers={"If-Match": tag})
    print(f"Ana   PATCH If-Match {tag} ->", a.status_code,
          "new ETag:", a.headers["ETag"])
    b = await c.patch(url, json={"title": "Bo's edit"}, headers={"If-Match": tag})
    print(f"Bo    PATCH If-Match {tag} ->", b.status_code,
          b.json()["type"].split("/")[-1])
    new = a.headers["ETag"]
    again = await c.get(url, headers={"If-None-Match": new})
    print(f"Bo    GET  If-None-Match {new} ->", again.status_code)
Python · demo03_reliability.py (8 of 8): run the three sections
async def main() -> None:
    transport = httpx.ASGITransport(app=app)  # in-process: no server, no port
    async with httpx.AsyncClient(transport=transport,
                                 base_url="http://demo") as client:
        for show in (show_idempotency, show_export, show_etags):
            print(f"== {show.__name__.removeprefix('show_')} ==")
            await show(client)


if __name__ == "__main__":
    asyncio.run(main())
Expected output (last part of the run)
== etags ==
Ana   GET  -> 200 ETag: "v1"
Bo    GET  -> 200 ETag: "v1"
Ana   PATCH If-Match "v1" -> 200 new ETag: "v2"
Bo    PATCH If-Match "v1" -> 412 version-conflict
Bo    GET  If-None-Match "v2" -> 304

The demo still accepts a PATCH without If-Match, which is a blind write. Decide, and document, whether If-Match is required on a resource; when it is and the client omits it, answer 428 Precondition Required (RFC 6585), a status that exists to teach clients the rule. The demo also compares one tag with ==. RFC 9110 allows lists and * in these headers and defines strong and weak tags; for JSON APIs a version number or a hash of the representation is enough.

05. Versioning and deprecation

The last reliability mechanism is time. Your API will change; the question is how to change it without breaking clients who cannot all upgrade at once. Split every change into two kinds:

  1. Compatible changes can ship inside a version: adding an optional request parameter, adding a response field, adding an endpoint, adding a new problem type. Clients must treat unknown response fields as normal. Many JSON libraries ignore them, but not all (a Pydantic model with extra="forbid" rejects them, and the default changes between library versions: Jackson 2 fails on unknown properties, Jackson 3 ignores them), so state the rule in your documentation and test your SDKs against it.
  2. Breaking changes need a new version: removing or renaming a field, changing a type or semantics, making an optional input required, changing error codes clients branch on.

Path versioning (/v1/teams/t7/tasks) is the most visible choice, and many public APIs use it: the version shows up in logs, cache keys and client code. Others, such as Stripe (Stripe-Version) and GitHub (X-GitHub-Api-Version), pin a dated version in a request header, which keeps URLs stable but needs the header logged on purpose. Pick one, document it, and make the version show up in your logs either way.

Deprecation is a process, not an announcement. When /v1 must give way to /v2: keep /v1 running under a written policy (a year is common); mark deprecated operations in the docs and in responses — the Deprecation (RFC 9745) and Sunset (RFC 8594) headers let a client learn its own expiry date from the traffic itself; measure per-client usage of deprecated paths so you know who to contact; and only then remove, with a 410 Gone answer that names the successor. A deprecation nobody measured is an outage scheduled in advance.

06. Check your understanding

Practice check · 3 questions

Reliability decisions

Three situations the mechanisms above exist for.

Q1. This lesson's contract states that clients must ignore unknown response fields. Under that rule, is adding a nullable assignee field to task responses a breaking change for /v1 clients?
Q2. Polling the export status resource works, but one client processes thousands of exports a day. What completes the design for them?
Q3. Your contract now requires If-Match on PATCH /teams/{team}/tasks/{id}. An older client sends a PATCH with no If-Match header at all. What should the server answer?
Practice only: not graded, not saved, not evidence.

07. Apply it

Grow the demo app into your team-tasks practice API. Give the export a callback_url option and, using a tiny second endpoint to receive it, verify that the webhook fires once in the normal case, that your receiver ignores a duplicate delivery of the same export id (webhooks are delivered at least once, not exactly once), and that a missed callback is recovered by polling the status resource. Make If-Match required on task updates and return 428 when it is missing. Then write the versioning policy paragraph for your API: which changes are compatible, how long a deprecated version lives, and which headers carry the deprecation. All of it becomes documented contract in the OpenAPI lab.

08. Review prompt

Without looking back: describe what the server does for an Idempotency-Key it has seen with the same body, with a different body, and one that is still being processed. Sketch the full life of an export, from POST to result, naming every status code and header a client sees. Explain how If-Match prevents a lost update, and which status code reports the failure. Finally, list three compatible changes and three breaking ones, and name the two headers that announce a deprecation.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check