The article was saved but the event was not sent: why use a transactional outbox

Record an article and delivery intent in one MySQL 8.4/InnoDB transaction: stable identity, a captured payload, a relay after commit, and a separate receiver’s local idempotency.

A recorded intent connects a data change with later delivery.

An editor clicks “Publish”. The article record has already been saved, but the process stops before passing the event to the search service. When the application returns, the article exists and search knows nothing about it. Simply repeating the HTTP request is ambiguous too: it might create another event or change the article again. The problem begins at the boundary between two separate actions, even when each action works correctly.

A transactional outbox puts the intent to notify a consumer into the same transaction that changes application data. External delivery happens later. This separation is described in the AWS pattern; duplicate deliveries remain possible.

Add the teaching model to one article_demo on Symfony 8.1 and PHP 8.4+ as TransactionalOutbox. The writer and local receiver use separate native PDO connections to MySQL 8.4 and their own temporary InnoDB schemas. The existing Notes store remains. These are two independent commit boundaries without a real broker or external effect.

What must survive the end of a request

The teaching model has an article about a small garden, its revision, and a publication event. The writer schema contains two tables: the article's current state and the outbox. A separate schema belongs to a local model of the consumer. Its connection and transaction are separate from the writer's, keeping two independent commit boundaries from disappearing behind one convenient connection.

The intent contains a stable event_id and a completed payload. The operation owner must retain this ID for retries; a new random value on every retry would mean a new event. An identical ID with the same payload returns the recorded intent. An identical ID with a different title is rejected instead of silently repairing the old record.

Event identity does not replace an article revision. A new edit has the next revision and a new ID. The example allows one writer; checking the next revision explains the sequence of changes without claiming a complete concurrent editing mechanism. Naming a table does not create these rules: they need to be defined before the first retry.

This also affects the editor's response. After the writer commits, the application can confirm that the article and intent were saved, but not yet that the article appears in search. If the HTTP response is lost, the client needs to resolve the result using the same operation identity. A later delivery failure must not masquerade as a rollback of the saved article. These are two distinct interface states, even when the happy path usually looks like one instantaneous action.

One transaction for state and intent

We explicitly create the schema through a separate migrator connection before the application transaction. The runtime account performs DML only and has no CREATE, ALTER, or DROP privileges. The same native PDO connection then changes the article and inserts the intent between beginTransaction() and commit(). If a write fails, the service rolls back its own active transaction and propagates the error. The PDO manual explains transaction boundaries; MySQL DDL can cause an implicit commit. This initialization is neither an atomic schema upgrade nor an automatic copy of data from the old SQLite store.

Explicit initialization prepares InnoDB tables for the article, outbox, receipts, and local effects. Identifiers use VARCHAR with utf8mb4_0900_bin, while titles and payloads use LONGTEXT; foreign keys and CHECK constraints restrict relationships and allowed values. Creating tables and triggers belongs to the migrator, not runtime service constructors.

File fixtures/transactional-outbox/article.sql:

CREATE TABLE IF NOT EXISTS article (
    article_id VARCHAR(64) NOT NULL PRIMARY KEY,
    revision BIGINT NOT NULL CHECK (revision > 0),
    title LONGTEXT NOT NULL
) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin;

File fixtures/transactional-outbox/outbox.sql:

CREATE TABLE IF NOT EXISTS outbox (
    sequence BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    event_id VARCHAR(64) NOT NULL UNIQUE,
    article_id VARCHAR(64) NOT NULL,
    revision BIGINT NOT NULL CHECK (revision > 0),
    payload LONGTEXT NOT NULL,
    delivered TINYINT NOT NULL DEFAULT 0 CHECK (delivered IN (0, 1)),
    UNIQUE (article_id, revision),
    FOREIGN KEY (article_id) REFERENCES article (article_id)
) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin;

CREATE TRIGGER IF NOT EXISTS outbox_intent_is_immutable
BEFORE UPDATE ON outbox
FOR EACH ROW
BEGIN
    IF NOT (BINARY NEW.event_id <=> BINARY OLD.event_id)
        OR NOT (BINARY NEW.article_id <=> BINARY OLD.article_id)
        OR NOT (NEW.revision <=> OLD.revision)
        OR NOT (BINARY NEW.payload <=> BINARY OLD.payload) THEN
        SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'immutable outbox intent';
    END IF;
