Handler idempotency: repeat the task without duplicating its result

Choose a business operation key and distinguish it from a delivery ID. A MySQL 8.4/InnoDB export example explains atomic receipts/results, payload conflicts, rollback, and replay after commit.

One business action should leave one predictable result.

Two tasks can have different message IDs and request the same action: export the same language revision of an article in the same format. If the handler treats every new message as new work, clicking the button again creates another result. Adjusting the retry count cannot fix this alone: the duplicate may have appeared before the worker ran for the first time.

The earlier outbox stored delivery intent with the data change. Now define how the handler recognizes a repeated business operation and returns its saved result.

Continue the same article_demo on Symfony 8.1 and PHP 8.4+: IdempotentExport defines business export identity and a receipt/result pair in a teaching MySQL 8.4 schema with InnoDB tables. The connection uses native PDO MySQL with emulated prepared statements disabled. The handler is called locally without adding a Messenger transport or external API.

The work repeats, not just the message

The Symfony Messenger documentation describes an ordinary cause of redelivery: a handler finishes its work, but the worker fails to acknowledge the message. The same need arises from submitting a form twice, when the messages were different from the start. A stable key must describe the business operation, not a random attempt ID.

Suppose an editor requests an export of the third revision of a note's English text. Delivering that request again does not create another export. A different format or the next revision is separate work. That choice is a rule of our product example, not a universal formula for idempotency.

Key component What it separates
Operation version export-v1 The semantics of producing a result
Site Independent identity spaces
Content ID Different pieces of content
Revision Different captured editions
Locale Different language texts
Format Plain text and JSON exports

The delivery ID is absent. The title and body are not key components either: they must match the revision already identified. If they change without a new revision, the handler needs an explicit conflict, not silent acceptance of another result.

Here is the method from the independent teaching class. Identifiers are validated beforehand: only lowercase Latin letters, digits, and hyphens are permitted, so a colon cannot silently change component boundaries.

<?php

declare(strict_types=1);

namespace App\IdempotentExport;

use InvalidArgumentException;

