Skip to content

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 forGo to
The five ways to get idempotency, in one tableEverything in one minute
Why consumers get duplicates and why the broker cannot fix itWhy 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 commitThe transactional pattern
Mark-then-process vs process-then-mark, with crash timelinesMark order
Two workers, same message, same momentConcurrent duplicates
Upserts, SET instead of +1, conditional updatesNatural idempotency
Email, HTTP, payment callsNon-transactional side effects
TTL, dedup window, cleanup, partition drops, sizingTTL, window and cleanup
Read models, version checks, out-of-order eventsIdempotent projections
Storing the Kafka offset next to the dataOffsets stored with the output
The HTTP twinIdempotency-Key at the HTTP edge
Knobs, error codes, dedup primitives per storeMechanics
Problem to solution tableSolving the classic problems
Which error to retryRetries and failure handling
Which technique for which workloadChoosing an approach
Go (pgx) and Laravel codeGo, Laravel
RabbitMQ, Kafka, Redis Streams specificsBroker differences
Monolith to multi-regionIn architecture
Reproduce duplicates and watch the inbox reject themLab
Wrong beliefs, a cheat sheet, every term definedMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The five ways to make a consumer safe against duplicates. Every row is unpacked below.

TechniqueIn plain wordsNeedsCoversDoes not cover
Natural idempotencyThe operation gives the same result however often it runs (SET status = 'paid', upsert by key)Nothing extraUpdates by key, projections, cache refreshesIncrements, appends, "send an email"
Inbox table (idempotent consumer)Remember every message id you finished; refuse a second oneA unique key per message, one databaseAnything written in the same database transactionEffects in other systems
Version checkApply an event only if its version is newer than the stored oneA per-aggregate version in the messageDuplicates and out-of-order delivery for read modelsCommands with no version
Downstream idempotency keyPass your message id to the system you call; it dedupsA downstream that honours a keyHTTP calls, payments, provider APIsProviders that ignore the key (most email APIs)
Broker-side dedup windowThe producer-side broker drops a repeat id within a windowA producer-chosen idProducer retries within the windowConsumer redelivery; anything after the window

The order of "mark" and "process".

OrderCrash between the two stepsDelivery semantics you really get
Process, then mark (two commits)Effect already happened, mark missing: next delivery repeats the effectAt-least-once (the original bug, one step later)
Mark, then process (two commits)Mark exists, effect missing: next delivery is skipped, work is lostAt-most-once
Mark and process in ONE transactionBoth roll back togetherEffectively-once, if the effect is in that database

Where each broker gives you a key.

BrokerProducer-chosen idBroker-assigned idStable across redeliveryStable across a producer retry
RabbitMQmessage-id property (optional, never checked)none (delivery tag is per channel)Yes (message-id survives requeue)Yes, if the producer reuses it
KafkaHeader or payload fieldtopic-partition-offsetYesOffset: no (two offsets). Header: yes
Redis StreamsA field such as event_id; or IDMP pid + iid (8.6+)Entry id ms-seqYes (same id after XCLAIM/XAUTOCLAIM)Entry id: no. IDMP: yes
Laravel queueYour own $messageId propertyPayload uuid ($this->job->uuid())Yesuuid: 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, weakerCostlier, 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 tableLong 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.
  • "SELECT to check, then INSERT, is enough." Two workers can both see "not seen". The unique constraint is the primitive; the SELECT is an optimisation at best.
  • "ShouldBeUnique (Laravel) makes my job idempotent." It de-duplicates dispatches through a cache lock. It does not stop handle() 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:

WordMeansExample
IdempotentRepeating gives the same stateUPDATE orders SET status = 'paid' WHERE id = 7
SafeRepeating changes nothing at all (read-only)SELECT, HTTP GET
Exactly-once (delivery)The receiver sees one copyImpossible end to end (two generals)
Exactly-once (effect)At-least-once delivery + idempotent handlerThe 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 value

Real 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:

