From 661026c85b9293fffed8d3f3e66f49c78ef85f4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammet=20=C5=9Eafak?= Date: Mon, 23 Nov 2026 10:04:11 +0300 Subject: [PATCH 1/2] docs: describe idempotent consumption without overstating its guarantees An in-flight claim is treated like a recorded key, so a redelivery that arrives while a dead worker's claim is held is acknowledged and discarded. Document that loss window, the double run after a crash before remember(), and how leaseSeconds relates to each transport's redelivery time. Also drop the at-most-once and no-message-is-lost wording, scope the keyResolver example by URN and return a string, correct the claim about messages without an identity, and explain how a PDO store frees an expired lease. --- README.md | 95 +++++++++++++++++++---- docs/Core-Concepts.md | 5 +- docs/FAQ.md | 7 +- docs/Idempotent-Consumption.md | 129 +++++++++++++++++++++++++++---- docs/Retries-and-Dead-Letters.md | 5 +- docs/The-Worker.md | 2 +- docs/Transport-PDO.md | 10 ++- docs/Troubleshooting.md | 9 +++ 8 files changed, 218 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index 12ead32..0109c1d 100644 --- a/README.md +++ b/README.md @@ -158,15 +158,16 @@ new WorkerOptions( ); ``` -Delivery is **at-least-once** — make handlers idempotent, or let the worker do -it for you (see below). +Delivery is **at-least-once** — make handlers idempotent. The dispatcher's +optional deduplication (see below) can skip some redeliveries, but it does not +replace an idempotent handler. ## Idempotent consumption Because delivery is at-least-once, a transport may hand the same message to a worker more than once (after a crash before the ack, a lapsed reservation, or a -broker hiccup). The dispatcher can dedupe these redeliveries so a message is -processed **at most once** — opt in by giving it an `IdempotencyOptions`: +broker hiccup). The dispatcher can skip such a redelivery instead of running the +handler again — opt in by giving it an `IdempotencyOptions`: ```php use InitPHP\Queue\Consumer\Dispatcher; @@ -182,12 +183,55 @@ $dispatcher = new Dispatcher( With no options (the default) deduplication is off and the dispatcher behaves exactly as before — this is fully backward-compatible. +> **Deduplication is not exactly-once delivery and does not replace an idempotent +> handler.** It can discard a message whose handler never completed, and it can +> still run a handler twice. Read "What deduplication does not guarantee" below. + **How it dedupes.** Before running a handler the dispatcher derives a stable -dedup key from the message and *claims* it; a key that is already recorded means -the message was processed before, so the handler is skipped and the message is -acknowledged and discarded. The key is **only recorded after the handler -succeeds** — a handler that throws leaves the key free, so the at-least-once -redelivery is retried as normal. +dedup key from the message and *claims* it in the store, holding the claim under a +lease (`leaseSeconds`). If the claim succeeds the handler runs; when it returns, +the key is **recorded** (`remember()`, kept for `ttl` seconds); when it throws, +the claim is released, so the normal retry runs it again. + +If the claim fails, the dispatcher skips the handler and acknowledges the message, +which discards it (the worker logs `job.dropped` with reason `duplicate`). A +failed claim means one of two things, and the dispatcher cannot tell them apart: + +- the key was **recorded**: the message was handled before, so discarding it is + right; or +- the key is **claimed but not recorded**: another worker is still inside the + handler, or died inside it and its lease has not expired yet. Discarding the + message here means the handler may never complete for it. + +The second case is the one to understand before you turn this on — see +[What deduplication does not guarantee](#what-deduplication-does-not-guarantee). + +### What deduplication does not guarantee + +The dispatcher treats a claimed-but-unrecorded key (a handler still running, or +one whose worker died) the same as a recorded one: it acknowledges and discards +the message. So: + +1. **A message can be lost.** A worker claims the key and dies inside the handler; + the transport redelivers; the claim is still held, so the redelivery is + discarded and the handler never completes. With the defaults + (`leaseSeconds: 300`) on a `PdoTransport` (`retryAfter: 90`) this is exactly + what happens, and on RabbitMQ a closed connection redelivers immediately. +2. **A handler can still run twice.** A worker that dies after the handler but + before `remember()` leaves no record; once the lease lapses the redelivery runs + the handler again. This is not "at most once". +3. **A failed attempt can lose its retry.** If a handler outlives the transport's + redelivery time, the duplicate is discarded; on PDO that deletes the row, so + when the first handler throws there is no row left to retry. + +Set `leaseSeconds` **above your slowest handler** and **below the time the +transport takes to redeliver a dead worker's message** (PDO: below `retryAfter`; +Redis: below your reaper's delay; RabbitMQ: no safe value). If no value fits, +leave deduplication off and rely on an idempotent handler. The details and the +per-transport table are in the +[full guide](docs/Idempotent-Consumption.md#choosing-leaseseconds). + +### Message keys The key is derived, in order, from: @@ -195,16 +239,23 @@ The key is derived, in order, from: 2. the producer-minted **`meta.id`** (the canonical message identity), else 3. the **`trace_id`**. -A message with none of these has no stable identity and is processed without -deduplication. +A resolver result counts only when it is a **non-empty string**; anything else +(`null`, `''`, an `int` order id) falls back to `meta.id`. A store is shared by +every URN and keys are not scoped by it, so scope the key yourself: ```php +use InitPHP\Queue\Message\ReceivedMessage; + new IdempotencyOptions( store: $store, keyPrefix: 'bq:idemp:', // namespaces keys in a shared store ttl: 86_400, // seconds a processed key is retained (null = forever) - leaseSeconds: 300, // in-flight claim lease (frees a crashed worker's claim) - keyResolver: fn ($m) => $m->getData()['order_id'] ?? null, // optional + leaseSeconds: 60, // in-flight claim lease; see the notes above + keyResolver: static function (ReceivedMessage $message): ?string { + $orderId = $message->getData()['order_id'] ?? null; + + return $orderId === null ? null : $message->getUrn() . ':' . $orderId; + }, ); ``` @@ -231,7 +282,8 @@ final class RedisIdempotencyStore implements IdempotencyStore public function claim(string $key, int $leaseSeconds = 0): bool { - // Atomic test-and-set: only the first caller wins the claim. + // Atomic test-and-set: only the first caller wins the claim. With EX the + // claim lapses on its own; without it (leaseSeconds 0) it never does. $options = ['NX']; if ($leaseSeconds > 0) { $options['EX'] = $leaseSeconds; @@ -254,9 +306,18 @@ final class RedisIdempotencyStore implements IdempotencyStore } ``` -A PDO-backed store works the same way: `claim()` is an `INSERT` that fails on a -unique `key` column (caught and reported as `false`), `remember()` upserts the -row, and a `processed_at`/`expires_at` column drives the TTL. +A PDO-backed store needs one more step than the Redis one, because a unique +constraint does not expire rows by itself. Redis `EX` frees a lapsed claim on its +own; with a table, `claim()` must free it explicitly or a dead worker's key stays +blocked and every redelivery is discarded. In a transaction, first remove the row +if its lease has lapsed (`DELETE FROM idempotency WHERE dedup_key = ? AND expires_at <= ?`), +then `INSERT` it with `expires_at = now + leaseSeconds` and report `true` only +when the insert affected a row (a unique-key violation means `false`). The same +effect in one statement is `INSERT … ON CONFLICT (dedup_key) DO UPDATE SET expires_at = +excluded.expires_at WHERE idempotency.expires_at <= ?` (SQLite and PostgreSQL), +again checking the affected-row count. `remember()` upserts the row with +`expires_at = now + ttl` (or `NULL` to keep it), `forget()` deletes it, and +`seen()` ignores rows whose `expires_at` has passed. Full guide: [docs/Idempotent-Consumption.md](docs/Idempotent-Consumption.md). diff --git a/docs/Core-Concepts.md b/docs/Core-Concepts.md index ae99da0..ab1a085 100644 --- a/docs/Core-Concepts.md +++ b/docs/Core-Concepts.md @@ -92,8 +92,9 @@ queue **polyglot** — see [Interoperability](Interoperability.md). Delivery is **at-least-once**. A message reserved by a worker that then crashes becomes reservable again (the PDO visibility timeout; the Redis processing list). A handler may therefore run more than once for the same message, so **handlers -must be idempotent** — or let the dispatcher dedupe redeliveries, see -[Idempotent Consumption](Idempotent-Consumption.md). +must be idempotent**. The dispatcher's optional deduplication can skip some +redeliveries but does not replace that, and it has a message-loss window of its +own — see [Idempotent Consumption](Idempotent-Consumption.md#what-deduplication-does-not-guarantee). ## Error handling diff --git a/docs/FAQ.md b/docs/FAQ.md index 4c62859..43d3eb5 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -46,9 +46,10 @@ installed. See [Retries & Dead-Letters](Retries-and-Dead-Letters.md). ### Is delivery exactly-once? No — it is **at-least-once**. A message can be delivered more than once (e.g. a -worker crashes after handling but before acking). Make handlers **idempotent**, -or turn on the dispatcher's deduplication — see -[Idempotent Consumption](Idempotent-Consumption.md). +worker crashes after handling but before acking). Make handlers **idempotent**. +The dispatcher's optional deduplication can skip some redeliveries, but it is not +a substitute: it can also discard a message whose handler never completed — see +[Idempotent Consumption](Idempotent-Consumption.md#what-deduplication-does-not-guarantee). ### Can a Go / Python / Node service consume what PHP produces (and vice-versa)? diff --git a/docs/Idempotent-Consumption.md b/docs/Idempotent-Consumption.md index 575df90..8a0c515 100644 --- a/docs/Idempotent-Consumption.md +++ b/docs/Idempotent-Consumption.md @@ -1,9 +1,9 @@ # Idempotent Consumption -Because delivery is at-least-once, a transport may hand the same message to a -worker more than once (after a crash before the ack, a lapsed reservation, or a -broker hiccup). The dispatcher can dedupe these redeliveries so a message is -processed **at most once** — opt in by giving it an `IdempotencyOptions`: +Delivery is at-least-once, so a transport may hand the same message to a worker +more than once (after a crash before the ack, a lapsed reservation, or a broker +hiccup). The dispatcher can skip such a redelivery instead of running the handler +again — opt in by giving it an `IdempotencyOptions`: ```php use InitPHP\Queue\Consumer\Dispatcher; @@ -19,12 +19,77 @@ $dispatcher = new Dispatcher( With no options (the default) deduplication is off and the dispatcher behaves exactly as before — this is fully backward-compatible. +> **Deduplication is not exactly-once delivery, and it is not a replacement for an +> idempotent handler.** It removes some redundant executions; it can also discard +> a message whose handler never completed, and it can still run a handler twice. +> Read [What deduplication does not guarantee](#what-deduplication-does-not-guarantee) +> before enabling it. + **How it dedupes.** Before running a handler the dispatcher derives a stable -dedup key from the message and *claims* it; a key that is already recorded means -the message was processed before, so the handler is skipped and the message is -acknowledged and discarded. The key is **only recorded after the handler -succeeds** — a handler that throws leaves the key free, so the at-least-once -redelivery is retried as normal. +dedup key from the message and *claims* it in the store, holding the claim under a +lease (`leaseSeconds`). If the claim succeeds the handler runs; when it returns, +the key is **recorded** (`remember()`, kept for `ttl` seconds); when it throws, +the claim is released, so the normal retry runs it again. + +If the claim fails, the dispatcher skips the handler and acknowledges the message, +which discards it (the worker logs `job.dropped` with reason `duplicate`). A +failed claim means one of two things, and the dispatcher cannot tell them apart: + +- the key was **recorded**: the message was handled before, so discarding it is + right; or +- the key is **claimed but not recorded**: another worker is still inside the + handler, or died inside it and its lease has not expired yet. Discarding the + message here means the handler may never complete for it. + +The second case is the one to understand before you turn this on — see +[What deduplication does not guarantee](#what-deduplication-does-not-guarantee). + +## What deduplication does not guarantee + +Because an in-flight claim is treated like a recorded key, three situations turn +out differently from what "dedupe" suggests. All three were reproduced against a +real `PdoTransport`, a shared store with a lease, and worker processes killed with +`SIGKILL`. + +1. **A message can be lost.** A worker claims the key and dies inside the handler. + The transport redelivers the message, but the claim is still held, so the + redelivery is acknowledged and discarded as a duplicate. The handler never + completes for that message, and nothing is retried or dead-lettered. With the + defaults (`leaseSeconds: 300`) on a `PdoTransport` (`retryAfter: 90`), the + redelivery arrives after 90 seconds, while the claim lives for 300. +2. **A handler can still run twice.** A worker finishes the handler and dies + before `remember()`. The key is not recorded, so once the lease lapses the + redelivery runs the handler again. The "processed at most once" reading does + not hold; handlers must stay idempotent. +3. **A failed attempt can lose its retry.** A handler outlives the transport's + redelivery time, so a second worker receives the same message, finds the claim + held, and discards it. On PDO that deletes the row, so when the first handler + then throws, its retry has no row to update and is silently lost: no retry and + no dead letter. + +### Choosing `leaseSeconds` + +The lease has to be **longer than your slowest handler** (otherwise a second +worker can start the same message while the first is running) and **shorter than +the time your transport takes to redeliver a message from a dead worker** (so the +redelivery finds the claim gone and runs the handler). + +| Transport | When a dead worker's message comes back | A safe `leaseSeconds` | +| --- | --- | --- | +| PDO | after `retryAfter` (default 90 s) | below `retryAfter`, above the slowest handler — for example `retryAfter: 120`, `leaseSeconds: 90` for handlers under a minute | +| Redis | when your reaper moves it from `:processing` back onto the queue (there is no automatic reclaim) | below the reaper's delay | +| RabbitMQ | as soon as the broker sees the connection or channel close, typically immediately | none — a crash inside a handler always discards the message while deduplication is on | + +`leaseSeconds: 0` is not "no lease": the bundled `InMemoryIdempotencyStore` and the +Redis store below then hold the claim with no expiry, so a dead worker's claim +never lapses. `InMemoryIdempotencyStore` lives and dies with its worker, so it +has no orphaned claim, but it also remembers nothing across a restart. + +If no value satisfies both bounds for your transport, leave deduplication off and +rely on an idempotent handler. An idempotent handler is the only guarantee that +holds on every transport, crash timing and store. + +## Message keys The key is derived, in order, from: @@ -32,16 +97,36 @@ The key is derived, in order, from: 2. the producer-minted **`meta.id`** (the canonical message identity), else 3. the **`trace_id`**. -A message with none of these has no stable identity and is processed without -deduplication. +A resolver result is used only when it is a **non-empty string**; `null`, `''` or +any other type (an `int` order id, for instance) is ignored and the key falls +back to `meta.id`. The producer in this library mints a `meta.id` for every +message, so the `trace_id` fallback matters only for messages from other +producers; a `trace_id` can be inherited by several messages of one trace, so a +producer without `meta.id` should supply a `keyResolver`. + +The dispatcher validates the envelope before it derives a key, and a message +without a `trace_id` is dead-lettered (`missing_trace_id`) before deduplication +is reached, so every message the handler sees has a key. + +A store is shared by every URN, and the key is not scoped by URN. A resolver +that returns only a business id would treat two different message types for the +same order as duplicates of each other — the second handler would never run. Put +the URN into the key and return a string: ```php +use InitPHP\Queue\Message\ReceivedMessage; + new IdempotencyOptions( store: $store, keyPrefix: 'bq:idemp:', // namespaces keys in a shared store ttl: 86_400, // seconds a processed key is retained (null = forever) - leaseSeconds: 300, // in-flight claim lease (frees a crashed worker's claim) - keyResolver: fn ($m) => $m->getData()['order_id'] ?? null, // optional + leaseSeconds: 60, // in-flight claim lease: see "Choosing leaseSeconds" + keyResolver: static function (ReceivedMessage $message): ?string { + $orderId = $message->getData()['order_id'] ?? null; + + // A string scoped by URN; null falls back to meta.id. + return $orderId === null ? null : $message->getUrn() . ':' . $orderId; + }, ); ``` @@ -68,7 +153,8 @@ final class RedisIdempotencyStore implements IdempotencyStore public function claim(string $key, int $leaseSeconds = 0): bool { - // Atomic test-and-set: only the first caller wins the claim. + // Atomic test-and-set: only the first caller wins the claim. With EX the + // claim lapses on its own; without it (leaseSeconds 0) it never does. $options = ['NX']; if ($leaseSeconds > 0) { $options['EX'] = $leaseSeconds; @@ -91,9 +177,18 @@ final class RedisIdempotencyStore implements IdempotencyStore } ``` -A PDO-backed store works the same way: `claim()` is an `INSERT` that fails on a -unique `key` column (caught and reported as `false`), `remember()` upserts the -row, and a `processed_at`/`expires_at` column drives the TTL. +A PDO-backed store needs one more step than the Redis one, because a unique +constraint does not expire rows by itself. Redis `EX` frees a lapsed claim on its +own; with a table, `claim()` must free it explicitly or a dead worker's key stays +blocked and every redelivery is discarded. In a transaction, first remove the row +if its lease has lapsed (`DELETE FROM idempotency WHERE dedup_key = ? AND expires_at <= ?`), +then `INSERT` it with `expires_at = now + leaseSeconds` and report `true` only +when the insert affected a row (a unique-key violation means `false`). The same +effect in one statement is `INSERT … ON CONFLICT (dedup_key) DO UPDATE SET expires_at = +excluded.expires_at WHERE idempotency.expires_at <= ?` (SQLite and PostgreSQL), +again checking the affected-row count. `remember()` upserts the row with +`expires_at = now + ttl` (or `NULL` to keep it), `forget()` deletes it, and +`seen()` ignores rows whose `expires_at` has passed. See also [Retries & Dead-Letters](Retries-and-Dead-Letters.md) and [Core Concepts › Delivery guarantee](Core-Concepts.md#delivery-guarantee). diff --git a/docs/Retries-and-Dead-Letters.md b/docs/Retries-and-Dead-Letters.md index 1976383..45edf42 100644 --- a/docs/Retries-and-Dead-Letters.md +++ b/docs/Retries-and-Dead-Letters.md @@ -116,5 +116,6 @@ from `orders:failed`; for RabbitMQ, consume `orders.failed`. rather than retrying them. See [Handlers & Routing](Handlers-and-Routing.md#unknown-urn-strategies). - Make handlers **idempotent** — at-least-once delivery means a handler can run again for a message that actually succeeded but whose ack was lost. The - dispatcher can also dedupe redeliveries — see - [Idempotent Consumption](Idempotent-Consumption.md). + dispatcher's optional deduplication is not a replacement: it can discard a + message whose handler never completed — see + [Idempotent Consumption](Idempotent-Consumption.md#what-deduplication-does-not-guarantee). diff --git a/docs/The-Worker.md b/docs/The-Worker.md index f178dea..ca1a7a2 100644 --- a/docs/The-Worker.md +++ b/docs/The-Worker.md @@ -125,7 +125,7 @@ $worker = new Worker($transport, new Dispatcher($handlers), new WorkerOptions(), | `job.ack` | A handler succeeded. | | `job.retry` | A failure was re-queued (context has `attempt`, `delay`). | | `job.dead_letter` | A message was quarantined (context has `reason`, `attempts`, `error`). | -| `job.dropped` | An unknown URN was acked-and-discarded (`DELETE` strategy). | +| `job.dropped` | The message was acked-and-discarded: an unknown URN (`DELETE` strategy) or, with deduplication on, a duplicate (`reason` `duplicate`). | | `job.released` | An unknown URN was put back (`RELEASE` strategy). | | `reserve.failed` | The transport threw while reserving (loop continues). | | `process.failed` | The transport threw while acting on a message (loop continues). | diff --git a/docs/Transport-PDO.md b/docs/Transport-PDO.md index 2fa0c56..9ef793c 100644 --- a/docs/Transport-PDO.md +++ b/docs/Transport-PDO.md @@ -102,8 +102,14 @@ This guarantees two workers never run the same job. A row reserved by a worker that then crashes would otherwise be stuck forever. Any reservation older than `retryAfter` seconds (default 90) is treated as abandoned -and becomes reservable again, so no message is lost. Set it comfortably above your -slowest handler's runtime. +and becomes reservable again, so the message is delivered again (at-least-once) +instead of staying stuck. Set it comfortably above your slowest handler's runtime. + +If you also enable the dispatcher's [deduplication](Idempotent-Consumption.md), +keep its `leaseSeconds` **below** `retryAfter`: with the defaults (`retryAfter` 90, +`leaseSeconds` 300) the redelivery of a dead worker's message arrives while its +claim is still held, and it is discarded as a duplicate — see +[Idempotent Consumption](Idempotent-Consumption.md#choosing-leaseseconds). ## Lifecycle in SQL terms diff --git a/docs/Troubleshooting.md b/docs/Troubleshooting.md index 32ffc3a..afec1f0 100644 --- a/docs/Troubleshooting.md +++ b/docs/Troubleshooting.md @@ -77,6 +77,15 @@ the cause is at-least-once redelivery (a reservation that lapsed after `retryAfter`), which is expected — make handlers idempotent. Raise `retryAfter` above your slowest handler's runtime if jobs are being reclaimed mid-flight. +## A message was dropped as a duplicate but its handler never finished + +With deduplication on, a redelivery that finds its key still claimed is +acknowledged and discarded (`job.dropped`, reason `duplicate`), even when the +worker that took the claim died inside the handler. Lower `leaseSeconds` below +the transport's redelivery time (PDO `retryAfter`) and above your slowest handler; +on RabbitMQ no value is safe. See +[Idempotent Consumption](Idempotent-Consumption.md#what-deduplication-does-not-guarantee). + ## A message produced by another language is rejected - Check `meta.schema_version` — a version newer than this SDK understands is From 8bf519a482030d9322e371dbc77fa9b8f52062af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammet=20=C5=9Eafak?= Date: Mon, 23 Nov 2026 10:18:42 +0300 Subject: [PATCH 2/2] docs: say a RabbitMQ redelivery is discarded only inside the lease --- README.md | 2 +- docs/Idempotent-Consumption.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0109c1d..1ec2a57 100644 --- a/README.md +++ b/README.md @@ -226,7 +226,7 @@ the message. So: Set `leaseSeconds` **above your slowest handler** and **below the time the transport takes to redeliver a dead worker's message** (PDO: below `retryAfter`; -Redis: below your reaper's delay; RabbitMQ: no safe value). If no value fits, +Redis: below your reaper's delay; RabbitMQ: no safe value, since the broker redelivers at once and a redelivery picked up before the lease lapses is discarded). If no value fits, leave deduplication off and rely on an idempotent handler. The details and the per-transport table are in the [full guide](docs/Idempotent-Consumption.md#choosing-leaseseconds). diff --git a/docs/Idempotent-Consumption.md b/docs/Idempotent-Consumption.md index 8a0c515..b956e6b 100644 --- a/docs/Idempotent-Consumption.md +++ b/docs/Idempotent-Consumption.md @@ -78,7 +78,7 @@ redelivery finds the claim gone and runs the handler). | --- | --- | --- | | PDO | after `retryAfter` (default 90 s) | below `retryAfter`, above the slowest handler — for example `retryAfter: 120`, `leaseSeconds: 90` for handlers under a minute | | Redis | when your reaper moves it from `:processing` back onto the queue (there is no automatic reclaim) | below the reaper's delay | -| RabbitMQ | as soon as the broker sees the connection or channel close, typically immediately | none — a crash inside a handler always discards the message while deduplication is on | +| RabbitMQ | as soon as the broker sees the connection or channel close, typically immediately | no value is safe: a redelivery that is picked up before the lease lapses is discarded, and the broker redelivers at once | `leaseSeconds: 0` is not "no lease": the bundled `InMemoryIdempotencyStore` and the Redis store below then hold the claim with no expiry, so a dead worker's claim