Idempotent Consumers & the Inbox Pattern
"Consequently, a consumer must be idempotent: the outcome of processing the same message repeatedly must be the same as processing the message once." — Chris Richardson, Pattern: Idempotent Consumer, microservices.io
Summary: Every broker that never loses a message is willing to deliver it twice, so the consumer must make the second delivery harmless: a stable key, a unique constraint, and the key written in the same transaction as the side effect. Focus: Idempotency keys (and where each broker gives you one), the inbox table, "process then mark" vs "mark then process", concurrent duplicates, TTL and cleanup, natural idempotency, non-transactional side effects, idempotent projections, and testing. Learning goal: Turn any at-least-once consumer into an effectively-once one, choose the key, size and expire the dedup table, and know which side effects the inbox can and cannot cover.
This page is the complete reference for consumer-side deduplication. It covers the idempotency key and its sources on RabbitMQ, Kafka, Redis Streams, NATS JetStream, Pulsar, SQS and Azure Service Bus, the inbox (processed_messages) table and the transactional pattern around it, the two orders of marking and processing, the race between concurrent duplicates, TTL and sizing, natural idempotency through upserts and conditional updates, side effects that cannot join a database transaction (email, HTTP), idempotent read-model projections with version checks, the HTTP Idempotency-Key twin, and how to test all of it. It deliberately does not re-teach its neighbours: why duplicates exist at all (the two-generals argument, Kafka's idempotent producer and transactions as the broker-side piece) is in Delivery Guarantees; how acks, offsets and XACK work is in Message Acknowledgment; the producing half of the pair is Transactional Outbox; order across partitions is Ordering & Partitioning; dead-lettering is Dead-Letter Queue; and the database side (unique indexes, transactions) is in ACID & Transactions.
Page map
| If you are looking for | Go to |
|---|---|
| The five ways to get idempotency, in one table | Everything in one minute |
| Why consumers get duplicates and why the broker cannot fix it | Why consumers must be idempotent |
| Where the idea comes from (EIP, Richardson, Stripe, Kafka design notes) | Where the idea comes from |
| Idempotent vs "safe" vs "exactly-once" | Idempotency and duplicate delivery |
| Which id to dedup on (message id, offset, entry id, business key) | The idempotency key |
| The table, its schema, and the other meaning of "inbox" | The inbox table |
| The transaction: check + effect + mark in one commit | The transactional pattern |
| Mark-then-process vs process-then-mark, with crash timelines | Mark order |
| Two workers, same message, same moment | Concurrent duplicates |
Upserts, SET instead of +1, conditional updates | Natural idempotency |
| Email, HTTP, payment calls | Non-transactional side effects |
| TTL, dedup window, cleanup, partition drops, sizing | TTL, window and cleanup |
| Read models, version checks, out-of-order events | Idempotent projections |
| Storing the Kafka offset next to the data | Offsets stored with the output |
| The HTTP twin | Idempotency-Key at the HTTP edge |
| Knobs, error codes, dedup primitives per store | Mechanics |
| Problem to solution table | Solving the classic problems |
| Which error to retry | Retries and failure handling |
| Which technique for which workload | Choosing an approach |
| Go (pgx) and Laravel code | Go, Laravel |
| RabbitMQ, Kafka, Redis Streams specifics | Broker differences |
| Monolith to multi-region | In architecture |
| Reproduce duplicates and watch the inbox reject them | Lab |
| Wrong beliefs, a cheat sheet, every term defined | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The five ways to make a consumer safe against duplicates. Every row is unpacked below.
| Technique | In plain words | Needs | Covers | Does not cover |
|---|---|---|---|---|
| Natural idempotency | The operation gives the same result however often it runs (SET status = 'paid', upsert by key) | Nothing extra | Updates by key, projections, cache refreshes | Increments, appends, "send an email" |
| Inbox table (idempotent consumer) | Remember every message id you finished; refuse a second one | A unique key per message, one database | Anything written in the same database transaction | Effects in other systems |
| Version check | Apply an event only if its version is newer than the stored one | A per-aggregate version in the message | Duplicates and out-of-order delivery for read models | Commands with no version |
| Downstream idempotency key | Pass your message id to the system you call; it dedups | A downstream that honours a key | HTTP calls, payments, provider APIs | Providers that ignore the key (most email APIs) |
| Broker-side dedup window | The producer-side broker drops a repeat id within a window | A producer-chosen id | Producer retries within the window | Consumer redelivery; anything after the window |
The order of "mark" and "process".
| Order | Crash between the two steps | Delivery semantics you really get |
|---|---|---|
| Process, then mark (two commits) | Effect already happened, mark missing: next delivery repeats the effect | At-least-once (the original bug, one step later) |
| Mark, then process (two commits) | Mark exists, effect missing: next delivery is skipped, work is lost | At-most-once |
| Mark and process in ONE transaction | Both roll back together | Effectively-once, if the effect is in that database |
Where each broker gives you a key.
| Broker | Producer-chosen id | Broker-assigned id | Stable across redelivery | Stable across a producer retry |
|---|---|---|---|---|
| RabbitMQ | message-id property (optional, never checked) | none (delivery tag is per channel) | Yes (message-id survives requeue) | Yes, if the producer reuses it |
| Kafka | Header or payload field | topic-partition-offset | Yes | Offset: no (two offsets). Header: yes |
| Redis Streams | A field such as event_id; or IDMP pid + iid (8.6+) | Entry id ms-seq | Yes (same id after XCLAIM/XAUTOCLAIM) | Entry id: no. IDMP: yes |
| Laravel queue | Your own $messageId property | Payload uuid ($this->job->uuid()) | Yes | uuid: no (new dispatch, new uuid) |
Why consumers must be idempotent
A consumer does two things: perform an effect, then tell the broker it is done (ack, offset commit, XACK). A failure between the two leaves the broker unsure, and an at-least-once broker resolves unsureness by delivering again. Duplicates also arrive from other directions: a producer that retried after a lost confirm, a consumer that lost its partition during a rebalance while still working, a visibility timeout (SQS), retry_after (Laravel), or an idle pending entry claimed by another consumer (Redis). Delivery Guarantees explains why no protocol removes this. The consequence lands here: the second delivery must be harmless.
| Cheaper, weaker | Costlier, stronger |
|---|---|
| No dedup, tolerate rare duplicates (a log line, a cache refresh) | Inbox table with unique key in the business transaction |
| Dedup on a convenient id (offset) | Dedup on a producer-chosen business id (catches producer duplicates) |
| Short TTL, small table | Long window, large table, replays stay safe |
Redis SET NX as dedup store (fast, separate system) | Same-database unique constraint (atomic with the effect) |
An everyday picture. A coat check. You hand over a coat and get a numbered ticket. If the attendant, unsure whether you collected it, offers it again, the ticket number tells them it is gone. The ticket is written when the coat changes hands: not before, not after. That is the transaction. A coat check that logs tickets in a separate book updated later is the "process then mark" design, and will occasionally hand out a coat twice.
Three common misunderstandings, up front
- "The broker is exactly-once, so I do not need this." Kafka's idempotent producer and transactions cover broker-side duplicates and Kafka-to-Kafka flows. The moment a consumer writes to a database or calls an HTTP API, redelivery can duplicate that effect.
- "
SELECTto check, thenINSERT, is enough." Two workers can both see "not seen". The unique constraint is the primitive; theSELECTis an optimisation at best. - "
ShouldBeUnique(Laravel) makes my job idempotent." It de-duplicates dispatches through a cache lock. It does not stophandle()from running twice for one job.
Where the idea comes from
The reasoning starts in delivery guarantees. Enterprise Integration Patterns states the problem in two lines:
"Even when a sender application only sends a message once, the receiver application may receive the message more than once. How can a message receiver deal with duplicate messages?"
and the solution as two means: "Explicit 'de-duping', i.e. the removal of duplicate messages" and "Defining the message semantics to support idempotency". That is the pattern's name, Idempotent Receiver, in the Messaging Endpoints group. Richardson's microservices.io page states the consequence for at-least-once delivery: "One side-effect, however, is that the consumer can be invoked repeatedly for the same message." His example, an AccountDebited message that subtracts from a balance, "would calculate the incorrect balance". His solution is a PROCESSED_MESSAGES table: after starting the database transaction, insert the message id; because (subscriberId, messageID) is the primary key, the insert fails if the message was already processed, so the handler rolls back and ignores it. He lists a second option too, storing ids on the business entities the consumer touches. Kafka's design documentation makes the natural-idempotency point: "In many cases messages have a primary key and so the updates are idempotent (receiving the same message twice just overwrites a record with another copy of itself)". The same idea predates brokers in HTTP APIs; Brandur Leach's 2017 Stripe article is the standard reference for the client-supplied key, and the IETF Idempotency-Key header draft standardises it (HTTP twin).
The word inbox has two meanings in practice, covered in the inbox table: a dedup-only table (Richardson's PROCESSED_MESSAGES) and a full receive-buffer table you process from asynchronously. Both start with the same unique key.
The concepts, one by one
Idempotency and duplicate delivery Must-know
In plain words: An operation is idempotent when doing it twice leaves the same result as doing it once. A consumer is idempotent when receiving the same message twice does the same.
Common misunderstanding: "Idempotent means the handler does nothing on the second call." No: it means the state afterwards is the same. A handler that recomputes and rewrites the same row is idempotent even though it did work. And the opposite trap: a handler that returns an error on the second call is not idempotent from the broker's view, because the broker will retry forever.
Definition: A function f is idempotent when f(f(x)) = f(x), the definition EIP borrows from mathematics. For messages: the effect of N deliveries equals the effect of one. Three related words are often mixed up:
| Word | Means | Example |
|---|---|---|
| Idempotent | Repeating gives the same state | UPDATE orders SET status = 'paid' WHERE id = 7 |
| Safe | Repeating changes nothing at all (read-only) | SELECT, HTTP GET |
| Exactly-once (delivery) | The receiver sees one copy | Impossible end to end (two generals) |
| Exactly-once (effect) | At-least-once delivery + idempotent handler | The goal of this page |
Delivery 1 Delivery 2 (duplicate)
1 receive m-17
2 balance = balance + 500 -- non-idempotent: 500
3 crash before ack
4 receive m-17 again
5 balance = balance + 500 -- 1000: wrong
6 SET status='paid' -- idempotent version: same row, same valueReal scenario: a wallet credit applied twice after a worker restart; an order marked shipped twice (harmless) vs two shipment labels printed (not harmless); a welcome email sent twice after a timeout; a counter that drifts upward after every deploy.
What provides it: natural operations, a unique key, or a version. The rest of this page is the catalogue.
The idempotency key Must-know
In plain words: The key is the answer to "is this the same message as one I already handled?" Pick the wrong key and you either miss duplicates or drop legitimate messages.
Common misunderstanding: "The Kafka message key identifies the message." It identifies the entity used for partitioning (all events of order 7 share a key). Many different messages have the same key, so deduplicating on it throws away every event after the first.
Definition: A stable, unique, producer-visible identity for one logical message, created once before the first send and carried unchanged through every retry and redelivery. Two candidates: a message id (UUID or ULID, identifies one logical publish) and a business key (order_id + "paid", payment_id; identifies the meaning, so it also catches a producer that published the same fact twice with two ids).
Producer Broker Consumer
1 id = uuid() (ONCE)
2 publish(id, body) -----------> stored
3 confirm lost; timeout
4 publish(id, body) -----------> stored again (same id)
5 deliver ------------------> inbox(id) -> run
6 deliver (2nd copy) --------> inbox(id) -> skip
7 (if the id were regenerated at step 4 the consumer would see two different ids)Where the key comes from, per source:
| Source | Example | Set by | Redelivery (same copy again) | Producer duplicate (two copies) | Watch out |
|---|---|---|---|---|---|
| Producer message id | uuid/ULID in header or field | Producer, once | Caught | Caught, if reused on retry | Must be created BEFORE the first attempt, not inside the retry loop |
RabbitMQ message-id | Publishing.MessageId / Delivery.MessageId | Publisher | Caught | Caught if reused | Optional; the broker never sets or checks it; empty means no dedup |
Kafka topic-partition-offset | wallet.credits-3-18204 | Broker at append | Caught (after rebalance or crash) | Not caught (two offsets) | Resets if the topic is recreated; offsets are per partition |
Kafka header message-id | Header written by the producer | Producer | Caught | Caught | Needs a client that exposes record headers |
| Redis Streams entry id | 1700000000000-0 | XADD | Caught (same id after XCLAIM/XAUTOCLAIM) | Not caught (two entries) | Prefer a producer-set event_id field |
Redis 8.6 IDMP pid + iid | XADD s IDMP billing-1 payment-42 * ... | Producer | n/a (producer side) | Caught: XADD returns the original entry id | Producer-side window only (IDMP-DURATION, IDMP-MAXSIZE) |
Laravel payload uuid | $this->job->uuid() | Laravel at dispatch | Caught | Not caught (new dispatch, new uuid) | Fine when the dispatch happens once per intent |
| Business key | order_id:paid, payment_id, (aggregate_id, version) | Domain | Caught | Caught | A legitimate repeat (second refund of the same order) needs a discriminator |
| Content hash | SHA-256 of the body; Redis IDMPAUTO | Consumer or Redis | Caught | Caught | Two legitimate identical commands (two "+500" credits) collide |
HTTP Idempotency-Key | Client-generated UUID | Client | Caught | Caught | Scope per user or tenant |
Real scenario: a payment service publishes PaymentCaptured with payment_id as the business key and a fresh UUID message id; the ledger consumer dedups on payment_id (one capture, one ledger entry), the notification consumer dedups on the message id (a second notification for the same payment would be a different message). Kafka's offset-only key lets a producer double-publish through; the Stripe design lets the client choose the key because only the client knows what "the same request" means.
What provides it: a producer discipline (generate the id once, persist it before sending, carry it as a header or field) plus, ideally, an outbox so the id is the outbox row's primary key (Transactional Outbox).
Fix: a business key plus message id as one string, scoped by consumer:
-- the dedup key is (consumer, message_id); consumer scopes it so two handlers
-- of the same message each run once
SELECT 'wallet-credit' AS consumer, 'pay_42:captured' AS message_id;The inbox table Must-know
In plain words: A table with one row per message you finished. A primary key stops a second row for the same message.
Common misunderstanding: "The inbox is a queue I read from." That is one meaning (below). In its dedup-only form the inbox is never read as a queue; it is only a set of "already done" ids.
Definition: processed_messages(consumer, message_id, processed_at) with PRIMARY KEY (consumer, message_id). The consumer column scopes the key because two handlers of one message must each run once. The unique constraint is the dedup primitive: the database enforces it even when two workers race, which an application-level SELECT then INSERT does not.
CREATE TABLE processed_messages (
consumer text NOT NULL,
message_id text NOT NULL,
processed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (consumer, message_id)
);
-- for the cleanup job (delete WHERE processed_at < now() - window)
CREATE INDEX processed_messages_processed_at_idx ON processed_messages (processed_at);Optional columns, each with a reason: topic, partition, "offset" for debugging and replays; payload_hash to detect "same id, different body" (a producer bug, the same condition the HTTP draft answers with 422); result to store the outcome and replay it; status and lease_until for non-transactional effects; received_at plus processed_at to measure latency. Use uuid instead of text for message_id when ids are UUIDs: 16 bytes against 37.
The second meaning: the full inbox. Some teams use "inbox" for a receive buffer: the consumer inserts the raw message into an inbox table (ON CONFLICT DO NOTHING), acks the broker straight after that commit, and a separate worker processes rows with FOR UPDATE SKIP LOCKED, marking each processed. Compare:
| Dedup-only inbox (idempotent consumer) | Full inbox (receive buffer) | |
|---|---|---|
| What is stored | The id only | The whole message, plus status |
| Ack timing | After the handler's transaction | Right after the buffer insert |
| Processing | Inline, in the consumer | Asynchronous, from the table |
| Gains | Simple; exactly one write path | Frees the broker fast; absorbs bursts; retry and poison handling live in SQL |
| Costs | Handler time holds the broker message | A second queue (your database) to operate and clean; extra latency |
-- full inbox: receive
INSERT INTO inbox (consumer, message_id, payload, received_at)
VALUES ($1, $2, $3, now())
ON CONFLICT (consumer, message_id) DO NOTHING; -- then ACK the broker
-- full inbox: process (many workers; see the SKIP LOCKED job queue in isolation-levels)
WITH next AS (
SELECT consumer, message_id FROM inbox
WHERE processed_at IS NULL
ORDER BY received_at
LIMIT 10
FOR UPDATE SKIP LOCKED
)
UPDATE inbox i SET processed_at = now()
FROM next WHERE i.consumer = next.consumer AND i.message_id = next.message_id
RETURNING i.*; -- apply business effects in this same transactionThe queue-from-a-table technique is described on Isolation Levels; the retry and dead-letter handling of rows that keep failing is Dead-Letter Queue. The rest of this page is about the dedup-only form, which is the one you need first.
The transactional pattern: check, effect and mark in ONE transaction Must-know
In plain words: Do three things as one all-or-nothing step: insert the message id, do the business write, commit. If anything fails, neither the mark nor the write exists.
Common misunderstanding: "I check SELECT 1 FROM processed_messages first, so I am safe." Two concurrent workers both see nothing and both proceed. The insert, protected by the unique constraint, is the check.
Definition: BEGIN; INSERT INTO processed_messages ... ON CONFLICT DO NOTHING; — if the command reports zero rows, the message is a duplicate: stop and acknowledge. Otherwise do the business write on the same transaction and COMMIT. Acknowledge the broker only after the commit.
Worker (new message m-17) Worker (redelivery of m-17)
1 BEGIN
2 INSERT processed_messages(c, m-17) -> 1 row
3 UPDATE wallets SET balance = balance + 500
4 COMMIT
5 ACK broker
6 BEGIN
7 INSERT processed_messages(c, m-17) -> 0 rows
8 ROLLBACK (nothing to undo); ACK brokerReal scenario: wallet credits, stock decrements, ledger postings, order state changes, inventory reservations, anything whose effect is rows in the same database as the inbox table.
What provides it:
| Store | Atomic "insert or tell me it existed" | Duplicate signal |
|---|---|---|
| PostgreSQL | INSERT ... ON CONFLICT (cols) DO NOTHING | INSERT 0 0 command tag, RowsAffected() == 0 |
| PostgreSQL (plain insert) | INSERT and catch the error | SQLSTATE 23505 unique_violation (aborts the transaction) |
| MySQL / InnoDB | INSERT IGNORE, or ON DUPLICATE KEY UPDATE | 0 affected rows, or ER_DUP_ENTRY (1062, SQLSTATE 23000) |
| SQLite | INSERT ... ON CONFLICT DO NOTHING | changes() is 0 |
| PostgreSQL 19 | INSERT ... ON CONFLICT DO SELECT returns the existing row (idempotent "insert or get") | The returned row is not yours |
| MongoDB | Unique index plus insertOne | Duplicate key error |
| Redis | SET key value NX EX seconds | Reply is nil when the key existed (separate system, not atomic with your DB write) |
Fix: Go (pgx) and Laravel below. A runnable core in Go:
// Package pginbox is the inbox (idempotent consumer) pattern on pgx v5.
//
// The id of a message is inserted into processed_messages in the SAME
// transaction as the business write. The primary key is the guard: a second
// attempt inserts zero rows, so the handler is skipped.
//
// CREATE TABLE processed_messages (
// consumer text NOT NULL,
// message_id text NOT NULL,
// processed_at timestamptz NOT NULL DEFAULT now(),
// PRIMARY KEY (consumer, message_id)
// );
// CREATE INDEX processed_messages_processed_at_idx
// ON processed_messages (processed_at); -- for the cleanup job
package pginbox
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
// Beginner is the part of *pgxpool.Pool (or *pgx.Conn) the inbox needs.
type Beginner interface {
Begin(ctx context.Context) (pgx.Tx, error)
}
// Result tells the caller what happened. Both values mean "acknowledge the
// message"; only an error means "leave it for redelivery".
type Result int
const (
Processed Result = iota // the handler ran and the transaction committed
Duplicate // the id was already in the inbox; handler skipped
)
func (r Result) String() string {
if r == Duplicate {
return "duplicate"
}
return "processed"
}
const markSQL = `INSERT INTO processed_messages (consumer, message_id)
VALUES ($1, $2)
ON CONFLICT (consumer, message_id) DO NOTHING`
// Handler performs the business write inside the transaction it is given.
// It must not commit or roll back; Process owns the transaction.
type Handler func(ctx context.Context, tx pgx.Tx) error
// Process runs fn at most once per (consumer, messageID): mark + side effect
// + commit in one transaction. A crash, an error or a lost connection rolls
// both back, so redelivery runs the handler again; a duplicate hits the
// primary key and is skipped.
func Process(ctx context.Context, db Beginner, consumer, messageID string, fn Handler) (Result, error) {
tx, err := db.Begin(ctx) // READ COMMITTED unless the pool says otherwise
if err != nil {
return 0, fmt.Errorf("begin: %w", err)
}
// Harmless after Commit (pgx returns ErrTxClosed); essential on every error path.
defer func() { _ = tx.Rollback(ctx) }()
tag, err := tx.Exec(ctx, markSQL, consumer, messageID)
if err != nil {
return 0, fmt.Errorf("mark: %w", err)
}
if tag.RowsAffected() == 0 {
return Duplicate, nil // already committed by someone else
}
if err := fn(ctx, tx); err != nil {
return 0, fmt.Errorf("handle: %w", err) // rollback also removes the mark
}
if err := tx.Commit(ctx); err != nil {
return 0, fmt.Errorf("commit: %w", err)
}
return Processed, nil
}
// IsUniqueViolation reports SQLSTATE 23505. You need it only when you use a
// plain INSERT instead of ON CONFLICT DO NOTHING; on PostgreSQL the failed
// statement aborts the transaction, so the caller must start a new one.
func IsUniqueViolation(err error) bool {
var pe *pgconn.PgError
return errors.As(err, &pe) && pe.Code == "23505"
}Process then mark vs mark then process Must-know
In plain words: Two separate writes always have a gap between them. If you crash in the gap, "process, then mark" repeats the work and "mark, then process" loses it.
Common misunderstanding: "Mark first, it is safer." Mark-first is safe against duplicates and unsafe against loss: a crash after the mark and before the effect means the redelivery is skipped and the message's work never happens. You turned at-least-once into at-most-once without noticing.
Definition: The order only matters when the two writes are in different transactions. In one transaction the order is irrelevant, because both are undone together.
A. process then mark (two commits)
1 receive m-17
2 UPDATE wallets ... COMMIT -- effect done
3 ---- crash ----
4 (mark never written)
5 redelivery: no mark -> UPDATE again -> balance +1000 DUPLICATE
B. mark then process (two commits)
1 receive m-17
2 INSERT mark ... COMMIT -- mark durable
3 ---- crash ----
4 (effect never applied)
5 redelivery: mark exists -> skipped -> balance +0 LOST
C. one transaction (inbox)
1 BEGIN; INSERT mark; UPDATE wallets;
2 ---- crash ---- -> both undone
3 redelivery: no mark -> BEGIN; INSERT mark; UPDATE; COMMIT CORRECTReal scenario: a Redis SET NX "seen" key plus a database write is A or B by construction (two systems, no shared transaction). The classic production incident is B hidden behind a cache: the key was set, the worker died, and every retry returned "already processed".
What prevents it: one transaction, in one database, containing both writes. When the effect lives elsewhere you are back to claim, perform, complete.
| Design | Crash gap | Result | When acceptable |
|---|---|---|---|
| Process then mark (two commits) | Effect done, mark missing | Duplicate effect | Effect is naturally idempotent |
| Mark then process (two commits) | Mark done, effect missing | Lost message | The effect is optional and a duplicate is worse than a miss (a marketing email) |
| Same transaction | None | Effectively-once | Effect is in the inbox's database |
| Claim, perform, complete (lease) | Effect done, "done" missing | Repeat effect with the same downstream key | Effect is external and the downstream dedups |
Concurrent duplicates Important
In plain words: Sometimes the duplicate is not later but simultaneous: a slow handler outlives its visibility timeout, the broker hands the same message to a second worker, and now two workers run at once.
Common misunderstanding: "The second worker will see the first worker's mark." Not until the first one commits. Until then the mark is invisible, which is exactly why a SELECT check fails and why the unique constraint matters.
Definition: PostgreSQL's index uniqueness check handles it: "If a conflicting row has been inserted by an as-yet-uncommitted transaction, the would-be inserter must wait to see if that transaction commits. If it rolls back then there is no conflict. If it commits without deleting the conflicting row again, there is a uniqueness violation." The INSERT documentation adds that tables with unique indexes "might block if concurrent sessions perform actions that lock or modify rows matching the unique index values being inserted". With ON CONFLICT DO NOTHING, "violation" becomes "insert zero rows".
Worker A (m-17) Worker B (m-17, duplicate)
1 BEGIN
2 INSERT mark(m-17) -> 1 row
3 BEGIN
4 INSERT mark(m-17) ... BLOCKS (A uncommitted)
5 UPDATE wallets ...
6 COMMIT (unblocks) -> INSERT 0 0 -> duplicate, ACK
-- variant: A rolls back at step 6 (unblocks) -> INSERT 0 1 -> B runs the handlerReal scenario: a Kafka consumer whose processing exceeds max.poll.interval.ms and is kicked from the group while its handler is still running; an SQS message whose visibility timeout expired; a Redis entry XAUTOCLAIMed while the original worker is only slow; Laravel's retry_after shorter than the job.
What prevents it: the unique constraint plus short transactions. Because B waits for A, keep the handler's transaction free of slow calls (HTTP, sleeps) so B does not hold a connection for long; set lock_timeout so a blocked duplicate gives up with SQLSTATE 55P03 and is requeued instead of occupying the pool (Connection Pooling). In READ COMMITTED (PostgreSQL's default) ON CONFLICT DO NOTHING may legitimately skip a row "due to the outcome of another transaction whose effects are not visible to the INSERT snapshot"; that is the case above and is what you want.
Fix: the code in The transactional pattern is already race-safe; add SET LOCAL lock_timeout = '2s' in the transaction when duplicates are common.
Natural idempotency Must-know
In plain words: Sometimes no table is needed, because repeating the operation changes nothing: set a value instead of adding to it, upsert by key, move a status forward only once.
Common misunderstanding: "Upsert is always idempotent." An upsert that adds (ON CONFLICT DO UPDATE SET qty = qty + EXCLUDED.qty) is not. It is idempotent only when the update writes a value that does not depend on the old value.
Definition: An operation whose repeated application converges to the same state.
| Operation | Idempotent? | Why | Idempotent rewrite |
|---|---|---|---|
SET status = 'paid' | Yes | Same value each time | none needed |
INSERT ... ON CONFLICT (id) DO UPDATE SET status = EXCLUDED.status | Yes | Writes the new value, not a delta | none needed |
UPDATE orders SET status = 'paid' WHERE id = 7 AND status = 'pending' | Yes | Conditional: only the first moves it | none needed |
balance = balance + 500 | No | Depends on the old value | Inbox, or store each credit as a ledger row keyed by message id and compute the balance |
likes = likes + 1 | No | Counter | A (post_id, user_id) unique table; count rows |
| Append to a list/log | No | Grows each time | Key each entry by message id |
| Send an email, call an API | No | External effect | Downstream key |
| Delete by id | Yes | Gone is gone (the second DELETE affects 0 rows) | none needed |
| Create with a client-chosen id | Yes | Second create conflicts or is ignored | none needed |
-- set, not add
UPDATE orders SET status = 'paid' WHERE id = 7;
-- upsert by business key
INSERT INTO order_projection (order_id, status) VALUES ('o-1', 'paid')
ON CONFLICT (order_id) DO UPDATE SET status = EXCLUDED.status;
-- move forward once
UPDATE orders SET status = 'paid' WHERE id = 7 AND status = 'pending';
-- counter as a set: replay-safe
INSERT INTO post_likes (post_id, user_id) VALUES (9, 42) ON CONFLICT DO NOTHING;Real scenario: read models and search indexes (rebuild the document from current state), last_seen_at columns, status transitions, cache invalidation, feature-flag sync. Kafka log compaction keeps the last record per key, which only makes sense when records are naturally idempotent snapshots.
What provides it: schema choices: unique keys, set-semantics tables instead of counters, ledger rows instead of balances, conditional updates. Prefer these before adding an inbox.
Non-transactional side effects Important
In plain words: An email, a payment call or a webhook is outside your database. The inbox cannot make "send it and record it" atomic, so you must pick which failure you prefer: sent twice, or never sent.
Common misunderstanding: "A transaction around the HTTP call fixes it." The transaction rolls back your rows; the email is already gone. Holding a database transaction open across a network call also blocks concurrent duplicates and exhausts the pool.
Definition: For an external effect, the crash gap cannot be closed locally, so you (a) make the downstream call itself idempotent by passing it a key derived from your message id, (b) track the effect with a lease so a crash is detected and repaired, or (c) move the effect into an outbox so a relay performs it at-least-once against a downstream that dedups.
Consumer Inbox row Mail provider
1 claim(m-17) ------------------> processing, lease 120 s
2 POST /send Idempotency-Key: welcome:m-17 --------------> sends, stores key
3 ---- crash before 4 ----
4 (lease expires)
5 redelivery: claim(m-17) lease expired -> re-claimed
6 POST /send same key ----------------------------------> returns the first result
7 complete(m-17) ----------------> doneReal scenario: welcome emails, SMS, payment captures with a PSP, shipping label creation, webhooks to customers, calling a legacy SOAP system. Stripe's API accepts an idempotency key on POST and replays the first result; a typical email API does not, so for email you choose at-least-once (nuisance) or at-most-once (never) by business consequence.
What provides it:
| Technique | How | Advantage | Cost or limit |
|---|---|---|---|
| Downstream idempotency key | Header such as Idempotency-Key: consumer:message_id | Simplest; no extra state | Downstream must support it and have a long enough window (Stripe documents that keys may be removed after at least 24 hours) |
| Claim, perform, complete | Inbox row with status and lease_until; ON CONFLICT DO UPDATE ... WHERE status = 'processing' AND lease_until < now() | Detects crashes; bounds concurrency | Effect may repeat after a lease expiry; still needs a downstream key |
| Outbox the effect | Handler writes an outbox row send_email in the business transaction; a relay sends it | Handler stays transactional; retries decoupled | Another moving part; at-least-once at the relay |
| Check the target first | GET the payment by your reference before POST | Works with some APIs without keys | Racy between check and act; extra latency |
| Accept the duplicate | Do nothing | Zero cost | Only when harmless (log, metric, refresh) |
Outbox + inbox pairing. Across two services the pair is the standard recipe: the producer's outbox guarantees every event is published at least once, the consumer's inbox guarantees each is applied at most once, together effectively-once between two databases.
Fix: Go (claim, perform with a downstream key, complete) and Laravel equivalents are in the sections below.
TTL, dedup window and cleanup Must-know
In plain words: The table grows with every message. A dedup row only has to live as long as a duplicate can still arrive; after that it is dead weight.
Common misunderstanding: "Keep rows for a day, that is plenty." The right number is derived, not guessed: expire too early and a late duplicate runs again silently; keep too long and the table, its index and its vacuum cost grow without benefit.
Definition: The dedup window is the longest time between the first delivery of a message and the last possible delivery of a copy of it. It is the sum of the redelivery paths: the broker's redelivery mechanism (visibility timeout, retry_after, pending-entry idle time, Kafka retention for replays), the retry and backoff schedule, the longest time a message may spend parked in a DLQ before replay, and the producer's own retry horizon, plus a margin. The TTL of a row is that window.
t=0 first delivery, mark written
t=5s broker redelivery (visibility timeout)
t=2min retry with backoff
t=1h message returns from DLQ replay
t=24h producer's retry job resends (outbox relay recovered after an outage)
t=7d longest path + margin -> TTL = 7 d; before this a duplicate must be caughtHow brokers bound the same problem on the producer side:
| System | Dedup key | Window | Notes |
|---|---|---|---|
| Amazon SQS FIFO | MessageDeduplicationId | 5 minutes | Continues tracking the id even after the message is received and deleted |
| Azure Service Bus | MessageId (with PartitionKey when partitioned) | Default 10 minutes; 20 seconds to 7 days | Scheduled messages included; bigger windows reduce throughput |
| NATS JetStream | Nats-Msg-Id header | Default 2 minutes (--dupe-window) | Only the id is consulted, not the body |
| Apache Pulsar | Producer name (the broker filters duplicates per producer) | Tracked in dedup snapshots; disabled by default (brokerDeduplicationEnabled=false); producer state dropped after 6 hours of inactivity by default | Producer name is mandatory; set the message timeout to 0 |
| Redis Streams 8.6+ | IDMP pid + iid | IDMP-DURATION default 100 s (1 to 86400); IDMP-MAXSIZE default 100 per producer (1 to 10000) | Monitor iids-duplicates in XINFO STREAM |
| Kafka | Idempotent producer sequence numbers | The producer session only | Not a time window; resets with a new producer id |
None of these covers consumer redelivery after their window. The inbox covers the rest, with a window you control.
Cleanup strategies:
| Strategy | How | Advantage | Limit |
|---|---|---|---|
Batched DELETE | Scheduled job: delete rows older than the window in small batches (index on processed_at) | Simple | Generates dead tuples and WAL; needs autovacuum headroom |
| Partition and drop | Partition by day, DROP or DETACH old partitions | Instant, no VACUUM ("far faster than a bulk operation", PostgreSQL docs) | A unique key on a partitioned table must include the partition key |
| TTL store | Redis EXPIRE / DynamoDB TTL as the dedup store | Self-cleaning | Not atomic with the DB write |
| Keep forever | Never delete | Dedup window = infinity | Cost grows with throughput; fine at low volume |
-- batched delete (PostgreSQL has no DELETE ... LIMIT)
DELETE FROM processed_messages
WHERE (consumer, message_id) IN (
SELECT consumer, message_id FROM processed_messages
WHERE processed_at < now() - interval '14 days'
ORDER BY processed_at LIMIT 5000
);The partitioning trap. PostgreSQL requires that a unique or primary key constraint on a partitioned table "must include all of the partition key columns". If you partition by processed_at (time of processing) the key becomes (consumer, message_id, processed_at), and a duplicate processed a day later has a different processed_at, so it is accepted: you have silently lost cross-day dedup. Partition by a property of the message instead, one that is identical on every copy (a producer-set timestamp or a ULID's time part):
CREATE TABLE processed_messages (
consumer text NOT NULL,
message_id text NOT NULL,
occurred_at timestamptz NOT NULL, -- from the message, identical on every copy
PRIMARY KEY (consumer, message_id, occurred_at)
) PARTITION BY RANGE (occurred_at);
CREATE TABLE processed_messages_2026_11_25 PARTITION OF processed_messages
FOR VALUES FROM ('2026-11-25') TO ('2026-11-26');
-- retire a day: DROP TABLE processed_messages_2026_11_18;
-- the conflict target must name the partition key too:
-- ... ON CONFLICT (consumer, message_id, occurred_at) DO NOTHINGSizing. Rows = message rate x window. Our estimate for the size is 100 to 150 bytes per row including the primary-key index entry for text ids (measure yours with pg_total_relation_size):
| Rate | Window | Rows | Approximate size at 120 B/row |
|---|---|---|---|
| 10 msg/s | 7 days | 6 million | under 1 GB |
| 100 msg/s | 7 days | 60 million | about 7 GB |
| 1,000 msg/s | 14 days | 1.2 billion | about 145 GB |
| 10,000 msg/s | 7 days | 6 billion | about 725 GB: partition, shorten, or drop the table |
Retention vs dedup window: the trade-off. A longer window means safer replays and late DLQ returns but a bigger table, a bigger index and more cleanup churn. A shorter window means a smaller table and a risk that a late duplicate (an outbox relay recovering after a day-long outage, a DLQ replayed after a week, a topic replayed from offset zero) is applied again. Two practical rules: the window must be at least your longest planned replay or delay path; and for deliberate replays (rebuilding a projection from a Kafka topic) use a new consumer name, which is a fresh dedup namespace, or rely on version-checked projections that do not need a table at all.
Idempotent projections Important
In plain words: A read model built from events must survive the same event arriving twice and an older event arriving after a newer one. A version number makes both cases a no-op.
Common misunderstanding: "Use the event timestamp to keep the newest." Clocks on different producers disagree. Use a per-aggregate version or sequence number assigned by the aggregate's owner.
Definition: Apply an event only if its version is greater than the stored version: INSERT ... ON CONFLICT (id) DO UPDATE ... WHERE projection.version < EXCLUDED.version. Replays (equal version) and stale events (lower version) change zero rows. Compare with Optimistic vs Pessimistic Locking: a version column on a read model is the same compare-and-set idea, applied to messages.
Messages arrive: v3, v3 (dup), v2 (late), v4
1 v3 -> INSERT, rows=1, projection = v3
2 v3 -> conflict, WHERE 3 < 3 false, rows=0 (duplicate ignored)
3 v2 -> conflict, WHERE 3 < 2 false, rows=0 (stale ignored)
4 v4 -> conflict, WHERE 3 < 4 true, rows=1 (applied)We ran exactly this statement sequence on SQLite 3 (same ON CONFLICT ... DO UPDATE ... WHERE syntax) to check the counts above: 1, 0, 0, 1, and the final row is o-1 | shipped | 4.
Real scenario: order status read models, search index documents, customer profile caches, materialised "orders per day" tables, anything fed by events from Event Sourcing & CQRS.
What provides it / limits: a version in the message envelope (Message Design & Schema Evolution). version < accepts jumps (v3 then v5), which is right when events are full state snapshots; when events are deltas a gap means a missing event, so require version = stored + 1 and park or retry on a gap (Ordering & Partitioning). Counters: do not store count + 1; recompute from a set of ids or store the count with the version of the last included event.
Fix: Go and Laravel:
// Package projection updates a read model from events that may arrive twice
// and out of order. A version column turns "apply" into "apply only if newer",
// which is naturally idempotent: replays and stale events are no-ops.
//
// CREATE TABLE order_projection (
// order_id text PRIMARY KEY,
// status text NOT NULL,
// version bigint NOT NULL,
// updated_at timestamptz NOT NULL DEFAULT now()
// );
package projection
import (
"context"
"github.com/jackc/pgx/v5/pgconn"
)
// OrderEvent carries the aggregate's version assigned by the producer.
type OrderEvent struct {
OrderID string
Status string
Version int64
}
const upsertSQL = `INSERT INTO order_projection (order_id, status, version)
VALUES ($1, $2, $3)
ON CONFLICT (order_id) DO UPDATE
SET status = EXCLUDED.status, version = EXCLUDED.version, updated_at = now()
WHERE order_projection.version < EXCLUDED.version`
// Execer is satisfied by pgx.Tx, *pgx.Conn and *pgxpool.Pool.
type Execer interface {
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
}
// Apply returns true when the event changed the projection, false when it was
// a duplicate (same version) or stale (older version).
func Apply(ctx context.Context, db Execer, e OrderEvent) (bool, error) {
tag, err := db.Exec(ctx, upsertSQL, e.OrderID, e.Status, e.Version)
if err != nil {
return false, err
}
return tag.RowsAffected() == 1, nil
}<?php
namespace App\Projections;
use Illuminate\Support\Facades\DB;
// A read model that tolerates duplicate AND out-of-order events: apply an
// event only if its version is newer than the stored one. A replay (same
// version) and a stale event (older version) both change zero rows.
final class ProjectionUpsert
{
public static function apply(string $orderId, string $status, int $version): bool
{
$changed = DB::affectingStatement(
'INSERT INTO order_projection (order_id, status, version, updated_at)
VALUES (?, ?, ?, now())
ON CONFLICT (order_id) DO UPDATE
SET status = EXCLUDED.status,
version = EXCLUDED.version,
updated_at = now()
WHERE order_projection.version < EXCLUDED.version',
[$orderId, $status, $version],
);
return $changed === 1;
}
}Offsets stored with the output Good to know
In plain words: Instead of one dedup row per message, store one row per partition: "I have applied up to offset N", updated in the same transaction as the business write. On restart, seek to N.
Common misunderstanding: "Kafka's exactly-once covers this." It covers Kafka to Kafka. For a database output, Kafka's design documentation recommends exactly this: "letting the consumer store its offset in the same place as its output."
Definition: kafka_offsets(group, topic, partition, next_offset), advanced in the business transaction with a guard (WHERE next_offset <= record_offset); on partition assignment, set the consumer position from that table.
Real scenario: a high-volume Kafka-to-PostgreSQL sink at hundreds of thousands of records per second where a row per message is too expensive; batch loaders that commit a batch and its end offset together.
What provides it / limits: it needs ordered, partition-aware consumption (the position is meaningful per partition), a transaction that includes every effect, and care on rebalance (the stored offset, not the broker's committed offset, is the truth). It does not dedup a producer that wrote the same event at two offsets. Compile-only Go sketch:
// Package main sketches the other way to get exactly-once EFFECT from Kafka
// into a database without a per-message inbox: store the consumer position
// in the same database transaction as the business write, and seek to it on
// assignment. Kafka's design notes describe it as letting "the consumer store
// its offset in the same place as its output". Compile-only sketch.
//
// CREATE TABLE kafka_offsets (
// consumer_group text NOT NULL,
// topic text NOT NULL,
// partition int NOT NULL,
// next_offset bigint NOT NULL,
// PRIMARY KEY (consumer_group, topic, partition)
// );
package main
import (
"context"
"log"
"os"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/twmb/franz-go/pkg/kgo"
)
const group = "wallet-credit"
// seekToStored runs when partitions are assigned: it overrides Kafka's
// committed offset with the position stored next to the data.
func seekToStored(pool *pgxpool.Pool) func(context.Context, *kgo.Client, map[string][]int32) {
return func(ctx context.Context, cl *kgo.Client, assigned map[string][]int32) {
set := map[string]map[int32]kgo.EpochOffset{}
for topic, parts := range assigned {
for _, p := range parts {
var next int64
err := pool.QueryRow(ctx,
`SELECT next_offset FROM kafka_offsets
WHERE consumer_group = $1 AND topic = $2 AND partition = $3`,
group, topic, p).Scan(&next)
if err != nil {
continue // no row yet: keep the broker's starting position
}
if set[topic] == nil {
set[topic] = map[int32]kgo.EpochOffset{}
}
set[topic][p] = kgo.EpochOffset{Epoch: -1, Offset: next}
}
}
cl.SetOffsets(set)
}
}
// apply writes the business row and advances the stored offset atomically.
// The guard makes a replayed record (offset below next_offset) a no-op.
func apply(ctx context.Context, tx pgx.Tx, r *kgo.Record, walletID string, amount int64) error {
tag, err := tx.Exec(ctx,
`INSERT INTO kafka_offsets (consumer_group, topic, partition, next_offset)
VALUES ($1, $2, $3, $4)
ON CONFLICT (consumer_group, topic, partition) DO UPDATE
SET next_offset = EXCLUDED.next_offset
WHERE kafka_offsets.next_offset <= $5`,
group, r.Topic, r.Partition, r.Offset+1, r.Offset)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return nil // already applied: stored position is past this record
}
_, err = tx.Exec(ctx, `UPDATE wallets SET balance = balance + $1 WHERE id = $2`, amount, walletID)
return err
}
func main() {
if os.Getenv("DATABASE_URL") == "" {
log.Fatal("set DATABASE_URL to run")
}
pool, err := pgxpool.New(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer pool.Close()
cl, err := kgo.NewClient(
kgo.SeedBrokers("localhost:9092"),
kgo.ConsumerGroup(group),
kgo.ConsumeTopics("wallet.credits"),
kgo.DisableAutoCommit(), // the database is the source of truth
kgo.OnPartitionsAssigned(seekToStored(pool)),
)
if err != nil {
log.Fatal(err)
}
defer cl.Close()
_ = apply // called per record inside pool.BeginFunc in real code
}Idempotency-Key at the HTTP edge Good to know
In plain words: The same pattern for HTTP: the client sends a unique Idempotency-Key, the server remembers the first response and replays it on a retry.
Common misunderstanding: "A POST is never safe to retry." With a key it is. Leach describes the failure it fixes: for an endpoint that charges money, "accidentally calling it twice would lead to the customer being double-charged, which is very bad".
Definition: The IETF draft defines the header as a client-generated unique value "which the resource uses to recognize subsequent retries of the same request". Reuse of a key with a different payload should answer 422, a retry while the first request is still running 409, and expiry is the server's policy ("The resource SHOULD define such expiration policy and publish it in the documentation"). It is still an Internet-Draft, so treat details as provisional. Stripe documents keys of up to 255 characters and says keys may be removed after at least 24 hours.
What provides it: a table or cache keyed by (tenant, key) storing the request fingerprint, state (in_progress/done) and the response. For money, put the key in a table inside the write transaction; a cache-only claim (as in the Laravel middleware below) suits low-stakes endpoints.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpFoundation\Response;
// HTTP flavour of the same idea: the client picks the key, the server
// remembers the first response and replays it. Register on mutating routes:
// Route::post('/payments', ...)->middleware(IdempotencyKey::class);
//
// Simplification: this middleware stores the response in the cache, so the
// "claim" and the business write are NOT in one transaction. For money, put
// the key in a table and insert it in the same transaction as the write.
class IdempotencyKey
{
public function handle(Request $request, Closure $next): Response
{
$key = $request->header('Idempotency-Key');
if ($key === null || $key === '') {
return $next($request);
}
$fingerprint = hash('sha256', $request->method().$request->path().$request->getContent());
$cacheKey = 'idem:'.$request->user()?->getAuthIdentifier().':'.$key;
// Cache::add is atomic: only the first caller claims the key.
$claimed = Cache::add($cacheKey, ['state' => 'in_progress', 'fingerprint' => $fingerprint], now()->addHours(24));
if (! $claimed) {
$entry = Cache::get($cacheKey);
if (($entry['fingerprint'] ?? null) !== $fingerprint) {
return response()->json(['error' => 'Idempotency-Key reused with a different request'], 422);
}
if (($entry['state'] ?? null) === 'in_progress') {
return response()->json(['error' => 'A request with this key is still being processed'], 409);
}
return response($entry['body'], $entry['status'])
->header('Content-Type', $entry['content_type'])
->header('Idempotent-Replayed', 'true');
}
try {
$response = $next($request);
} catch (\Throwable $e) {
Cache::forget($cacheKey); // let the client retry after a crash
throw $e;
}
if ($response->getStatusCode() >= 500) {
Cache::forget($cacheKey);
return $response;
}
Cache::put($cacheKey, [
'state' => 'done',
'fingerprint' => $fingerprint,
'status' => $response->getStatusCode(),
'body' => $response->getContent(),
'content_type' => $response->headers->get('Content-Type', 'application/json'),
], now()->addHours(24));
return $response;
}
}Mechanics
What each store gives you as the dedup primitive
| Store | Primitive | Atomic with a business write? | Failure signature | Note |
|---|---|---|---|---|
| PostgreSQL | Unique/PK index + ON CONFLICT DO NOTHING | Yes (same transaction) | 23505 or 0 rows | Waits for an uncommitted conflicting insert |
| MySQL / InnoDB | Unique/PK + INSERT IGNORE or ON DUPLICATE KEY UPDATE | Yes | ER_DUP_ENTRY 1062, SQLSTATE 23000 | IGNORE downgrades errors to warnings, so it can hide errors other than duplicates (we could not fetch the MySQL reference; verify the details there) |
| SQLite | INSERT ... ON CONFLICT DO NOTHING | Yes | changes() = 0 | Single writer: no races, still needs the transaction |
| MongoDB | Unique index | Only with a multi-document transaction | Duplicate key error | Insert-then-act without a transaction is mark-then-process |
| Redis | SET key v NX EX n | No (separate system) | nil reply | Cache eviction or failover loses the mark: duplicates return |
| DynamoDB / Cassandra | Conditional write (attribute_not_exists, IF NOT EXISTS) | Only within one item or partition | Conditional check failed | Cross-item atomicity is limited |
Table design knobs
| Knob | Choice | Why |
|---|---|---|
| Key columns | (consumer, message_id) | Scope per handler; one id may be consumed by many handlers |
| Key type | uuid or text | uuid is 16 bytes; text ids cost about 37 bytes plus index overhead |
| Index | Only the PK plus processed_at | Every extra index is write amplification on the hottest insert path |
| Fill factor | Default | The table is insert-only until cleanup |
| Transaction isolation | READ COMMITTED | ON CONFLICT already serialises on the key; higher levels add 40001 retries (Isolation Levels) |
lock_timeout | A few seconds | A blocked duplicate gives up (55P03) instead of holding a connection |
| Autovacuum | Tune for the delete batches | Cleanup creates dead tuples (MVCC & VACUUM) |
| Placement | Same database and shard as the business tables | Otherwise mark and effect are not atomic (Storage & Data Scaling) |
Error codes and signals you will meet
| Signal | Where | Meaning | What to do |
|---|---|---|---|
INSERT 0 0 / RowsAffected() = 0 | PostgreSQL ON CONFLICT DO NOTHING | Duplicate | Skip and acknowledge |
SQLSTATE 23505 unique_violation | PostgreSQL plain INSERT | Duplicate; the transaction is aborted | Roll back, treat as duplicate, acknowledge |
ER_DUP_ENTRY 1062 (SQLSTATE 23000) | MySQL | Duplicate | Same |
SQLSTATE 40001, 40P01 | PostgreSQL | Serialization failure, deadlock | Retry the whole transaction (Deadlocks) |
SQLSTATE 55P03 lock_not_available | PostgreSQL with lock_timeout | A concurrent duplicate holds the key | Nack and requeue, or skip after a pause |
redelivered = true | RabbitMQ delivery | Maybe seen before (hint only) | Be careful; still use the inbox |
redelivered not set | RabbitMQ delivery | Guaranteed not seen before by this queue | The only case the flag proves something |
UniqueConstraintViolationException | Laravel (Illuminate\Database) | Duplicate on a plain insert | Catch outside the transaction |
ErrTxClosed | pgx | Rollback after Commit | Ignore in the deferred rollback |
Solving the classic problems
| Problem | Solution | How | Advantage | Cost or limit |
|---|---|---|---|---|
| Double credit after restart | Inbox in the business transaction | INSERT ... ON CONFLICT DO NOTHING, then UPDATE, one commit | Exactly one effect | One extra insert per message |
| Two workers, same message | Unique constraint + short tx + lock_timeout | The second insert waits, then reports 0 rows | Race-proof | Blocked duplicate holds a connection briefly |
| Duplicate email/SMS | Claim, perform with key, complete; or accept | Lease row plus Idempotency-Key | Bounded repeats | Provider must honour the key |
| Duplicate webhook from a third party | Dedup on their event id | Inbox keyed by the provider's event_id | Works without producer changes | Window must cover their retry horizon |
| Out-of-order and duplicate events in a read model | Version-checked upsert | WHERE version < EXCLUDED.version | No table needed | Needs a trustworthy version |
| Counter drift | Set semantics | post_likes(post_id, user_id) unique; count rows | Naturally idempotent | Count cost; materialise with a version |
| Replay a topic after a bug fix | New consumer name, or idempotent writes | A fresh dedup namespace | Safe rebuild | Duplicates inside the replay still need natural idempotency |
| Huge inbox table | Window from the redelivery paths; partition by message time | DROP PARTITION after the window | Cheap cleanup | Partition key must be a message property |
| Producer double-publish with two ids | Business-key dedup | Key (consumer, 'pay_42:captured') | Catches semantic duplicates | A legitimate repeat needs a discriminator |
| Poison message retried forever | Reject to DLQ, never mark it processed | Handler error rolls the mark back; the DLQ policy bounds attempts | Visible failures | See Dead-Letter Queue |
Retries and failure handling
An inbox makes retrying safe, so the handler can fail loudly. Decide per error whether to acknowledge, requeue or dead-letter.
| Outcome | Inbox state | Broker action | Retry? |
|---|---|---|---|
Duplicate (0 rows) | Existing mark | Ack | No |
| Handler succeeded, commit succeeded | Mark committed | Ack | No |
Transient error (deadlock 40P01, serialization 40001, connection lost, 55P03) | Rolled back | No ack or nack with requeue | Yes, with backoff (Retry, Backoff & Delayed Delivery) |
| Permanent error (bad payload, business rule) | Rolled back | Reject without requeue to DLQ | No |
| Crash before commit | Rolled back | Broker redelivers | Yes |
| Crash after commit, before ack | Mark committed | Broker redelivers; duplicate path acks | Yes, absorbed |
Rules: ack only after the commit; never mark a message processed that failed permanently; do not retry the whole message inside the handler while holding the transaction; wrap the transaction in a bounded retry for 40001/40P01. The Go helper below returns an error for anything transient so the consumer loop nacks; the Laravel job uses $tries and $backoff and DB::transaction($callback, $attempts) for deadlock retries.
Choosing an approach
| Workload | Recommended | Extra technique | Reason |
|---|---|---|---|
| Money: wallet credits, ledger, payments | Inbox in the business transaction | Append-only ledger keyed by message id; downstream idempotency keys | One duplicate costs more than a table |
| Order/status read models | Version-checked upsert | Rebuild from the log | Duplicates and reordering handled, no table |
| Search index / cache refresh | Natural idempotency (rebuild from state) | ShouldBeUnique to coalesce dispatches (Laravel) | Cheap; a duplicate is harmless |
| Counters, likes, views | Set table (unique pairs) or a periodic recount | Approximate counters if acceptable | +1 is never idempotent |
| Email/SMS | At-least-once with claim and lease, or at-most-once | Provider key if offered | Choose by business consequence of a duplicate vs a miss |
| Third-party webhooks | Inbox keyed by the provider's event id | Window covers their retry schedule | You cannot change the producer |
| Kafka to database at very high volume | Offsets in the same transaction | Idempotent writes | A row per message is too costly |
| Kafka to Kafka | Kafka transactions (EOS) | Read committed consumers | Broker-side atomic commit works here |
| Multi-region active-active | Natural idempotency, single owner per key | CRDTs for counters | A unique constraint is per region |
Go
Before
A RabbitMQ consumer that adds to a balance and acks afterwards. A crash between the UPDATE and the ack, a network drop before the ack arrives, or a consumer timeout all lead to the same redelivery, and the wallet is credited again.
// Package main is the "before": a consumer that is only correct if every
// message arrives exactly once. Brokers do not promise that.
package main
import (
"context"
"database/sql"
"encoding/json"
"log"
amqp "github.com/rabbitmq/amqp091-go"
)
type credit struct {
WalletID string `json:"wallet_id"`
Amount int64 `json:"amount"`
}
// handle adds the amount to the balance and acks afterwards. If the process
// dies between the UPDATE and the ack, the broker redelivers the message and
// the wallet is credited a second time.
func handle(ctx context.Context, db *sql.DB, d amqp.Delivery) error {
var c credit
if err := json.Unmarshal(d.Body, &c); err != nil {
return d.Reject(false)
}
if _, err := db.ExecContext(ctx,
`UPDATE wallets SET balance = balance + $1 WHERE id = $2`,
c.Amount, c.WalletID); err != nil {
return d.Nack(false, true)
}
return d.Ack(false)
}
func main() {
// Wiring omitted: this snippet only shows the handler's shape.
log.Println("see handle()")
_ = handle
}After
The shared helper for pgx is above (pginbox): begin a transaction, INSERT ... ON CONFLICT DO NOTHING into processed_messages, check RowsAffected, run the business write on the same pgx.Tx, commit. A zero means "duplicate"; the caller still acks so the broker stops redelivering. A portable database/sql version for other drivers:
// Package inbox implements the idempotent-consumer pattern: the id of a
// message is inserted into a processed_messages table in the SAME transaction
// as the business write, and the primary key rejects the second attempt.
//
// CREATE TABLE processed_messages (
// consumer text NOT NULL,
// message_id text NOT NULL,
// processed_at timestamptz NOT NULL DEFAULT now(),
// PRIMARY KEY (consumer, message_id)
// );
package inbox
import (
"context"
"database/sql"
"fmt"
)
// Handler performs the business write inside the transaction it is given.
type Handler func(ctx context.Context, tx *sql.Tx) error
// Process runs fn at most once per (consumer, messageID). It returns
// processed=false when the message was already handled; the caller should
// still acknowledge it so the broker stops redelivering.
func Process(ctx context.Context, db *sql.DB, consumer, messageID string, fn Handler) (processed bool, err error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return false, fmt.Errorf("begin: %w", err)
}
defer func() { _ = tx.Rollback() }() // no-op after Commit
// Mark and process in one transaction: both happen or neither does.
res, err := tx.ExecContext(ctx,
`INSERT INTO processed_messages (consumer, message_id)
VALUES ($1, $2)
ON CONFLICT (consumer, message_id) DO NOTHING`,
consumer, messageID)
if err != nil {
return false, fmt.Errorf("mark: %w", err)
}
if n, err := res.RowsAffected(); err != nil {
return false, err
} else if n == 0 {
return false, nil // duplicate: roll back (nothing to undo) and skip
}
if err := fn(ctx, tx); err != nil {
return false, fmt.Errorf("handle: %w", err) // rollback also removes the mark
}
if err := tx.Commit(); err != nil {
return false, fmt.Errorf("commit: %w", err)
}
return true, nil
}For effects outside the database, the claim/complete variant (TryClaim, Complete) keeps a lease so a crash is repaired, and the HTTP call carries a downstream key:
package pginbox
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
// Claim is for side effects that cannot join the database transaction (an
// email, an HTTP call). The inbox row becomes a small state machine:
//
// CREATE TABLE inbox_messages (
// consumer text NOT NULL,
// message_id text NOT NULL,
// status text NOT NULL CHECK (status IN ('processing', 'done')),
// lease_until timestamptz NOT NULL,
// attempts int NOT NULL DEFAULT 1,
// received_at timestamptz NOT NULL DEFAULT now(),
// PRIMARY KEY (consumer, message_id)
// );
//
// Claim -> perform the effect with a downstream idempotency key -> Complete.
// A crash between Claim and Complete is repaired by the lease: after it
// expires, the redelivered message may claim the row again and repeat the
// effect, which is safe only because the downstream deduplicates on the key.
type ClaimState int
const (
Acquired ClaimState = iota // you own the row: perform the effect
AlreadyDone // a previous attempt completed
InFlight // another worker holds a live lease
)
const claimSQL = `INSERT INTO inbox_messages (consumer, message_id, status, lease_until)
VALUES ($1, $2, 'processing', now() + make_interval(secs => $3))
ON CONFLICT (consumer, message_id) DO UPDATE
SET lease_until = EXCLUDED.lease_until,
attempts = inbox_messages.attempts + 1
WHERE inbox_messages.status = 'processing'
AND inbox_messages.lease_until < now()
RETURNING status`
// TryClaim inserts the row, or re-claims it when a previous lease expired.
func TryClaim(ctx context.Context, q interface {
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
}, consumer, messageID string, lease time.Duration) (ClaimState, error) {
var status string
err := q.QueryRow(ctx, claimSQL, consumer, messageID, lease.Seconds()).Scan(&status)
if err == nil {
return Acquired, nil
}
if !errors.Is(err, pgx.ErrNoRows) {
return 0, fmt.Errorf("claim: %w", err)
}
// The WHERE clause rejected us: either done, or someone else's live lease.
err = q.QueryRow(ctx,
`SELECT status FROM inbox_messages WHERE consumer = $1 AND message_id = $2`,
consumer, messageID).Scan(&status)
if err != nil {
return 0, fmt.Errorf("claim status: %w", err)
}
if status == "done" {
return AlreadyDone, nil
}
return InFlight, nil
}
// Complete marks the effect as performed. Run it after the external call
// succeeded; if it fails, the lease expires and the effect is repeated with
// the same downstream idempotency key.
func Complete(ctx context.Context, q interface {
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
}, consumer, messageID string) error {
_, err := q.Exec(ctx,
`UPDATE inbox_messages SET status = 'done' WHERE consumer = $1 AND message_id = $2`,
consumer, messageID)
return err
}// Package main shows an idempotent consumer whose side effect is an HTTP
// call to another system (a mail provider, a payment gateway). The inbox
// cannot make that call atomic with the database, so the consumer claims the
// message, calls with a downstream idempotency key, then marks it done.
package main
import (
"bytes"
"context"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"academy/idempotent-consumer-inbox/after/pginbox"
)
const consumer = "welcome-email"
// sendEmail calls the provider. The Idempotency-Key header makes the call
// safe to repeat: a provider that supports it returns the first response.
func sendEmail(ctx context.Context, messageID string, body []byte) error {
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
os.Getenv("MAIL_API_URL"), bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
// Derived from the message id, so every retry of THIS message repeats
// the same key and a new message gets a new one.
req.Header.Set("Idempotency-Key", consumer+":"+messageID)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err // timeout: outcome unknown, the retry is safe because of the key
}
defer resp.Body.Close()
if resp.StatusCode >= 500 {
return fmt.Errorf("provider returned %d", resp.StatusCode)
}
return nil
}
// handle returns nil when the message may be acknowledged.
func handle(ctx context.Context, pool *pgxpool.Pool, messageID string, body []byte) error {
state, err := pginbox.TryClaim(ctx, pool, consumer, messageID, 2*time.Minute)
if err != nil {
return err
}
switch state {
case pginbox.AlreadyDone:
return nil // acknowledge: the email was sent
case pginbox.InFlight:
// Another worker holds a live lease. Do NOT acknowledge: if that
// worker dies, this redelivery repeats the effect after the lease.
return fmt.Errorf("message %s is in flight elsewhere", messageID)
}
if err := sendEmail(ctx, messageID, body); err != nil {
return err // lease expires, redelivery claims again
}
return pginbox.Complete(ctx, pool, consumer, messageID)
}
func main() {
if os.Getenv("DATABASE_URL") == "" {
log.Fatal("set DATABASE_URL and MAIL_API_URL to run")
}
pool, err := pgxpool.New(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer pool.Close()
// In real code this is called from the broker consumer loop.
if err := handle(context.Background(), pool, "msg-1", []byte(`{"to":"a@example.com"}`)); err != nil {
log.Println(err)
}
}Cleanup and the dedup window:
// Package cleanup deletes dedup records that can no longer matter. A record
// only has to live as long as a duplicate can still arrive, so retention is
// derived from the longest redelivery path, not from a round number.
package cleanup
import (
"context"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
// Window is the dedup window: the longest time between the first and the
// last possible delivery of the same message. Add every source of lateness:
// broker retention or visibility timeout, retry and backoff schedule, the
// longest DLQ parking time, and the producer's own retry horizon.
func Window(brokerRedelivery, retrySchedule, dlqParking, producerRetry, margin time.Duration) time.Duration {
return brokerRedelivery + retrySchedule + dlqParking + producerRetry + margin
}
// Prune deletes expired rows in small batches so that no single statement
// holds locks or generates WAL for long. It returns the number deleted.
func Prune(ctx context.Context, pool *pgxpool.Pool, window time.Duration, batch int) (int64, error) {
var total int64
for {
tag, err := pool.Exec(ctx, `
DELETE FROM processed_messages
WHERE (consumer, message_id) IN (
SELECT consumer, message_id
FROM processed_messages
WHERE processed_at < now() - make_interval(secs => $1)
ORDER BY processed_at
LIMIT $2
)`, window.Seconds(), batch)
if err != nil {
return total, err
}
total += tag.RowsAffected()
if tag.RowsAffected() < int64(batch) {
return total, nil
}
select {
case <-ctx.Done():
return total, ctx.Err()
case <-time.After(100 * time.Millisecond): // let autovacuum and replicas breathe
}
}
}A test that replays the same message twice, with a fake transaction so it needs no database (we ran it: ok):
package pginbox
import (
"context"
"errors"
"testing"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
// fakeDB mimics the one property the inbox relies on: a primary key that
// rejects a second committed (consumer, message_id), and a transaction whose
// inserts vanish on rollback. No PostgreSQL needed.
type fakeDB struct{ committed map[string]bool }
type fakeTx struct {
pgx.Tx // nil: any method the inbox does not use panics loudly
db *fakeDB
pending map[string]bool
}
func (d *fakeDB) Begin(context.Context) (pgx.Tx, error) {
return &fakeTx{db: d, pending: map[string]bool{}}, nil
}
func (t *fakeTx) Exec(_ context.Context, _ string, args ...any) (pgconn.CommandTag, error) {
key := args[0].(string) + "/" + args[1].(string)
if t.db.committed[key] || t.pending[key] {
return pgconn.NewCommandTag("INSERT 0 0"), nil // ON CONFLICT DO NOTHING
}
t.pending[key] = true
return pgconn.NewCommandTag("INSERT 0 1"), nil
}
func (t *fakeTx) Commit(context.Context) error {
for k := range t.pending {
t.db.committed[k] = true
}
return nil
}
func (t *fakeTx) Rollback(context.Context) error { return nil } // pending is dropped
func TestReplayTwiceRunsHandlerOnce(t *testing.T) {
db := &fakeDB{committed: map[string]bool{}}
calls := 0
fn := func(context.Context, pgx.Tx) error { calls++; return nil }
first, err := Process(context.Background(), db, "wallet-credit", "msg-1", fn)
if err != nil || first != Processed {
t.Fatalf("first delivery: %v, %v", first, err)
}
second, err := Process(context.Background(), db, "wallet-credit", "msg-1", fn)
if err != nil || second != Duplicate {
t.Fatalf("redelivery: %v, %v", second, err)
}
if calls != 1 {
t.Fatalf("handler ran %d times, want 1", calls)
}
}
func TestFailedHandlerRollsBackTheMark(t *testing.T) {
db := &fakeDB{committed: map[string]bool{}}
boom := errors.New("boom")
if _, err := Process(context.Background(), db, "c", "msg-2",
func(context.Context, pgx.Tx) error { return boom }); !errors.Is(err, boom) {
t.Fatalf("want boom, got %v", err)
}
// The mark was rolled back, so redelivery must run the handler again.
calls := 0
res, err := Process(context.Background(), db, "c", "msg-2",
func(context.Context, pgx.Tx) error { calls++; return nil })
if err != nil || res != Processed || calls != 1 {
t.Fatalf("retry: %v, %v, calls=%d", res, err, calls)
}
}
func TestSameIDDifferentConsumerBothRun(t *testing.T) {
db := &fakeDB{committed: map[string]bool{}}
calls := 0
fn := func(context.Context, pgx.Tx) error { calls++; return nil }
_, _ = Process(context.Background(), db, "billing", "msg-3", fn)
_, _ = Process(context.Background(), db, "shipping", "msg-3", fn)
if calls != 2 {
t.Fatalf("two consumers must each run once, got %d", calls)
}
}The Go angle
database/sql has no portable "unique violation" error type, which is why the helper uses ON CONFLICT DO NOTHING and counts rows instead of parsing driver errors; with pgx, errors.As(err, &pgErr) on *pgconn.PgError and pgErr.Code == "23505" is the explicit form, and on MySQL the driver reports ER_DUP_ENTRY (1062). The transaction shape is plain Begin, defer tx.Rollback(ctx), Commit, the same idiom you would use for any atomic write. The decision of when to ack stays in the consumer loop, outside the helper: ack after Process returns, whether it reported processed or duplicate, and nack only on error. A Beginner interface (satisfied by *pgxpool.Pool) is what makes the fake in the test possible. See message acknowledgment.
Laravel
Before
A queued job that calls increment(). Laravel's workers give at-least-once: a job that times out or whose worker is killed after the UPDATE is released and runs again. The queue docs explain the knobs behind it: retry_after and --timeout "work together to ensure that jobs are not lost and that jobs are only successfully processed once", and the --timeout should be shorter than retry_after; if not, a still-running job is retried by a second worker.
<?php
namespace App\Jobs;
use App\Models\Wallet;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
// Only correct if the queue delivers this job exactly once. A worker that
// dies after the UPDATE but before the job is deleted (or a retry after a
// timeout) credits the wallet again.
class CreditWallet implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
public int $walletId,
public int $amount,
) {}
public function handle(): void
{
$wallet = Wallet::findOrFail($this->walletId);
// balance = balance + N, executed on every delivery.
$wallet->increment('balance', $this->amount);
}
}After
A processed_messages table whose primary key is (consumer, message_id), and a DB::transaction that does insertOrIgnore first. The query builder documents insertOrIgnore as ignoring errors while inserting, and the returned row count tells you whether the row was new. The message id is a constructor argument generated by the producer, so every retry of the serialized job carries the same value.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
// The inbox table. The composite primary key is the dedup primitive: the
// database rejects a second (consumer, message_id) even when two workers race.
return new class extends Migration
{
public function up(): void
{
Schema::create('processed_messages', function (Blueprint $table) {
$table->string('consumer', 100);
$table->string('message_id', 200);
$table->timestampTz('processed_at')->useCurrent()->index(); // for the cleanup job
$table->primary(['consumer', 'message_id']);
});
// For effects that cannot join the transaction (email, HTTP): the row
// is a small state machine, see SendWelcomeEmail.php.
Schema::create('inbox_messages', function (Blueprint $table) {
$table->string('consumer', 100);
$table->string('message_id', 200);
$table->string('status', 20); // processing | done
$table->timestampTz('lease_until');
$table->unsignedInteger('attempts')->default(1);
$table->timestampTz('received_at')->useCurrent();
$table->primary(['consumer', 'message_id']);
});
}
public function down(): void
{
Schema::dropIfExists('inbox_messages');
Schema::dropIfExists('processed_messages');
}
};<?php
namespace App\Jobs;
use App\Models\Wallet;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
// Migration (once):
//
// Schema::create('processed_messages', function (Blueprint $table) {
// $table->string('consumer');
// $table->string('message_id');
// $table->timestamp('processed_at')->useCurrent()->index(); // for cleanup
// $table->primary(['consumer', 'message_id']);
// });
class CreditWallet implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
public int $walletId,
public int $amount,
// Generated once by the producer, e.g. (string) Str::uuid(), and
// carried inside the payload so every redelivery has the same value.
public string $messageId,
) {}
public function handle(): void
{
DB::transaction(function () {
// insertOrIgnore returns the number of rows inserted: 0 means the
// primary key already holds this (consumer, message_id).
$inserted = DB::table('processed_messages')->insertOrIgnore([
'consumer' => 'wallet-credit',
'message_id' => $this->messageId,
]);
if ($inserted === 0) {
return; // duplicate: acknowledge by returning normally
}
// Same transaction as the mark: both commit or neither does.
Wallet::whereKey($this->walletId)->increment('balance', $this->amount);
});
}
}insertOrIgnore has a caveat the docs call out: it ignores duplicate-key errors, and "other types of errors may also be ignored depending on the database engine". If you prefer failures to be loud, insert plainly and catch UniqueConstraintViolationException, a subclass of QueryException in Illuminate\Database. The catch must sit outside the transaction, because on PostgreSQL a failed statement aborts it.
<?php
namespace App\Support;
use Closure;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Facades\DB;
// The same inbox, written with a plain insert and the unique-violation
// exception instead of insertOrIgnore. Use this form when you want other
// database errors to surface instead of being swallowed.
final class Inbox
{
/**
* Run $work at most once per ($consumer, $messageId).
* Returns true when it ran, false when the message was a duplicate.
*/
public static function once(string $consumer, string $messageId, Closure $work): bool
{
try {
DB::transaction(function () use ($consumer, $messageId, $work) {
DB::table('processed_messages')->insert([
'consumer' => $consumer,
'message_id' => $messageId,
]);
$work();
});
} catch (UniqueConstraintViolationException) {
// Caution: on PostgreSQL a violation aborts the surrounding
// transaction, which is why the catch sits OUTSIDE it.
return false;
}
return true;
}
}To make any job idempotent without touching its handle(), wrap it in a job middleware that runs $next($job) inside the inbox. It uses the producer's $messageId when present, otherwise the queue payload's uuid, which Laravel writes at dispatch ($this->job->uuid()):
<?php
namespace App\Jobs\Middleware;
use App\Support\Inbox;
use Closure;
// A job middleware that turns any job into an idempotent consumer: the job's
// handle() runs inside the inbox transaction, once per (consumer, message id).
//
// Which id? Prefer one the PRODUCER chose and put on the job (a public
// $messageId property). Fall back to the queue payload's uuid, which Laravel
// writes when the job is dispatched and which survives retries and releases
// of that one dispatch. It does not catch a producer that dispatches the same
// logical event twice; only a business id does.
class OncePerMessage
{
public function __construct(private string $consumer) {}
public function handle(object $job, Closure $next): void
{
$id = $job->messageId ?? $job->job?->uuid();
if ($id === null || $id === '') {
// No identity means no dedup. Fail loudly instead of double-applying.
throw new \LogicException('OncePerMessage needs a messageId or a queue uuid');
}
Inbox::once($this->consumer, (string) $id, fn () => $next($job));
}
}<?php
namespace App\Jobs;
use App\Jobs\Middleware\OncePerMessage;
use App\Models\Wallet;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
// The handler stays plain; idempotency is the middleware's job.
class CreditWalletOnce implements ShouldQueue
{
use Queueable;
public function __construct(
public int $walletId,
public int $amount,
public string $messageId, // generated once by the producer
) {}
/** @return array<int, object> */
public function middleware(): array
{
return [new OncePerMessage('wallet-credit')];
}
public function handle(): void
{
// Runs inside the inbox transaction: mark + increment commit together.
Wallet::whereKey($this->walletId)->increment('balance', $this->amount);
}
}Natural idempotency in the query builder: update to a value, upsert by key, and a conditional where('status', 'pending') update.
<?php
namespace App\Jobs;
use App\Models\Wallet;
use Illuminate\Support\Facades\DB;
// Natural idempotency: operations whose repetition changes nothing.
final class Natural
{
public static function examples(int $walletId, string $orderId): void
{
// Set, do not increment: running it twice leaves the same row.
Wallet::whereKey($walletId)->update(['status' => 'frozen']);
// Upsert keyed on a business key.
DB::table('order_projection')->upsert(
[['order_id' => $orderId, 'status' => 'paid']],
['order_id'],
['status'],
);
// Conditional update: only moves forward once.
DB::table('orders')
->where('id', $orderId)
->where('status', 'pending')
->update(['status' => 'paid']);
}
}External effects with a lease and a downstream key, and the scheduled cleanup:
<?php
namespace App\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
// The side effect (an HTTP call) cannot join the database transaction, so the
// inbox row becomes claim -> perform -> complete, and the call carries a
// downstream Idempotency-Key. If the worker dies between the call and
// complete(), the lease expires, the redelivered job claims the row again and
// repeats the call; the provider returns the first result for the same key.
class SendWelcomeEmail implements ShouldQueue
{
use Queueable;
public function __construct(
public string $userId,
public string $messageId, // chosen once by the producer
) {}
public function handle(): void
{
$consumer = 'welcome-email';
// Insert the claim, or re-claim it when a previous lease expired.
$claimed = DB::select(
"INSERT INTO inbox_messages (consumer, message_id, status, lease_until)
VALUES (?, ?, 'processing', now() + make_interval(secs => ?))
ON CONFLICT (consumer, message_id) DO UPDATE
SET lease_until = EXCLUDED.lease_until,
attempts = inbox_messages.attempts + 1
WHERE inbox_messages.status = 'processing'
AND inbox_messages.lease_until < now()
RETURNING status",
[$consumer, $this->messageId, 120],
);
if ($claimed === []) {
$status = DB::table('inbox_messages')
->where('consumer', $consumer)
->where('message_id', $this->messageId)
->value('status');
if ($status === 'done') {
return; // already sent: acknowledge by returning
}
// A live lease belongs to another worker: release and retry later.
$this->release(30);
return;
}
Http::withHeaders(['Idempotency-Key' => $consumer.':'.$this->messageId])
->timeout(10)
->post(config('services.mail.url'), ['user_id' => $this->userId])
->throw(); // non-2xx throws: the job is retried after the lease
DB::table('inbox_messages')
->where('consumer', $consumer)
->where('message_id', $this->messageId)
->update(['status' => 'done']);
}
}<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
// Deletes inbox rows older than the dedup window, in small batches so that no
// single statement holds locks or produces a huge WAL burst. PostgreSQL's
// DELETE has no LIMIT, hence the ctid sub-select.
//
// Schedule it (routes/console.php):
// Schedule::command('inbox:prune --days=14')->hourly()->onOneServer();
class PruneProcessedMessages extends Command
{
protected $signature = 'inbox:prune {--days=14} {--batch=5000}';
protected $description = 'Delete processed_messages rows older than the dedup window';
public function handle(): int
{
$batch = (int) $this->option('batch');
$cutoff = now()->subDays((int) $this->option('days'));
$total = 0;
do {
$deleted = DB::delete(
'DELETE FROM processed_messages WHERE ctid IN (
SELECT ctid FROM processed_messages
WHERE processed_at < ? ORDER BY processed_at LIMIT ?
)',
[$cutoff, $batch],
);
$total += $deleted;
usleep(100_000); // let autovacuum and replicas breathe
} while ($deleted === $batch);
$this->info("pruned {$total} rows older than {$cutoff}");
return self::SUCCESS;
}
}And the test every consumer needs, deliver the same message twice (written for PHPUnit with RefreshDatabase; syntax-checked, not run here because there is no Laravel app on this machine):
<?php
namespace Tests\Feature;
use App\Jobs\CreditWalletOnce;
use App\Models\Wallet;
use App\Support\Inbox;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
// The one test every consumer needs: deliver the same message twice and
// assert the effect happened once. dispatch_sync runs handle() in-process,
// the way a redelivery would run it on a worker.
class ReplayTwiceTest extends TestCase
{
use RefreshDatabase;
public function test_a_redelivered_message_is_applied_once(): void
{
$wallet = Wallet::factory()->create(['balance' => 0]);
CreditWalletOnce::dispatchSync($wallet->id, 500, 'msg-1');
CreditWalletOnce::dispatchSync($wallet->id, 500, 'msg-1'); // the duplicate
$this->assertSame(500, $wallet->fresh()->balance);
$this->assertDatabaseCount('processed_messages', 1);
}
public function test_different_messages_are_both_applied(): void
{
$wallet = Wallet::factory()->create(['balance' => 0]);
CreditWalletOnce::dispatchSync($wallet->id, 500, 'msg-1');
CreditWalletOnce::dispatchSync($wallet->id, 500, 'msg-2');
$this->assertSame(1000, $wallet->fresh()->balance);
}
public function test_a_failing_handler_does_not_leave_a_mark(): void
{
try {
Inbox::once('wallet-credit', 'msg-3', function () {
throw new \RuntimeException('boom'); // fails after the mark was inserted
});
} catch (\RuntimeException) {
// expected: the broker would redeliver the message
}
// The transaction rolled back, so the redelivery is allowed to run.
$this->assertDatabaseMissing('processed_messages', ['message_id' => 'msg-3']);
$this->assertTrue(Inbox::once('wallet-credit', 'msg-3', fn () => null));
}
}The Laravel angle
ShouldBeUnique is not an inbox. The Laravel 13 queue docs describe it as ensuring "only one instance of a specific job is on the queue at any point in time", implemented by acquiring a cache lock keyed by uniqueId and released when the job "completes processing or fails all of its retry attempts" (or after #[UniqueFor] seconds). It prevents duplicate dispatch of equivalent jobs. It needs a cache driver with atomic locks, does not apply to jobs inside batches, and does not protect handle() from redelivery of one job. In the framework source (Illuminate\Bus\UniqueLock) the lock lifetime is uniqueFor or 0, and a lifetime of 0 means no expiry; a crash that skips the release leaves the lock until you clear it, so always set #[UniqueFor]. ShouldBeUniqueUntilProcessing releases the lock when processing starts, which allows a second copy to be dispatched while the first is still running: weaker still. It fits "refresh this index, one at a time"; for a balance, use the inbox.
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\Attributes\UniqueFor;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
// ShouldBeUnique stops a second copy from being DISPATCHED while the first is
// queued or running (it takes a cache lock on uniqueId()). It does not make
// handle() safe against redelivery after the lock is released, and the lock
// lives in the cache, not in your database transaction. Use it for "refresh
// this thing, one at a time", never for money.
#[UniqueFor(3600)] // seconds until the lock is released even if the job never finishes
class RefreshSearchIndex implements ShouldQueue, ShouldBeUnique
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(public int $productId) {}
public function uniqueId(): string
{
return (string) $this->productId;
}
public function handle(): void
{
// Naturally idempotent: rebuilds the document from current state.
}
}WithoutOverlapping is not an inbox either. Illuminate\Queue\Middleware\WithoutOverlapping holds an atomic cache lock only while handle() runs ($next($job) inside try, release() in finally), so two jobs with the same key never run at once, but a redelivery after the first finished runs normally. The docs warn that releasing an overlapping job "will still increment the job's total number of attempts", so tune Tries and MaxExceptions; releaseAfter() requeues it, dontRelease() deletes it, expireAfter() frees a lock left by a dead worker. Use it to serialise per key, and combine with the inbox when you need both:
<?php
namespace App\Jobs;
use App\Jobs\Middleware\OncePerMessage;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Middleware\WithoutOverlapping;
// WithoutOverlapping answers "never two of these at the same time for this
// key". It does NOT answer "never twice". It holds an atomic cache lock only
// while handle() runs; once released, a redelivery runs normally. Combine it
// with the inbox when you need both: serialise per wallet, dedup per message.
class SerializedPerWallet implements ShouldQueue
{
use Queueable;
public int $tries = 5; // releasing an overlapping job still counts as an attempt
public function __construct(
public int $walletId,
public int $amount,
public string $messageId,
) {}
/** @return array<int, object> */
public function middleware(): array
{
return [
(new WithoutOverlapping((string) $this->walletId))
->releaseAfter(10) // put the job back and retry in 10 s
->expireAfter(180), // free the lock even if the worker died
new OncePerMessage('wallet-credit'),
];
}
public function handle(): void
{
// ...business write; safe against both overlap and redelivery
}
}Transactions and dispatch. A job dispatched inside a transaction can be picked up before the commit; the queue docs offer after_commit on the connection or ->afterCommit() per dispatch. That solves "job runs before the row exists", not duplicates. HTTP. A middleware can claim Idempotency-Key with the atomic Cache::add, replay the stored response on a retry, return 409 while the first request is in flight and 422 for a different payload, as in the HTTP twin. The draft types the header as a quoted structured-field string; the middleware treats it as an opaque value.
Broker differences
What each broker gives you to build the key from, what it does for you, and what it does not.
| Capability | RabbitMQ | Kafka | Redis Streams |
|---|---|---|---|
| Producer-chosen id | message-id property | Header or payload field | Entry field; IDMP iid (8.6+) |
| Broker-assigned id | None usable (delivery tag is per channel) | topic-partition-offset | Entry id ms-seq |
| Broker-side dedup | No | Idempotent producer, per producer session | IDMP / IDMPAUTO (8.6+, windowed) |
| Redelivery signal | redelivered flag (hint when set) | None: only your committed position | Delivery counter in XPENDING |
| Consumer position | Ack per message | Offset per partition | XACK per entry (the PEL) |
| Redelivery trigger | Channel closes with unacked messages, basic.nack/reject with requeue | Rebalance, crash before commit, seek back | Idle pending entry claimed by XCLAIM/XAUTOCLAIM, or XREADGROUP with id 0 |
| What breaks dedup | Empty message-id | Coordinates-only key; producer double-send | XADD retry without IDMP |
NATS JetStream, SQS FIFO, Azure Service Bus and Pulsar each have their own producer-side window (see the TTL table); Other Brokers covers them.
RabbitMQ
AMQP 0-9-1 defines a message-id property; the RabbitMQ publishers guide lists "Message ID" as an "Arbitrary message ID", optional, and the broker never sets, interprets or checks it, so dedup is entirely the consumer's job and the producer must populate it (in amqp091-go, Publishing.MessageId, read back as Delivery.MessageId). The consumer also gets a redelivered flag. The reliability guide is precise about it: when set, "this is a hint that a consumer may have seen this message before. This is not guaranteed as the original delivery might have not made it to any consumers"; when not set, "it is guaranteed that the message has not been seen before". So a consumer that finds dedup expensive "can do this only for messages with the redelivered flag set". That optimisation is only safe against broker redelivery: a producer that republished after a lost confirm creates a new message with redelivered unset, so if you need producer-duplicate protection, use the inbox on every message. Quorum queues count requeues towards the queue's delivery limit, which bounds a requeue loop. The Laravel package vladimir-yuldashev/laravel-queue-rabbitmq sets the AMQP correlation_id property from the job payload's id (we read createMessage() in its source) and does not expose message-id that we found, so in Laravel dedup on your own $messageId or the payload uuid.
// Package main consumes from RabbitMQ and dedups on the AMQP message-id
// property, which the publisher must set. The redelivered flag is only logged.
package main
import (
"context"
"encoding/json"
"log"
"os"
amqp "github.com/rabbitmq/amqp091-go"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"academy/idempotent-consumer-inbox/after/pginbox"
)
type credit struct {
WalletID string `json:"wallet_id"`
Amount int64 `json:"amount"`
}
func handle(ctx context.Context, pool *pgxpool.Pool, d amqp.Delivery) error {
if d.MessageId == "" {
// No id means no dedup; refuse rather than silently double-apply.
return d.Reject(false) // dead-letters when the queue has a DLX
}
if d.Redelivered {
// A hint, never a verdict: "delivered before" is not "processed before".
log.Printf("redelivery of %s: relying on the inbox", d.MessageId)
}
var c credit
if err := json.Unmarshal(d.Body, &c); err != nil {
return d.Reject(false)
}
res, err := pginbox.Process(ctx, pool, "wallet-credit", d.MessageId,
func(ctx context.Context, tx pgx.Tx) error {
_, err := tx.Exec(ctx,
`UPDATE wallets SET balance = balance + $1 WHERE id = $2`,
c.Amount, c.WalletID)
return err
})
if err != nil {
return d.Nack(false, true) // transient: requeue and try again
}
log.Printf("%s: %s", d.MessageId, res)
// Ack both for "processed" and for "already processed".
return d.Ack(false)
}
func main() {
if os.Getenv("DATABASE_URL") == "" {
log.Fatal("set DATABASE_URL to run")
}
pool, err := pgxpool.New(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer pool.Close()
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
if err := ch.Qos(10, 0, false); err != nil {
log.Fatal(err)
}
deliveries, err := ch.Consume("wallet.credits", "", false, false, false, false, nil)
if err != nil {
log.Fatal(err)
}
for d := range deliveries {
if err := handle(context.Background(), pool, d); err != nil {
log.Println("ack/nack failed:", err)
}
}
}Kafka
Kafka's idempotent producer is a broker-side feature only. The design documentation says since 0.11.0.0 it "guarantees that resending will not result in duplicate entries in the log" using producer ids and sequence numbers, and the producer Javadoc notes it is the default since Kafka 3.0 (enable.idempotence=true, acks=all) and only guarantees idempotence "within a single session". That removes duplicates caused by producer retries. It does nothing for a consumer that processes a record, crashes before committing its offset, and reads the record again after a rebalance, and it does not help if your application publishes the same event twice from two code paths.
Kafka's exactly-once (consume-transform-produce) is not an inbox. With transactional.id on the producer, isolation.level=read_committed and enable.auto.commit=false on the consumer, the consumer's offsets are written in the same Kafka transaction as the output records (sendOffsetsToTransaction; franz-go's GroupTransactSession handles the begin and end for you). If the transaction aborts, both the output and the offsets revert. This is correct for Kafka-to-Kafka. The design notes state the limit: "Exactly-once delivery for other destination systems generally requires cooperation with such systems". A database write inside that loop is outside the Kafka transaction, so you still need the inbox, or offsets stored with the output.
A record has no id of its own, so the options are an application header (message-id, written by the producer) or the coordinates topic-partition-offset. Coordinates are stable and need no producer cooperation, but they will not dedup two copies written at different offsets, and they change if a topic is recreated or mirrored to another cluster. Commit offsets only after the inbox transaction (DisableAutoCommit); see message acknowledgment.
// Package main consumes from Kafka with franz-go and dedups on a producer
// supplied "message-id" header, falling back to topic-partition-offset.
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/twmb/franz-go/pkg/kgo"
"academy/idempotent-consumer-inbox/after/pginbox"
)
type credit struct {
WalletID string `json:"wallet_id"`
Amount int64 `json:"amount"`
}
// messageID prefers an id the producer put in a header: it survives producer
// retries that wrote the same event at two offsets. The coordinates are only
// stable per log position, so they catch redelivery after a rebalance but not
// a duplicate produced upstream.
func messageID(r *kgo.Record) string {
for _, h := range r.Headers {
if h.Key == "message-id" {
return string(h.Value)
}
}
return fmt.Sprintf("%s-%d-%d", r.Topic, r.Partition, r.Offset)
}
func main() {
if os.Getenv("DATABASE_URL") == "" {
log.Fatal("set DATABASE_URL to run")
}
ctx := context.Background()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer pool.Close()
cl, err := kgo.NewClient(
kgo.SeedBrokers("localhost:9092"),
kgo.ConsumerGroup("wallet-credit"),
kgo.ConsumeTopics("wallet.credits"),
kgo.DisableAutoCommit(), // commit only after the inbox transaction
)
if err != nil {
log.Fatal(err)
}
defer cl.Close()
for {
fetches := cl.PollFetches(ctx)
if fetches.IsClientClosed() {
return
}
fetches.EachRecord(func(r *kgo.Record) {
var c credit
if err := json.Unmarshal(r.Value, &c); err != nil {
return // poison message: route to a DLQ in real code
}
_, err := pginbox.Process(ctx, pool, "wallet-credit", messageID(r),
func(ctx context.Context, tx pgx.Tx) error {
_, err := tx.Exec(ctx,
`UPDATE wallets SET balance = balance + $1 WHERE id = $2`,
c.Amount, c.WalletID)
return err
})
if err != nil {
log.Println("will be redelivered:", err)
return
}
// A crash before this commit only causes a redelivery,
// which the inbox turns into a no-op.
if err := cl.CommitRecords(ctx, r); err != nil {
log.Println("commit:", err)
}
})
}
}// Package main is Kafka's exactly-once consume-transform-produce loop with
// franz-go. It is correct for Kafka -> Kafka only: the output topic and the
// consumer offsets commit in one Kafka transaction. A database write inside
// the loop is NOT part of that transaction, so this is not an inbox.
package main
import (
"context"
"log"
"github.com/twmb/franz-go/pkg/kgo"
)
func main() {
sess, err := kgo.NewGroupTransactSession(
kgo.SeedBrokers("localhost:9092"),
kgo.TransactionalID("wallet-enricher-1"), // stable per instance
kgo.ConsumerGroup("wallet-enricher"),
kgo.ConsumeTopics("wallet.credits"),
kgo.FetchIsolationLevel(kgo.ReadCommitted()),
kgo.RequireStableFetchOffsets(),
)
if err != nil {
log.Fatal(err)
}
defer sess.Close()
ctx := context.Background()
for {
fetches := sess.PollFetches(ctx)
if fetches.IsClientClosed() {
return
}
if err := sess.Begin(); err != nil {
log.Fatal(err)
}
fetches.EachRecord(func(r *kgo.Record) {
// Transform, then produce INSIDE the transaction. Writing to
// PostgreSQL here would still be at-least-once.
out := &kgo.Record{Topic: "wallet.credits.enriched", Key: r.Key, Value: r.Value}
sess.Produce(ctx, out, func(_ *kgo.Record, err error) {
if err != nil {
log.Println("produce:", err)
}
})
})
// Commits the produced records and the consumed offsets together,
// or aborts both (also when a rebalance happened meanwhile).
if _, err := sess.End(ctx, kgo.TryCommit); err != nil {
log.Println("end:", err)
}
}
}In Laravel with mateusjunges/laravel-kafka, the handler receives a ConsumerMessage with getHeaders(), getTopicName(), getPartition() and getOffset(), which are the same ingredients.
<?php
namespace App\Kafka;
use App\Support\Inbox;
use Illuminate\Support\Facades\DB;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Contracts\MessageConsumer;
// Registered with: Kafka::consumer(['wallet.credits'])->withHandler(new CreditHandler)
// (mateusjunges/laravel-kafka; getHeaders/getTopicName/getPartition/getOffset
// are listed on its "Message handlers" page).
class CreditHandler
{
public function __invoke(ConsumerMessage $message, MessageConsumer $consumer): void
{
$headers = $message->getHeaders() ?? [];
// Prefer an id the producer put in a header; the log coordinates only
// catch redelivery of the same record, not a duplicate produced twice.
$id = $headers['message-id']
?? sprintf('%s-%d-%d', $message->getTopicName(), $message->getPartition(), $message->getOffset());
$body = $message->getBody();
Inbox::once('wallet-credit', (string) $id, function () use ($body) {
DB::table('wallets')
->where('id', $body['wallet_id'])
->increment('balance', $body['amount']);
});
}
}Redis Streams
Redis generates a unique id for each stream entry (ms-seq from XADD). A consumer group delivers each entry to one consumer and tracks it in the pending entries list (PEL) until XACK; an entry whose consumer died is reclaimed with XCLAIM or XAUTOCLAIM after a minimum idle time and delivered again with the same entry id, and the delivery counter shown by XPENDING goes up. So the entry id is a stable dedup key for redelivery. It is not a stable key for producer retries: if XADD timed out and the producer retried, there are two entries with two ids.
Redis 8.6 added producer-side idempotency to XADD (the docs call it "at-most-once production"): XADD stream IDMP producer-id idempotent-id * ... (or IDMPAUTO producer-id, where Redis hashes the content). If the same producer-id and idempotent-id were already used, the command "returns the ID of the original entry instead of creating a duplicate". The window is per stream (XCFGSET stream IDMP-DURATION s IDMP-MAXSIZE n, defaults 100 seconds and 100 ids per producer) and the producer must reuse its pid after a restart. It removes duplicate entries, not duplicate deliveries of one entry: consumers still need the inbox. Laravel's redis queue driver does not use streams, so the consumer uses the Redis facade directly.
// Package main reads a Redis Stream consumer group with go-redis, reclaims
// entries abandoned by dead consumers with XAUTOCLAIM, and dedups on a
// producer-supplied event_id (falling back to the entry id).
package main
import (
"context"
"errors"
"log"
"os"
"strconv"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
"academy/idempotent-consumer-inbox/after/pginbox"
)
const (
stream = "wallet.credits"
group = "wallet-credit"
)
func handle(ctx context.Context, rdb *redis.Client, pool *pgxpool.Pool, m redis.XMessage) {
// m.ID is assigned by XADD, so it identifies a log entry, not an event.
// If the producer retried XADD there are two entries; prefer an id the
// producer put in the fields.
id := m.ID
if v, ok := m.Values["event_id"].(string); ok && v != "" {
id = v
}
walletID, _ := m.Values["wallet_id"].(string)
amount, _ := m.Values["amount"].(string)
n, err := strconv.ParseInt(amount, 10, 64)
if err != nil {
return // poison entry: park it, do not loop forever
}
_, err = pginbox.Process(ctx, pool, group, id,
func(ctx context.Context, tx pgx.Tx) error {
_, err := tx.Exec(ctx,
`UPDATE wallets SET balance = balance + $1 WHERE id = $2`,
n, walletID)
return err
})
if err != nil {
log.Println("left in the PEL for retry:", err)
return
}
if err := rdb.XAck(ctx, stream, group, m.ID).Err(); err != nil {
log.Println("xack:", err) // the entry is redelivered; the inbox absorbs it
}
}
// reclaim takes over entries idle in the pending list for over a minute
// (their consumer died). They arrive again with the SAME entry id.
func reclaim(ctx context.Context, rdb *redis.Client, pool *pgxpool.Pool) {
start := "0-0"
for {
msgs, next, err := rdb.XAutoClaim(ctx, &redis.XAutoClaimArgs{
Stream: stream, Group: group, Consumer: "worker-1",
MinIdle: time.Minute, Start: start, Count: 50,
}).Result()
if err != nil {
log.Println("xautoclaim:", err)
return
}
for _, m := range msgs {
handle(ctx, rdb, pool, m)
}
if next == "0-0" {
return
}
start = next
}
}
func main() {
if os.Getenv("DATABASE_URL") == "" {
log.Fatal("set DATABASE_URL to run")
}
ctx := context.Background()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer pool.Close()
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
defer rdb.Close()
for {
reclaim(ctx, rdb, pool)
res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: group, Consumer: "worker-1",
Streams: []string{stream, ">"}, Count: 10, Block: 5 * time.Second,
}).Result()
if err != nil {
if !errors.Is(err, redis.Nil) {
log.Println("read:", err)
}
continue
}
for _, s := range res {
for _, m := range s.Messages {
handle(ctx, rdb, pool, m)
}
}
}
}// Package main shows producer-side deduplication in Redis 8.6+: XADD with
// IDMP (a producer id plus an idempotent id the producer chooses). Resending
// the same pair is ignored while it is inside the stream's IDMP window.
package main
import (
"context"
"log"
"github.com/redis/go-redis/v9"
)
func main() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
defer rdb.Close()
// Window: keep each iid for 300 s, at most 1000 per producer.
// (XCFGSET stream IDMP-DURATION 300 IDMP-MAXSIZE 1000)
if err := rdb.Do(ctx, "XCFGSET", "wallet.credits",
"IDMP-DURATION", 300, "IDMP-MAXSIZE", 1000).Err(); err != nil {
log.Println("xcfgset:", err)
}
add := func() (string, error) {
return rdb.XAdd(ctx, &redis.XAddArgs{
Stream: "wallet.credits",
ProducerID: "billing-1", // must be stable across restarts
IdempotentID: "payment-42", // reuse the SAME id when retrying
Values: map[string]any{"wallet_id": "w-7", "amount": 500, "event_id": "payment-42"},
}).Result()
}
first, err := add()
if err != nil {
log.Fatal(err)
}
second, err := add() // the retry after a lost reply
if err != nil {
log.Fatal(err)
}
log.Println("first:", first, "retry:", second) // expected: same entry id
}<?php
namespace App\Console\Commands;
use App\Support\Inbox;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
// Laravel's redis queue driver does not use streams, so this goes through the
// Redis facade. The calls below are the phpredis signatures
// (xReadGroup/xAck); Predis uses different argument shapes.
class ConsumeCredits extends Command
{
protected $signature = 'credits:consume';
public function handle(): void
{
$stream = 'wallet.credits';
$group = 'wallet-credit';
while (true) {
$batch = Redis::xReadGroup($group, 'worker-1', [$stream => '>'], 10, 5000);
foreach ($batch[$stream] ?? [] as $entryId => $fields) {
// The entry id names a log entry; an event_id field names the event.
$id = $fields['event_id'] ?? $entryId;
Inbox::once($group, $id, function () use ($fields) {
DB::table('wallets')
->where('id', $fields['wallet_id'])
->increment('balance', (int) $fields['amount']);
});
// Ack after the transaction committed; a crash before this line
// leaves the entry pending and the inbox absorbs the redelivery.
Redis::xAck($stream, $group, [$entryId]);
}
}
}
}In production systems
- Eventuate is named on Richardson's pattern page: "The Eventuate framework implements this pattern."
- Kafka's design notes describe the idempotent producer as the fix for duplicates from resending, and point to keyed updates as naturally idempotent for the consumer side and to storing the offset with the output for external systems.
- Stripe's
Idempotency-KeyonPOSTis the reference design for the HTTP form: a retry with the same key is safe; keys are at most 255 characters and may be pruned after at least 24 hours; and per Leach's article the Ruby library retries automatically with a key using increasing backoff and jitter. - Amazon SQS FIFO, Azure Service Bus, NATS JetStream, Apache Pulsar each ship a producer-side dedup window (5 minutes, 10 minutes by default, 2 minutes by default, off by default); all four documents say the id is chosen by the application, which is the same discipline an inbox key needs.
- PostgreSQL
INSERT ... ON CONFLICT DO NOTHINGis the documented single-statement primitive the Go inbox relies on; PostgreSQL 19 addsON CONFLICT DO SELECT, documented as "idempotent insert or get or create". - Laravel
retry_after/--timeoutare the documented source of redelivery in Laravel workers;UniqueLockandWithoutOverlappingare in the framework source and are cache locks, not transactions.
In architecture: from a single process to a distributed system
Monolith: one process, one database
A Laravel app with the database or redis queue and one PostgreSQL. A listener credits a wallet when OrderPaid fires. Start with natural idempotency (UPDATE orders SET status = 'paid' WHERE status = 'pending') and a version-checked projection; add the OncePerMessage job middleware only for handlers that add, append or call out. Because the business tables and the inbox share a database, one DB::transaction makes it exact. Dispatch with afterCommit so the job never runs before the row exists. Tradeoff: nothing to coordinate, so the simplest correct usage wins.
Modular monolith and multiple databases
Modules publish in-process domain events (Domain Events & Integration Events) and each module's handler is a separate consumer. The consumer column is the module and handler name (billing.credit-wallet, notifications.send-receipt), so one event is processed once per handler. Each module owns its inbox table in its own schema; a handler never writes another module's tables inside its transaction. If a module moves to its own database, only the connection string changes. Pitfall: a shared inbox table with no consumer column makes the first handler "win" and the others silently skip.
Microservices: outbox + inbox, with an example
Orders publishes OrderPlaced, Payments charges, Shipping ships. The message id is the outbox row's primary key (stable across relay retries); each consuming service has its own inbox in its own database.
| Step | Service | Transaction | Message |
|---|---|---|---|
| 1 | Orders | order row + outbox row (id=ord-7:placed) in one commit | none yet |
| 2 | Orders relay | publishes at least once (may publish twice after a crash) | OrderPlaced id ord-7:placed |
| 3 | Payments | inbox (payments.charge, ord-7:placed) + payment row + outbox row pay-7:captured | PaymentCaptured |
| 3b | Payments (duplicate delivery) | inbox insert hits 0 rows; ack | nothing |
| 4 | Shipping | inbox (shipping.create-label, pay-7:captured) + label row | none |
| 5 | Shipping calls the carrier API | claim/perform/complete with Idempotency-Key: shipping.create-label:pay-7:captured | carrier request |
What survives service boundaries: ids, the inbox in each service, and downstream keys. What does not: a single transaction across services, which is why a saga coordinates compensation and the pair outbox + inbox gives effectively-once delivery of each step. Service contracts and the message flow are in Service Communication and Designing for Failure: Reliable Messaging.
Distributed data: replicas, caches, shards, regions
- Replicas: the inbox write goes to the primary; never check for duplicates on a read replica, lag makes "not seen" wrong (Replication & Failover). After a failover the inbox row and the business row were in one transaction, so they are lost or kept together: still consistent.
- Caches as the dedup store: Redis
SET NXis fast but separate from your database: eviction, expiry or failover silently drops marks (duplicates return), and a mark without an effect (mark-then-process) loses work. Use it as a cheap pre-filter in front of the database inbox, never instead of it, for effects that matter. - Sharded databases: shard the inbox by the same key as the business data so the mark and the effect are in one shard and one transaction; a cross-shard effect needs two-phase commit or a saga (Distributed SQL & Consensus). Global unique constraints on distributed SQL cost cross-node coordination.
- Multi-region active-active: a unique constraint is per region; two regions can both accept the same message. Route each key to one owning region, or make every effect naturally idempotent (CRDTs for counters), or accept eventual convergence with a version check.
- Clocks: do not decide "newer" with wall-clock timestamps from different producers; use aggregate versions (Eventual Consistency in Databases).
Scaling path: 1x, 10x, 100x
| Load | Design | Change |
|---|---|---|
| 1x (about 10 msg/s) | One worker, inbox row per message, DELETE nightly | Nothing special; measure pg_total_relation_size |
| 10x (about 100 msg/s) | Several workers, batch the inbox insert, partition cleanup, lock_timeout | Batch dedup, tune autovacuum, watch pool size |
| 100x (1000+ msg/s) | Partition by message time, shard by key, shorten the window, move hot paths to natural idempotency or offsets-in-DB | Table is the bottleneck: remove it where you can |
Batching the inbox insert (one round trip per batch, find which ids are new):
-- returns only the ids that were NOT already in the inbox
INSERT INTO processed_messages (consumer, message_id)
SELECT 'wallet-credit', unnest($1::text[])
ON CONFLICT (consumer, message_id) DO NOTHING
RETURNING message_id;The batch and its effects must still share one transaction; if any effect fails, the whole batch (marks included) rolls back, so size batches to what you are willing to redo.
Lab
Every command and output below is expected, not run unless it says "ran". The cheap parts we did run: the Go test (go test ./after/pginbox/ printed ok), the PHP syntax checks, and the ON CONFLICT statements on SQLite 3 (counts 1, 0 for the inbox and 1, 0, 0, 1 for the version-checked projection). No broker or PostgreSQL was started.
Setup (PostgreSQL):
CREATE TABLE wallets (id text PRIMARY KEY, balance bigint NOT NULL);
INSERT INTO wallets VALUES ('w-7', 0);
CREATE TABLE processed_messages (
consumer text NOT NULL, message_id text NOT NULL,
processed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (consumer, message_id));Experiment 1: duplicates without an inbox. Deliver the same credit three times (RabbitMQ: publish three times with the same message-id; or restart the consumer before it acks):
$ psql -c "SELECT balance FROM wallets WHERE id='w-7'"
balance
---------
1500 -- expected: 3 x 500. Wrong: the message was one credit.Experiment 2: the same deliveries with the inbox.
$ go run ./after/rabbitmq # message-id: m-17, published three times
2026/11/25 10:00:01 m-17: processed
2026/11/25 10:00:01 m-17: duplicate
2026/11/25 10:00:01 m-17: duplicate
$ psql -c "SELECT balance FROM wallets WHERE id='w-7'"
balance
---------
500 -- expected
$ psql -c "SELECT count(*) FROM processed_messages"
count
-------
1Experiment 3: two sessions race on the same id.
session A session B
BEGIN;
INSERT INTO processed_messages VALUES ('c','m-17'); BEGIN;
-- INSERT 0 1 INSERT INTO processed_messages VALUES ('c','m-17')
ON CONFLICT (consumer, message_id) DO NOTHING;
-- blocks (A uncommitted)
UPDATE wallets SET balance = balance + 500 ...;
COMMIT; -- unblocks: INSERT 0 0 (duplicate)Experiment 4: A rolls back, B proceeds. Repeat 3 but run ROLLBACK; in A: expected, B's insert returns INSERT 0 1 and B runs the handler.
Experiment 5: crash between effect and ack. kill -9 the consumer after the commit and before the ack (put a time.Sleep in the handler). Expected: the broker redelivers, the log shows duplicate, the balance stays 500.
Experiment 6: per-broker duplicates (expected, not run).
# RabbitMQ: same message-id twice (check your rabbitmqadmin version's syntax)
rabbitmqadmin publish routing_key=wallet.credits payload='{"wallet_id":"w-7","amount":500}' properties='{"message_id":"m-17"}'
rabbitmqadmin publish routing_key=wallet.credits payload='{"wallet_id":"w-7","amount":500}' properties='{"message_id":"m-17"}'
# Kafka (kcat): same message-id header twice
echo '{"wallet_id":"w-7","amount":500}' | kcat -P -b localhost:9092 -t wallet.credits -H "message-id=m-17"
echo '{"wallet_id":"w-7","amount":500}' | kcat -P -b localhost:9092 -t wallet.credits -H "message-id=m-17"
# Redis Streams: two entries, two ids, same event_id; then a pending entry
redis-cli XGROUP CREATE wallet.credits wallet-credit 0 MKSTREAM
redis-cli XADD wallet.credits '*' event_id m-17 wallet_id w-7 amount 500
redis-cli XADD wallet.credits '*' event_id m-17 wallet_id w-7 amount 500
redis-cli XPENDING wallet.credits wallet-credit
redis-cli XAUTOCLAIM wallet.credits wallet-credit worker-2 60000 0-0
# Redis 8.6+: producer-side dedup; the second XADD returns the first entry id
redis-cli XADD wallet.credits IDMP billing-1 payment-42 '*' event_id payment-42 wallet_id w-7 amount 500
redis-cli XADD wallet.credits IDMP billing-1 payment-42 '*' event_id payment-42 wallet_id w-7 amount 500Expected for all three brokers: balance ends at 500 and processed_messages has one row for m-17 (Redis: for event_id).
Experiment 7: window too short. Delete the row early and redeliver:
DELETE FROM processed_messages WHERE message_id = 'm-17'; -- simulate TTL expiry
-- redeliver m-17: expected, processed again, balance 1000Common misconceptions
| Belief | Reality |
|---|---|
| "My broker is exactly-once, so consumers need no dedup" | Broker guarantees stop at the broker; a database write or HTTP call in the handler can still repeat |
"SELECT then INSERT is a safe check" | Two workers both see "not seen"; the unique constraint is the check |
| "Mark first, it is the safe order" | A crash after the mark loses the message's effect; at-most-once in disguise |
| "The Kafka message key is a dedup key" | It identifies the entity for partitioning; many messages share it |
"topic-partition-offset catches every duplicate" | It catches redelivery of one record, not a producer that wrote the event twice |
"redelivered = false means I can skip the inbox" | It proves the broker has not delivered that message before, not that the producer did not send it twice |
"ShouldBeUnique makes a job idempotent" | It de-duplicates dispatch through a cache lock; handle() can still run twice |
"WithoutOverlapping prevents double processing" | It prevents simultaneous runs; a redelivery after the first run finished is not blocked |
"A Redis SET NX key is as good as an inbox row" | It is a second system: no shared transaction, lost on eviction or failover |
| "Keep dedup rows one day" | The window is derived from retry, DLQ, replay and producer paths; a guess silently reintroduces duplicates |
"Partition the inbox by processed_at and drop old partitions" | Unique keys must include the partition key, so cross-day duplicates slip through; partition by a message property |
| "Idempotent upsert is always idempotent" | Not if it writes a delta (qty = qty + EXCLUDED.qty) |
Cheat sheet
| Topic | What to remember |
|---|---|
| The pattern | BEGIN; INSERT mark ON CONFLICT DO NOTHING; if 0 rows skip; business write; COMMIT; ack |
| The guard | The primary key (consumer, message_id), not a SELECT |
| The key | Producer-created, once, before the first send; business key for semantic duplicates |
| Ack rule | Ack after commit, for both "processed" and "duplicate" |
| Mark order | Only one transaction is correct; two commits are either duplicates or loss |
| Natural first | Set not add; upsert by key; conditional WHERE status = 'pending'; set tables not counters |
| Projections | WHERE version < EXCLUDED.version; versions from the aggregate, not clocks |
| External effects | Downstream Idempotency-Key plus a lease; or accept at-least-once or at-most-once by consequence |
| TTL | Window = broker redelivery + retries + DLQ parking + producer retry + margin |
| Cleanup | Batched DELETE, or partition by a message property and drop |
| Kafka | Idempotent producer and EOS are Kafka-to-Kafka; DB sinks need the inbox or offsets-in-DB |
| RabbitMQ | Set message-id; redelivered is a hint when set |
| Redis Streams | Entry id for redelivery; event_id or IDMP (8.6+) for producer retries |
| Laravel | ShouldBeUnique dedups dispatch; WithoutOverlapping serialises; neither is an inbox |
| Test | Deliver the same message twice; fail after the mark; assert one effect |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why can an at-least-once broker never be fully safe without consumer-side dedup? Must-know
Answer
Answer: A failure between performing the effect and acknowledging leaves the broker unable to tell whether the effect happened, so it redelivers. Producer retries and rebalances add more duplicates. See delivery guarantees.
2 — Why does a SELECT before the INSERT not make dedup safe? Must-know
Answer
Answer: Two concurrent workers both see no row and both proceed. The unique constraint, enforced inside the transaction, is the primitive; the second insert waits for the first transaction's outcome and then reports a conflict.
3 — What goes wrong with "mark then process" in two commits? Must-know
Answer
Answer: A crash after the mark and before the effect leaves the mark in place and the effect missing; the redelivery is skipped and the work is lost (at-most-once).
4 — Why must the mark and the effect be in one transaction, and what limits that? Must-know
Answer
Answer: So they succeed or fail together. It works only when the effect is in the same database as the inbox table; external effects need a downstream idempotency key or a lease.
5 — Name three sources of an idempotency key and one weakness each. Important
Answer
Answer: Producer message id (must be created before the first send); Kafka topic-partition-offset (does not catch a producer double-send); business key (a legitimate repeat collides). Also Redis entry id (a retried XADD makes a second entry).
6 — How do you choose the TTL of dedup rows? Important
Answer
Answer: Sum the longest redelivery paths (broker redelivery, retry and backoff, DLQ parking and replay, producer retry horizon) and add a margin. Too short silently reintroduces duplicates; too long wastes storage.
7 — Why can partitioning the inbox by processed_at break dedup? Good to know
Answer
Answer: PostgreSQL requires a unique key on a partitioned table to include the partition key, so the key contains processed_at; a duplicate processed on another day has a different value and is accepted. Partition by a property that is identical on every copy.
8 — Why are Kafka's exactly-once transactions not an inbox? Important
Answer
Answer: They commit output records and consumer offsets atomically inside Kafka. A database write in the handler is outside that transaction, so redelivery can still repeat it; you need the inbox or offsets stored with the output.
9 — What is the difference between ShouldBeUnique and an idempotent consumer? Must-know
Answer
Answer: ShouldBeUnique takes a cache lock to prevent dispatching an equivalent job while one is queued or running. It does not stop one job's handle() from running twice on redelivery, and the lock is not in your transaction.
10 — How does a version check make a projection idempotent and order-tolerant? Important
Answer
Answer: The upsert applies an event only when its version is greater than the stored one, so a replay (equal) and a stale event (lower) change zero rows, while a newer event applies.
11 — A third-party webhook can arrive five times over three days. What key and window? Must-know
Answer
Answer: The provider's event id as the key, scoped by consumer, and a window longer than their retry schedule (three days plus margin).
Glossary
| Term | Meaning |
|---|---|
| Idempotent | Repeating an operation leaves the same state as doing it once |
| Idempotent consumer / receiver | A consumer (EIP: Idempotent Receiver) that can safely receive the same message several times |
| Duplicate delivery | The same message handed to a consumer more than once |
| At-least-once | Delivery semantics that never lose a message but may repeat it |
| Effectively-once | At-least-once delivery plus an idempotent effect: one visible effect |
| Idempotency key | The stable identity of a logical message used to recognise a repeat |
| Message id | A producer-chosen unique id for one logical message (RabbitMQ message-id) |
| Business key | A domain identifier of the meaning (payment_id) usable as a dedup key |
| Coordinates | Kafka topic-partition-offset, assigned by the broker at append |
| Entry id | Redis Streams ms-seq id assigned by XADD |
IDMP / IDMPAUTO | Redis 8.6 XADD modes for producer-side deduplication by producer id + idempotent id, or content hash |
| Inbox (dedup) table | processed_messages: one row per handled message, primary key (consumer, message_id) |
| Full inbox | A table that buffers whole incoming messages and is processed asynchronously |
| Consumer name | The scope of a dedup key; one message may be handled once per consumer |
ON CONFLICT DO NOTHING | PostgreSQL/SQLite clause that skips an insert violating a unique constraint and reports zero rows |
INSERT IGNORE | MySQL form that skips rows that would raise errors such as duplicates |
unique_violation (23505) | PostgreSQL SQLSTATE for a unique constraint failure |
ER_DUP_ENTRY (1062) | MySQL duplicate-key error |
| Mark | Writing the message id into the inbox |
| Process then mark | Effect first, record second; a crash gap repeats the effect |
| Mark then process | Record first, effect second; a crash gap loses the effect |
| Dedup window | Longest time between first and last possible copy of a message |
| TTL (of a dedup row) | How long the row is kept; derived from the dedup window |
| Lease | A time-limited claim (lease_until) letting a crashed claimant be replaced |
| Claim, perform, complete | State machine for non-transactional effects |
| Downstream idempotency key | A key passed to an external system so it can dedup repeated calls |
| Natural idempotency | Operations that converge to the same state however often they run (set, upsert, conditional update) |
| Version check | Apply an event only if its version is newer than the stored version |
| Projection / read model | A table derived from events for querying |
ShouldBeUnique | Laravel interface that locks a job's uniqueId in the cache to prevent duplicate dispatch |
WithoutOverlapping | Laravel job middleware that serialises jobs by key with a cache lock |
uniqueFor / #[UniqueFor] | Seconds before a Laravel unique lock is released (default 0, which never expires) |
retry_after | Laravel queue setting after which a reserved job is retried |
redelivered flag | RabbitMQ flag set when a message was delivered before and requeued; a hint |
| PEL | Redis Streams pending entries list: delivered, not yet acknowledged |
XAUTOCLAIM | Redis command that takes over entries idle in the PEL |
| Exactly-once semantics (EOS) | Kafka's transactional consume-transform-produce within Kafka |
| Idempotent producer | Kafka producer feature that deduplicates its own retries by sequence number |
| Outbox + inbox | Producer-side guaranteed publish paired with consumer-side dedup |
| Partition key (table) | The column(s) that route a row to a table partition; must be in unique keys |
lock_timeout | PostgreSQL setting that aborts a statement waiting too long for a lock (55P03) |
References
- Chris Richardson, "Pattern: Idempotent Consumer", microservices.io. microservices.io
- Hohpe and Woolf, "Idempotent Receiver", Enterprise Integration Patterns. enterpriseintegrationpatterns.com
- Brandur Leach, "Designing robust and predictable APIs with idempotency", Stripe, 22 February 2017. stripe.com
- Stripe API documentation, Idempotent requests. docs.stripe.com
- J. Jena, S. Dalal, D. Tishkin, "The Idempotency-Key HTTP Header Field", Internet-Draft draft-ietf-httpapi-idempotency-key-header (work in progress). datatracker.ietf.org
- PostgreSQL documentation: INSERT, Index Uniqueness Checks, Table Partitioning, Transaction Isolation, Error Codes
- SQLite, UPSERT. sqlite.org
- MongoDB manual, Unique Indexes. mongodb.com
- Redis documentation: Streams, Idempotent message processing, XADD, SET
- Apache Kafka documentation: Design, message delivery semantics, KafkaProducer Javadoc; KIPs: KIP-98, KIP-447
- RabbitMQ documentation: Publishers, Reliability, Consumer Acknowledgements and Publisher Confirms
- NATS, JetStream model deep dive; Apache Pulsar, Message deduplication; Amazon SQS, Using the message deduplication ID; Azure Service Bus, Duplicate detection
- Laravel 13 documentation: Queues (unique jobs,
WithoutOverlapping, database transactions), Query builder; framework source: UniqueLock, WithoutOverlapping - Packages: mateusjunges/laravel-kafka, message handlers, vladimir-yuldashev/laravel-queue-rabbitmq
- Go: amqp091-go, franz-go kgo, go-redis, pgx
- MySQL error constants (third-party list): VividCortex/mysqlerr
- See also: Delivery Guarantees, Message Acknowledgment, Ordering & Partitioning, Transactional Outbox, Dead-Letter Queue, Retry, Backoff & Delayed Delivery, Saga Pattern, Testing Messaging Systems