SourceExampleSet byRedelivery (same copy again)Producer duplicate (two copies)Watch out
Producer message iduuid/ULID in header or fieldProducer, onceCaughtCaught, if reused on retryMust be created BEFORE the first attempt, not inside the retry loop
RabbitMQ message-idPublishing.MessageId / Delivery.MessageIdPublisherCaughtCaught if reusedOptional; the broker never sets or checks it; empty means no dedup
Kafka topic-partition-offsetwallet.credits-3-18204Broker at appendCaught (after rebalance or crash)Not caught (two offsets)Resets if the topic is recreated; offsets are per partition
Kafka header message-idHeader written by the producerProducerCaughtCaughtNeeds a client that exposes record headers
Redis Streams entry id1700000000000-0XADDCaught (same id after XCLAIM/XAUTOCLAIM)Not caught (two entries)Prefer a producer-set event_id field
Redis 8.6 IDMP pid + iidXADD s IDMP billing-1 payment-42 * ...Producern/a (producer side)Caught: XADD returns the original entry idProducer-side window only (IDMP-DURATION, IDMP-MAXSIZE)
Laravel payload uuid$this->job->uuid()Laravel at dispatchCaughtNot caught (new dispatch, new uuid)Fine when the dispatch happens once per intent
Business keyorder_id:paid, payment_id, (aggregate_id, version)DomainCaughtCaughtA legitimate repeat (second refund of the same order) needs a discriminator
Content hashSHA-256 of the body; Redis IDMPAUTOConsumer or RedisCaughtCaughtTwo legitimate identical commands (two "+500" credits) collide
HTTP Idempotency-KeyClient-generated UUIDClientCaughtCaughtScope 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:

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

sql
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 storedThe id onlyThe whole message, plus status
Ack timingAfter the handler's transactionRight after the buffer insert
ProcessingInline, in the consumerAsynchronous, from the table
GainsSimple; exactly one write pathFrees the broker fast; absorbs bursts; retry and poison handling live in SQL
CostsHandler time holds the broker messageA second queue (your database) to operate and clean; extra latency
sql
-- 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 transaction

The 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 broker
Brokerat-least-oncem-17ONE database transaction (READ COMMITTED is enough)BEGININSERT (consumer, id)ON CONFLICT DO NOTHINGrows affected?RowsAffected()0duplicateskip handler1business writeUPDATE wallets (same tx)COMMIT mark + writeACKoffset / XACKerror / crashROLLBACKno ACK: broker redeliversThe mark rolled back with the write, so the retry runs the handler again.

Real 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:

StoreAtomic "insert or tell me it existed"Duplicate signal
PostgreSQLINSERT ... ON CONFLICT (cols) DO NOTHINGINSERT 0 0 command tag, RowsAffected() == 0
PostgreSQL (plain insert)INSERT and catch the errorSQLSTATE 23505 unique_violation (aborts the transaction)
MySQL / InnoDBINSERT IGNORE, or ON DUPLICATE KEY UPDATE0 affected rows, or ER_DUP_ENTRY (1062, SQLSTATE 23000)
SQLiteINSERT ... ON CONFLICT DO NOTHINGchanges() is 0
PostgreSQL 19INSERT ... ON CONFLICT DO SELECT returns the existing row (idempotent "insert or get")The returned row is not yours
MongoDBUnique index plus insertOneDuplicate key error
RedisSET key value NX EX secondsReply 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:

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   CORRECT
A. process, then mark (two commits)side effect donecrashmark (never ran)redelivery finds no mark: effect runs TWICEB. mark, then process (two commits)mark committedcrasheffect (never ran)redelivery sees the mark, skips: work LOSTC. mark + process in ONE transaction (inbox)BEGIN, mark, effect, COMMIT (all-or-nothing)crash before COMMIT:both undoneafter COMMIT: duplicatehits the primary keyOnly C is correct, and only when the effect lives in the same database as the inbox table.

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

DesignCrash gapResultWhen acceptable
Process then mark (two commits)Effect done, mark missingDuplicate effectEffect is naturally idempotent
Mark then process (two commits)Mark done, effect missingLost messageThe effect is optional and a duplicate is worse than a miss (a marketing email)
Same transactionNoneEffectively-onceEffect is in the inbox's database
Claim, perform, complete (lease)Effect done, "done" missingRepeat effect with the same downstream keyEffect 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 handler

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

