PythiloLesson 1 of 12 · progress kept in this browser

Commit a business row and an outbox atomically

A database transaction cannot atomically commit a remote message broker too. A transactional outbox stores the business change and a message intent in the same database commit. A separate dispatcher may publish that intent more than once, so consumers still need deduplication.

The local exercise uses two real SQLite tables and an injected failure between their writes. It checks durable database state after the failure rather than trusting a returned success flag. Do not describe this pattern as exactly-once delivery: the uncertain window moves to dispatch and acknowledgement.

import sqlite3
with sqlite3.connect(":memory:") as db:
    db.execute("create table events(id text)")
    try:
        with db:
            db.execute("insert into events values ('a')")
            raise ValueError("abort")
    except ValueError:pass
    print(db.execute("select count(*) from events").fetchone())
Your task

Implement commit_order(db,key,amount,fail=False). In one transaction insert orders(id,amount), then outbox(id,payload) with payload=str(amount). If fail, raise RuntimeError between writes. The tables exist; propagate uniqueness errors and roll back both writes.