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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,8 @@ 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.

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

## Unknown-URN strategy

When a message arrives whose URN has no mapped handler, the dispatcher applies one
Expand Down
3 changes: 2 additions & 1 deletion docs/Core-Concepts.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,8 @@ 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**.
must be idempotent** — or let the dispatcher dedupe redeliveries, see
[Idempotent Consumption](Idempotent-Consumption.md).

## Error handling

Expand Down
4 changes: 3 additions & 1 deletion docs/FAQ.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ 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**.
worker crashes after handling but before acking). Make handlers **idempotent**,
or turn on the dispatcher's deduplication — see
[Idempotent Consumption](Idempotent-Consumption.md).

### Can a Go / Python / Node service consume what PHP produces (and vice-versa)?

Expand Down
99 changes: 99 additions & 0 deletions docs/Idempotent-Consumption.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# 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`:

```php
use InitPHP\Queue\Consumer\Dispatcher;
use InitPHP\Queue\Consumer\IdempotencyOptions;
use InitPHP\Queue\Consumer\InMemoryIdempotencyStore;

$dispatcher = new Dispatcher(
$handlers,
idempotency: new IdempotencyOptions(new InMemoryIdempotencyStore()),
);
```

With no options (the default) deduplication is off and the dispatcher behaves
exactly as before — this is fully backward-compatible.

**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.

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.

```php
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
);
```

## Bring your own store

`InMemoryIdempotencyStore` is correct for a **single long-running worker** but it
is not shared between processes and does not survive a restart, so it cannot
dedupe across the whole fleet. For that, back the
`InitPHP\Queue\Contracts\IdempotencyStore` contract with a durable, atomic store —
exactly how the InitPHP ecosystem treats Cache and Database backends as
pluggable seams:

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

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

public function seen(string $key): bool
{
return (bool) $this->redis->exists($key);
}

public function claim(string $key, int $leaseSeconds = 0): bool
{
// Atomic test-and-set: only the first caller wins the claim.
$options = ['NX'];
if ($leaseSeconds > 0) {
$options['EX'] = $leaseSeconds;
}

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

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');
}

public function forget(string $key): void
{
$this->redis->del($key);
}
}
```

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.

See also [Retries & Dead-Letters](Retries-and-Dead-Letters.md) and
[Core Concepts › Delivery guarantee](Core-Concepts.md#delivery-guarantee).
4 changes: 3 additions & 1 deletion docs/Retries-and-Dead-Letters.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,6 @@ from `orders:failed`; for RabbitMQ, consume `orders.failed`.
- Use `UnknownUrnStrategy::DEAD_LETTER` to quarantine unmapped messages for review
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.
again for a message that actually succeeded but whose ack was lost. The
dispatcher can also dedupe redeliveries — see
[Idempotent Consumption](Idempotent-Consumption.md).
1 change: 1 addition & 0 deletions docs/_Sidebar.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
- [Handlers & Routing](Handlers-and-Routing.md)
- [The Worker](The-Worker.md)
- [Retries & Dead-Letters](Retries-and-Dead-Letters.md)
- [Idempotent Consumption](Idempotent-Consumption.md)

**Transports**
- [Overview](Transports.md)
Expand Down
Loading