Deadlines and Outboxes for Agent Work

Lesson 3 of 4

Write the Message with the Record

Estimated time: 10 minutes

Write the message with the record

An agent that saves a record and then publishes a message performs two writes with a gap between them. A crash in that gap leaves either a record with no message or a message with no record, and nothing afterwards can tell which.

Write both rows in one local transaction. The record and the outbound message land together or not at all.

def commit(conn, record, message):
    with conn:
        conn.execute("insert into records values (?, ?)", (record["id"], record["body"]))
        conn.execute("insert into outbox values (?, ?)", (message["id"], message["topic"]))

This is the outbox pattern. The message row is a promise that something must be published, written by the same commit that created the reason to publish it.

The relay reads those rows later. Because the promise is durable, the relay can crash and rerun without losing the message.