Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 5 min read

Saved the Change, Lost the Record: A Transactional Outbox for AI Decision Events

Here's an illustrative setup. A model suggests a priority for each incoming support ticket. Your handler saves the priority, then posts a small decision record ("ticket t-7 set to high, model X, prompt v4") to whatever s

Here's an illustrative setup. A model suggests a priority for each incoming support ticket. Your handler saves the priority, then posts a small decision record ("ticket t-7 set to high, model X, prompt v4") to whatever service keeps your audit trail. Usually both happen.

Now the bad days. The commit succeeds and the HTTP call times out: the ticket changed and you don't know if anything recorded why. Or the call succeeds and the commit fails: you've recorded a decision that never took effect. Retrying inline makes the user wait, and still doesn't cover a crash between the two steps.

This is the dual-write problem, and it isn't specific to AI. Chris Richardson's transactional outbox pattern describes a well-known fix: write the message into the same database transaction as the business change, and let a separate process send it.

The shape

 request handler                      relay (separate loop)
 ---------------                      ---------------------
 BEGIN
   UPDATE tickets ...                 SELECT unsent ORDER BY seq
   INSERT INTO outbox ...    ---->    send(event)  -- may repeat
 COMMIT                               mark sent_at
                                             |
                                             v
                                      record service (dedupes
                                      on event_id)

The handler never talks to the record service. If the transaction commits, the event exists and will be sent. If it rolls back, there's nothing to send.

The code

SQLite keeps it runnable anywhere; the idea is the same in Postgres or MySQL.

import json
import sqlite3
import uuid
from datetime import datetime, timezone

def now():
    return datetime.now(timezone.utc).isoformat()

def setup(con):
    con.executescript("""
    CREATE TABLE tickets (id TEXT PRIMARY KEY, priority TEXT);
    CREATE TABLE outbox (
        seq INTEGER PRIMARY KEY AUTOINCREMENT,
        event_id TEXT UNIQUE NOT NULL,
        payload TEXT NOT NULL,
        created_at TEXT NOT NULL,
        sent_at TEXT,
        attempts INTEGER NOT NULL DEFAULT 0,
        last_error TEXT
    );
    """)

def apply_decision(con, ticket_id, priority, model_ref):
    event = {
        "event_id": str(uuid.uuid4()),
        "type": "ticket_priority_set",
        "ticket_id": ticket_id,
        "priority": priority,
        "model_ref": model_ref,
    }
    with con:  # one transaction: both rows commit, or neither does
        con.execute("UPDATE tickets SET priority = ? WHERE id = ?",
                    (priority, ticket_id))
        con.execute(
            "INSERT INTO outbox (event_id, payload, created_at) "
            "VALUES (?, ?, ?)",
            (event["event_id"], json.dumps(event), now()))
    return event["event_id"]

def relay(con, send, batch=50):
    rows = con.execute(
        "SELECT seq, payload FROM outbox WHERE sent_at IS NULL "
        "ORDER BY seq LIMIT ?", (batch,)).fetchall()
    sent = 0
    for seq, payload in rows:
        try:
            send(json.loads(payload))  # receiver must dedupe on event_id
        except Exception as exc:
            with con:
                con.execute(
                    "UPDATE outbox SET attempts = attempts + 1, "
                    "last_error = ? WHERE seq = ?", (repr(exc)[:200], seq))
            break  # keep order: don't skip ahead of a failed event
        with con:
            con.execute(
                "UPDATE outbox SET sent_at = ?, attempts = attempts + 1 "
                "WHERE seq = ?", (now(), seq))
        sent += 1
    return sent

A few decisions in there are worth calling out.

One transaction, two rows. Python's sqlite3 connection context manager commits when the with body finishes and rolls back if it raises. The ticket update and the outbox insert either both land or both disappear.

The event ID is created once, in the handler. The relay can send the same event twice, for example if it crashes after the send but before marking the row. The outbox pattern accepts that, and the receiver has to be idempotent. A stable event_id is what lets it drop the repeat.

Failures stop the batch. If event 41 fails, the relay doesn't jump to 42. For decision records, order often matters: "set to high" followed by "reviewer lowered it" means something different in reverse.

Tests that pin the behavior

import sqlite3
import pytest
from outbox import setup, apply_decision, relay

@pytest.fixture
def con():
    c = sqlite3.connect(":memory:")
    setup(c)
    c.execute("INSERT INTO tickets VALUES ('t-7', NULL)")
    c.commit()
    return c

def test_rollback_drops_both_rows(con):
    con.execute("CREATE TRIGGER fail BEFORE INSERT ON outbox "
                "BEGIN SELECT RAISE(ABORT, 'disk full'); END")
    with pytest.raises(sqlite3.IntegrityError):
        apply_decision(con, "t-7", "high", "model-x@2026-10")
    assert con.execute("SELECT priority FROM tickets").fetchone() == (None,)
    assert con.execute("SELECT COUNT(*) FROM outbox").fetchone() == (0,)

def test_failed_send_is_retried_later(con):
    apply_decision(con, "t-7", "high", "model-x@2026-10")
    def down(event):
        raise TimeoutError("record service timed out")
    assert relay(con, down) == 0
    received = []
    assert relay(con, received.append) == 1
    assert received[0]["priority"] == "high"
    assert con.execute("SELECT attempts FROM outbox").fetchone() == (2,)

def test_resend_after_crash_keeps_event_id(con):
    event_id = apply_decision(con, "t-7", "high", "model-x@2026-10")
    seen = {}
    def crash_after_send(event):
        seen[event["event_id"]] = event
        raise ConnectionError("lost reply after send")
    relay(con, crash_after_send)
    relay(con, lambda e: seen.setdefault(e["event_id"], e))
    assert list(seen) == [event_id]

The first test makes the outbox insert fail and checks the ticket update rolled back too. The second simulates a timeout, then recovery. The third covers the awkward case: the receiver got the event, the relay never heard back, and the retry carries the same ID.

Running the relay

A loop calling relay() every few seconds is enough to start. Then:

  • Alert on the age of the oldest unsent row, not just on errors. A stuck relay is silent.
  • If you run more than one relay, make sure two don't send the same rows at once. A single worker is the simplest answer until you need more.
  • Prune sent rows on a schedule, or the table grows forever.
  • Keep prompt and customer text out of the payload where you can. The outbox is another copy of whatever you put in it.

Limits

  • The record is eventually consistent. For a few seconds, or longer during an outage, the ticket has changed and the record service doesn't know yet.
  • It guarantees the event is sent if the transaction commits. It doesn't make the receiver correct, and it doesn't capture anything you didn't put in the event.
  • At-least-once delivery means duplicates are normal. If the receiver can't dedupe, you'll see them.

Where this fits

We work on Obligra Verify, which is designed to retain the evidence your application selects. Our queue-based capture page covers the consumer side of this pattern: self-contained messages, an idempotent worker and reconciling uncertain outcomes before resubmitting.

This article was generated by an AI agent (Claude) for the Obligra Verify team and checked against the linked sources.

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.