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
73 changes: 73 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,79 @@ All notable changes to `initphp/queue` are documented here. The format is based
on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project
adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- `Contracts\CompletionAwareIdempotencyStore` (extends `IdempotencyStore`) with
`isCompleted(string $key): bool`, which lets the `Dispatcher` tell a key that
was recorded as processed from one that another handler still holds. The bundled
`InMemoryIdempotencyStore` implements it.
- `IdempotencyOptions::$inFlightDelaySeconds` (new optional last argument,
default 5): how long a message waits before it re-checks a key held by another
handler.
- `Outcome::release()` takes an optional `$delaySeconds` and `Outcome` exposes it
as `delaySeconds` (default 0, so existing releases are unchanged). The `Worker`
passes it to the transport and logs it as `delay` on `job.released`.

### Fixed

- **A message could be lost with idempotency enabled.** A redelivery that found its
key claimed by a handler that had not finished was acknowledged and discarded as
a `duplicate`. If that handler's worker had died, the message was gone; if the
handler outlived the transport's redelivery time and then threw, the discarded
duplicate had deleted the PDO row, so its retry updated nothing and was lost with
no dead letter. With a `CompletionAwareIdempotencyStore` such a redelivery is now
released back to the queue (`job.released`, reason `in_flight`) without counting
an attempt, so it never moves towards the dead-letter queue by waiting, and it is
re-checked after `inFlightDelaySeconds`. A recorded (completed) duplicate is
still dropped. After a delayed release the `Worker` pauses for `sleepWhenEmpty`
(at least 0.1 s) so that RabbitMQ, which has no native delay, does not reserve
the message again in a tight loop.
- `RedisTransport::release()`, `deadLetter()` and the delayed-set migration are
single Lua scripts. They act only while the worker still owns the message (its
`LREM` removed one processing entry), so a crash cannot leave a message on no
list. A release or dead-letter from a worker whose message a reaper already moved
back replaces the live copy (in the delayed set, or on the queue) instead of
adding a second one, so `attempts` still climbs and `maxAttempts` still ends the
message. A client that cannot `EVAL` (an adapter without `eval`, or a Redis user
without scripting permission) falls back to the same steps as separate commands
with the same rules, without atomicity; `reserve()`, `ack()` and `publish()` need
no scripting.
- `AmqpTransport::release()` and `deadLetter()` publish the new copy (waiting for
the broker's confirm when the channel is in confirm mode) **before** acking the
original, so a crash between the two leaves a duplicate instead of losing the
message, and a failed publish leaves the original unacked. In confirm mode a
broker `nack` or a returned copy requeues the original (`basic_nack`, requeue)
and throws a `QueueException` instead of acking; the channel's own nack handler
and return listener keep running.
- `PdoTransport::release()` no longer overwrites a reservation another worker took
over, and a message put back unchanged no longer rewrites `payload` or `attempts`
or shortens a recorded back-off. A failure reported by a worker whose reservation
was taken over still counts (the new `attempts`, payload and back-off are
recorded without touching the holder's reservation, and `attempts` never goes
back), so a handler slower than `retryAfter` that always fails still reaches
`maxAttempts` and the dead-letter table.
- The `Worker` pauses after the transport fails to act on a message
(`process.failed`): the larger of 0.1 s, `sleepWhenEmpty` and the back-off for the
message's next attempt, at most 5 s, in short slices that a stop signal ends at
once. A message RabbitMQ keeps refusing (a nacked republish) no longer re-runs its
handler in a tight loop. Its `attempts` still do not advance while the broker
refuses the copy; see the RabbitMQ page.
- A message deferred to wait for an in-flight key no longer counts towards
`maxJobs` or `processedCount()`, and the worker pauses at least 0.1 s after a
deferral even with `sleepWhenEmpty: 0`.
- Wrong docblocks: `IdempotencyStore::forget()` is called by the dispatcher when a
handler throws, and the contract's description now lists `forget()`.

### Compatibility

- `IdempotencyStore` and its signatures are unchanged. A custom store that
implements only `IdempotencyStore` keeps the previous behaviour (any failed claim
is discarded as a duplicate); implement `CompletionAwareIdempotencyStore` to get
the fix. Records written by 2.1/2.2 should be treated as completed by that
method; see the upgrade notes in `docs/Idempotent-Consumption.md`.

## [2.2.0] - 2026-11-22

### Changed
Expand Down
112 changes: 71 additions & 41 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,51 +184,61 @@ 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.
> handler.** 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 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).
If the claim fails, the key is either **recorded** (the message was handled before:
it is acknowledged and discarded, `job.dropped` with reason `duplicate`) or
**claimed but not recorded** (another worker is still inside the handler, or died
inside it and its lease has not lapsed). In the second case the message is **not**
discarded: it is put back on the queue (`job.released`, reason `in_flight`)
without counting an attempt, and looked at again after `inFlightDelaySeconds`
(default 5). It ends when the other handler records the key (the message is then
dropped), when that handler fails and releases the claim, or when a dead worker's
lease lapses (the handler then runs). Waiting never moves a message towards the
dead-letter queue, and it is paced rather than a tight loop: the message is held
back for `inFlightDelaySeconds` and the worker pauses for `sleepWhenEmpty` (at
least 0.1 s) after each deferral. A deferral is not counted as processing, so it
does not use up `maxJobs`; on RabbitMQ a `stopWhenEmpty` (drain) worker stays
until the other handler finishes or its lease lapses. Each transport puts the
message back without a step that could lose it: PDO in one `UPDATE`, RabbitMQ by
publishing the copy before acking the original (a crash in between leaves a
duplicate, never a gap), Redis in one Lua script.

This needs a store that implements `CompletionAwareIdempotencyStore`
(`InMemoryIdempotencyStore` does). A store that implements only `IdempotencyStore`
cannot tell the two cases apart and keeps the previous behaviour: any failed claim
is discarded.

### 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
1. **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
2. **A handler that outlives its lease can run twice**, because a second worker
then wins the claim.
3. **A claim that never lapses keeps its message waiting.** Give every claim a
lease; `leaseSeconds: 0` holds it until `forget()`.
4. **A handler that kills its process never counts as failed**, so its `attempts`
does not rise and it never reaches the dead-letter queue; it is picked up again
each time the lease lapses.
5. **On Redis, a reaper that rewrites the envelope hides the late failure.** A
handler that outlives the reaper still has its failure counted (it replaces the
reclaimed copy, so `maxAttempts` ends the message), but only while the copy has
the body the handler was given. Keep the reaper's delay above your slowest
handler and move the body back unchanged. A Redis client without `EVAL` keeps the
same rules, but a crash in the middle of a retry can lose the message.

Set `leaseSeconds` **above your slowest handler**, and as short as that allows: it
is how long a dead worker's message waits before it is handled again. The
per-transport table and the upgrade notes for 2.1/2.2 (drain the old workers
first) are in the
[full guide](docs/Idempotent-Consumption.md#choosing-leaseseconds).

### Message keys
Expand All @@ -251,6 +261,7 @@ new IdempotencyOptions(
keyPrefix: 'bq:idemp:', // namespaces keys in a shared store
ttl: 86_400, // seconds a processed key is retained (null = forever)
leaseSeconds: 60, // in-flight claim lease; see the notes above
inFlightDelaySeconds: 5, // wait before re-checking a key another handler holds
keyResolver: static function (ReceivedMessage $message): ?string {
$orderId = $message->getData()['order_id'] ?? null;

Expand All @@ -269,9 +280,9 @@ exactly how the InitPHP ecosystem treats Cache and Database backends as
pluggable seams:

```php
use InitPHP\Queue\Contracts\IdempotencyStore;
use InitPHP\Queue\Contracts\CompletionAwareIdempotencyStore;

final class RedisIdempotencyStore implements IdempotencyStore
final class RedisIdempotencyStore implements CompletionAwareIdempotencyStore
{
public function __construct(private \Redis $redis) {}

Expand All @@ -289,14 +300,23 @@ final class RedisIdempotencyStore implements IdempotencyStore
$options['EX'] = $leaseSeconds;
}

return (bool) $this->redis->set($key, '1', $options);
return (bool) $this->redis->set($key, 'claimed', $options);
}

public function isCompleted(string $key): bool
{
// 'claimed' is an in-flight claim. Anything else that exists is a record,
// including the '1' that 2.1/2.2 stored for both claims and records.
$value = $this->redis->get($key);

return $value !== false && $value !== 'claimed';
}

public function remember(string $key, ?int $ttl = null): void
{
$ttl !== null && $ttl > 0
? $this->redis->set($key, '1', ['EX' => $ttl])
: $this->redis->set($key, '1');
? $this->redis->set($key, 'done', ['EX' => $ttl])
: $this->redis->set($key, 'done');
}

public function forget(string $key): void
Expand All @@ -306,6 +326,10 @@ final class RedisIdempotencyStore implements IdempotencyStore
}
```

`CompletionAwareIdempotencyStore` extends `IdempotencyStore`; the one method it adds,
`isCompleted()`, is what lets the dispatcher keep an in-flight message instead of
discarding it. Without it a store still works, with the 2.2 behaviour.

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
Expand All @@ -314,10 +338,16 @@ if its lease has lapsed (`DELETE FROM idempotency WHERE dedup_key = ? AND expire
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),
excluded.expires_at, completed = 0 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.
`expires_at = now + ttl` (or `NULL` to keep it) and marks it completed, `forget()`
deletes it, and `seen()` ignores rows whose `expires_at` has passed. For
`isCompleted()` add a `completed` flag column: `claim()` sets it to `0`, **also when
it takes over a lapsed row** (the one-statement form needs `completed = 0` in its
`DO UPDATE SET` list: a takeover that keeps the old `1` makes the next redelivery
look completed and drops the message), `remember()` sets it to
`1`, and `isCompleted()` returns true for a live row whose flag is `1`. Give the
column a default of `1`, so rows written before you added it read as completed.

Full guide: [docs/Idempotent-Consumption.md](docs/Idempotent-Consumption.md).

Expand Down
50 changes: 49 additions & 1 deletion docs/API-Reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,27 @@ public function dispatch(InitPHP\Queue\Message\ReceivedMessage $message): InitPH

An unknown strategy string throws `ConfigurationException`.

### IdempotencyOptions / InMemoryIdempotencyStore

`InitPHP\Queue\Consumer\IdempotencyOptions` (immutable), passed to
`Dispatcher`'s `idempotency:` argument:

```php
public function __construct(
InitPHP\Queue\Contracts\IdempotencyStore $store,
string $keyPrefix = 'bq:idemp:',
?int $ttl = 86_400, // seconds a processed key is kept (null = forever)
int $leaseSeconds = 300, // in-flight claim lease
?callable $keyResolver = null, // fn (ReceivedMessage): ?string
int $inFlightDelaySeconds = 5, // wait before re-checking a key another handler holds (>= 1)
)
public function keyFor(InitPHP\Queue\Message\ReceivedMessage $message): ?string
```

A negative `ttl` or `leaseSeconds`, or an `inFlightDelaySeconds` below 1, throws
`ConfigurationException`. `InitPHP\Queue\Consumer\InMemoryIdempotencyStore`
implements `CompletionAwareIdempotencyStore` and adds `count(): int`.

### Outcome / OutcomeKind

`InitPHP\Queue\Consumer\Outcome` — the dispatcher's decision (immutable).
Expand All @@ -100,12 +121,13 @@ An unknown strategy string throws `ConfigurationException`.
public readonly OutcomeKind $kind;
public readonly string $reason; // '' | 'failed' | 'unknown_urn' | a validator reason
public readonly ?\Throwable $exception;
public readonly int $delaySeconds; // 0 unless a release is delayed

public static function ack(): self
public static function retry(?\Throwable $exception = null, string $reason = 'failed'): self
public static function deadLetter(string $reason, ?\Throwable $exception = null): self
public static function drop(string $reason): self
public static function release(string $reason): self
public static function release(string $reason, int $delaySeconds = 0): self
```

`InitPHP\Queue\Consumer\OutcomeKind` is an enum: `Ack`, `Retry`, `DeadLetter`,
Expand Down Expand Up @@ -165,6 +187,32 @@ interface HandlerResolver
}
```

### IdempotencyStore

```php
interface IdempotencyStore
{
public function seen(string $key): bool;
public function claim(string $key, int $leaseSeconds = 0): bool;
public function remember(string $key, ?int $ttl = null): void;
public function forget(string $key): void;
}
```

### CompletionAwareIdempotencyStore

```php
interface CompletionAwareIdempotencyStore extends IdempotencyStore
{
public function isCompleted(string $key): bool; // recorded with remember(), still live
}
```

Lets the `Dispatcher` tell a recorded key from one another handler still holds: a
failed claim on a completed key is dropped, on an in-flight key the message is
released. A store that implements only `IdempotencyStore` keeps the previous
behaviour (always dropped). See [Idempotent Consumption](Idempotent-Consumption.md).

### ConsumerTransport

```php
Expand Down
4 changes: 2 additions & 2 deletions docs/Core-Concepts.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ 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**. 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).
redeliveries but does not replace that, and it can still run a handler twice —
see [Idempotent Consumption](Idempotent-Consumption.md#what-deduplication-does-not-guarantee).

## Error handling

Expand Down
2 changes: 1 addition & 1 deletion docs/FAQ.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ installed. See [Retries & Dead-Letters](Retries-and-Dead-Letters.md).
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**.
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
a substitute: it can still run a handler twice — 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
Loading
Loading