OperationIdempotent?WhyIdempotent rewrite
SET status = 'paid'YesSame value each timenone needed
INSERT ... ON CONFLICT (id) DO UPDATE SET status = EXCLUDED.statusYesWrites the new value, not a deltanone needed
UPDATE orders SET status = 'paid' WHERE id = 7 AND status = 'pending'YesConditional: only the first moves itnone needed
balance = balance + 500NoDepends on the old valueInbox, or store each credit as a ledger row keyed by message id and compute the balance
likes = likes + 1NoCounterA (post_id, user_id) unique table; count rows
Append to a list/logNoGrows each timeKey each entry by message id
Send an email, call an APINoExternal effectDownstream key
Delete by idYesGone is gone (the second DELETE affects 0 rows)none needed
Create with a client-chosen idYesSecond create conflicts or is ignorednone needed
sql
-- 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) ----------------> done

Real 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:

TechniqueHowAdvantageCost or limit
Downstream idempotency keyHeader such as Idempotency-Key: consumer:message_idSimplest; no extra stateDownstream must support it and have a long enough window (Stripe documents that keys may be removed after at least 24 hours)
Claim, perform, completeInbox row with status and lease_until; ON CONFLICT DO UPDATE ... WHERE status = 'processing' AND lease_until < now()Detects crashes; bounds concurrencyEffect may repeat after a lease expiry; still needs a downstream key
Outbox the effectHandler writes an outbox row send_email in the business transaction; a relay sends itHandler stays transactional; retries decoupledAnother moving part; at-least-once at the relay
Check the target firstGET the payment by your reference before POSTWorks with some APIs without keysRacy between check and act; extra latency
Accept the duplicateDo nothingZero costOnly 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.

Service A (producer)ONE transactionorders row + outbox row (id m-17)relay (poll / CDC)publish at least onceBrokermay deliver m-17 twicem-17 (+ retry)Service B (consumer)ONE transactioninbox row (m-17) + business writem-17second m-17: inbox INSERT hits 0 rowsskipped, still ACKedOutbox: every event is published at least once (nothing lost).Inbox: every event is applied at most once. Together: effectively once.

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.

timefirst deliveryrow insertedbroker redeliveryretry + backoffDLQ parking + replayproducer retrylatest possible duplicate = sum of the fourTTL (window + margin)row deleted heresafe: a duplicate in this span hits the primary keyrow deleted too early: late duplicate runs again
     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 caught

How brokers bound the same problem on the producer side:

SystemDedup keyWindowNotes
Amazon SQS FIFOMessageDeduplicationId5 minutesContinues tracking the id even after the message is received and deleted
Azure Service BusMessageId (with PartitionKey when partitioned)Default 10 minutes; 20 seconds to 7 daysScheduled messages included; bigger windows reduce throughput
NATS JetStreamNats-Msg-Id headerDefault 2 minutes (--dupe-window)Only the id is consulted, not the body
Apache PulsarProducer 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 defaultProducer name is mandatory; set the message timeout to 0
Redis Streams 8.6+IDMP pid + iidIDMP-DURATION default 100 s (1 to 86400); IDMP-MAXSIZE default 100 per producer (1 to 10000)Monitor iids-duplicates in XINFO STREAM
KafkaIdempotent producer sequence numbersThe producer session onlyNot 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:

StrategyHowAdvantageLimit
Batched DELETEScheduled job: delete rows older than the window in small batches (index on processed_at)SimpleGenerates dead tuples and WAL; needs autovacuum headroom
Partition and dropPartition by day, DROP or DETACH old partitionsInstant, no VACUUM ("far faster than a bulk operation", PostgreSQL docs)A unique key on a partitioned table must include the partition key
TTL storeRedis EXPIRE / DynamoDB TTL as the dedup storeSelf-cleaningNot atomic with the DB write
Keep foreverNever deleteDedup window = infinityCost grows with throughput; fine at low volume
sql
-- 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):

sql
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 NOTHING

Sizing. 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):

RateWindowRowsApproximate size at 120 B/row
10 msg/s7 days6 millionunder 1 GB
100 msg/s7 days60 millionabout 7 GB
1,000 msg/s14 days1.2 billionabout 145 GB
10,000 msg/s7 days6 billionabout 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:

go
// 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
<?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:

go
// 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
<?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 ​

StorePrimitiveAtomic with a business write?Failure signatureNote
PostgreSQLUnique/PK index + ON CONFLICT DO NOTHINGYes (same transaction)23505 or 0 rowsWaits for an uncommitted conflicting insert
MySQL / InnoDBUnique/PK + INSERT IGNORE or ON DUPLICATE KEY UPDATEYesER_DUP_ENTRY 1062, SQLSTATE 23000IGNORE downgrades errors to warnings, so it can hide errors other than duplicates (we could not fetch the MySQL reference; verify the details there)
SQLiteINSERT ... ON CONFLICT DO NOTHINGYeschanges() = 0Single writer: no races, still needs the transaction
MongoDBUnique indexOnly with a multi-document transactionDuplicate key errorInsert-then-act without a transaction is mark-then-process
RedisSET key v NX EX nNo (separate system)nil replyCache eviction or failover loses the mark: duplicates return
DynamoDB / CassandraConditional write (attribute_not_exists, IF NOT EXISTS)Only within one item or partitionConditional check failedCross-item atomicity is limited

Table design knobs ​

KnobChoiceWhy
Key columns(consumer, message_id)Scope per handler; one id may be consumed by many handlers
Key typeuuid or textuuid is 16 bytes; text ids cost about 37 bytes plus index overhead
IndexOnly the PK plus processed_atEvery extra index is write amplification on the hottest insert path
Fill factorDefaultThe table is insert-only until cleanup
Transaction isolationREAD COMMITTEDON CONFLICT already serialises on the key; higher levels add 40001 retries (Isolation Levels)
lock_timeoutA few secondsA blocked duplicate gives up (55P03) instead of holding a connection
AutovacuumTune for the delete batchesCleanup creates dead tuples (MVCC & VACUUM)
PlacementSame database and shard as the business tablesOtherwise mark and effect are not atomic (Storage & Data Scaling)

Error codes and signals you will meet ​

SignalWhereMeaningWhat to do
INSERT 0 0 / RowsAffected() = 0PostgreSQL ON CONFLICT DO NOTHINGDuplicateSkip and acknowledge
SQLSTATE 23505 unique_violationPostgreSQL plain INSERTDuplicate; the transaction is abortedRoll back, treat as duplicate, acknowledge
ER_DUP_ENTRY 1062 (SQLSTATE 23000)MySQLDuplicateSame
SQLSTATE 40001, 40P01PostgreSQLSerialization failure, deadlockRetry the whole transaction (Deadlocks)
SQLSTATE 55P03 lock_not_availablePostgreSQL with lock_timeoutA concurrent duplicate holds the keyNack and requeue, or skip after a pause
redelivered = trueRabbitMQ deliveryMaybe seen before (hint only)Be careful; still use the inbox
redelivered not setRabbitMQ deliveryGuaranteed not seen before by this queueThe only case the flag proves something
UniqueConstraintViolationExceptionLaravel (Illuminate\Database)Duplicate on a plain insertCatch outside the transaction
ErrTxClosedpgxRollback after CommitIgnore in the deferred rollback

Solving the classic problems ​

ProblemSolutionHowAdvantageCost or limit
Double credit after restartInbox in the business transactionINSERT ... ON CONFLICT DO NOTHING, then UPDATE, one commitExactly one effectOne extra insert per message
Two workers, same messageUnique constraint + short tx + lock_timeoutThe second insert waits, then reports 0 rowsRace-proofBlocked duplicate holds a connection briefly
Duplicate email/SMSClaim, perform with key, complete; or acceptLease row plus Idempotency-KeyBounded repeatsProvider must honour the key
Duplicate webhook from a third partyDedup on their event idInbox keyed by the provider's event_idWorks without producer changesWindow must cover their retry horizon
Out-of-order and duplicate events in a read modelVersion-checked upsertWHERE version < EXCLUDED.versionNo table neededNeeds a trustworthy version
Counter driftSet semanticspost_likes(post_id, user_id) unique; count rowsNaturally idempotentCount cost; materialise with a version
Replay a topic after a bug fixNew consumer name, or idempotent writesA fresh dedup namespaceSafe rebuildDuplicates inside the replay still need natural idempotency
Huge inbox tableWindow from the redelivery paths; partition by message timeDROP PARTITION after the windowCheap cleanupPartition key must be a message property
Producer double-publish with two idsBusiness-key dedupKey (consumer, 'pay_42:captured')Catches semantic duplicatesA legitimate repeat needs a discriminator
Poison message retried foreverReject to DLQ, never mark it processedHandler error rolls the mark back; the DLQ policy bounds attemptsVisible failuresSee 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.

OutcomeInbox stateBroker actionRetry?
Duplicate (0 rows)Existing markAckNo
Handler succeeded, commit succeededMark committedAckNo
Transient error (deadlock 40P01, serialization 40001, connection lost, 55P03)Rolled backNo ack or nack with requeueYes, with backoff (Retry, Backoff & Delayed Delivery)
Permanent error (bad payload, business rule)Rolled backReject without requeue to DLQNo
Crash before commitRolled backBroker redeliversYes
Crash after commit, before ackMark committedBroker redelivers; duplicate path acksYes, 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 ​

WorkloadRecommendedExtra techniqueReason
Money: wallet credits, ledger, paymentsInbox in the business transactionAppend-only ledger keyed by message id; downstream idempotency keysOne duplicate costs more than a table
Order/status read modelsVersion-checked upsertRebuild from the logDuplicates and reordering handled, no table
Search index / cache refreshNatural idempotency (rebuild from state)ShouldBeUnique to coalesce dispatches (Laravel)Cheap; a duplicate is harmless
Counters, likes, viewsSet table (unique pairs) or a periodic recountApproximate counters if acceptable+1 is never idempotent
Email/SMSAt-least-once with claim and lease, or at-most-onceProvider key if offeredChoose by business consequence of a duplicate vs a miss
Third-party webhooksInbox keyed by the provider's event idWindow covers their retry scheduleYou cannot change the producer
Kafka to database at very high volumeOffsets in the same transactionIdempotent writesA row per message is too costly
Kafka to KafkaKafka transactions (EOS)Read committed consumersBroker-side atomic commit works here
Multi-region active-activeNatural idempotency, single owner per keyCRDTs for countersA 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.

go
// 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:

go
// 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:

go
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
}
go
// 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:

go
// 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):

go
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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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.

CapabilityRabbitMQKafkaRedis Streams
Producer-chosen idmessage-id propertyHeader or payload fieldEntry field; IDMP iid (8.6+)
Broker-assigned idNone usable (delivery tag is per channel)topic-partition-offsetEntry id ms-seq
Broker-side dedupNoIdempotent producer, per producer sessionIDMP / IDMPAUTO (8.6+, windowed)
Redelivery signalredelivered flag (hint when set)None: only your committed positionDelivery counter in XPENDING
Consumer positionAck per messageOffset per partitionXACK per entry (the PEL)
Redelivery triggerChannel closes with unacked messages, basic.nack/reject with requeueRebalance, crash before commit, seek backIdle pending entry claimed by XCLAIM/XAUTOCLAIM, or XREADGROUP with id 0
What breaks dedupEmpty message-idCoordinates-only key; producer double-sendXADD 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.

go
// 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.

go
// 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)
			}
		})
	}
}
go
// 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
<?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.

go
// 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)
			}
		}
	}
}
go
// 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
<?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-Key on POST is 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 NOTHING is the documented single-statement primitive the Go inbox relies on; PostgreSQL 19 adds ON CONFLICT DO SELECT, documented as "idempotent insert or get or create".
  • Laravel retry_after / --timeout are the documented source of redelivery in Laravel workers; UniqueLock and WithoutOverlapping are 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.

StepServiceTransactionMessage
1Ordersorder row + outbox row (id=ord-7:placed) in one commitnone yet
2Orders relaypublishes at least once (may publish twice after a crash)OrderPlaced id ord-7:placed
3Paymentsinbox (payments.charge, ord-7:placed) + payment row + outbox row pay-7:capturedPaymentCaptured
3bPayments (duplicate delivery)inbox insert hits 0 rows; acknothing
4Shippinginbox (shipping.create-label, pay-7:captured) + label rownone
5Shipping calls the carrier APIclaim/perform/complete with Idempotency-Key: shipping.create-label:pay-7:capturedcarrier 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 NX is 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 ​

LoadDesignChange
1x (about 10 msg/s)One worker, inbox row per message, DELETE nightlyNothing special; measure pg_total_relation_size
10x (about 100 msg/s)Several workers, batch the inbox insert, partition cleanup, lock_timeoutBatch 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-DBTable is the bottleneck: remove it where you can

