Skip to content

fix(consumer): keep an in-flight message instead of dropping it as a duplicate - #7

Open
muhammetsafak wants to merge 4 commits into
mainfrom
fix/queue-in-flight-message-loss
Open

muhammetsafak wants to merge 4 commits into
mainfrom
fix/queue-in-flight-message-loss

Conversation

@muhammetsafak

@muhammetsafak muhammetsafak commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

With idempotency enabled, a redelivery whose key was claimed by a handler that had not finished was acknowledged and discarded as a duplicate. Two ways to lose the message followed:

  1. The first worker dies inside the handler. The redelivery arrives while the lease is held, is discarded, and the handler never completes for that message.
  2. The first handler outlives the transport's redelivery time, a second worker receives and discards the duplicate (on PDO that deletes the row), and the first handler then throws: its retry updates no row, so there is no retry and no dead letter.

Changes

  • New Contracts\CompletionAwareIdempotencyStore (extends IdempotencyStore) with isCompleted(string $key): bool. InMemoryIdempotencyStore implements it.
  • Dispatcher: when a claim fails and the store is completion-aware, a completed key is dropped as before; an in-flight key is released (job.released, reason in_flight) without counting an attempt, so waiting never walks a message to the dead-letter queue.
  • IdempotencyOptions::$inFlightDelaySeconds (optional last argument, default 5, must be >= 1) paces the re-check. Outcome::release() gets an optional $delaySeconds; the Worker passes it to the transport and pauses sleepWhenEmpty after a delayed release so RabbitMQ (no native delay) does not spin.
  • Docblocks corrected (forget() is called by the dispatcher; the contract lists forget()).
  • Docs rewritten (Idempotent-Consumption, README, Troubleshooting, Transport-PDO, FAQ, The-Worker, API-Reference, Core-Concepts, Retries) and CHANGELOG.md [Unreleased].

Compatibility (minor, 2.3.0)

IdempotencyStore and its signatures are unchanged. A custom store that implements only IdempotencyStore keeps the previous behaviour (any failed claim is dropped). Records written by 2.1/2.2 should be read as completed by isCompleted(); the upgrade notes are in docs/Idempotent-Consumption.md.

Not covered

A worker that finishes the handler and dies before remember() still runs the handler twice after the lease lapses, and a handler that outlives its lease can run concurrently. Both are documented. A claim that never lapses (leaseSeconds: 0) keeps its message waiting until forget().

Verification

  • composer validate --strict, php-cs-fixer fix --dry-run --diff, phpstan analyse, phpunit (118 tests) pass locally.
  • The new InFlightRedeliveryTest fails 7 of 10 tests when the dispatcher is made to drop in-flight keys again (both loss paths, on a real SQLite PdoTransport too).
  • A cross-process reproduction (real PdoTransport, shared lease-aware store, workers killed with SIGKILL) shows S1 and S4 ending LOST before and with the row kept (jobs=1, released) after.
  • wiki-sync.sh --check docs exits 0.

Update: transport fixes (review round 1)

