Idempotent upsert by version

mediumPipelines~25 min · 8 tests

Queues deliver at least once. That means duplicates, and after a retry, events out of order. A consumer that just writes whatever arrives last will sometimes go backwards in time. A version number on each event fixes that, if the consumer uses it.

Write apply_events(state, events):

  • state is a dict: id -> {"version": int, "data": ...}.
  • Each event is a dict with "id", "version" and "data". "data": None means the record was deleted.
  • Apply an event only if its id isn’t in the state yet, or its version is greater than the stored version. Otherwise ignore it. Equal versions are duplicates.
  • A delete is stored like any other event, as {"version": v, "data": None}. Keeping it (a tombstone) stops an older update from bringing the record back.
  • Return a new dict. Don’t change state.

Applying the same batch twice must give the same result as applying it once.

>>> apply_events({}, [
...     {"id": "a", "version": 2, "data": "new"},
...     {"id": "a", "version": 1, "data": "old"},
... ])
{'a': {'version': 2, 'data': 'new'}}
Learn the ideaRead the lesson →
solution.pyPython 3.14 · Pyodide

Press ⌘ ↵ or Run to check the visible tests. Submit runs the hidden ones too. Everything runs in your browser.

⌘ ↵ to run