PHPERS WROCŁAW

More than a queue

5 rules to better async messaging

1

RULE ONE

Store first

Write the event in the same transaction and the same database as the business change. Send it later.

Two writes, two systems

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 outbox: one transaction, one database

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

Three things to take home

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

Choose the relay

Two ways to claim a batch, how they scale, and what slows them down.

Long claim or lease

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

Rows per second, by workers and batch size

WorkersBatch 10 · long claimBatch 10 · leaseBatch 100 · long claimBatch 100 · lease
11,7281,47314,40012,370
816,36610,68993,100 (peak)71,880
3236,562 (peak)30,60451,31087,700 (peak)
6419,71034,489 (peak)28,19061,450
1289,82020,68122,18029,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

Past the peak, more workers send fewer rows

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

After the peak, the lock manager takes over

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.

WorkersTop wait samples, long claim, batch 100
8broker wait 42%, CPU 29%, WAL write 12%
32LockManager 47%, transactionid 26%
64LockManager 55%, transactionid 32%
128LockManager 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

These are synthetic runs, not your traffic

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

One open transaction slows every relay

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.

SessionHolds cleanup?
READ COMMITTED, idle after a SELECTNo
Idle in a transaction after a writeYes
REPEATABLE READ after a SELECTYes
A long running statementYes
A replication slotYes, 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

Three things to take home

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

Choose the ack

Delete on publish or partition retention: what happens to a row after the broker confirms it.

TWO WAYS TO FINISH A SENT ROW

Same claim, different last step

A · DELETE ON PUBLISH

The row goes away after the confirm

DELETE FROM outbox
WHERE id = ANY(:ids);

In the claim transaction. VACUUM removes the dead rows later.

B · MARK AND DROP

The row stays until its partition drops

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

Both leave one dead row per message

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

Under a backlog, delete wins

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

Under a steady load, mark and drop wins

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

An empty table gets a bad plan

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

Pick by your load, not by habit

QuestionA · Delete on publishB · Mark and drop
Draining a backlogBetter: ~40% less CPUSlower
Steady trafficPlan can flip, CPU upBetter: ~25% less CPU
WAL volumeBetter: about halfMore: new row versions
Table sizeSmall: 12 MB81 MB until the drop
Replay and auditNothing keptBetter: rows kept for the retention
Moving partsBetter: fewer; autovacuum must keep upPartitions ahead, daily job, unsent-row guard

RULE 3 · CHOOSE THE ACK

RULE THREE · CHOOSE THE ACK

Three things to take home

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

Retry, then park

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

Two kinds of failure

Temporary

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.

Permanent

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

Wait longer after each failure

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.

AttemptWait before it
Retry 1about 1 s
Retry 2about 2 s
Retry 3about 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

How to schedule a retry in the future

WhereHow the message comes back later
SQSChangeMessageVisibility: the failed message comes back after N seconds (max 12 h from the first receive). DelaySeconds on a send: max 15 min.¹
RabbitMQQuorum 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.
KafkaNo delay per message: retry topics (for example 1 min, 10 min) and a dead letter topic, in the client.
DatabaseA 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

A message that always fails: limit, then park

Retry limitAfter the limit
SQSmaxReceiveCount in the redrive policyMoved to the DLQ
RabbitMQ quorum queuedelivery-limit, default 20 since 4.0Dead-lettered to the DLX. No DLX: dropped
KafkaYour consumer codeYour dead letter topic
Symfony Messengermax_retries, default 3The 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

Native DLQ or a failed_messages table

SQS DLQ (native)RabbitMQ DLQ (native)failed_messages (yours)
SetupA redrive policy on the queueA dead letter exchange and a queueA table, a write on failure, a replay command
The errorNone: the move is by receive countx-death: reason, queue, count; no exceptionWhat you store: exception, trace, attempts
RetentionMax 14 days; standard queues count from the first enqueueUntil consumed, or the queue’s own limitsUntil you delete it
Search, replayNo query; DLQ redrive to the source queueNo query; move back with a shovelSQL with joins; replay one message or a filter

Native DLQ for simplicity; failed_messages when you need features.

RULE 4 · RETRY, THEN PARK

Why park a message, and why retry first

WHY TAKE IT OFF THE QUEUE

To unblock the channel

A message that keeps failing holds a consumer and its prefetch. In an ordered queue it stops every message behind it.

WHY REDELIVER FIRST

To survive a short outage

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

A DLQ is hard to empty

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

Four things to take home

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

Deduplicate

Exactly-once processing on top of at-least-once delivery. Even with idempotent handlers, do not do the work twice.

WHAT THE BROKER GIVES

Exactly-once stops at the broker

BrokerWhat it removesWhere it stops
SQS FIFOProducer retries with the same dedup ID, within 5 minutesA redelivery after the visibility timeout
KafkaDuplicates in read-process-write between Kafka topicsAny write outside Kafka: your database, an API
RabbitMQNothing: acks give at-least-onceThe 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

The message ID and the change in one transaction

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

  1. INSERT adds the ID: 1 row.
  2. UPDATE adds 50 points.
  3. COMMIT saves both together.
  4. Ack: the broker drops the message.

DUPLICATE

  1. INSERT hits the unique key: 0 rows.
  2. ROLLBACK: the UPDATE never runs.
  3. Ack: the broker drops the message.

RULE 5 · DEDUPLICATE

EVEN WITH IDEMPOTENT HANDLERS

A duplicate still costs a full handler run

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

Prune the dedup table

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

Why chunks, not one DELETE by time

DELETE ... WHERE processed_at < XChunks of 10,000
TransactionOne, open until the last row is goneMany, a few milliseconds each
VACUUMHeld back in the whole database, the outbox tooReleased at each commit; cleans between chunks
WAL and replicasOne large burst; replicas lagSpread out; the job can pause between chunks
A failureRolls back all the workLoses 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

Three things to take home

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

Talks