The in-flight wait itself could lose or fork a message on some transports, so src/Transport/** is in scope:

  • RabbitMQ: release()/deadLetter() publish the new copy (waiting for the confirm when the channel is in confirm mode) before acking the original. A crash in between leaves a duplicate the dispatcher recognises, not a gap; a failed publish leaves the original unacked. basic_nack(requeue) was rejected because it puts the waiting message back at the head and blocks the queue behind it.
  • Redis: release(), deadLetter() and the delayed-set migration are Lua scripts and act only when the worker's LREM removed its own processing entry, so a reaped message is not forked into two copies.
  • PDO: release() is conditional on the reservation stamp, and a message put back unchanged no longer rewrites payload/attempts.
  • Worker: a deferral is not counted towards maxJobs/processedCount() and pauses at least 0.1 s.
  • Docs: PDO store recipe resets completed on takeover, rolling-upgrade notes (drain first), Redis reaper requirements, drain/maxJobs behaviour, API reference. Redis and RabbitMQ integration tests added (run in the existing Integration job; also run locally against redis:7 and rabbitmq:3.13).

Update: review round 2

  • PDO / Redis: a failure reported by a worker that no longer holds its message still counts. PDO records attempts/payload/back-off without touching the holder's reservation; Redis replaces the live copy (delayed set, then queue) instead of ignoring the call. A handler slower than retryAfter or the reaper still reaches maxAttempts and the dead-letter list, with idempotency on or off.
  • Redis: EVAL is optional. A client without it (an adapter limited to the documented commands, or no scripting permission) falls back to the same steps as separate commands; the docs state each path's guarantees.
  • RabbitMQ: in confirm mode a broker nack or returned copy requeues the original and throws instead of acking; the caller's own handlers keep running. Verified against a real broker with a reject-publish queue.

…duplicate

With idempotency enabled, a redelivery that found its key claimed by an
unfinished handler was acknowledged and discarded. If that handler's worker
had died the message was lost, and if the handler outlived the transport's
redelivery time and then threw, the discarded duplicate had already deleted
the PDO row, so the retry updated nothing.

Add CompletionAwareIdempotencyStore (extends IdempotencyStore, adds
isCompleted()). When the store implements it, the Dispatcher drops a
completed duplicate but releases an in-flight one without counting an
attempt, delayed by the new IdempotencyOptions::$inFlightDelaySeconds.
Outcome::release() gains an optional delay, which the Worker passes to the
transport and follows with a short pause so transports without native delay
do not spin. Stores that implement only IdempotencyStore keep the old
behaviour. Correct the forget() and contract docblocks and rewrite the
idempotent consumption docs.
Putting a message back to wait for another handler's in-flight key ran
through transport steps that could lose or fork it.

- AmqpTransport: publish the new copy (waiting for the broker confirm when
  the channel is in confirm mode) before acking the original, for both
  release() and deadLetter(). A crash in between leaves a duplicate the
  dispatcher recognises instead of nothing, and a failed publish leaves the
  original unacked. nack(requeue) was rejected: it would put the waiting
  message back at the head and block the queue behind it.
- RedisTransport: release(), deadLetter() and the delayed-set migration are
  Lua scripts, atomic, and act only when the worker's LREM removed its own
  processing entry, so a worker whose message a reaper already reclaimed no
  longer forks it into two copies.
- PdoTransport: release() updates only a row still held with the
  reservation stamp it wrote, and a message put back unchanged no longer
  rewrites payload or attempts.
- Worker: a deferral is not counted towards maxJobs or processedCount(),
  and pauses at least 0.1s even with sleepWhenEmpty 0.

Docs: the PDO store recipe resets completed on takeover, rolling-upgrade
notes, the reaper requirements on Redis, drain and maxJobs behaviour, and
the API reference for the idempotency types. Tests cover AMQP and Redis
with fixtures and against real brokers in the integration job.
…trust a nack

A failure reported by a worker that no longer holds its message was
dropped on PDO and Redis, so a handler slower than the reservation or the
reaper never reached maxAttempts, and the consume path started to need
EVAL. RabbitMQ in confirm mode acked the original after a broker nack.

- PdoTransport: a retry from a worker whose reservation was taken over
  records attempts, payload and back-off without touching the holder's
  reservation. attempts never moves back and an unchanged release never
  shortens a back-off.
- RedisTransport: a worker that lost its processing entry replaces the live
  copy (delayed set, then queue) instead of being ignored, for release and
  dead-letter, so attempts climb and maxAttempts ends the message without
  forking it. A client that cannot EVAL falls back to the same steps as
  separate commands; reserve, ack and publish never need scripting.
- AmqpTransport: a broker nack or returned copy requeues the original with
  basic_nack and throws QueueException instead of acking. The caller's own
  nack handler and return listener are wrapped and put back.

Docs state the guarantees of the scripted and command-by-command Redis
paths separately, the confirm-mode behaviour, and the PDO release rules.
When RabbitMQ nacked a republish, the original was requeued and the
worker took it straight back, re-running its handler in a tight loop
without counting an attempt or applying a back-off.

The worker now pauses after a process failure: the larger of 0.1s,
sleepWhenEmpty and the back-off for the message's next attempt, capped at
5s and taken in short slices that a stop signal ends at once. Attempts
cannot advance while the broker refuses the new copy; the RabbitMQ docs
state that limit and advise a separate channel for a handler's own
publishes. The Redis fallback now treats only NOPERM and unknown command
as "scripting unavailable".
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant