Invalidation after commit: what happens when a transaction rolls back?

Use MySQL 8.4/InnoDB and native PDO to persist invalidation intent with an article edit, check rollback and committed visibility, and retry delivery without another business revision.

An accepted change and its notification reach completion at different moments.

In a teaching journal, an editor changes a title. The application writes the value and clears the cache. A later step fails, and the database rolls back. What happened to the cache?

The consequence needs careful wording. Deleting an old entry does not itself cache nonexistent data. It can cause unnecessary rebuilding, however, and an unfortunate ordering of concurrent reads and writes can leave a stale result after a successful commit. Writing the new cached value before commit is more dangerous: readers may see a change the database ultimately rejects.

The database and cache are not one transaction

Assume the article edit and its revision record share a database transaction, while the cache is a separate store. Rolling back the database does not undo a cache deletion or write that has already happened.

Invalidation represents a decision: a new revision has been accepted, and previous reads need refreshing. That fact does not exist before the transaction succeeds. The simplest synchronous sequence is to begin, edit the article, record the revision, commit, and only then invalidate the relevant dependencies. An earlier failure rolls back without announcing an accepted change.

In Doctrine DBAL, Connection::transactional() can define this boundary, but a nested call using a savepoint does not establish the final commit of the outer transaction. See DBAL 4.5 transactions. The implementation below instead uses MySQL 8.4/InnoDB through native PDO with emulated prepares disabled: it calls beginTransaction(), commit() and, when necessary, rollBack() directly. Errors propagate after rollback of its own still-active transaction. The driver is covered in the PDO MySQL documentation.

For the teaching code, choose a simple rule: the edit opens its own outer transaction and rejects calls made inside another one. An application with a different composition must place completion with the transaction owner. A method name such as “after saving” does not establish this ordering by itself.

Failure is still possible after commit

A gap remains between committing the database and clearing the cache. The process can terminate, the network can fail, or the cache service can be unavailable. The new data persists while the derived result remains old.

This is not a rolled-back edit: commit has already happened. Blindly repeating the whole business operation could create another revision or repeat another side effect. Recovery should target the unfinished delivery of the change.

A more durable model stores an invalidation intent in the same transactional database as the article update. A separate handler reads that record and clears the cache. This does not make two stores atomic, but it leaves a recoverable record of work still to be completed.

A small model to reproduce

Continue the single Symfony 8.1 project, article_demo, on PHP 8.4+. Run commands from its root and preserve earlier routes, services and stores. The added modules use synthetic data and their own teaching context.

composer require symfony/cache:'8.1.*' doctrine/dbal:'4.5.*'

Below is the ArticleStore implementation, including explicit initialization of the teaching schema. Both tables use InnoDB; identities are VARCHAR(64) values compared using utf8mb4_0900_bin, and the title is LONGTEXT. A foreign key links each intent to its article, while CHECK constraints require positive revisions and restrict completed to 0 or 1. Call createSchema() before the business transaction through a separate migrator connection: it creates the tables and initial record, but is neither an atomic schema upgrade nor an automatic data migration from SQLite. MySQL DDL can cause an implicit commit; the runtime account has no CREATE, ALTER or DROP privileges.

<?php

declare(strict_types=1);

namespace App\AfterCommit;

/** One writer and one dispatcher in a local teaching lab, not a concurrent outbox. */
final class ArticleStore
{
    public function __construct(private \PDO $db)
    {
    }

