PHPERS WROCŁAW
5 rules to better async messaging
1
RULE ONE
Write the event in the same transaction and the same database as the business change. Send it later.
SEND, THEN COMMIT
$db->beginTransaction();
$wallet->addPoints($member, 50);
$broker->publish(new PointsGained(...));
$db->commit(); // fails
Ghost event. The wallet rolls back; the event is already out.
COMMIT, THEN SEND
$db->beginTransaction();
$wallet->addPoints($member, 50);
$db->commit();
// the process stops here
$broker->publish(new PointsGained(...));
Missing event. The wallet has the points; the event is never sent.
No order of the two writes is safe. A shared transaction across the database and the broker (2PC) is usually not available.
RULE 1 · STORE FIRST
THE PRODUCER
$db->beginTransaction();
$wallet->addPoints($member, 50);
$outbox->insert(new PointsGained(...));
$db->commit();
// a relay sends the row later
Both rows commit together, or neither does.
THE TABLE
CREATE TABLE outbox (
id bigserial PRIMARY KEY,
type text NOT NULL,
payload jsonb NOT NULL,
created_at timestamptz
NOT NULL DEFAULT now(),
published_at timestamptz
);
One more INSERT per event, in the business database.
Same database, not a second one: an outbox in another database is two writes again.
RULE 1 · STORE FIRST
RULE ONE · STORE FIRST
1
Never write to the database and the broker as two steps. Each order loses or invents an event.
2
Write the event to an outbox. Same transaction, same database as the business change.
3
Keep the outbox in the business database. It costs one INSERT per event; a second database brings the two writes back.
RULE 1 · STORE FIRST
2
RULE TWO
Two ways to claim a batch, how they scale, and what slows them down.
LONG CLAIM · ONE TRANSACTION
BEGIN;
SELECT id, payload FROM outbox
WHERE published_at IS NULL
ORDER BY id LIMIT :batch
FOR UPDATE SKIP LOCKED;
-- publish, wait for the confirm
UPDATE outbox SET published_at = now()
WHERE id = ANY(:ids);
COMMIT;
Row locks and the transaction stay open during the publish. One commit per batch.
LEASE · SHORT STATEMENTS
UPDATE outbox
SET available_at = now() + '30 s'
WHERE id IN (SELECT id FROM outbox
WHERE published_at IS NULL
AND available_at <= now()
ORDER BY available_at, id
LIMIT :batch FOR UPDATE SKIP LOCKED)
RETURNING id, payload;
-- publish, no transaction open
UPDATE outbox SET published_at = now()
WHERE id = ANY(:ids);
Locks only during the claim statement. Two commits per batch; a row returns when its lease ends.
RULE 2 · CHOOSE THE RELAY
LONG CLAIM OR LEASE · TEST RESULTS
| Workers | Batch 10 · long claim | Batch 10 · lease | Batch 100 · long claim | Batch 100 · lease |
|---|---|---|---|---|
| 1 | 1,728 | 1,473 | 14,400 | 12,370 |
| 8 | 16,366 | 10,689 | 93,100 (peak) | 71,880 |
| 32 | 36,562 (peak) | 30,604 | 51,310 | 87,700 (peak) |
| 64 | 19,710 | 34,489 (peak) | 28,190 | 61,450 |
| 128 | 9,820 | 20,681 | 22,180 | 29,310 |
Below its peak, the long claim sends more. Past it, the lease falls more slowly. Which side your production traffic lands on decides.
RULE 2 · CHOOSE THE RELAY
THE RULE OF SCALING
100k
75k
50k
25k
1
8
32
64
128
Long claim: peak 93,100 at 8
Lease: peak 87,700 at 32
ROWS/S · RELAY WORKERS · BATCH 100
Cycle time at the peak: 8.6 ms. At 128 workers: 837 ms.
A smaller server peaks earlier: a profile like m8g.large peaks at 8 workers with 76,080 rows/s and falls to 14,600 at 64.
RULE 2 · CHOOSE THE RELAY
WHERE THE TIME GOES
Every worker starts at the head of the pending index. Each row another worker holds is skipped, and each skip is one or two calls to the shared lock manager.
A skipped row never waits. The calls add up.
| Workers | Top wait samples, long claim, batch 100 |
|---|---|
| 8 | broker wait 42%, CPU 29%, WAL write 12% |
| 32 | LockManager 47%, transactionid 26% |
| 64 | LockManager 55%, transactionid 32% |
| 128 | LockManager 51%, transactionid 43% |
Find your peak and stay below it. Raise the batch before you add workers: 1 worker sends 166 rows/s at batch 1, 14,400 at batch 100.
RULE 2 · CHOOSE THE RELAY
DISCLAIMER · RULES TWO AND THREE
PostgreSQL 16 on one laptop, 200-byte rows, short runs. Rule two simulates the broker confirm as a 2 ms sleep; rule three uses RabbitMQ at one rate, 2,000 rows/s. No bursts, no mixed queries, no network round trip.
Test the designs with your own load before you choose.
RULE 2 · CHOOSE THE RELAY
DISCLAIMER · CHECKED, IT IS TRUE
ROWS/S AFTER 30 S · 8 WORKERS · BATCH 100
89,960
nothing else open
13,080
one idle transaction that wrote one row
A 40 s running statement: 14,919. The lease falls the same way: 49,650 to 14,019.
| Session | Holds cleanup? |
|---|---|
| READ COMMITTED, idle after a SELECT | No |
| Idle in a transaction after a write | Yes |
| REPEATABLE READ after a SELECT | Yes |
| A long running statement | Yes |
| A replication slot | Yes, all databases |
VACUUM cannot remove dead rows, so every claim reads them again. Long claim and lease both slow down. Autovacuum settings do not fix it.
RULE 2 · CHOOSE THE RELAY
RULE TWO · CHOOSE THE RELAY
1
Long claim or lease. Below its peak the long claim sends more; past it the lease falls more slowly. Your production traffic decides.
2
Every relay has a worker peak. Past it, the lock manager eats the gain. Raise the batch first, then add workers up to the peak.
3
Hunt long transactions. One idle transaction can cut the relay to a seventh, with either claim design.
RULE 2 · CHOOSE THE RELAY
3
RULE THREE
Delete on publish or partition retention: what happens to a row after the broker confirms it.
TWO WAYS TO FINISH A SENT ROW
A · DELETE ON PUBLISH
DELETE FROM outbox
WHERE id = ANY(:ids);
In the claim transaction. VACUUM removes the dead rows later.
B · MARK AND DROP
UPDATE outbox SET published_at = now()
WHERE id = ANY(:ids);
A daily job runs DETACH … CONCURRENTLY and DROP TABLE on the old day.
RULE 3 · CHOOSE THE ACK
WHAT EACH WRITE COSTS
DELETE
Writes only the end mark on the old row version.
MARK (UPDATE)
Writes a full new row version and new index entries.
Never a HOT update: published_at is in the predicate of the pending index, and PostgreSQL counts a predicate column as indexed.
The partition drop takes the bulk cleanup away from VACUUM. It does not remove the dead rows of the mark.
RULE 3 · CHOOSE THE ACK
BACKLOG · 1,000,000 ROWS WAIT, 4 WORKERS
POSTGRESQL CPU PER ROW
9.6
µs · delete
15.0
µs · mark
WAL WRITTEN
440
MB · delete
942
MB · mark
About 40% less CPU and half the WAL. At 200,000 rows: 8.4 against 14.6 µs.
RULE 3 · CHOOSE THE ACK
STEADY LOAD · 2,000 ROWS/S IN, 2 RELAY WORKERS, 120 S
POSTGRESQL CPU, MEDIAN OF 4 RUNS
63.0
s · delete
47.6
s · mark
CLAIM PLAN, SAMPLED EACH SECOND
Delete: a bitmap or sequential scan in 3 of 4 runs.
Mark: an index scan in every sample.
About 25% less CPU for mark, and a stable plan. Delete writes less WAL: 156 against 203 MB.
RULE 3 · CHOOSE THE ACK
WHY THE WINNER FLIPS
1
With delete, the table is almost empty. After ANALYZE, the planner sometimes picks a bitmap or a sequential scan for the claim.
2
Only a plain index scan marks a dead index entry as dead. A bitmap scan reads the same dead entries on every claim.
3
The mark table keeps many live rows, so the planner keeps the index scan.
INDEX ENTRIES READ, ONE RUN
909 M
delete, with plan changes
0.73 M
mark
RULE 3 · CHOOSE THE ACK
WHERE EACH ONE IS BETTER
| Question | A · Delete on publish | B · Mark and drop |
|---|---|---|
| Draining a backlog | Better: ~40% less CPU | Slower |
| Steady traffic | Plan can flip, CPU up | Better: ~25% less CPU |
| WAL volume | Better: about half | More: new row versions |
| Table size | Small: 12 MB | 81 MB until the drop |
| Replay and audit | Nothing kept | Better: rows kept for the retention |
| Moving parts | Better: fewer; autovacuum must keep up | Partitions ahead, daily job, unsent-row guard |
RULE 3 · CHOOSE THE ACK
RULE THREE · CHOOSE THE ACK
1
Delete wins a backlog. Mark and drop wins a steady load. The same two statements, two different winners.
2
An almost empty queue table can get a bad plan. Watch the claim plan, not only the CPU.
3
Test both with your own traffic before you choose. These numbers come from synthetic runs.
RULE 3 · CHOOSE THE ACK
4
RULE FOUR
On the consumer side: which failures to retry, how to wait before the next try, and where a message goes when it never succeeds.
CLASSIFY FIRST
The database, the broker or a partner API is down for a while. A timeout, a 503, a deadlock.
Time fixes it: retry later, with a growing wait.
The payload cannot be read, the member does not exist, a bug in the handler.
Time does not fix it: park it at once. In Symfony, throw UnrecoverableMessageHandlingException.
A retry helps only a failure that time can fix. Retrying a permanent error only delays the alarm.
RULE 4 · RETRY, THEN PARK
A message that comes back at once fails again: the outage is still there.
Double the wait after each failure, and add a random part (jitter), so that many consumers do not retry at the same moment.
| Attempt | Wait before it |
|---|---|
| Retry 1 | about 1 s |
| Retry 2 | about 2 s |
| Retry 3 | about 4 s, then park |
SYMFONY MESSENGER
framework:
messenger:
failure_transport: failed
transports:
points:
dsn: '%env(POINTS_DSN)%'
retry_strategy:
max_retries: 3
delay: 1000
multiplier: 2
max_delay: 60000
jitter: 0.1
All defaults except max_delay (default 0: no cap).
RULE 4 · RETRY, THEN PARK
| Where | How the message comes back later |
|---|---|
| SQS | ChangeMessageVisibility: the failed message comes back after N seconds (max 12 h from the first receive). DelaySeconds on a send: max 15 min.¹ |
| RabbitMQ | Quorum queues: native delayed retry (4.3+). Older: a wait queue with a TTL that dead-letters back. The delayed-message plugin is no longer maintained. |
| Kafka | No delay per message: retry topics (for example 1 min, 10 min) and a dead letter topic, in the client. |
| Database | A row with available_at; the worker takes rows where available_at <= now(). The Symfony Doctrine transport works this way. |
A retry is a message scheduled for later, not a sleep in the handler.
RULE 4 · RETRY, THEN PARK
| Retry limit | After the limit | |
|---|---|---|
| SQS | maxReceiveCount in the redrive policy | Moved to the DLQ |
| RabbitMQ quorum queue | delivery-limit, default 20 since 4.0 | Dead-lettered to the DLX. No DLX: dropped |
| Kafka | Your consumer code | Your dead letter topic |
| Symfony Messenger | max_retries, default 3 | The failure transport. None set: discarded |
A default can drop the message. Set the limit and the parking place on purpose.
RULE 4 · RETRY, THEN PARK
| SQS DLQ (native) | RabbitMQ DLQ (native) | failed_messages (yours) | |
|---|---|---|---|
| Setup | A redrive policy on the queue | A dead letter exchange and a queue | A table, a write on failure, a replay command |
| The error | None: the move is by receive count | x-death: reason, queue, count; no exception | What you store: exception, trace, attempts |
| Retention | Max 14 days; standard queues count from the first enqueue | Until consumed, or the queue’s own limits | Until you delete it |
| Search, replay | No query; DLQ redrive to the source queue | No query; move back with a shovel | SQL with joins; replay one message or a filter |
Native DLQ for simplicity; failed_messages when you need features.
RULE 4 · RETRY, THEN PARK
WHY TAKE IT OFF THE QUEUE
A message that keeps failing holds a consumer and its prefetch. In an ordered queue it stops every message behind it.
WHY REDELIVER FIRST
A database failover of a few seconds fails every message in flight. With no retries, hundreds or thousands land in the DLQ within seconds.
WHY THE DLQ IS LAST
Every parked message needs a person or a dedicated job to redrive or requeue it.
Retries absorb short outages; the DLQ gets only what time cannot fix.
RULE 4 · RETRY, THEN PARK
RULE FOUR · RETRY, THEN PARK
1
Classify the error. Retry only what time can fix; park a permanent failure at once.
2
Retry later, not at once. A growing wait with jitter, scheduled by the broker or by an available_at column.
3
Limit the retries, then park. Taking the message off the queue unblocks the channel; only what time cannot fix lands there.
4
Have the tools before you need them. A way to see, search and replay the DLQ or failed_messages, and an alert on each new message.
RULE 4 · RETRY, THEN PARK
5
RULE FIVE
Exactly-once processing on top of at-least-once delivery. Even with idempotent handlers, do not do the work twice.
WHAT THE BROKER GIVES
| Broker | What it removes | Where it stops |
|---|---|---|
| SQS FIFO | Producer retries with the same dedup ID, within 5 minutes | A redelivery after the visibility timeout |
| Kafka | Duplicates in read-process-write between Kafka topics | Any write outside Kafka: your database, an API |
| RabbitMQ | Nothing: acks give at-least-once | The redelivered flag is only a hint |
Exactly-once delivery does not exist. Exactly-once processing is at-least-once delivery plus deduplication on the receiving side.
RULE 5 · DEDUPLICATE
ONE TRANSACTION
BEGIN;
INSERT INTO processed_messages
(message_id, processed_at)
VALUES (:id, now())
ON CONFLICT (message_id) DO NOTHING;
-- 0 rows: duplicate, ROLLBACK, ack
UPDATE member_points
SET total = total + 50
WHERE member_id = :member;
COMMIT;
-- then ack to the broker
FIRST DELIVERY
DUPLICATE
RULE 5 · DEDUPLICATE
EVEN WITH IDEMPOTENT HANDLERS
IDEMPOTENT HANDLER, DUPLICATE
Loads the data, calls services, computes the result, then finds that nothing changes.
Correct, and the full price of the work, again.
DEDUP CHECK, DUPLICATE
One insert on a unique key. Zero rows, rollback, ack. The handler does not run.
The cost of one index lookup.
RULE 5 · DEDUPLICATE
DELETE IN CHUNKS
DELETE FROM processed_messages
WHERE ctid IN (
SELECT ctid FROM processed_messages
WHERE processed_at <
now() - interval '14 days'
LIMIT 10000);
Run it again until it deletes zero rows. An index on processed_at finds the old rows.
WHY THIS SHAPE
Why a subquery? PostgreSQL has no DELETE ... LIMIT: it is a syntax error.
Why ctid? It is the row address (page, slot). The DELETE reads each row directly.
Why not message_id? The planner read and hashed the whole table: 125 ms against 9 ms per chunk.
Keep IDs longer than the redelivery window. SQS can redeliver for 14 days.
RULE 5 · DEDUPLICATE
WHY NOT ONE STATEMENT
| DELETE ... WHERE processed_at < X | Chunks of 10,000 | |
|---|---|---|
| Transaction | One, open until the last row is gone | Many, a few milliseconds each |
| VACUUM | Held back in the whole database, the outbox too | Released at each commit; cleans between chunks |
| WAL and replicas | One large burst; replicas lag | Spread out; the job can pause between chunks |
| A failure | Rolls back all the work | Loses one chunk; the next run continues |
One large DELETE is the long transaction of rule two. It slows the relay too.
RULE 5 · DEDUPLICATE
RULE FIVE · DEDUPLICATE
1
No broker gives exactly-once to your database. Plan for duplicates: deduplicate on the receiving side.
2
One transaction. The message ID and the business change commit together, then ack. Effects outside the database need their own outbox or an idempotency key.
3
Choose a prune strategy for your database. PostgreSQL: chunks by ctid. MySQL / Percona: DELETE ... LIMIT on a monotonic key. Keep IDs longer than the redelivery window.
RULE 5 · DEDUPLICATE