Skip to content

Technical ·

An Event ID Is Not Enough: Making Retries Safe

A crash-tested consumer example showing how to commit a database effect and its completion record together, and where that guarantee ends.

A consumer adds seven units to a usage counter, then crashes before recording that it processed the event. The broker delivers the same event again. Its ID is unchanged, but the consumer has no completion record to find. Seven becomes fourteen.

Recognizing a duplicate requires a stable identity. Safely skipping it also requires durable evidence that its effect committed. For a database effect, the useful invariant is simple: the effect and its completion record commit together, or neither does.

This is a follow-up to Building an Event-Driven AI Monorepo, for backend engineers already familiar with transactions and asynchronous consumers. The earlier article sketched the plumbing. Here, a small runnable experiment supplies the missing crash-recovery behavior.

The gap between processing and recording completion

The earlier consumer reduced to this sequence:

if await self._is_already_processed(event.event_id):
    continue

await self.process_message(event.payload)
await self._mark_processed(event.event_id)

Both deduplication methods were placeholders. That makes this an incomplete guarantee in an architectural sketch, not evidence of a production incident. Even after implementing those methods, a completion set alone cannot close the gap between the last two calls.

Suppose processing increments a durable counter. The failure unfolds like this:

StepCounterCompletion record
Receive event-42; check for completion0Absent
Commit the increment7Absent
Process crashes7Absent
Redelivery checks the same ID7Absent
Retry commits another increment14Absent
Retry records completion14Present

Nothing about the ID tells the restarted consumer whether the first increment happened.

The same uncertainty appears in Raft’s client-interaction section (§8): a leader can commit a command and crash before replying. A client retry can then execute the command again. The paper describes unique command serial numbers and remembered responses in the state machine to suppress repeat execution. The relevant lesson here is that request identity must be paired with recoverable execution state; consensus alone does not recognize a retried logical operation.

Changing the order creates a different failure

Recording completion first creates the opposite window. If the record commits and the consumer dies before applying the increment, the next delivery finds “completed” and skips work that never happened. The counter stays at zero.

Two consumers introduce another problem without any crash:

Consumer A: completion absent
Consumer B: completion absent
Consumer A: increment commits
Consumer B: increment commits

A unique constraint on a completion row written afterward cannot undo two independently committed increments. The constraint must participate in the transaction that controls the effect.

One transaction owns the decision and the effect

The experiment uses SQLite and a deliberately non-idempotent operation: incrementing a counter. Repeating that operation has a visible consequence. Both tables live in one database:

CREATE TABLE completed (
    consumer TEXT NOT NULL,
    tenant TEXT NOT NULL,
    event_id TEXT NOT NULL,
    units INTEGER NOT NULL,
    PRIMARY KEY (consumer, tenant, event_id)
);
CREATE TABLE usage (
    id INTEGER PRIMARY KEY,
    units INTEGER NOT NULL
);
INSERT INTO usage VALUES (1, 0);

usage is a single shared test counter, not a tenant billing schema. The request payload is just the integer units; retaining it lets the consumer reject reuse of a key with different input.

Here is the transaction from the experiment with its crash hooks removed. The connection uses isolation_level=None so transaction boundaries are explicit, a ten-second lock timeout, and PRAGMA synchronous=FULL.

def apply(db, key, units):
    db.execute("BEGIN IMMEDIATE")
    try:
        inserted = db.execute(
            "INSERT INTO completed VALUES (?, ?, ?, ?) "
            "ON CONFLICT (consumer, tenant, event_id) DO NOTHING",
            (*key, units),
        ).rowcount

        if inserted:
            db.execute(
                "UPDATE usage SET units = units + ? WHERE id = 1",
                (units,),
            )
        else:
            previous = db.execute(
                "SELECT units FROM completed "
                "WHERE consumer = ? AND tenant = ? AND event_id = ?",
                key,
            ).fetchone()[0]
            if previous != units:
                raise ValueError("same key, different payload")

        db.execute("COMMIT")
    except BaseException:
        if db.in_transaction:
            db.execute("ROLLBACK")
        raise

The row is inserted before the increment, but it is still uncommitted. A crash in between rolls back both. Only a committed row means completed. This is different from committing a marker before doing the work.

SQLite permits one writer at a time. BEGIN IMMEDIATE acquires the write transaction before the duplicate decision; a competing writer waits or receives a busy error. That makes the check and effect serialized in this example. It also limits write concurrency. A busy error must leave the delivery unacknowledged and eligible for a later attempt. Other databases require their own constraint, locking, and isolation analysis; this is not a portability claim. SQLite transaction documentation

A matching duplicate commits without incrementing. A conflicting payload raises and rolls back. The caller acknowledges only after apply returns successfully, including when it finds an already committed matching request.

Crash the process, then inspect what survived

The complete experiment uses only Python’s standard library. Download it and run:

python3 experiment.py

The recorded run used Python 3.14.7 and SQLite 3.53.4 on Linux, with rollback journaling (journal_mode=DELETE) and synchronous=FULL. Each scenario starts with fresh temporary databases. Child processes exit through os._exit, bypassing exception handlers and graceful connection cleanup. Two independent processes exercise the concurrency cases; a barrier forces both unsafe consumers to observe the missing record before either writes.

Acknowledgment is a model, stored in a separate database: an unacknowledged delivery is retried by the test controller. This tests application ordering around acknowledgment, not a real broker, network, or client library.

ScenarioCounter beforeCounter after
Separate writes: crash after effect, before marker714
Separate writes: crash after marker, before effect00
Transaction: crash before beginning07
Transaction: crash after inserting record07
Transaction: crash after increment, before commit07
Transaction: crash immediately before commit07
Transaction: crash immediately after commit77
Transaction: crash before acknowledgment77
Transaction: crash after acknowledgment77
Two consumers using separate writes—14
Two consumers using the transaction—7

All fifteen scenarios passed their assertions, including those intentionally demonstrating unsafe outcomes. The other four checks covered payload conflicts, tenant scope, consumer scope, and premature deletion of the completion record. In the transaction crash cases, every uncommitted attempt left neither the increment nor its record, and none was acknowledged. Every committed retry retained one record and one increment. Once the acknowledgment model recorded success, the controller stopped redelivering.

These are deterministic process-crash checks on either side of commit. They do not inject a crash inside SQLite’s commit implementation, simulate power loss, or test database failover. Recovery during commit depends on the database and storage guarantees; SQLite documents its assumptions and recovery mechanism in Atomic Commit in SQLite.

Acknowledge the committed outcome

The ordering at the consumer boundary is:

receive → commit effect plus completion record → acknowledge

If the process dies after commit but before acknowledgment reaches the broker, redelivery is harmless to this database effect: the next consumer finds the committed record. If it dies before commit, the missing acknowledgment allows recovery to try the work again.

For a concrete broker mapping, RabbitMQ’s manual consumer acknowledgments tell the broker it can discard a delivery. Unacknowledged deliveries are requeued when their channel or connection closes. An acknowledgment should therefore follow the database commit, and a verified duplicate should also be acknowledged. Delivery tags belong to a channel; they are not durable business request IDs. These are documented broker semantics, not a RabbitMQ integration tested by this experiment. RabbitMQ consumer acknowledgments

A remote database can also commit without the consumer receiving its commit response. Treat that outcome as uncertain: reconnect and retry through the same identity protocol. A timeout alone is not evidence of rollback. Blindly rerunning only the increment would bypass the protection.

The boundaries are part of the guarantee

External effects need their own recovery protocol. The original analysis worker called an LLM and published another event. A local transaction cannot roll back a remote generation, charge, email, or publication. If the remote operation succeeds and its response is lost, a local “started” row still cannot establish the result. Use a stable remote idempotency key when the provider supports the needed semantics, or reconcile the outcome through a durable operation identifier. Otherwise, repeated external execution remains possible.

For outgoing messages, one design is to write an outbox row in the same transaction as the local effect and completion record. A separate publisher retries that durable intent. The publisher can still send twice after an uncertain acknowledgment, so the downstream consumer needs its own duplicate handling. This is a design extension, not part of the tested example.

The key names a logical operation. This example scopes event-42 by tenant and logical consumer. Worker replicas share a consumer identity; using a process ID would defeat deduplication across replicas. Different consumer operations can legitimately handle the same event. A producer must preserve the event ID across retries, and multiple events representing the same business action may require a business-operation key instead. Changing the consumer namespace during deployment can also make old events appear new.

A matching key must mean matching input. The experiment compares the entire effect-bearing payload, the integer units. A real request may need normalized fields or a canonical payload digest. Reusing a key with changed input should produce an explicit conflict, not silent success. The experiment leaves conflicts unacknowledged; a deployed consumer also needs a durable quarantine or operator-resolution path to avoid retrying them forever. APIs that return a result may need to retain that result alongside the completion record.

Retention limits how long retries remain safe. Deleting the completion record and redelivering the original event changed the counter from seven to fourteen in the experiment. The transaction still worked; its memory of the operation was gone. Retention must cover the supported retry and replay horizon, including delayed deliveries, dead-letter replays, and recovery procedures. If old requests can return indefinitely, a finite TTL alone cannot preserve indefinite duplicate suppression. A longer-lived business uniqueness constraint or an enforced expiry protocol may be needed.

The bounded promise is one committed database increment per scoped request while its completion record survives, assuming the database preserves committed state. Eventual completion additionally depends on retries, available storage, and successful processing. Before treating a consumer as safe to retry, identify both where the effect becomes durable and where the evidence of that effect becomes durable. For this example, they become durable in the same commit.