Batching the inbox insert (one round trip per batch, find which ids are new):

sql
-- 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):

sql
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
-------
     1

Experiment 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 500

Expected 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:

sql
DELETE FROM processed_messages WHERE message_id = 'm-17';   -- simulate TTL expiry
-- redeliver m-17: expected, processed again, balance 1000

Common misconceptions ​

BeliefReality
"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 ​

TopicWhat to remember
The patternBEGIN; INSERT mark ON CONFLICT DO NOTHING; if 0 rows skip; business write; COMMIT; ack
The guardThe primary key (consumer, message_id), not a SELECT
The keyProducer-created, once, before the first send; business key for semantic duplicates
Ack ruleAck after commit, for both "processed" and "duplicate"
Mark orderOnly one transaction is correct; two commits are either duplicates or loss
Natural firstSet not add; upsert by key; conditional WHERE status = 'pending'; set tables not counters
ProjectionsWHERE version < EXCLUDED.version; versions from the aggregate, not clocks
External effectsDownstream Idempotency-Key plus a lease; or accept at-least-once or at-most-once by consequence
TTLWindow = broker redelivery + retries + DLQ parking + producer retry + margin
CleanupBatched DELETE, or partition by a message property and drop
KafkaIdempotent producer and EOS are Kafka-to-Kafka; DB sinks need the inbox or offsets-in-DB
RabbitMQSet message-id; redelivered is a hint when set
Redis StreamsEntry id for redelivery; event_id or IDMP (8.6+) for producer retries
LaravelShouldBeUnique dedups dispatch; WithoutOverlapping serialises; neither is an inbox
TestDeliver the same message twice; fail after the mark; assert one effect

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
IdempotentRepeating an operation leaves the same state as doing it once
Idempotent consumer / receiverA consumer (EIP: Idempotent Receiver) that can safely receive the same message several times
Duplicate deliveryThe same message handed to a consumer more than once
At-least-onceDelivery semantics that never lose a message but may repeat it
Effectively-onceAt-least-once delivery plus an idempotent effect: one visible effect
Idempotency keyThe stable identity of a logical message used to recognise a repeat
Message idA producer-chosen unique id for one logical message (RabbitMQ message-id)
Business keyA domain identifier of the meaning (payment_id) usable as a dedup key
CoordinatesKafka topic-partition-offset, assigned by the broker at append
Entry idRedis Streams ms-seq id assigned by XADD
IDMP / IDMPAUTORedis 8.6 XADD modes for producer-side deduplication by producer id + idempotent id, or content hash
Inbox (dedup) tableprocessed_messages: one row per handled message, primary key (consumer, message_id)
Full inboxA table that buffers whole incoming messages and is processed asynchronously
Consumer nameThe scope of a dedup key; one message may be handled once per consumer
ON CONFLICT DO NOTHINGPostgreSQL/SQLite clause that skips an insert violating a unique constraint and reports zero rows
INSERT IGNOREMySQL 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
MarkWriting the message id into the inbox
Process then markEffect first, record second; a crash gap repeats the effect
Mark then processRecord first, effect second; a crash gap loses the effect
Dedup windowLongest 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
LeaseA time-limited claim (lease_until) letting a crashed claimant be replaced
Claim, perform, completeState machine for non-transactional effects
Downstream idempotency keyA key passed to an external system so it can dedup repeated calls
Natural idempotencyOperations that converge to the same state however often they run (set, upsert, conditional update)
Version checkApply an event only if its version is newer than the stored version
Projection / read modelA table derived from events for querying
ShouldBeUniqueLaravel interface that locks a job's uniqueId in the cache to prevent duplicate dispatch
WithoutOverlappingLaravel 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_afterLaravel queue setting after which a reserved job is retried
redelivered flagRabbitMQ flag set when a message was delivered before and requeued; a hint
PELRedis Streams pending entries list: delivered, not yet acknowledged
XAUTOCLAIMRedis command that takes over entries idle in the PEL
Exactly-once semantics (EOS)Kafka's transactional consume-transform-produce within Kafka
Idempotent producerKafka producer feature that deduplicates its own retries by sequence number
Outbox + inboxProducer-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_timeoutPostgreSQL setting that aborts a statement waiting too long for a lock (55P03)

References ​

Built by Morteza Negahi