END;

File fixtures/transactional-outbox/receiver.sql:

CREATE TABLE IF NOT EXISTS receipt (
    event_id VARCHAR(64) NOT NULL PRIMARY KEY,
    payload LONGTEXT NOT NULL,
    accepted_calls BIGINT NOT NULL CHECK (accepted_calls > 0)
) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin;

CREATE TABLE IF NOT EXISTS local_effect (
    event_id VARCHAR(64) NOT NULL PRIMARY KEY,
    article_id VARCHAR(64) NOT NULL,
    revision BIGINT NOT NULL CHECK (revision > 0),
    title LONGTEXT NOT NULL,
    FOREIGN KEY (event_id) REFERENCES receipt (event_id)
) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin;

The unique article-and-revision pair adds a constraint alongside the stable ID. A MySQL trigger rejects changes to the identity and payload of an existing intent using SIGNAL SQLSTATE '45000'. This is a local model rule, not protection against an administrator who can change the schema itself.

A separate native PDO connection to the same schema checks that the uncommitted pair of records is invisible to another reader. Under InnoDB REPEATABLE READ, a new read after commit must account for its own snapshot boundary: an already-open reader transaction may retain the earlier snapshot. Checking through the writer connection would be weaker: it already sees its own intermediate changes.

The service refuses to run inside someone else's active transaction. Otherwise, its commit() might finish more work than the method promises, while its rollback might undo another change. The MySQL implicit-commit rules matter here too: transactions do not nest, and a new START TRANSACTION can end the current one. We do not introduce a hidden SAVEPOINT protocol here.

An event describes a captured revision

While the relay was stopped, the author might have changed the title again. If delivery rereads the current article, an old event suddenly starts describing a new state. The payload is therefore created while recording the first revision and stored alongside it.

In this model, it contains a schema version, event type, article ID, revision, and title. This is a small explicit field set, not serialization of the entire object. Internal editorial notes and incidental extra properties should not become a message because an ORM model changes.

The schema version describes the message shape separately from the article revision. The local consumer accepts only the known structure and the producer's exact serialization. An unknown contract must not be marked delivered merely because its JSON could be parsed. The intent remains pending until the problem is resolved. Rewriting its payload retrospectively would conceal what the writer originally committed, so a contract change requires an explicit decision.

This choice fits an event meaning “a particular revision was published”. A different task could send only a signal meaning “reread the current state”, but its contract should say precisely that. Mixing the two meanings makes replay unpredictable: the same identity begins to carry different facts.

The relay runs after commit

One relay is enough for the first example. It reads the oldest unmarked intent, finishes the read, passes the stored payload to the consumer, and only then sets delivered = 1. No writer transaction is held while calling the consumer.

<?php

declare(strict_types=1);

namespace App\TransactionalOutbox;

use Closure;
use LogicException;
use PDO;
use RuntimeException;
use Throwable;

final class OutboxRelay
{
    public function __construct(private readonly PDO $db, private readonly Receiver $receiver)
    {
    }

    public function dispatchOne(?Closure $afterAccept = null): bool
    {
        if ($this->db->inTransaction()) {
            throw new LogicException('Delivery must start outside a writer transaction.');
        }

        $query = $this->db->query('SELECT event_id, payload FROM outbox WHERE delivered = 0 ORDER BY sequence LIMIT 1');
        $row = $query->fetch();
        $query->closeCursor();

        if ($row === false) {
            return false;
        }

        $this->receiver->accept($row['event_id'], $row['payload']);
        $afterAccept?->__invoke();

        $this->db->beginTransaction();

        try {
            $mark = $this->db->prepare('UPDATE outbox SET delivered = 1 WHERE event_id = ? AND delivered = 0');
            $mark->execute([$row['event_id']]);

            if ($mark->rowCount() !== 1) {
                throw new RuntimeException('Unexpected marker state; this lab permits one relay.');
            }

            $this->db->commit();
        } catch (Throwable $error) {
            if ($this->db->inTransaction()) {
                $this->db->rollBack();
            }

            throw $error;
        }

        return true;
    }
}

Returning from accept() means only that the local receiver has completed its contract. A real adapter needs a separate definition of acknowledgement: broker acceptance, a consumer record, or completion of a particular effect. The delivered marker must not promise more than that acknowledgement.

Ordering by sequence describes this relay's sequential traversal. It is not a global order across several services. Concurrent workers would require a separate protocol for claiming work, reclaiming it, and managing order; a SELECT with LIMIT alone is insufficient.

Where ambiguity remains

The table defines controlled interruption boundaries. Accepted calls count calls that the local receiver committed in its own database rather than every possible network attempt.

Scenario boundary Pending intent Accepted calls Local effects
Interruption before the writer commit 0 0 0
Interruption after commit, before the receiver 1 0 0
The receiver refuses before its own write 1 0 0
The receiver commits, but the marker is still absent 1 1 1
A retry after the preceding case 0 2 1
Normal completion without a retry 0 1 1

The hardest boundary comes after the consumer's effect but before the local marker. The writer cannot undo another system's commit. Treating an unknown outcome as success can lose a delivery; retrying can give the consumer a duplicate. The outbox preserves a reason to retry without removing that uncertainty.

The teaching receiver has its own receipt keyed by event_id. Its receipt and local effect are written in one InnoDB transaction in a separate schema through its own connection. A retry increments accepted_calls, checks the same payload, and creates no additional effect. The receiver itself supplies this local idempotency; it does not turn two commits into one shared transaction.

Calling a third-party API instead of performing the local INSERT would not bring that API's action into the receiver's transaction. It needs its own replay contract. The example sends no emails, Telegram messages, or requests to an external broker, and does not establish that their effects happen only once.

An independent lab with explicit limits

Checks on actual MySQL 8.4 cover rollback between writes, refused intent INSERT, replay after commit, identity conflict, captured old payload, receiver failure, and marker failure, as well as the Console command through the Kernel. Separate native connections check data visibility, and replay after the receiver commits without a marker produces two accepted calls and one local effect. Test setup performs explicit migration through the helper; runtime assertions use DML. An ordinary checkpoint exception establishes neither process-death resilience, power-loss resilience, nor disk recovery.

Add module classes and SQL fixtures to the same application. Reuse SearchLab EvidenceDirectory for run artifacts, not database files; a trusted canonical parent must exist, while the target directory must not. The shared App\Infrastructure\MysqlLab creates owned temporary schemas on the guarded disposable MySQL fixture, runs DDL through the migrator, and supplies runtime connections with DML privileges only. The command preserves existing artifacts and creates no second skeleton; these lab schemas are not intended for existing application data.

services:
    App\Command\OutboxDemoCommand: ~

Add new entries under the existing services block, preserving earlier services and routes. After wiring, explicitly clear the dev no-debug cache: this is the runtime variant used by the CLI check. From the same article_demo root, run the command through the shared guarded fixture wrapper, passing a new absolute artifact directory. The wrapper selects the lab MySQL server; the directory path is not a DSN and supplies no credentials:

php bin/console cache:clear --env=dev --no-debug
LAB_WORKSPACE="$(mktemp -d)"
bash fixtures/mysql_labs/run.sh php bin/console app:outbox-demo "$LAB_WORKSPACE/run" --env=dev --no-debug

What must accompany an intent

Completed records are retained here. Detecting a repeated publication and the receiver's receipt both depend on them. A real application's cleanup policy must account for the permitted replay window; mechanically deleting rows changes the guarantee.

Likewise, a pending intent does not mean that a worker will eventually read it. Queue-age observation, retry rules, and a decision about permanent failure are needed. In the sequential model, a failed first intent holds up the following ones: a visible trade-off, not an implicit promise of continuous progress.

Start the design with three concrete answers: which state and intent commit together, what the consumer's acknowledgement means, and how it recognizes a retry. The outbox then becomes an understandable contract between data recording and delivery, rather than just another table backed by hope that a retry succeeds.

The shared MySQL fixture and its files are introduced in the transaction chapter. Run commands from the single article_demo root; do not create a separate Symfony application for each article.

Check the current example against an owned disposable MySQL schema:

bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/TransactionalOutbox
  1. Symfony Core One business operation, one transaction: saving a note with its tags
  2. Caching Invalidation after commit: what happens when a transaction rolls back?
  3. Databases Handler idempotency: repeat the task without duplicating its result
  4. Platform Engineering Timeout after an external request: when the outcome is unknown