final readonly class ExportRequest
{
    public function __construct(
        public string $site,
        public string $contentId,
        public int $revision,
        public string $locale,
        public string $format,
        public string $title,
        public string $body,
    ) {
        foreach ([$site, $contentId] as $identifier) {
            if (preg_match('/\A[a-z][a-z0-9-]{0,63}\z/', $identifier) !== 1) {
                throw new InvalidArgumentException('Invalid synthetic identifier.');
            }
        }

        if ($revision < 1 || $revision > 2147483647) {
            throw new InvalidArgumentException('Revision is outside the teaching contract.');
        }

        if (!in_array($locale, ['uk', 'ru', 'en'], true) || !in_array($format, ['text', 'json'], true)) {
            throw new InvalidArgumentException('Unsupported locale or format.');
        }

        if (trim($title) === '' || strlen($title) > 500 || strpbrk($title, "\r\n") !== false
            || trim($body) === '' || strlen($body) > 100000
            || preg_match('//u', $title) !== 1 || preg_match('//u', $body) !== 1) {
            throw new InvalidArgumentException('Invalid UTF-8 title or body.');
        }
    }

    public function businessKey(): string
    {
        return implode(':', [
            'export-v1', $this->site, $this->contentId,
            (string) $this->revision, $this->locale, $this->format,
        ]);
    }

    public function payloadHash(): string
    {
        // Fixed field order is this lab's contract, not a general JSON canonicalizer.
        return hash('sha256', json_encode([
            'schema' => 1,
            'site' => $this->site,
            'content_id' => $this->contentId,
            'revision' => $this->revision,
            'locale' => $this->locale,
            'format' => $this->format,
            'title' => $this->title,
            'body' => $this->body,
        ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }

    public function render(): string
    {
        return $this->format === 'text'
            ? $this->title."\n\n".$this->body."\n"
            : json_encode(['title' => $this->title, 'body' => $this->body],
                JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)."\n";
    }
}

A “unique” key is unhelpful if every retry gets a new random component. Likewise, a key containing only Content ID is too broad: it blocks the next edition and a different locale. Two questions test the key's meaning: which requests must converge on one action, and which must remain separate actions?

One key does not permit replacing the input

Alongside the key, we store the SHA-256 of the serialized payload. Serialization uses a fixed order of known fields: schema version, site, Content ID, revision, locale, format, title, and body. This is the contract of this particular example, not a general canonicalization scheme for arbitrary JSON. The delivery identifier is excluded from the payload hash.

A repeat request has three distinct cases. No key exists: a result can be created. The key exists and the hash matches: return the saved result. The key exists but the hash differs: reject the conflict. The last case must not automatically become success merely because a row exists in the table.

Under this contract, even changing a space in the body without a new revision changes the payload. If a product needs normalization, its rules must be defined before hashing and kept stable. Quietly introducing normalization during a retry changes what “the same” means.

A hash helps detect a data change, but neither authorizes the action nor proves the data's origin. The handler receives prepared synthetic data; authentication, export permission, and access checks must precede this call in a real application.

The receipt and local result commit together

The result in our model is text in the exports table. This is a deliberately narrow boundary: both tables use InnoDB, so the result and the receipts record can belong to one MySQL transaction. Uploading a file to object storage or sending an email cannot simply replace the INSERT while preserving the same promise.

Two tables serve different roles. A receipt associates the business key with the payload hash. A result contains the finished bytes, their hash, and a stable result ID. Identities use VARCHAR with the utf8mb4_0900_bin collation; result text uses LONGTEXT. Business key uniqueness is enforced in both tables; a foreign key prevents a result from referencing a missing receipt, and CHECK constraints restrict hash lengths. Below is the explicit schema initializer, which accepts a separate migrator connection.

File fixtures/idempotent-export/export.sql:

CREATE TABLE receipts (
    business_key VARCHAR(158) NOT NULL PRIMARY KEY,
    payload_sha256 VARCHAR(64) NOT NULL,
    CONSTRAINT receipts_payload_hash_length CHECK (CHAR_LENGTH(payload_sha256) = 64)
) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin;

CREATE TABLE exports (
    result_id VARCHAR(71) NOT NULL PRIMARY KEY,
    business_key VARCHAR(158) NOT NULL UNIQUE,
    bytes LONGTEXT NOT NULL,
    content_sha256 VARCHAR(64) NOT NULL,
    CONSTRAINT exports_receipt_fk FOREIGN KEY (business_key) REFERENCES receipts (business_key),
    CONSTRAINT exports_content_hash_length CHECK (CHAR_LENGTH(content_sha256) = 64)
) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin;

Create the schema explicitly through a separate migrator before the business transaction; the runtime account performs DML only and has no CREATE/ALTER/DROP privileges. The PDO transaction manual explains commit/rollback, while the MySQL documentation explains implicit commits during DDL. This initializer is neither an atomic schema upgrade nor an automatic transfer of data from the old SQLite database. Our handler also refuses to run inside somebody else's active transaction: it must own the boundary it promises to complete.

After beginTransaction(), the first SQL action is an ordinary receipt INSERT. Only native duplicate-key error 1062 from this operation identifies a replay candidate. If a row is created, the handler adds the result and commits. If the key already exists, SELECT … FOR UPDATE reads the current saved pair even under InnoDB REPEATABLE READ and protects it while the payload hash and result integrity are checked. The handler returns the saved bytes themselves. Other SQL errors propagate; the handler rolls back its owned transaction if it remains active. The distinction between statement failure and transaction rollback is described in the InnoDB error-handling documentation.

There is no separate “has this finished?” SELECT before attempting the write. An initial SELECT alone would not reserve the key. The database constraint remains necessary even with an application check; it does not turn every failed write into a duplicate. Storage failure, locking, and a conflicting payload remain different reasons for an unsuccessful call.

After the effect, two boundaries remain distinct

“Failure after the effect” is insufficiently precise for a test. The INSERT may have run inside an unfinished transaction, or it may already have become visible after commit. In the first case there is something to roll back; in the second, a retry must find the completed result.

Controlled interruption point Receipts after the call ends Results Retry
After receipt INSERT, before the result 0 0 Creates the result
After result INSERT, before commit 0 0 Creates the result
After commit, before returning a response 1 1 Returns the saved result
Full completion followed by another delivery of the same work 1 1 Returns the saved result

These are expectations for the prepared scenarios. An exception at a checkpoint produces the interruption. It does not test forcibly terminating a process, disk failure, or loss of power. The retry check after commit opens a fresh PDO connection so that the outcome cannot depend on the previous handler instance's memory.

The checkpoint after commit sits outside the block that performs rollback. Otherwise, the error path would suggest that it could undo a result already committed. At this boundary the response can be lost, but the local pair already exists, and the client needs a retry using the same business identity.

An existing receipt without a result is also not treated as success. Separate scenarios delete the result or damage its bytes and expect rejection. This diagnoses a broken invariant; it does not defend against an administrator who can rewrite both the data and its hashes consistently.

Partial progress cannot always be rolled back

In this local model, intermediate records before commit must not appear as completed work to another connection. They disappear together on rollback. If a business workflow has several independent commits, that common boundary no longer exists: it must identify the completed step, the identity under which the step can be retried, and the response to an unknown outcome.

For example, an external service may accept a request while recording its response locally fails. A local receipt cannot undo somebody else's action. The next step depends on the service contract: repeat with a stable key it supports, query status by operation identity, or explicitly reconcile an ambiguous result. An arbitrary external call gains no exactly-once guarantee merely from a receipts table.

This also differs from an external version conflict. A rule that permits a write only against an expected revision protects against stale updates, but does not necessarily return the result of an action that already ran. Idempotency addresses repeating logical work; version checks address whether changing the current state is allowed. A product may need both mechanisms.

How to check the prepared example

Checks on actual MySQL 8.4 cover delivery ID versus business key, new revision/site/content/locale/format values, payload conflict, rollback, replay after commit, refused INSERT, a damaged receipt/result pair, and the Console command through the Kernel. Tests use the shared guarded MySQL fixture and App\Infrastructure\MysqlLab: the helper explicitly initializes the schema through a migrator, while handler operations and data assertions use runtime DML. Separate native PDO connections share one schema; replay after commit does not depend on the previous handler's memory. The conclusion concerns this local contract rather than an external API or disaster recovery.

A separate scenario holds a row lock in a transaction on another native connection to the same MySQL schema. A locking failure must not mark work complete; the same request is submitted again after the lock is released. Native lock wait timeout 1205 and deadlock 1213 errors do not become successful replays. The InnoDB documentation describes handling these errors; this scenario is not a throughput measurement for many workers. There is no automatic backoff here.

Add module classes and the MySQL schema fixture to the same application. Reuse SearchLab EvidenceDirectory; a trusted canonical parent must exist, while the target directory must not. The command preserves existing data and creates no second skeleton. Run it through the guarded MySQL wrapper introduced earlier: the module creates its own temporary teaching schema through MysqlLab and explicitly initializes it with a separate migrator before runtime DML. The output directory is not a database path; the wrapper is only for this isolated lab.

services:
    App\Command\ExportDemoCommand: ~

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 at a new absolute directory:

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

How long to remember a completed action

The example never clears receipts or results. Once they are deleted, an old request looks new again. Retention must therefore match the permitted retry horizon: queue delivery, manual reruns, and recovery of deferred tasks.

Changing the export algorithm also needs a decision. For the same key, the handler returns the saved result rather than promising to recompute it with new code. A new business operation can use a new key version; migrating old results must be explicit. Retries then remain predictable even after the application changes.

A useful handler contract starts with an understandable identity for the work, continues with the atomic boundary of the local effect, and ends with a response to a repeat request. If any part is undefined, a “processed” row in a table cannot explain whether the action finished or merely began.

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/IdempotentExport
  1. Databases The article was saved but the event was not sent: why use a transactional outbox
  2. Distribution Repeated Telegram updates: avoiding a repeated local action
  3. Platform Engineering Timeout after an external request: when the outcome is unknown
  4. Platform Engineering Two workers took one job: lease, expiry, and fencing