Who should retry a failed operation: one retry owner
Separate delivery, fetch, and persisted-work retries. A MySQL/InnoDB importer explains one attempt ledger, the commit boundary, and continuation without an unnecessary HTTP request.
An importer receives no response from its source. The HTTP client retries the request, the queue retries the message, and a separate scheduler sees an unfinished import and starts it again. Each mechanism looks useful on its own. Together, they leave an awkward question: who knows how many attempts have already happened and which part of the work actually needs repeating?
The problem becomes clearer after the response has been saved. If the data is already in the local database, a subsequent transformation error does not necessarily require another call to the source. Repeating the entire import may retrieve a different revision of the data and replace the work we were trying to finish.
Continue one article_demo on Symfony 8.1 and PHP 8.4+: RetryOwner imports one synthetic note in two phases with one attempt ledger in MySQL 8.4/InnoDB through native PDO. MockHttpClient supplies responses without contacting an external HTTP service. The shared MysqlLab creates a separate temporary schema for the experiment, leaving earlier application stores intact.
Name the responsibility before configuring retries
The word “retry” hides different events. Message delivery means a worker has received a signal. Receiving a response means an HTTP request has completed. Accepting work means we have saved enough state to continue it. None of these events automatically proves that the others have completed.
In this example, a message, if we added a queue, would merely remind the worker to inspect job_key. The MySQL row would remain the authoritative work state. It defines the phase, attempt limit, and next eligible execution time. Every additional wakeup reads this row; it does not create a retry calendar of its own.
| Responsibility | What determines the next action | What should not appear alongside it |
|---|---|---|
| Deliver a signal to the worker | Transport rules and acknowledgements | A conclusion that the business work has finished |
| Fetch and persist a response | The fetch_wait phase, its budget, and next_due |
An internal HTTP client retry loop |
| Process the persisted response | The apply_wait phase in the same ledger |
Another download caused by a local processing error |
| Complete a local change | A joint commit of the result and done |
A separate “success” record before the result is saved |
One retry owner does not mean a single attempt forever or one queue for every task. It means that a particular responsibility has one state that decides whether another attempt is allowed. Different operations may have different owners and budgets, but those owners must not independently schedule the same work.
A persisted response changes the continuation point
The order import-note-7 refers to note-7. The source returns two properties: note_id and title. After validating their shape, the example serializes them in a fixed order and saves that snapshot. Changing the phase to apply_wait happens in the same transaction.
Before this commit, we do not yet have an accepted response. After it, local processing must use the persisted data. If the source later changes its title, that does not overwrite the accepted snapshot. A new revision will require a new order under a separate product rule.
| State | Data in the ledger | Permitted next action |
|---|---|---|
fetch_wait |
Work identity, attempt count, next_due |
One request if it is due and budget remains |
apply_wait |
The same fields plus a fixed payload | Local processing without another HTTP request |
done |
Payload and completed local result | Return the known state |
failed |
Stop reason; the payload may be retained | Separate investigation, without automatically resetting counters |
Submitting the same job_key with the same note_id again does not reset the work. A different note_id under the same key is rejected. This is a narrow identity rule for our import. It does not replace a complete idempotency contract for every possible operation.
Phase selection in the teaching JobRunner begins with this read. It runs under the local worker lock, not against a row copied some time earlier:
$job = $this->store->job($key);
if (in_array($job['status'], ['done', 'failed'], true) || $now < $job['next_due']) {
return $job;
}
An extra wakeup before next_due downloads nothing and spends no attempt. A wakeup after done does not restart the action either. The decision comes from the work state, not from the mere arrival of a message.
Reserve the budget before the external action
We allow three fetch attempts in total: the initial attempt and two retries. Applying the snapshot gets two attempts. These small teaching limits make the behavior easy to follow; they should not be transferred to someone else’s API without examining its contract.
Before calling the HTTP client, the ledger increments fetch_attempts and records the next eligible time. The first two failed fetches use delays of one and two synthetic ticks. Local reprocessing waits one tick. The test supplies these ticks: they are not stopwatch readings and do not depend on sleep().
If a new retry deadline exceeds the model clock’s permitted horizon, reservation is rejected before changing the ledger or performing the action. Input outside the experiment’s time domain must not leave an unreachable next_due.
Reserving before acting has a cost. If execution is interrupted after the attempt is recorded but before the HTTP request starts, the budget has already decreased. The counter therefore means reserved attempts, not an exact count of HTTP calls to the source. MySQL connections are a separate interaction that this counter does not measure. This is a deliberate choice in the example, preventing an uncertain attempt from creating an unlimited supply of new ones.
The tests include an exception immediately after reservation. A subsequent call at the same tick must not start another request. Once the waiting interval ends, the next attempt may be used. If all three reservations have been exhausted, the ledger enters failed with attempt_budget_exhausted, even if no request actually started.
This reservation does not prove resilience to power loss. The example uses InnoDB transactions through PDO, whose boundaries are described in the PHP documentation. A separate migrator executes DDL before business transactions: MySQL DDL can cause an implicit commit. Runtime uses DML only and has no CREATE, ALTER, or DROP privileges. Server and storage behavior during crashes require separate experiments.
Failure before a response and failure after its commit
A synthetic transport error before headers leaves no payload. The ledger records transport and, if budget remains, keeps the fetch_wait phase. An incomplete response whose read is interrupted does not become an accepted snapshot either. Symfony supports simulating both cases with MockResponse.
A different scenario starts with a complete response. The payload and apply_wait have already been committed when a controlled checkpoint throws an exception. The next invocation opens a separate native PDO connection to the same MySQL schema and should continue with local processing. Its HTTP client has no prepared responses at all: any unnecessary download will break the scenario.
This checks continuation after an exception at a known commit boundary. There is no actual SIGKILL, broker, or lost network response from a database server. Connecting to MySQL does not itself test an unknown commit outcome: that scenario requires separate state inspection and a recovery protocol.
Why not return to the beginning “just in case”? Because the beginning has changed after the commit. We accepted a specific snapshot and are now responsible for processing it. Reading the source again mixes recovery of this work with the creation of new work.
The local result and completion share a boundary
In apply_wait, the example inserts one row into imported_notes and changes the job to done in a shared transaction. If a controlled ApplyFailure occurs after the insert but before commit, both changes roll back. A separate short transaction then records the retry reason; the reserved attempt remains spent.
InnoDB supports concurrent writers and row locks; REPEATABLE READ alone does not serialize the entire runner. The teaching runner serializes its invocations with an advisory flock on one local host. Every participant must use the same lock file. This is not a distributed lease or protection against a program that bypasses the protocol. Native lock-wait error 1205 and deadlock error 1213 do not become business retries: they propagate with rollback of the transaction owned by the code. The InnoDB documentation explains the rollback boundaries of different errors.
Schema errors, unexpected SQL exceptions, and a corrupt snapshot are not disguised as successfully scheduled retries. They propagate to the worker invocation. The ledger already contains the reservation, so an operator can inspect the phase in which the problem occurred; the example has no universal automatic repair mechanism.
If an exception occurs after the done commit, rereading should return the completed state without another insert. This extends the idea of an idempotent local result while adding a different decision: who owns the wait, and which phase should resume?
For an email, payment, or external API call, this transaction is insufficient. The remote effect is outside the MySQL commit. It needs an idempotency-key contract, a status check, or separate reconciliation of an unknown outcome; increasing the retry budget does not fix that boundary.
Where Messenger and HTTP retries fit
Symfony Messenger has its own retry rules after a handler exception. If the handler has already persisted the next attempt in the business ledger, throwing the same expected error again brings in another scheduler. In our model, a known failure ends the current invocation after the state is recorded; the ledger determines the next step.
This does not eliminate redelivery. The transport may deliver the signal again, and the worker must read job_key again. A future integration also needs a way to find overdue rows if a signal is lost. Such a scanner may wake the worker according to next_due, but should not maintain independent counters and its own queue of dates.
In Symfony 8.1, RecoverableMessageHandlingException defaults to forceRetry=true and bypasses max_retries. Passing forceRetry:false lets the configured retry strategy bound attempts. See forcing retries. This exercise connects no Messenger transport and does not present local calls as broker verification.
The HTTP layer can own retries too, if the operation is designed that way. In that case, the outer budget must account for every internal call. Here the gateway issues one request and does not wrap its client in RetryableHttpClient. That gives the ledger a single, clear unit of execution.
A 429 response, or any unsuccessful response carrying Retry-After, stops automatic processing with retry_after_requires_policy. Synthetic ticks cannot correctly apply a server date or delay. For a real source, that policy belongs with the same schedule owner; silently retrying before the permitted time is inappropriate.
Read the sequence before running it
The demonstration command is designed as a short history of one order. Its first HTTP call returns 503 without Retry-After; the second returns a valid note. The first local processing attempt throws a controlled exception before commit, and the second should complete.
| Tick | Event | Expected state after the invocation | Reserved fetch / apply |
|---|---|---|---|
| 0 | Synthetic 503 response | fetch_wait, next tick 1 |
1 / 0 |
| 0 | Extra early wakeup | Unchanged | 1 / 0 |
| 1 | Valid response persisted | apply_wait |
2 / 0 |
| 1 | Error after the local insert, before commit | apply_wait, insert rolled back |
2 / 1 |
| 2 | Processing the persisted snapshot | done, one note |
2 / 2 |
We expect two HTTP calls, one local result, and the title A small garden. After apply_wait appears, the scenario has no new HTTP responses. Acceptance criteria must check that absence of unnecessary effects alongside the final state.
The ledger/gateway and native Console checks through the Kernel cover early wakeups, budgets, replay after commit, local-result rollback, reconnecting to the same MySQL schema, and contention for the local lock. These checks use actual MySQL 8.4 with separate native PDO connections, not SQL emulation. MockHttpClient supplies the two HTTP attempts: there are no external provider calls, although connections to the MySQL server are real. This does not test a broker, power loss, or an unknown commit outcome.
Add module classes 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; the directory contains experiment artifacts, not a database file. MySQL requires the PDO_MYSQL driver and the shared guarded disposable fixture. App\Infrastructure\MysqlLab creates a temporary schema, and a separate migrator explicitly initializes InnoDB tables with FK/CHECK constraints before runtime DML. Identities use VARCHAR with utf8mb4_0900_bin; text payloads and titles use LONGTEXT. This is neither an atomic schema upgrade nor automatic data copying from the old SQLite database.
services:
App\Command\RetryDemoCommand: ~
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 through the shared guarded MySQL fixture. The wrapper supplies test-server configuration for MysqlLab, not credentials for an arbitrary runtime database:
php bin/console cache:clear --env=dev --no-debug
LAB_WORKSPACE="$(mktemp -d)"
bash fixtures/mysql_labs/run.sh php bin/console app:retry-owner-demo "$LAB_WORKSPACE/run" --env=dev --no-debug
When examining an importer of your own, start with one question: which persisted record is allowed to authorize the next attempt? Then trace its acceptance boundary, budget, and completion. When those decisions have one owner, an additional message remains a reason to read state instead of a reason to start the whole operation again.
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/RetryOwner