Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 78 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -182,29 +183,79 @@ $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, 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).

### Message keys

The key is derived, in order, from:

1. a custom `keyResolver` you supply (`fn (ReceivedMessage): ?string`), else
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;
},
);
```

Expand All @@ -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;
Expand All @@ -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).

Expand Down
5 changes: 3 additions & 2 deletions docs/Core-Concepts.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
7 changes: 4 additions & 3 deletions docs/FAQ.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)?

Expand Down
129 changes: 112 additions & 17 deletions docs/Idempotent-Consumption.md
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -19,29 +19,114 @@ $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 `<queue>: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 | 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
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:

1. a custom `keyResolver` you supply (`fn (ReceivedMessage): ?string`), else
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;
},
);
```

Expand All @@ -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;
Expand All @@ -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).
5 changes: 3 additions & 2 deletions docs/Retries-and-Dead-Letters.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
2 changes: 1 addition & 1 deletion docs/The-Worker.md
Original file line number Diff line number Diff line change
Expand Up @@ -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). |
Expand Down
Loading
Loading