    /** Explicit fixture initialization; never run DDL on the runtime connection. */
    public function createSchema(\PDO $migrator): void
    {
        if ($this->db->inTransaction() || $migrator->inTransaction()) {
            throw new \LogicException('Schema initialization must precede transactions.');
        }
        if ($migrator === $this->db) {
            throw new \LogicException('Schema initialization requires a separate migrator connection.');
        }

        $migrator->exec('CREATE TABLE article (
            id VARCHAR(64) NOT NULL PRIMARY KEY,
            title LONGTEXT NOT NULL,
            revision BIGINT NOT NULL,
            CONSTRAINT article_revision_positive CHECK (revision > 0)
        ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin');
        $migrator->exec('CREATE TABLE invalidation_intent (
            event_id VARCHAR(64) NOT NULL PRIMARY KEY,
            article_id VARCHAR(64) NOT NULL,
            revision BIGINT NOT NULL,
            completed TINYINT NOT NULL DEFAULT 0,
            CONSTRAINT intent_article_fk FOREIGN KEY (article_id) REFERENCES article (id),
            CONSTRAINT intent_revision_positive CHECK (revision > 0),
            CONSTRAINT intent_completed_boolean CHECK (completed IN (0, 1))
        ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin');
        $statement = $migrator->prepare('INSERT INTO article (id, title, revision) VALUES (?, ?, ?)');
        $statement->execute(['note-17', 'Old title', 1]);
    }

    public function edit(string $title, bool $failBeforeCommit = false, ?callable $observeBeforeCommit = null): int
    {
        if ($this->db->inTransaction()) {
            throw new \LogicException('The teaching operation must own the outer transaction.');
        }

        $this->db->beginTransaction();
        try {
            $value = $this->value('SELECT revision FROM article WHERE id = ?', ['note-17']);
            if ($value === false) {
                throw new \RuntimeException('Revision conflict');
            }
            $current = (int) $value;
            if ($current === PHP_INT_MAX) {
                throw new \OverflowException('Article revision exhausted');
            }
            $next = $current + 1;
            $statement = $this->db->prepare('UPDATE article SET title = ?, revision = ? WHERE id = ? AND revision = ?');
            $statement->execute([$title, $next, 'note-17', $current]);
            if ($statement->rowCount() !== 1) {
                throw new \RuntimeException('Revision conflict');
            }

            // Fixed article identity plus a signed BIGINT revision always fits VARCHAR(64).
            $statement = $this->db->prepare('INSERT INTO invalidation_intent (event_id, article_id, revision, completed) VALUES (?, ?, ?, ?)');
            $statement->execute(['note-17:revision:'.$next, 'note-17', $next, 0]);

            if ($observeBeforeCommit !== null) {
                $observeBeforeCommit();
            }
            if ($failBeforeCommit) {
                throw new \RuntimeException('Injected before-commit failure');
            }

            $this->db->commit();

            return $next;
        } catch (\Throwable $error) {
            if ($this->db->inTransaction()) {
                $this->db->rollBack();
            }
            throw $error;
        }
    }

    public function title(): string
    {
        return (string) $this->value('SELECT title FROM article WHERE id = ?', ['note-17']);
    }

    public function revision(): int
    {
        return (int) $this->value('SELECT revision FROM article WHERE id = ?', ['note-17']);
    }

    public function pendingCount(): int
    {
        return (int) $this->value('SELECT COUNT(*) FROM invalidation_intent WHERE completed = 0');
    }

    public function dispatch(callable $invalidate, bool $failAfterEffect = false): void
    {
        if ($this->db->inTransaction()) {
            throw new \LogicException('Dispatch must read committed work outside the business transaction.');
        }

        $statement = $this->db->prepare('SELECT event_id, article_id FROM invalidation_intent WHERE completed = 0 ORDER BY revision');
        $statement->execute();
        $rows = $statement->fetchAll(\PDO::FETCH_ASSOC);

        foreach ($rows as $row) {
            if ($invalidate($row['article_id']) !== true) {
                throw new \RuntimeException('Cache invalidation did not report success');
            }
            if ($failAfterEffect) {
                throw new \RuntimeException('Injected after-effect failure');
            }

            $acknowledge = $this->db->prepare('UPDATE invalidation_intent SET completed = 1 WHERE event_id = ? AND completed = 0');
            $acknowledge->execute([$row['event_id']]);
        }
    }

    private function value(string $sql, array $parameters = []): mixed
    {
        $statement = $this->db->prepare($sql);
        $statement->execute($parameters);

        return $statement->fetchColumn();
    }
}

Initially, article note-17 has title Old title and revision 1. One operation changes its title to New title, increments the revision to 2, and adds intent note-17:revision:2. All three changes share a transaction. The update condition includes the previous revision; anything other than exactly one changed row stops the operation. This protects the chosen model against an unnoticed conflict, rather than defining a universal concurrent-editing policy.

The dispatcher uses another connection, selects records where completed = 0, performs invalidation, and changes the flag to 1 only after success. In this exercise, the dependency follows from a fixed context and article_id. A category move would require the intent to retain old and new dependencies: the ID and revision alone cannot reconstruct the old category.

The MySQL integration check reproduces this sequence: after commit the cached card still contains the old title, and after invalidation delivery the read returns the new one. The cache uses TagAwareAdapter: tags associate a result with a dependency, and invalidateTags() invalidates it. The API is described in the Symfony Cache documentation. This checks a specific read, not the absence of every concurrency race.

A retry belongs to a specific effect

The intent contains a stable event identity and relevant dependencies, not an arbitrary clear-everything command. After success, the handler records delivery. Termination between clearing and acknowledgement may cause the same record to be processed again.

Repeated deletion of the same keys can usually be designed to be safe. That is not a proof of exactly-once execution of the entire workflow. The cache adapter's semantics, error handling, and separation between invalidation retry and article editing must be tested explicitly.

Someone may rebuild the card after the first invalidation. A second delivery can then cause another recomputation. Safe repetition preserves the meaning and boundaries of the operation, not zero additional cost. This model is limited to one writer and one dispatcher: completed does not claim work across several workers. Delivery has at-least-once semantics: failure after the effect but before acknowledgement leaves the intent available for repeated invalidation. Concurrent leases, retry schedules, and queue monitoring need separate design.

Four checks instead of one happy path

Scenario Expected teaching-model outcome
Failure before commit Old article remains; the handler cannot see the intent
Successful commit New revision and intent are accepted together
Cache unavailable after commit New article remains; intent awaits retry
Duplicate delivery No second business revision is created

Checking that invalidate() was called is insufficient. The tests use separate native PDO connections sharing a MySQL schema: before commit the reader sees the old article without the new intent; after commit it sees the accepted change and intent. A newly opened connection also reads the persisted intent. Checks cover rollback of both writes on a pre-commit failure, retention of the intent after a cache failure, repeated effects after lost acknowledgement, and skipping an already completed intent. An intent identity collision produces native MySQL error 1062; the exception propagates, and the earlier article update is rolled back with the owned transaction.

A failure during commit introduces uncertainty

The preceding cases distinguish an injected failure before commit from a confirmed successful commit. With a networked database, the connection may fail while confirmation is in progress. An exception alone does not establish whether the server accepted the transaction.

Blindly repeating the edit is then as risky as automatically declaring a rollback. Reconcile the state using a stable operation identifier and a chosen recovery policy. This exercise uses real MySQL, but its deliberate failures before commit and after the effect do not reproduce loss of network confirmation during commit. An intent identifier based on a revision does not make arbitrary retries of a business request idempotent.

Post-commit invalidation does not eliminate every race

A reader may start before the update and finish rebuilding afterwards. Correctly delivered invalidation does not prevent it from writing a stale value. That requires a separate cache-version or generation contract and a concurrent test.

The acceptable delay between commit and projection refresh must also be defined. A title may tolerate some delay. Revoking access cannot rely solely on a future cache clear: authorization must remain effective at read time.

The outcome is not a promise of instant consistency. It is a clear distinction between two facts: the data was accepted, and derived results were refreshed. Until the second becomes true, delivery needs a visible, bounded, recoverable path.

Add the module to the same application

src/AfterCommit/FixtureConnection.php obtains a runtime PDO connection from the shared App\Infrastructure\MysqlLab; ArticleStore owns the transactional operation and dispatcher. Use the guarded disposable MySQL fixture already introduced and its fixtures/mysql_labs/run.sh wrapper. PHP needs the pdo_mysql driver. The command creates its own temporary schema through MysqlLab::create('after_commit'), explicitly initializes it with a separate migrator, and cleans it up through close() in finally. Tests likewise explicitly prepare the schema with the migrator and perform assertions through runtime connections. The wrapper configures the fixture server and access only for lab runs; this module does not change the earlier articles’ stores.

The following extends the existing services block in config/services.yaml. Preserve earlier registrations, imports and _defaults; keep the rest of the file.

services:
    App\Command\AfterCommitDemoCommand: ~

The app:after-commit-demo command demonstrates a persisted intent and delivery retry after lost acknowledgement: its callback counts effect executions instead of using a cache. The command creates no cache and does not check a card read through TagAwareAdapter. ArticleStoreTest::testCommittedIntentInvalidatesRealSymfonyCachedRead() in tests/AfterCommit/ArticleStoreTest.php performs that check: after commit the read still returns Old title, while dispatching invalidation makes it return Committed title and leaves no pending intent.

bash fixtures/mysql_labs/run.sh php bin/console app:after-commit-demo
APP_ENV=test bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/AfterCommit/ArticleStoreTest.php

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.

File src/AfterCommit/FixtureConnection.php:

<?php

declare(strict_types=1);

namespace App\AfterCommit;

use App\Infrastructure\MysqlLab;

/** Explicit synthetic CLI/test storage; never uses the application's Notes connection. */
final class FixtureConnection
{
    public static function connect(MysqlLab $lab): \PDO
    {
        return $lab->runtime();
    }
}

File src/Command/AfterCommitDemoCommand.php:

<?php

declare(strict_types=1);

namespace App\Command;

use App\AfterCommit\ArticleStore;
use App\AfterCommit\FixtureConnection;
use App\Infrastructure\MysqlLab;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(name: 'app:after-commit-demo', description: 'Run an isolated MySQL intent and retry exercise')]
final class AfterCommitDemoCommand extends Command
{
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $lab = MysqlLab::create('after_commit');
        try {
            $db = FixtureConnection::connect($lab);
            $store = new ArticleStore($db);
            $store->createSchema($lab->migrator());
            $store->edit('Committed title');
            $effects = 0;
            $invalidate = static function (string $article) use (&$effects): bool {
                ++$effects;

                return true;
            };

            try {
                $store->dispatch($invalidate, true);
            } catch (\RuntimeException $error) {
                if ($error->getMessage() !== 'Injected after-effect failure') {
                    throw $error;
                }
                // Only the deliberate loss after effect and before acknowledgement is expected.
            }

            $pending = $store->pendingCount();
            $store->dispatch($invalidate);
            $result = ['title' => $store->title(), 'revision' => $store->revision(), 'pending_after_failure' => $pending,
                'pending_after_retry' => $store->pendingCount(), 'effects' => $effects, 'scope' => 'one_writer_one_dispatcher'];
        } finally {
            $lab->close();
        }
        $output->writeln(json_encode($result, JSON_THROW_ON_ERROR));

        return $pending === 1 && $result['pending_after_retry'] === 0 && $effects === 2
            ? Command::SUCCESS : Command::FAILURE;
    }
}

Check the current example against an owned disposable MySQL schema:

  1. Symfony Core One business operation, one transaction: saving a note with its tags
  2. Caching An article changed: which cached results are now stale?
  3. Databases The article was saved but the event was not sent: why use a transactional outbox
  4. Databases Handler idempotency: repeat the task without duplicating its result