Skip to content

Message Acknowledgment: ack/nack, Offsets, PEL & Redelivery ​

"Therefore, automatic message acknowledgement should be considered unsafe and not suitable for all workloads." — RabbitMQ documentation, Consumer Acknowledgements and Publisher Confirms

Summary: An acknowledgment is the moment the broker stops being responsible for a message; where you put it decides whether a crash loses the message or repeats it. Focus: What "ack" means on RabbitMQ, Kafka, Redis Streams and Laravel queues, the three ack timings and their failure windows, nack and requeue, batch acks, consumer timeouts, prefetch, redelivery and how to find a stuck unacked message. Learning goal: Pick the ack point and the in-flight window for a consumer on purpose, predict what is redelivered after a crash, and diagnose a message that is neither processed nor returned.

This page is the complete reference for consumer-side acknowledgment: basic.ack, basic.nack and basic.reject on RabbitMQ, the committed offset and the consumer position on Kafka, XACK and the pending entries list (PEL) on Redis Streams, and the job lifecycle (delete, release, fail, retry_after, --timeout) on Laravel queues. It covers auto vs manual acknowledgment, the three timings (ack-before-process, ack-after-process, ack-after-side-effects), multiple and batch acks, requeue vs dead-letter, consumer timeouts, prefetch and fairness, the redelivered flag and per-broker diagnostics. It deliberately does not re-teach its neighbours: what at-most-once, at-least-once and exactly-once mean is in Delivery Guarantees; the consumer-side dedup table is in Idempotent Consumers & the Inbox; the parking lot for poison messages is in Dead-Letter Queue; backoff schedules are in Retry, Backoff & Delayed Delivery; rebalance protocols and scaling are in Competing Consumers & Scaling; and the Laravel list and sorted-set internals are in Laravel Queue Internals.

Page map ​

If you are looking forGo to
Tables you can memorise in one minuteEverything in one minute
Why a broker needs acknowledgment at allWhy acknowledgment exists, Where it comes from
What "ack" literally does on each brokerOwnership transfer
Auto ack (auto-ack), NOACK, auto-commitAuto vs manual
Ack before, after, after side effectsAck timing
nack, reject, requeue, poison loopsNegative acknowledgment
multiple=true, batch commit, XACK with many idsBatch acknowledgment
Prefetch, QoS, max.poll.records, COUNTThe in-flight window
Committed offset vs positionKafka offsets
PEL, XPENDING, XCLAIM, XAUTOCLAIM, XNACKRedis pending list
consumer_timeout, max.poll.interval.ms, idle time, retry_afterConsumer timeouts
Redelivery and the redelivered flagRedelivery
"Why is this message stuck?"Stuck-message diagnostics
Laravel release, delete, fail, --timeout, block_forLaravel outcomes
Knobs, defaults, error messagesMechanics
Code for all three timings and manual commitSolving the classic problems, Go, Laravel
Which ack for which workloadChoosing
Monolith to multi-regionIn architecture
Reproduce a crash per brokerLab
Wrong beliefs, cheat sheet, every termMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

What an ack means. Every row is unpacked in the concept catalogue.

BrokerPrimitive that carries the ackWhat the ack doesGranularityIf it never comes
RabbitMQbasic.ack for a delivery tagThe message is recorded as delivered and deleted from the queueOne delivery, or all tags up to N with multiple=trueRequeued when the channel closes or the consumer timeout fires; redelivered is set
KafkaCommitted offset of (group, partition)The stored position moves to the next offset to readA position: everything before it is "done"The group resumes from the last committed offset after a rebalance or restart
Redis StreamsXACK against the consumer group's PELThe id leaves the PEL (the entry stays in the stream)One entry, many ids per callThe entry stays in the PEL for ever until another consumer claims it
Laravel queueReturning from handle() (the worker calls delete)The job is deletedOne jobretry_after seconds later the job becomes available again
NATS JetStreamAck against the consumer with AckExplicitThe message is settledOne message by defaultRedelivered after AckWait, up to MaxDeliver
Amazon SQSDeleteMessageThe message is removedOne messageVisible again after the visibility timeout (default 30 s)

The three timings.

TimingOrderA crash in the window causesDelivery semanticsUse when
Ack-before-processdeliver, ack, processThe message is lostat-most-onceLosing one is cheaper than doing it twice (metrics, cache warm-up)
Ack-after-processdeliver, process, ackThe work may be done twiceat-least-onceThe default for almost everything, with an idempotent handler
Ack-after-side-effectsdeliver, process, COMMIT, ackA redelivery that hits a dedup row and only acksat-least-once delivery, effectively-once effectMoney, stock, anything with a visible side effect

The negative outcomes.

You want to sayRabbitMQKafkaRedis StreamsLaravel
"Done"basic.ackcommit offset N+1XACKreturn from handle()
"Not now, try again"basic.nack / basic.reject with requeue=truedo not commit, stop or retry in placedo not XACK (stays in the PEL), or XNACK (Redis 8.8+)$this->release($seconds)
"Never, park it"basic.reject with requeue=false (dead-letter exchange if configured)publish to a dead-letter topic, then commitXACK after copying to a dead-letter stream$this->fail($e)
"Nothing to do, forget it"basic.ackcommitXACK$this->delete()

Three things to do.

SituationDo this
Any consumer you writeManual ack after the work, a bounded in-flight window, an idempotent handler
Any failure that retrying cannot fixDo not requeue; send it to the dead-letter queue
Any unacked message you cannot explainLook at the owner, the idle time and the delivery count (see diagnostics)

Why acknowledgment exists ​

A broker that deletes a message the moment it hands it out loses the message when the consumer crashes. A broker that never deletes it cannot tell the difference between "being processed" and "forgotten". The acknowledgment is the signal that closes that gap. Everything else on this page is detail about who sends the signal, how finely, and what happens while nobody has.

Ack early (before the work)Ack late (after the work)
No duplicatesDuplicates after every crash
Messages lost on a crashNothing lost on a crash
Small in-flight windowThe unacked window is your backlog and your memory
Nothing to redeliver, nothing to time outNeeds a failure detector: channel close, session timeout, idle time, retry_after
Simple handlerHandler must be idempotent

The analogy we reuse on this page: a restaurant order slip. The waiter hands the cook a slip, and the slip stays on the rail until the dish is plated and the cook takes it down. If the cook faints, the slip is still on the rail, the manager gives it to someone else, and the table may get a second soup if the first was half made. Taking the slip down the moment it is handed over (ack-before-process, auto-ack) is fast, and a fainting cook silently drops the order. Kafka's version is one clip on the rail marking "everything up to here is done": cheap to move, but you cannot take down order 7 while order 5 is still cooking.

Three common misunderstandings, up front ​

  1. "An ack means the message was processed successfully." An ack means the consumer takes responsibility for the outcome and the broker may forget the message. A consumer can ack a message it decided to discard ($this->delete()), and RabbitMQ's own docs note that a basic.reject has the same effect on the broker as an ack: "positive acknowledgements assume a message was successfully processed while their negative counterpart suggests that a delivery wasn't processed but still should be deleted".
  2. "Kafka acknowledges each message." Kafka stores one integer per partition and group. Committing offset 100 says everything before 100 is done, so one failed record blocks the commit for everything after it.
  3. "Redis Streams redelivers unacked entries by itself." It does not. The entry stays in the PEL under the dead consumer until somebody claims it with XCLAIM or XAUTOCLAIM.

Where it comes from ​

Acknowledgment is older than any one broker: it is the answer to the question every messaging protocol must settle, when does the broker stop being responsible for a message? Kafka's design document states the problem plainly:

"If the broker records a message as consumed immediately every time it is handed out over the network, then if the consumer fails to process the message (say because it crashes or the request times out or whatever) that message will be lost." — Apache Kafka documentation, Design, "Message Delivery Semantics"

The classic remedy is the one the same document names: "many messaging systems add an acknowledgement feature which means that messages are only marked as sent not consumed when they are sent; the broker waits for a specific acknowledgement from the consumer to record the message as consumed." RabbitMQ implements it as basic.ack, basic.reject and the extension basic.nack, which exists because basic.reject "doesn't historically have the field" for bulk operation. Redis added consumer groups with Streams in 5.0 (XACK is marked since 5.0.0), XAUTOCLAIM in 6.2 (XCLAIM is as old as groups, 5.0), and XNACK in 8.8. Kafka took a different road: it replaced per-message acknowledgment with a stored position, and only recently added the per-record alternative, share groups (production-ready in Kafka 4.2, per the 4.2 release announcement). Laravel's queue workers hide all of it behind the return of handle().

The word "ack" is overloaded. This page is about the consumer acknowledgment (consumer to broker). The publisher confirm (broker to producer, RabbitMQ confirm.select, Kafka acks=all) answers a different question, "did the broker take my message?", and belongs to Delivery Guarantees and the outbox pattern.

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, the precise definition, a timeline, real scenarios, what each broker does, and the fix with code.

Ownership transfer: what an ack means Must-know ​

In plain words: before the ack the broker owns the message and must be able to give it to someone else; after the ack the consumer owns the outcome and the broker is allowed to forget.

Common misunderstanding: "The ack tells the broker the business operation succeeded." The broker cannot know that. It learns only that the consumer is done with the delivery, for whatever reason.

Definition: an acknowledgment is a consumer-to-broker signal that ends the broker's obligation to redeliver. What it changes in storage differs by broker: RabbitMQ deletes the message from the queue, Kafka advances the committed offset of the consumer group for that partition, Redis removes the entry id from the group's PEL (the entry itself stays in the stream until trimmed).

text
    consumer                      broker (RabbitMQ)                   broker (Kafka)                 broker (Redis)
1   receive delivery tag 7  <---  message 7 "unacked", still stored   position 7 (in the consumer)    PEL: 1700-0 owner A, n=1
2   work ...
3   basic.ack(7)            --->  message 7 deleted from the queue
3'  commitSync(offset 8)     ------------------------------------>   committed offset of (billing,p0) = 8
3'' XACK orders billing 1700-0 ---------------------------------------------------------------------------->  PEL entry removed

Real scenario: an order-confirmation consumer; a handler that discards an obsolete reminder; a consumer that rejects a malformed payload. In all three the ack ends the broker's duty, and only the first is "success".

BrokerWhat changes in the brokerWhat is not changed
RabbitMQThe message is removed from the queue (a stream queue is a log and keeps data until retention)Nothing is written back to the publisher
KafkaOne integer in the internal offsets topic for (group, partition)The record stays in the log until retention deletes it; other groups are unaffected
Redis StreamsThe id leaves the group's PELThe entry stays in the stream; other groups still see it; XACKDEL (Redis 8.2+) also deletes it
Laravel (redis driver)ZREM of the reserved payload from queues:<name>:reservedA failed job is copied to failed_jobs before deletion

Fix / how to use it: decide, per consumer, which of the three outcomes each failure maps to (done, retry later, never) and write that mapping in one place. The Go and Laravel code is in Solving the classic problems.

Auto vs manual acknowledgment Must-know ​

In plain words: auto mode lets the broker decide you are done the instant it sends the message; manual mode makes you say so.

Common misunderstanding: "My handler takes 5 ms, so auto-ack is safe." Speed does not matter for the crash window: the message is already forgotten when it is written to the socket. Auto-ack is also unbounded, because there is no prefetch limit by definition.

Definition: in RabbitMQ, autoAck=true (AMQP no-ack) means "a message is considered to be successfully delivered immediately after it is sent"; the docs call it "fire-and-forget". In Redis, XREADGROUP ... NOACK skips the PEL and "is equivalent to acknowledging the message when it is read". In Kafka, enable.auto.commit=true (default) commits "periodically ... in the background", every auto.commit.interval.ms (default 5000).

text
    broker                      consumer
1   write message 7 to socket
2   treat 7 as delivered        (auto-ack: broker forgets it NOW)
3                               kill -9 before the handler ends
4   -- nothing to requeue, message 7 is gone --

Real scenario: a cache-warming consumer where a lost message only costs a cold cache; a firehose of metrics where the next sample replaces this one. For orders, payments and emails, auto-ack is a bug.

ProductAuto modeDefaultSafe to use?
RabbitMQautoAck=true in Channel.Consume (basic.consume with no-ack)you choose it per Channel.Consume callOnly for steady, cheap, loss-tolerant consumers
Kafka (Java consumer, librdkafka)enable.auto.commit=truetrueAt-least-once only if you finish everything poll returned before the next poll
Kafka (franz-go)default autocommit of previously polled records; GreedyAutoCommit commits what was just polledautocommit onDefault is safe; greedy "may result in message loss if your application crashes"
Redis StreamsNOACK on XREADGROUPoffSame as fire-and-forget
Laravelnone: the worker deletes after handle() returnsalways onSafe, but a caught exception counts as success
laravel-kafkaauto-commit "after your handler runs, even when it fails"onUse withManualCommit()

Fix: use manual ack with a bounded window. The before/after Go and Laravel code is in the Go and Laravel sections.

Ack timing: before, after, after side effects Must-know ​

In plain words: the position of one line of code, the ack, decides whether a crash loses the work or repeats it.

Common misunderstanding: "Ack after processing gives exactly-once." It gives at-least-once. If the process dies between the side effect and the ack, the broker redelivers and the side effect runs again. Exactly-once effect needs an idempotent handler or a dedup row committed together with the side effect.

Definition: three placements. Ack-before-process acks first. Ack-after-process acks when the handler returns. Ack-after-side-effects acks only after every external effect is durable, typically after the database transaction that wrote both the business change and the dedup row has committed.

1. Ack first2. Ack after3. Ack afterside effectsdeliverackprocessdeliverprocessackdeliverprocessCOMMITackcrash here: gonecrash here: redeliveredcrash here: redelivered, dedup row hitat-most-onceno duplicates, lost on crashat-least-onceduplicate side effect on crasheffectively onceduplicate is detected and skippedtimetime flows left to right; the dashed band is the window in which a crash changes the outcome
text
    ack-before          ack-after                ack-after-side-effects
1   deliver             deliver                  deliver
2   ACK                 process (charge card)    BEGIN; INSERT inbox; charge row; COMMIT
3   process             ACK                      ACK
    crash at 3          crash between 2 and 3    crash between COMMIT and ACK
    -> lost             -> card charged twice    -> redelivery: inbox row exists, skip, ACK

Real scenario: (1) a page-view counter acks first; losing 3 of 10 million is fine. (2) an email sender acks after sending; a crash after SMTP accepts and before the ack sends a duplicate email, which is tolerable. (3) a payment consumer writes the charge and the inbox row in one transaction and acks afterwards; the redelivery is harmless.

TimingRabbitMQKafkaRedis StreamsLaravel
Befored.Ack(false) then handleCommitRecords then handleXACK then handle (or NOACK)$this->delete() at the top of handle()
Afterhandle then d.Ack(false)handle then CommitRecordshandle then XACKreturn normally (the default)
After side effectscommit the DB transaction, then ackcommit the DB transaction, then MarkCommitRecordscommit the DB transaction, then XACKDB::transaction() inside handle(), then return

Fix: the three timings for each broker in Go are below, SQL for the dedup row once, and Laravel after it.

go
// Package rabbittiming shows the three acknowledgment timings on RabbitMQ and
// batched acknowledgments with multiple=true.
package rabbittiming

import (
	"context"
	"database/sql"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"
)

// AckBeforeProcess acknowledges first. A crash after the Ack and before the
// handler finishes loses the message: at-most-once.
func AckBeforeProcess(d amqp.Delivery, handle func([]byte) error) error {
	if err := d.Ack(false); err != nil {
		return err
	}
	return handle(d.Body)
}

// AckAfterProcess acknowledges once the handler returned. A crash before the
// Ack makes the broker redeliver (Redelivered=true): at-least-once.
func AckAfterProcess(d amqp.Delivery, handle func([]byte) error) error {
	if err := handle(d.Body); err != nil {
		// Requeue a first failure; a message that already came back once goes
		// to the dead-letter exchange (or is dropped) instead of looping.
		return d.Nack(false, !d.Redelivered)
	}
	return d.Ack(false)
}

// AckAfterSideEffects acknowledges only after the database transaction that
// holds the side effect AND the dedup row has committed. If the process dies
// between Commit and Ack the redelivery finds the dedup row and just acks.
func AckAfterSideEffects(ctx context.Context, db *sql.DB, d amqp.Delivery,
	apply func(context.Context, *sql.Tx, []byte) error) error {

	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return d.Nack(false, true) // nothing happened yet: safe to requeue
	}
	defer tx.Rollback() // no-op after a successful Commit

	res, err := tx.ExecContext(ctx,
		`INSERT INTO inbox (message_id) VALUES ($1) ON CONFLICT DO NOTHING`, d.MessageId)
	if err != nil {
		return d.Nack(false, true)
	}
	if n, _ := res.RowsAffected(); n == 1 { // first time we see this message
		if err := apply(ctx, tx, d.Body); err != nil {
			return d.Nack(false, !d.Redelivered)
		}
	}
	if err := tx.Commit(); err != nil {
		return d.Nack(false, true)
	}
	return d.Ack(false) // ownership returns to the broker only now
}

// ConsumeBatched acknowledges every `size` deliveries (or every `every`) with
// one multiple=true frame. Order matters: a failing delivery is settled
// BEFORE any later tag is acked with multiple=true, otherwise the broker would
// silently acknowledge it too.
func ConsumeBatched(ctx context.Context, ch *amqp.Channel, queue string, size int,
	every time.Duration, handle func([]byte) error) error {

	// The window must be at least as large as the batch, or the broker stops
	// delivering before we ever reach `size` unacknowledged messages.
	if err := ch.Qos(size, 0, false); err != nil {
		return err
	}
	deliveries, err := ch.Consume(queue, "", false, false, false, false, nil)
	if err != nil {
		return err
	}

	var (
		last    *amqp.Delivery // highest handled-and-not-yet-acked delivery
		pending int
	)
	flush := func() error {
		if last == nil {
			return nil
		}
		err := last.Ack(true) // acks every outstanding tag up to and including this one
		last, pending = nil, 0
		return err
	}
	tick := time.NewTicker(every)
	defer tick.Stop()

	for {
		select {
		case <-ctx.Done():
			_ = flush()
			return ctx.Err()
		case <-tick.C:
			if err := flush(); err != nil {
				return err
			}
		case d, ok := <-deliveries:
			if !ok {
				return flush()
			}
			if err := handle(d.Body); err != nil {
				if err := flush(); err != nil { // settle the good ones first
					return err
				}
				if err := d.Reject(false); err != nil { // then the bad one, alone
					return err
				}
				continue
			}
			dd := d
			last, pending = &dd, pending+1
			if pending >= size {
				if err := flush(); err != nil {
					return err
				}
			}
		}
	}
}

The same three timings for Kafka (franz-go), including a client that marks records and flushes the marks when a partition is revoked:

go
// Package kafkatiming shows commit-before, commit-after and
// commit-after-side-effects with franz-go, plus a rebalance-safe client.
package kafkatiming

import (
	"context"
	"database/sql"
	"fmt"

	"github.com/twmb/franz-go/pkg/kgo"
)

// lastPerPartition keeps the highest-offset record of each partition, which is
// all CommitRecords needs: it commits last offset + 1 for every partition seen.
func lastPerPartition(rs []*kgo.Record) []*kgo.Record {
	type tp struct {
		topic string
		part  int32
	}
	idx := map[tp]int{}
	var out []*kgo.Record
	for _, r := range rs {
		k := tp{r.Topic, r.Partition}
		if i, ok := idx[k]; ok {
			out[i] = r
			continue
		}
		idx[k] = len(out)
		out = append(out, r)
	}
	return out
}

// CommitBeforeProcess moves the position first: a crash while handling skips
// the records forever (at-most-once).
func CommitBeforeProcess(ctx context.Context, cl *kgo.Client, handle func(*kgo.Record) error) error {
	recs := cl.PollRecords(ctx, 100).Records() // bounded batch, like max.poll.records
	if len(recs) == 0 {
		return ctx.Err()
	}
	if err := cl.CommitRecords(ctx, lastPerPartition(recs)...); err != nil {
		return err
	}
	for _, r := range recs {
		if err := handle(r); err != nil {
			return err // the record is already "consumed"
		}
	}
	return nil
}

// CommitAfterProcess handles the whole batch, then commits its tail
// (at-least-once). The client must use kgo.DisableAutoCommit().
func CommitAfterProcess(ctx context.Context, cl *kgo.Client, handle func(*kgo.Record) error) error {
	recs := cl.PollRecords(ctx, 100).Records()
	if len(recs) == 0 {
		return ctx.Err()
	}
	for _, r := range recs {
		if err := handle(r); err != nil {
			// Offsets of the records before r in this batch are NOT committed
			// either: they will be re-read. That is the price of a position.
			return fmt.Errorf("%s/%d@%d: %w", r.Topic, r.Partition, r.Offset, err)
		}
	}
	return cl.CommitRecords(ctx, lastPerPartition(recs)...)
}

// NewMarkingClient builds a client where only records you MARK are committed,
// in the background, and where a rebalance flushes the marks first.
func NewMarkingClient(brokers []string, group, topic string) (*kgo.Client, error) {
	return kgo.NewClient(
		kgo.SeedBrokers(brokers...),
		kgo.ConsumerGroup(group),
		kgo.ConsumeTopics(topic),
		kgo.AutoCommitMarks(), // autocommit, but only what MarkCommitRecords marked
		kgo.OnPartitionsRevoked(func(ctx context.Context, cl *kgo.Client, _ map[string][]int32) {
			// Commit finished work before the partition moves to another member.
			_ = cl.CommitMarkedOffsets(ctx)
		}),
	)
}

// CommitAfterSideEffects marks a record only after its database transaction
// (business write + dedup row) committed. Mark, never mark-before-commit.
func CommitAfterSideEffects(ctx context.Context, cl *kgo.Client, db *sql.DB,
	apply func(context.Context, *sql.Tx, *kgo.Record) error) error {

	fetches := cl.PollRecords(ctx, 100)
	if fetches.IsClientClosed() {
		return fmt.Errorf("client closed")
	}
	for _, r := range fetches.Records() {
		tx, err := db.BeginTx(ctx, nil)
		if err != nil {
			return err
		}
		res, err := tx.ExecContext(ctx,
			`INSERT INTO inbox (message_id) VALUES ($1) ON CONFLICT DO NOTHING`,
			fmt.Sprintf("%s/%d/%d", r.Topic, r.Partition, r.Offset))
		if err != nil {
			tx.Rollback()
			return err
		}
		if n, _ := res.RowsAffected(); n == 1 {
			if err := apply(ctx, tx, r); err != nil {
				tx.Rollback()
				return err // stop: nothing after this record may be marked
			}
		}
		if err := tx.Commit(); err != nil {
			return err
		}
		cl.MarkCommitRecords(r) // the background autocommit will pick it up
	}
	return nil
}

// ProcessWithoutRebalance blocks rebalances while a polled batch is being
// handled, so commits always refer to partitions this member still owns.
// Keep the batch small: a long block can get the member kicked out.
func ProcessWithoutRebalance(ctx context.Context, cl *kgo.Client, handle func(*kgo.Record) error) error {
	// The client was built with kgo.DisableAutoCommit() and kgo.BlockRebalanceOnPoll().
	recs := cl.PollRecords(ctx, 50).Records()
	defer cl.AllowRebalance()
	for _, r := range recs {
		if err := handle(r); err != nil {
			return err
		}
	}
	if len(recs) == 0 {
		return ctx.Err()
	}
	return cl.CommitRecords(ctx, lastPerPartition(recs)...)
}

And for Redis Streams, including batched XACK, replaying this consumer's own history and releasing entries with XNACK:

go
// Package redistiming shows the three acknowledgment timings on a Redis
// Streams consumer group, batched XACK, replaying our own history and XNACK.
package redistiming

import (
	"context"
	"database/sql"
	"time"

	"github.com/redis/go-redis/v9"
)

const (
	stream = "orders"
	group  = "billing"
)

func readNew(ctx context.Context, rdb *redis.Client, consumer string, count int64) ([]redis.XMessage, error) {
	res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
		Group: group, Consumer: consumer, Streams: []string{stream, ">"},
		Count: count, Block: 5 * time.Second,
	}).Result()
	if err == redis.Nil {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	var out []redis.XMessage
	for _, s := range res {
		out = append(out, s.Messages...)
	}
	return out, nil
}

// AckBeforeProcess removes the entry from the PEL first: a crash while
// handling loses it (at-most-once). XREADGROUP ... NOACK has the same effect
// without the extra round trip.
func AckBeforeProcess(ctx context.Context, rdb *redis.Client, consumer string, handle func(redis.XMessage) error) error {
	msgs, err := readNew(ctx, rdb, consumer, 50)
	if err != nil {
		return err
	}
	for _, m := range msgs {
		if err := rdb.XAck(ctx, stream, group, m.ID).Err(); err != nil {
			return err
		}
		if err := handle(m); err != nil {
			return err
		}
	}
	return nil
}

// AckAfterProcess leaves a failed entry in the PEL (at-least-once). Somebody
// must claim it later: see the reaper in the redis_after snippet.
func AckAfterProcess(ctx context.Context, rdb *redis.Client, consumer string, handle func(redis.XMessage) error) error {
	msgs, err := readNew(ctx, rdb, consumer, 50)
	if err != nil {
		return err
	}
	for _, m := range msgs {
		if err := handle(m); err != nil {
			continue // stays pending, idle time keeps growing
		}
		if err := rdb.XAck(ctx, stream, group, m.ID).Err(); err != nil {
			return err
		}
	}
	return nil
}

// AckAfterSideEffects acknowledges only after the database transaction with
// the business write and the dedup row has committed.
func AckAfterSideEffects(ctx context.Context, rdb *redis.Client, db *sql.DB, consumer string,
	apply func(context.Context, *sql.Tx, redis.XMessage) error) error {

	msgs, err := readNew(ctx, rdb, consumer, 50)
	if err != nil {
		return err
	}
	for _, m := range msgs {
		tx, err := db.BeginTx(ctx, nil)
		if err != nil {
			return err
		}
		res, err := tx.ExecContext(ctx,
			`INSERT INTO inbox (message_id) VALUES ($1) ON CONFLICT DO NOTHING`, stream+"/"+m.ID)
		if err != nil {
			tx.Rollback()
			return err
		}
		if n, _ := res.RowsAffected(); n == 1 {
			if err := apply(ctx, tx, m); err != nil {
				tx.Rollback()
				continue // stays pending
			}
		}
		if err := tx.Commit(); err != nil {
			return err
		}
		if err := rdb.XAck(ctx, stream, group, m.ID).Err(); err != nil {
			return err // redelivery will hit the dedup row and just ack
		}
	}
	return nil
}

// AckBatch handles a whole batch and acknowledges the successes with ONE
// XACK carrying many ids. Ids that failed simply stay in the PEL.
func AckBatch(ctx context.Context, rdb *redis.Client, consumer string, handle func(redis.XMessage) error) (int64, error) {
	msgs, err := readNew(ctx, rdb, consumer, 200)
	if err != nil {
		return 0, err
	}
	done := make([]string, 0, len(msgs))
	for _, m := range msgs {
		if handle(m) == nil {
			done = append(done, m.ID)
		}
	}
	if len(done) == 0 {
		return 0, nil
	}
	return rdb.XAck(ctx, stream, group, done...).Result() // number really removed from the PEL
}

// ResumeHistory re-reads this consumer's own pending entries (id "0" instead
// of ">"), which is how a restarted consumer picks up what it never acked.
func ResumeHistory(ctx context.Context, rdb *redis.Client, consumer string, handle func(redis.XMessage) error) error {
	res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
		Group: group, Consumer: consumer, Streams: []string{stream, "0"}, Count: 50,
	}).Result()
	if err != nil {
		return err
	}
	if len(res) == 0 {
		return nil // history is empty: switch to ">"
	}
	for _, m := range res[0].Messages {
		if handle(m) == nil {
			if err := rdb.XAck(ctx, stream, group, m.ID).Err(); err != nil {
				return err
			}
		}
	}
	// An entry that keeps failing is returned again by the next call with "0";
	// a real consumer remembers the last id, or counts deliveries (see redis_diag).
	return nil
}

// ReleaseOnShutdown hands entries back to the group at once instead of making
// the others wait for min-idle-time. XNACK needs Redis 8.8 or newer.
func ReleaseOnShutdown(ctx context.Context, rdb *redis.Client, ids []string) error {
	return rdb.XNack(ctx, &redis.XNackArgs{
		Stream: stream, Group: group,
		Mode: redis.XNackModeSilent, // undo this delivery in the counter
		IDs:  ids,
	}).Err()
}

The dedup row that makes the third timing safe is one statement; the pattern, its failure modes and its retention are owned by Idempotent Consumers & the Inbox:

sql
-- One row per processed message id; the PRIMARY KEY is what rejects the replay.
CREATE TABLE inbox (
    message_id   text        PRIMARY KEY,
    processed_at timestamptz NOT NULL DEFAULT now()
);

-- Inside the same transaction as the business write:
-- 1 row inserted  -> first time, do the work
-- 0 rows inserted -> redelivery, skip the work, then ack
INSERT INTO inbox (message_id) VALUES ($1) ON CONFLICT DO NOTHING;

Negative acknowledgment: nack, reject, requeue Must-know ​

In plain words: a negative ack says "I could not do this", plus a second decision: put it back, or get rid of it.

Common misunderstanding: "Requeue is a retry policy." Requeue puts the message straight back, usually at its old position, so the same consumer gets it again immediately. If the failure is deterministic that is a hot loop. The RabbitMQ docs warn that such loops "can be costly in terms of network bandwidth and CPU resources" and suggest tracking redeliveries and then rejecting for good or "schedule requeueing after a delay".

Definition: on RabbitMQ, basic.reject rejects one delivery; basic.nack (a RabbitMQ extension to AMQP 0-9-1) can reject many with multiple=true; both take requeue. With requeue=false the message is dead-lettered if a dead-letter exchange is configured, otherwise discarded. Kafka and Redis have no negative ack in the classic protocol: you do not commit or do not XACK. Redis 8.8 added XNACK (modes SILENT, FAIL, FATAL). Laravel's equivalents are release() and fail().

text
    consumer                         RabbitMQ (quorum queue, delivery-limit 20)
1   delivery 7 (x-delivery-count absent)
2   basic.reject(7, requeue=true)    -> delivery-count 1, message back in the queue
3   delivery 7 again (redelivered=true, x-delivery-count=1)
    ... 19 more rejects ...
22  limit exceeded                   -> dead-lettered (if a DLX is configured) or dropped

Real scenario: a downstream API returns 503 for 30 s (transient: requeue with delay); an order references a customer that was deleted (permanent: reject without requeue); a deserialization error on a message from a newer producer (permanent: park it).

Product"Retry""Never"Poison protection built in
RabbitMQ classic queuenack/reject with requeue=truereject with requeue=falseNone: you track redelivered yourself, but it is only a boolean
RabbitMQ quorum queuesamesamedelivery-limit (default 20 since 4.0, -1 disables it) and the x-delivery-count header; basic.reject counts, basic.nack does not
Kafkado not commit, retry in place or republish to a retry topicpublish to a dead-letter topic, then commitNone (share groups count delivery attempts)
Redis Streamsleave in the PEL; XNACK ... FAIL (8.8+)copy to a dead-letter stream, XACKThe delivery counter in XPENDING; XNACK ... FATAL sets it to the maximum
Laravelrelease($delay), exceptionfail($e)Tries, MaxExceptions, failed_jobs
NATS JetStreamnak or no ack until AckWait (redelivery)reach MaxDeliverMaxDeliver (default -1: no limit)

Fix: pick basic.reject with requeue=true when you want the quorum-queue delivery limit to count the attempt. The RabbitMQ docs say it directly: "Applications that rely on the delivery limit to dead-letter messages that repeatedly fail processing should use basic.reject with the requeue flag set to true." From RabbitMQ 4.3 on, a basic.nack requeue no longer counts, so a consumer that nack-requeues a poison message can loop for ever. What to do with the message afterwards is the subject of the dead-letter queue page and the delay schedule that of retry & backoff.

Multiple acks and batch acks Important ​

In plain words: instead of one ack per message you send one ack that covers a run of messages, to save network frames.

Common misunderstanding: "multiple=true acks only this tag." It acks this tag and every outstanding tag below it on the same channel, including ones you have not finished or have not even looked at.

Definition: multiple=true acknowledges "all outstanding delivery tags up to and including the tag specified". Kafka's commit of offset N+1 is the same idea, built in: it acknowledges everything before it. XACK key group id [id ...] takes many ids but each is independent and the call returns the number actually removed from the PEL.

Queuetags 9, 10 ... waitchannel: unacked window, prefetch = 45678Consumerhandles 5, 6, 7, 8basic.ack(delivery_tag=8, multiple=true)tags 5, 6, 7, 8 acknowledged in one framewindow full: nomore deliverieswindow opens: 9..12 are pushedtags are per channel: an ack sent on another channelcloses it with PRECONDITION_FAILED (unknown delivery tag)
text
    channel Ch, prefetch 4                          broker
1   deliveries 5, 6, 7, 8 unacked                   window full: nothing more is pushed
2   handle 5 ok, 6 FAILS, 7 ok, 8 ok
3   WRONG: basic.ack(8, multiple=true)              acks 5, 6, 7, 8  -> 6 is silently lost
3'  RIGHT: basic.ack(5, false); basic.reject(6)     then ack 7 and 8 (multiple=true on 8 is safe now)
4   window reopens, deliveries 9..12 pushed

Real scenario: a bulk indexer handling 500 documents per round trip acks once per batch; an ETL consumer commits the last offset of each processed batch of 500 records; a Redis consumer acks 200 ids per call after a batch insert. Trade-off: a crash loses the ack for the whole unacked batch, so the redelivered duplicates are as many as the batch size.

ProductBatch ackRule to stay correct
RabbitMQbasic.ack and basic.nack with multiple=true (not basic.reject)Settle failures first, then ack with multiple; tags are per channel
KafkaCommitRecords(lastRecord) / commitSync with the next offsetCommit in order per partition; committing an older offset rewinds the group
Redis StreamsXACK key group id1 id2 ...Only list ids that succeeded; failed ids stay pending
Laravelnone: one job per handle(); for bulk work use job batches (see durable workflows)Make the batch itself one job

Fix: the RabbitMQ batcher above is ConsumeBatched in the timing snippet (shown earlier); the Kafka batch is CommitAfterProcess; the Redis batch is AckBatch.

The in-flight window: prefetch, QoS, max.poll.records, COUNT Must-know ​

In plain words: how many messages a consumer may hold that nobody has acknowledged yet. It is your memory use, your fairness between workers and the amount that is redelivered when you die.

Common misunderstanding: "A bigger prefetch is always faster." Throughput flattens: RabbitMQ says "values in the 100 through 300 range usually offer optimal throughput" and "a prefetch of 2,000 won't be meaningfully different from that of 300". A large window also starves other consumers and makes a crash expensive.

Definition: RabbitMQ basic.qos(prefetch_count) caps unacked deliveries; 0 means no limit. RabbitMQ deviates from the AMQP text: the AMQP spec says the count is shared across all consumers on a channel, RabbitMQ "applied separately to each new consumer on the channel", and the older per-channel (global) form is deprecated and disabled by default starting with RabbitMQ 4.3. Kafka bounds a poll with max.poll.records (default 500). Redis bounds a read with COUNT on XREADGROUP (the PEL itself is unbounded). Quorum queues cap an "unlimited" prefetch at 2,000.

text
    prefetch=1 (fair, slow)                  prefetch=100 (fast, unfair, big redelivery on crash)
1   worker A gets m1, worker B gets m2       worker A gets m1..m100 before B connects
2   A takes 10 s, B takes 1 s                B gets nothing for as long as A holds 100 unacked
3   m3 goes to B (A still busy)              A crashes: 100 messages are requeued, all redelivered=true

Real scenario: a mixed workload (image resize 10 ms, video transcode 5 min) on one queue needs prefetch 1 for the slow consumers; a pure fast consumer at 3,000 msg/s needs 100 to 300; a Kafka consumer that processes slowly lowers max.poll.records so one poll finishes inside max.poll.interval.ms.

KnobProductDefaultScope
basic.qos(prefetch_count)RabbitMQ0 (no limit) unless default_consumer_prefetch is configuredper consumer in RabbitMQ; per channel with the deprecated global flag
rabbit.default_consumer_prefetchRabbitMQ (advanced.config)noneapplied when a consumer sets no prefetch
basic.getRabbitMQ pull APIn/aprefetch "has no effect" on it
max.poll.recordsKafka consumer500per poll() call
PollRecords(ctx, n)franz-gon/aper call (no max.poll.records option; you choose n)
COUNTRedis XREADGROUPoptional; set itper read
MAXCOUNT, MAXSIZERedis 8.10+nonecumulative cap across streams
--prefetch-countlaravel-queue-rabbitmq rabbitmq:consume1000per consumer

Fix: start at prefetch 1 for slow or variable work, 100 to 300 for fast work, and measure. The flow-control side (consumer lag, load shedding, producer limits) is owned by Backpressure & Flow Control.

Kafka offsets: committed offset vs position Must-know ​

In plain words: Kafka does not remember which messages you finished, only one number per partition: where to resume.

Common misunderstanding: "Not committing a failed record makes Kafka redeliver it." Only if nothing later in the same partition is committed. Offsets are per partition; committing any later record moves past the failed one, and it is lost unless you parked it. The laravel-kafka docs say the same: "Not committing a failed message is not enough to consume it again."

Definition: position is the offset of the next record poll() will return (an in-memory value of the consumer). Committed offset is what the group stored in Kafka for the partition, the position a new owner starts from; "the committed offset should always be the offset of the next message that your application will read", so after handling record 9 you commit 10. auto.offset.reset applies only when no committed offset exists.

0510141520consumed and committedpolled, not yet committednot yet readcommitted offset = 10(next record to read after a restart)position = 15(next record poll() returns)log endcommit ran ahead of the workcommit 15 while handler is at 12:records 12..14 are lost on a crashcrash after handling, before commitrestart at 10: records 10..14 aredelivered again (at-least-once)Kafka stores one integer per partition and group; there is no per-record ack, so record 11 cannot be acknowledged while 10 is not.
text
    partition p0, group billing                  committed   position
1   poll() returns 10..14 (500 max)              10          15
2   handler finishes 10..12, dies on 13          10          15      (in memory, lost with the process)
3   restart: group resumes from committed        10          10
4   records 10..14 are delivered again           (11 and 12 were handled twice)

Real scenario: an invoicing consumer that does the HTTP call for 10..12 and crashes on 13 re-sends invoices 10..12 after restart unless the handler is idempotent. A consumer with auto-commit that hands records to goroutines and polls again commits offsets it has not finished (committed offset "ahead of the consumed position"), and a crash then loses records.

QuestionJava consumer / librdkafkafranz-go
Auto-commit defaultenable.auto.commit=true, every 5000 mson, every 5 s (AutoCommitInterval)
What auto-commit commitsthe offsets of the last poll when the next poll or close is called; safe only if you finish a poll's records firstrecords from earlier polls (non-"dirty"); GreedyAutoCommit commits the current poll
Manual commitcommitSync(), commitSync(offsets), commitAsync()DisableAutoCommit() then CommitRecords, CommitUncommittedOffsets
Halfway modenoneAutoCommitMarks() + MarkCommitRecords + CommitMarkedOffsets
Commit on rebalanceConsumerRebalanceListener.onPartitionsRevokedOnPartitionsRevoked (the default does a blocking commit when autocommit is on)
Rewind by committing an old offsetpossibleCommitRecords "will rewind your commit" if you go backwards
laravel-kafkawithManualCommit(); $consumer->commit($message), commitAsync($message)n/a

Fix: disable auto-commit for anything with side effects, use commit-after-process (commit the next offset after the work), commit per partition in order, and commit in the revoke callback. The Go code is kafka_after in the Go section and CommitAfterProcess above; the Laravel command is in the Laravel section. The alternative to a committed offset in Kafka is storing the offset in your own database inside the business transaction, which is how exactly-once into a SQL sink is done; the transactional producer variant is in Delivery Guarantees.

Redis Streams: PEL, XPENDING, XCLAIM, XAUTOCLAIM, XNACK Must-know ​

In plain words: a consumer group keeps a "to-do and being-worked-on" list. An entry you read and have not acknowledged is on that list under your name, and stays there until somebody acks it or takes it over.

Common misunderstanding: "If my consumer dies, another one gets the message." Only if you write the code that claims it. The docs are explicit: "A consumer has to inspect the list of pending messages, and will have to claim specific messages using a special command, otherwise the server will leave the messages pending forever and assigned to the old consumer."

Definition: the PEL (pending entries list) holds, per group, every delivered-but-unacked entry with its owner, last-delivery time (idle) and delivery counter. XREADGROUP ... > delivers never-delivered entries and adds them; reading with id 0 returns this consumer's own pending history. XACK removes ids. XPENDING inspects (summary, or per entry, with an IDLE filter). XCLAIM and XAUTOCLAIM transfer ownership of entries idle longer than min-idle-time, reset the idle time and increment the delivery counter (unless JUSTID). XNACK (Redis 8.8) releases entries back so they are "immediately available for re-delivery to other consumers".

Streamentries by idPEL of group billing1700-0 owner A idle 2 s n=11700-1 owner A idle 9 min n=1Consumer Ahandles, then XACKConsumer B (reaper)XAUTOCLAIM min-idle 5 minowner becomes B, idle reset, n=2Dead-letter streamn at the limit: XACKand park the entryReleasedXNACK (Redis 8.8+)back to the group now1 XREADGROUP >2 deliver3 XACK idremoves it from the PELA crashed: nothing redelivers by itself4 idle time keeps growing in XPENDING
text
    consumer A                         PEL of group billing                      consumer B
1   XREADGROUP > COUNT 1               1700-0 owner A idle 0 n=1
2   handler running ...
3   kill -9                            1700-0 owner A idle 9 min n=1             (nothing happens by itself)
4                                                                                XAUTOCLAIM orders billing B 300000 0-0
5                                      1700-0 owner B idle 0 n=2                 handle, then XACK
6                                      (empty)

Real scenario: an order stream with three workers; a deploy kills one mid-entry; the reaper in the survivors claims the entry five minutes later. A poison entry that crashes every worker shows up as n climbing in XPENDING, which is the signal to park it. The XAUTOCLAIM reference says it: messages that cannot be processed, "for example, because consumers systematically crash when processing them", "will exhibit high attempted delivery counts that can be detected by monitoring".

CommandPurposeNotes
XREADGROUP GROUP g c STREAMS s >read new entries, add to the PELNOACK skips the PEL
XREADGROUP ... STREAMS s 0replay this consumer's own pending historyhow a restarted consumer resumes
XREADGROUP ... CLAIM min-idle-timeclaim idle pending entries while reading (Redis 8.4+)folds the reaper into the read
XACK s g id [id ...]remove ids from the PELreturns the count really removed
XPENDING s gsummary: count, smallest id, greatest id, per consumerread-only
XPENDING s g [IDLE ms] start end count [consumer]one row per entry: id, owner, idle ms, deliveriesfind stuck entries
XCLAIM s g c min-idle id ... [JUSTID] [RETRYCOUNT n]take specific idsJUSTID does not bump the counter
XAUTOCLAIM s g c min-idle start [COUNT n] [JUSTID]scan the PEL and claim, cursor stylereturns next cursor; 0-0 means done; default count 100; scans at most ten times COUNT entries per call
XNACK s g SILENT|FAIL|FATAL IDS n id ...release entries without acking (Redis 8.8+)SILENT undoes the counter increment, FAIL keeps it, FATAL sets it to the maximum
XINFO CONSUMERS s gper consumer: pending, idle, inactivefind dead consumers
XACKDELack and delete in one atomic step (Redis 8.2+)for single-group streams

Fix: a reaper loop around XAUTOCLAIM, or XREADGROUP ... CLAIM on 8.4+, plus a delivery-count check that parks poison entries. The Go consumer and reaper is redis_after in the Go section; the PHP version is StreamConsumerCommand in the Laravel section. The poison policy (what counts as "too many") is owned by Dead-Letter Queue.

Consumer timeouts: how the system notices you are gone Must-know ​

In plain words: redelivery needs a failure detector. Something must decide "this consumer is dead or stuck, give its messages to someone else", and each system uses a different clock.

Common misunderstanding: "Redelivery happens the moment the consumer dies." It happens when the detector fires: a TCP close and channel shutdown (fast), a missed heartbeat (seconds), a session timeout (tens of seconds), consumer_timeout (30 minutes), retry_after (90 seconds by default in Laravel's sample config). Until then the message sits unacked and nobody else sees it.

Definition: the clocks, per product.

  • RabbitMQ: a closed channel or connection requeues its unacked messages at once, but "it takes a period of time to detect an unavailable client" (heartbeats). Separately, a delivery acknowledgement timeout (consumer_timeout, default 30 minutes, in milliseconds in rabbitmq.conf) limits how long a consumer may hold an unacked delivery. In the 4.0 docs: if a consumer does not ack within the timeout "its channel is closed with a PRECONDITION_FAILED channel exception" and all following deliveries on that channel, from all consumers, are requeued; the check runs about once a minute and values under five minutes are not recommended. From RabbitMQ 4.3 the timeout is supported only by quorum queues and, for AMQP 0-9-1, the consumer is cancelled (when the client supports consumer cancel notifications) instead of the channel being closed. Per-queue overrides exist: policy key consumer-timeout and queue argument x-consumer-timeout (since 3.12).
  • Kafka: three separate clocks. session.timeout.ms (default 45000) with heartbeat.interval.ms (default 3000) detects a dead process: no heartbeat, the broker removes the member and rebalances. max.poll.interval.ms (default 300000) detects a live but stuck process, "if poll() is not called before expiration of this timeout, then the consumer is considered failed and the group will rebalance", and an offset commit after that fails with CommitFailedException. The new consumer group protocol (group.protocol=consumer) moves the session timeout to the broker (group.consumer.session.timeout.ms). franz-go has no max.poll.interval.ms option: heartbeats run in the background, so a hung handler is not detected by poll cadence; the risks there are RebalanceTimeout (default 60 s) while a rebalance waits for you, which BlockRebalanceOnPoll makes real.
  • Redis Streams: nothing detects it. Idle time is only a number you read in XPENDING and filter with min-idle-time; the reaper you write is the detector.
  • Laravel: retry_after on the connection (reserved job returns after N seconds), and --timeout (worker kills a run, default 60 s, needs PCNTL). The rule: "your --timeout value should always be at least several seconds shorter than your retry_after".
text
    time     consumer A (RabbitMQ 4.0 classic queue, consumer_timeout 30 min)      broker
0:00     delivery 12 received, handler hangs on a socket                            12 unacked
0:30     (still hung)                                                               check at ~1 min intervals: 30 min elapsed
0:31     channel closed: PRECONDITION_FAILED ... timed out waiting for a            12 and every other unacked delivery on
         consumer acknowledgement of a delivery with delivery tag = 12              the channel requeued, redelivered=true

Real scenario: a report job that legitimately takes 40 minutes on a 30-minute consumer_timeout is closed and redelivered repeatedly: raise the timeout for that queue. A Kafka consumer that calls an external API for 6 minutes per batch with max.poll.interval.ms=300000 gets kicked out and every commit fails: lower max.poll.records or move the work to a worker pool. A Laravel job that runs 100 s with retry_after=90 is picked up by a second worker while the first still runs it.

ProductDetects a dead processDetects a stuck processRedelivery triggerDefault
RabbitMQchannel/connection close, heartbeatconsumer_timeoutrequeue of all unacked deliveries30 min
Kafka (Java)session.timeout.msmax.poll.interval.msrebalance, resume from the committed offset45 s / 5 min
Kafka (franz-go)SessionTimeoutnone by poll cadencerebalance45 s
Redis Streamsnone built innone built inyour XAUTOCLAIM with min-idle-timen/a
Laravelretry_after--timeout kills it, then retry_afterjob returns to the queue90 s / 60 s
NATS JetStreamAckWaitAckWaitredelivery, up to MaxDeliversee NATS docs
SQSvisibility timeoutvisibility timeoutmessage visible again30 s (min 0, max 12 h)

Fix: set the stuck-detector above your slowest legitimate run and set the work timeout below the detector. Rebalance protocols and static membership (group.instance.id) are owned by Competing Consumers & Scaling.

Redelivery and the redelivered flag Important ​

In plain words: a message that has been handed out before comes with a "second time" mark, so your handler can be more careful.

Common misunderstanding: "redelivered=true tells me how often, or whether the earlier attempt finished." It tells you neither. It is a boolean, not a counter, and a consumer cannot tell a message that died before the side effect from one that died after it. The docs also warn that "a consumer can receive a message that was previously delivered to another consumer".

Definition: RabbitMQ sets the AMQP redelivered property (Go: Delivery.Redelivered) on deliveries that were requeued; quorum queues add the x-delivery-count header and x-acquired-count (4.3+). Kafka has no flag: you detect duplicates yourself by (topic, partition, offset) or a business key; the offset you read is always the same on a replay. Redis exposes a counter in XPENDING (and XREADGROUP with id 0 returns your own history), but not a flag in the entry. Laravel's $this->attempts() counts deliveries.

text
    attempt   what the broker sends                               what the handler should do
1         redelivered=false                                       normal path
2         redelivered=true                                        check the dedup row; process only if absent
3..       redelivered=true, x-delivery-count=2 (quorum queue)     still check; log it; the delivery limit dead-letters at 20

Real scenario: an email consumer uses redelivered=true to look up "was this message id already sent" in its log table before sending; a payments consumer treats every delivery as possibly repeated and relies on the inbox table instead of the flag.

ProductSignalCounterWhere to read it
RabbitMQ classicredelivered booleannoneDelivery.Redelivered
RabbitMQ quorumredelivered booleanx-delivery-count, x-acquired-count headermessage headers
Kafkanonenone (offsets are stable; share groups count attempts)the record
Redis Streamsnonedelivery counter in the PELXPENDING extended form
Laravelnoneattempts()the job

Fix: treat the flag as a hint for logging and caution, not as the dedup mechanism; use the inbox pattern.

Stuck unacked messages: diagnostics per broker Important ​

In plain words: a message is "stuck" when it is not being processed and not available to anyone else. The questions are always the same: who holds it, since when, and how many times has it been delivered.

Common misunderstanding: "An unacked message in the UI means a consumer is working on it." It may be held by a dead consumer, a consumer blocked on a downstream, a consumer with prefetch 1000 that is on message 3, or a consumer whose channel leaked.

Definition and commands:

QuestionRabbitMQKafkaRedis StreamsLaravel
How many are in flight?messages_unacknowledged (management UI, rabbitmqctl list_queues name messages_ready messages_unacknowledged consumers)consumer lag: kafka-consumer-groups.sh --describe --group g (CURRENT-OFFSET, LOG-END-OFFSET, LAG)XPENDING s g (count)ZCARD queues:<q>:reserved (redis driver); the database driver is covered in Laravel Queue Internals
Who holds them?rabbitmqctl list_channels (per channel prefetch_count), management UI consumers tabthe CONSUMER-ID column of the --describe outputXPENDING s g - + 100 (owner) and XINFO CONSUMERS s gworker process list, Horizon
For how long?consumer timeout log line on the nodecommit age: compare committed offset movement over timeidle ms in XPENDING extended formthe job's score in queues:<q>:reserved (redis driver) and its attempts
How many times?x-delivery-count (quorum), redeliverednot trackeddelivery counter in XPENDINGattempts column / $this->attempts()
Release itclose the consumer's channel or connection; basic.nackrestart the member or trigger a rebalanceXAUTOCLAIM, XCLAIM, XNACK (8.8+)wait for retry_after; queue:retry for failed jobs
text
$ redis-cli XPENDING orders billing
1) (integer) 3                  # count
2) "1700-0"                     # smallest id
3) "1700-2"                     # greatest id
4) 1) 1) "worker-1"             # owners
      2) "3"
$ redis-cli XPENDING orders billing IDLE 60000 - + 10
1) 1) "1700-0"
   2) "worker-1"
   3) (integer) 543112          # idle ms
   4) (integer) 1               # deliveries

The two Go helpers that print the same answers programmatically are Report for Redis and Report for Kafka lag:

go
// Package redisdiag answers "which entries are stuck, with whom, for how long,
// and how many times were they delivered" for a consumer group.
package redisdiag

import (
	"context"
	"fmt"
	"time"

	"github.com/redis/go-redis/v9"
)

// Report prints the group-level summary, per-consumer counters and the
// entries idle for more than stuckAfter, with their delivery counters.
func Report(ctx context.Context, rdb *redis.Client, stream, group string, stuckAfter time.Duration, maxDeliveries int64) error {
	// XPENDING key group: count, smallest id, greatest id, pending per consumer.
	sum, err := rdb.XPending(ctx, stream, group).Result()
	if err != nil {
		return err
	}
	fmt.Printf("pending=%d range=%s..%s per-consumer=%v\n", sum.Count, sum.Lower, sum.Higher, sum.Consumers)

	// XINFO CONSUMERS: per consumer, pending count plus idle and inactive durations.
	cons, err := rdb.XInfoConsumers(ctx, stream, group).Result()
	if err != nil {
		return err
	}
	for _, c := range cons {
		fmt.Printf("consumer=%s pending=%d idle=%s inactive=%s\n", c.Name, c.Pending, c.Idle, c.Inactive)
	}

	// XPENDING key group IDLE ms - + count: one row per stuck entry.
	rows, err := rdb.XPendingExt(ctx, &redis.XPendingExtArgs{
		Stream: stream, Group: group, Idle: stuckAfter, Start: "-", End: "+", Count: 100,
	}).Result()
	if err != nil {
		return err
	}
	for _, r := range rows {
		verdict := "retry"
		if r.RetryCount >= maxDeliveries {
			verdict = "POISON: park it (see the dead-letter queue page)"
		}
		fmt.Printf("id=%s owner=%s idle=%s deliveries=%d %s\n", r.ID, r.Consumer, r.Idle, r.RetryCount, verdict)
	}
	return nil
}
go
// Package kafkalag reads committed offsets and the log end for a group, which
// is the Kafka answer to "how much is unacknowledged".
package kafkalag

import (
	"context"
	"fmt"

	"github.com/twmb/franz-go/pkg/kadm"
	"github.com/twmb/franz-go/pkg/kgo"
)

// Report prints CURRENT-OFFSET, LOG-END-OFFSET and LAG per partition, the same
// columns as `kafka-consumer-groups.sh --describe --group <group>`.
func Report(ctx context.Context, cl *kgo.Client, group string) error {
	lags, err := kadm.NewClient(cl).Lag(ctx, group)
	if err != nil {
		return err
	}
	for _, g := range lags {
		if err := g.Error(); err != nil {
			return err
		}
		fmt.Printf("group=%s state=%s\n", g.Group, g.State)
		for _, p := range g.Lag.Sorted() {
			fmt.Printf("%s %d committed=%d end=%d lag=%d\n",
				p.Topic, p.Partition, p.Commit.At, p.End.Offset, p.Lag)
		}
	}
	return nil
}

Real scenario: the queue graph shows 5,000 unacked and a flat consumption rate: one consumer with prefetch 5,000 is stuck on a hung HTTP call; closing its channel requeues all 5,000 at once. A Redis stream's PEL grows by 200 an hour: the reaper is not running. A Kafka group's lag grows on one partition only: the consumer of that partition is stuck on a poison record that is retried in place.

Fix: alert on three numbers per queue or group: unacked/pending count, oldest idle time (or commit age), and maximum delivery count. The metrics endpoints and dashboards are owned by Messaging Observability.

Laravel queue outcomes: release, delete, fail, --timeout, block_for Must-know ​

In plain words: in Laravel the ack is implicit: when handle() returns, the job is done and gets deleted. Everything else is an exception or one of three methods.

Common misunderstanding: "I caught the exception and logged it, so the job will be retried." Catching it makes handle() return normally, so the worker deletes the job: a success, no retry, no failed_jobs row, no failed() call.

Definition: handle() returns, the worker deletes (ack). An uncaught exception releases it "so it may be attempted again", until the attempts run out, then it is a failed job. $this->release($delay) puts it back for later and still counts as an attempt. $this->delete() removes it without running more attempts; it does not stop a job chain, only a failure does. $this->fail($e) marks it failed at once (the negative ack). The default is blunt: "By default, Laravel will only attempt a job once".

text
    worker                                   redis queue (driver internals)
1   pop: job moved to queues:default:reserved with score = now + retry_after, attempts+1
2   handle() runs ...
3a  returns                  -> delete()  -> ZREM from reserved                     (ack)
3b  release(30)              -> ZREM from reserved + ZADD to queues:default:delayed (retry later)
3c  throws, attempts left    -> release(backoff)                                    (retry)
3d  throws, attempts spent   -> failJob -> failed_jobs                              (negative ack)
3e  worker killed            -> nothing happens until the score (now + retry_after) passes,
                                then migrateExpiredJobs moves it back to queues:default

Real scenario: a 503 from the invoice API becomes release(30); a malformed order becomes fail($e); a reminder for an order that was paid in the meantime becomes delete().

ConcernSettingDefaultSource of truth
Time before a reserved job is retriedretry_after on the connection90 in the sample redis config; SQS uses the queue's Default Visibility Timeoutconfig/queue.php
Time a run may take--timeout or #[Timeout(n)]60 sworker, needs PCNTL
Fail on timeout instead of retrying#[FailOnTimeout]offjob class
Attempts--tries or #[Tries(n)]1worker or job
Exceptions before failing#[MaxExceptions(n)]nonejob class
Delay between attempts#[Backoff([10, 30, 60])] or releaseUsingBackoff()0job class
Block instead of polling (redis)block_fornull (poll)config/queue.php; 0 blocks for ever and delays SIGTERM

Fix: keep --timeout several seconds below retry_after; give jobs Tries and Backoff; use release, delete and fail deliberately. The Laravel code is in the Laravel section. The internals of the redis and database drivers are in Laravel Queue Internals.

Mechanics ​

Knobs and defaults Important ​

KnobProductDefaultEffect on acknowledgment
autoAck / no-ackRabbitMQper client calltrue means ack on send
prefetch_countRabbitMQ0 (no limit)caps unacked deliveries
consumer_timeoutRabbitMQ rabbitmq.conf1800000 msmax time to hold an unacked delivery
delivery-limitRabbitMQ quorum queue policy20 (4.0+)dead-letter or drop after N failed deliveries
enable.auto.commitKafka consumertruebackground commit
auto.commit.interval.msKafka consumer5000autocommit cadence
max.poll.recordsKafka consumer500records per poll
max.poll.interval.msKafka consumer300000max gap between polls
session.timeout.msKafka consumer (classic protocol)45000dead-member detection
heartbeat.interval.msKafka consumer (classic protocol)3000heartbeat cadence, at most a third of the session timeout
auto.offset.resetKafka consumerlateststart when there is no committed offset
isolation.levelKafka consumerread_uncommittedread_committed hides aborted transactional records
group.instance.idKafka consumerunsetstatic membership; a timed-out static member is reassigned only after the session timeout
COUNT, BLOCK, NOACK, CLAIMRedis XREADGROUPnoneread size, wait, skip the PEL, claim while reading
min-idle-timeRedis XCLAIM/XAUTOCLAIMrequiredwhich pending entries may be taken
retry_after, block_forLaravel connection90, nullreserved-job return time, blocking pop
--timeout, --tries, --backoffqueue:work60, 1, released immediatelyrun limit, attempts, delay

Error messages and exceptions you will catch Important ​

WhereMessage or classMeaningWhat to do
RabbitMQPRECONDITION_FAILED - unknown delivery tag 100you acked the same tag twice, an unknown tag, or acked on another channelack once, on the channel that received it
RabbitMQPRECONDITION_FAILED with "timed out waiting for a consumer acknowledgement of a delivery with delivery tag = N"consumer_timeout firedspeed up, raise the timeout for the queue, or ack earlier
RabbitMQchannel closed, deliveries requeuedchannel or connection diedredelivery with redelivered=true; be idempotent
KafkaCommitFailedExceptionthe member left the group (missed max.poll.interval.ms) before committingshorten work per poll; accept the redelivery
Kafkarebalance, partitions revokedanother member now owns the partitioncommit finished work in the revoke callback
RedisNOGROUPthe stream or group does not existXGROUP CREATE ... MKSTREAM
RedisXACK returns 0the id was not pending (already acked, or never delivered to the group)harmless; check for double processing
LaravelIlluminate\Queue\MaxAttemptsExceededExceptionattempts exhausted (often because of repeated timeouts)raise Tries, fix the cause
LaravelIlluminate\Queue\TimeoutExceededExceptionrun exceeded --timeout / #[Timeout]shorten work; keep retry_after above it

Atomicity: why the ack is not part of your transaction Must-know ​

The ack is a network call to the broker; your side effect is a commit to a database. There is no transaction that spans both, which is the same atomicity question as the outbox pattern seen from the consuming side. The ack therefore lands before the commit (loss window), after it (duplicate window), or never (the connection dropped). An ack that fails to reach the broker produces a duplicate even in a perfect handler. See ACID & Transactions for what the commit itself guarantees and Durability & Crash Recovery for what survives a crash.

Solving the classic problems ​

1. A crash loses messages Must-know ​

SolutionHowAdvantageCost
Manual ack after the workautoAck=false, DisableAutoCommit, XACK after the handlerNo loss on a crashDuplicates after a crash
Replace greedy autocommitfranz-go default, or AutoCommitMarksOnly finished work is committedA little code
Commit in the revoke callbackOnPartitionsRevokedLess rework at a rebalanceA blocking commit during the rebalance

The "before" code shows the three shortcuts; the "after" code is in the Go and Laravel sections.

2. A crash repeats the work Must-know ​

SolutionHowAdvantageCost
Idempotent handlerupsert, natural key, ON CONFLICT DO NOTHINGSimplestOnly for operations that can be made idempotent
Inbox table in the same transactionthe AckAfterSideEffects snippetsWorks for any side effect in your own databaseOne table, one insert per message
Idempotency key to the downstream APIpass the message idCovers external effectsThe API must support it

3. A poison message loops forever Must-know ​

SolutionHowAdvantageCost
Reject without requeue after the first redeliveryd.Redelivered check, basic.reject(false)Stops the hot loopA transient error on the second try also dead-letters
Quorum queue delivery limitdelivery-limit plus basic.reject(requeue=true)Broker counts for youMust use reject, not nack (4.3+)
Delivery counter checkXPENDING count versus a limit, then parkWorks on RedisYou write the reaper
Retry topic and dead-letter topicpublish the record, then commitKeeps the partition movingMore topics
Tries, MaxExceptions, fail()Laravel attributesBuilt inNone

The dead-letter semantics (what the parking lot looks like, x-death, failed_jobs, queue:retry) are owned by Dead-Letter Queue; the delays between attempts by Retry, Backoff & Delayed Delivery.

4. A slow handler is declared dead Important ​

SolutionHowAdvantageCost
Raise the detectorconsumer_timeout per queue; max.poll.interval.ms; retry_afterFits legitimate long workA real hang is detected later
Shrink the unit of worklower max.poll.records, prefetch 1Each unit fits inside the detectorLower throughput per round trip
Hand work to a pool and ack from the poolworker pool, then MarkCommitRecords or d.Ack on the owning channelPoll or heartbeat is never blockedOrdering and ack-on-the-right-goroutine care
Split into stepsdurable workflowNo single long deliveryMore moving parts

5. A rebalance or deploy causes a burst of duplicates Important ​

Stop taking new work, finish or give back what is in flight, then close: ctx cancellation, wait for handlers, commit marks (Kafka), ack or XNACK (Redis, 8.8+), close the channel (RabbitMQ). A group rebalance can hand your partition to another member while you are still working; franz-go's DisableAutoCommit documentation spells out the double processing and the rewind risk when you commit after losing a partition.

Retry and failure handling ​

FailureRetry?Ack decision
Timeout, 5xx, deadlock, connection lostYes, with delayRabbitMQ reject(requeue=true) or delayed queue; Redis leave pending; Laravel release($delay) or exception
Validation error, missing entity, unknown schemaNoRabbitMQ reject(requeue=false); Kafka dead-letter topic then commit; Redis dead-letter stream then XACK; Laravel fail()
Handler panic or OOMYes (the process is gone)no ack was sent: the broker redelivers; the delivery count rises
The ack call itself failsTreat as success of the workthe broker redelivers; the next run must be idempotent

Rules: ack on the goroutine and channel that owns the delivery; never ack twice; never ack before a failure you can still recover from; count deliveries, do not trust a boolean; make shutdown wait for in-flight handlers.

Choosing ​

WorkloadAck timingWindowExtra techniqueReason
Payments, ledger entries, stockAfter side effectsSmall (prefetch 1 to 10, one poll of tens of records)Inbox table, per-key orderingOne duplicate or one loss costs money
Emails, notificationsAfter process10 to 50Idempotency key per recipientA duplicate email is tolerable, a lost one is not
Metrics, logs, cache warm-upBefore process or autoLargeNoneLoss is cheaper than the round trips
Mixed fast and slow jobs on one queueAfter processPrefetch 1 for slow consumersSeparate queues per class of workFairness
High-throughput event pipelineAfter process, batched100 to 300 (RabbitMQ), 500 (Kafka poll)Commit per batch, AutoCommitMarksFewer ack round trips
Long-running work (minutes)After process, with a raised timeout1Raise consumer_timeout or split into stepsThe default detector is shorter than the work
Laravel app with the redis driverDefault (return from handle)--tries, Backoffretry_after above --timeoutThe defaults are single-attempt
BrokerPick this ack styleBecause
RabbitMQManual ack, prefetch 100 to 300, reject(false) plus DLX for permanent failuresPer-message control and the broker deletes on ack
KafkaManual commit after processing, per partition, AutoCommitMarks for throughputOne position per partition; a share group when you need per-record ack
Redis StreamsXACK after processing plus a reaperNo built-in redelivery

Go ​

Before ​

Every broker has an "ack on receipt" shortcut. RabbitMQ: autoAck=true and no prefetch.

go
// Package rabbitbefore consumes with autoAck=true: RabbitMQ treats a message
// as handled the moment it is written to the socket.
package rabbitbefore

import (
	"context"
	"log"

	amqp "github.com/rabbitmq/amqp091-go"
)

func Consume(ctx context.Context, conn *amqp.Connection, handle func([]byte) error) error {
	ch, err := conn.Channel()
	if err != nil {
		return err
	}
	defer ch.Close()

	// autoAck=true: the broker forgets the message as soon as it is sent.
	// No prefetch is set either, so the broker pushes as fast as it can.
	deliveries, err := ch.Consume("orders", "", true, false, false, false, nil)
	if err != nil {
		return err
	}

	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		case d, ok := <-deliveries:
			if !ok {
				return nil
			}
			// If this fails, or the process dies mid-handler, the message is gone.
			if err := handle(d.Body); err != nil {
				log.Printf("dropped message: %v", err)
			}
		}
	}
}

Kafka (franz-go): GreedyAutoCommit commits everything polled, on a timer, whatever the handler has done.

go
// Package kafkabefore commits offsets greedily, before the work is done.
package kafkabefore

import (
	"context"
	"log"

	"github.com/twmb/franz-go/pkg/kgo"
)

func Run(ctx context.Context, brokers []string, handle func(*kgo.Record) error) error {
	cl, err := kgo.NewClient(
		kgo.SeedBrokers(brokers...),
		kgo.ConsumerGroup("billing"),
		kgo.ConsumeTopics("orders"),
		// Commits everything that was polled, on a timer, whether or not the
		// handler has finished. A crash can skip records.
		kgo.GreedyAutoCommit(),
	)
	if err != nil {
		return err
	}
	defer cl.Close()

	for {
		fetches := cl.PollFetches(ctx)
		if fetches.IsClientClosed() || ctx.Err() != nil {
			return ctx.Err()
		}
		fetches.EachRecord(func(r *kgo.Record) {
			if err := handle(r); err != nil {
				// Logged and forgotten: the offset moves on regardless.
				log.Printf("lost %s/%d@%d: %v", r.Topic, r.Partition, r.Offset, err)
			}
		})
	}
}

Redis Streams: XREADGROUP ... NOACK, so entries never enter the pending list.

go
// Package redisbefore reads with NOACK: entries never enter the pending list.
package redisbefore

import (
	"context"
	"log"
	"time"

	"github.com/redis/go-redis/v9"
)

func Run(ctx context.Context, rdb *redis.Client, consumer string, handle func(redis.XMessage) error) error {
	for {
		streams, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
			Group:    "billing",
			Consumer: consumer,
			Streams:  []string{"orders", ">"},
			Count:    100,
			Block:    5 * time.Second,
			// NoAck: the entry is "acknowledged on read", so nothing tracks it.
			NoAck: true,
		}).Result()
		if err == redis.Nil {
			continue
		}
		if err != nil {
			return err
		}
		for _, s := range streams {
			for _, m := range s.Messages {
				if err := handle(m); err != nil {
					// Nothing to retry from: the entry is not in the PEL.
					log.Printf("lost %s: %v", m.ID, err)
				}
			}
		}
	}
}

After ​

RabbitMQ: manual acks after the work, a bounded prefetch, and a distinct path for permanent failure and for a message already marked Redelivered.

go
// Package rabbitafter acknowledges manually, after the work is done, behind a
// bounded prefetch window.
package rabbitafter

import (
	"context"
	"errors"
	"fmt"

	amqp "github.com/rabbitmq/amqp091-go"
)

// ErrPermanent marks a failure that retrying cannot fix.
var ErrPermanent = errors.New("permanent failure")

func Consume(ctx context.Context, conn *amqp.Connection, handle func([]byte) error) error {
	ch, err := conn.Channel()
	if err != nil {
		return err
	}
	defer ch.Close()

	// At most 50 unacknowledged deliveries on this consumer.
	if err := ch.Qos(50, 0, false); err != nil {
		return err
	}

	// autoAck=false: the message stays "unacked" until we say otherwise.
	deliveries, err := ch.Consume("orders", "", false, false, false, false, nil)
	if err != nil {
		return err
	}

	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		case d, ok := <-deliveries:
			if !ok {
				return fmt.Errorf("deliveries channel closed")
			}
			switch err := handle(d.Body); {
			case err == nil:
				// Ownership returns to the broker only now.
				if err := d.Ack(false); err != nil {
					return err
				}
			case errors.Is(err, ErrPermanent) || d.Redelivered:
				// Do not requeue: dead-letter it (if a DLX is set) or drop it.
				// A requeue of a message that already failed once risks a hot loop.
				if err := d.Reject(false); err != nil {
					return err
				}
			default:
				// Transient failure on the first attempt: give it back.
				if err := d.Nack(false, true); err != nil {
					return err
				}
			}
		}
	}
}

Kafka: DisableAutoCommit, handle a partition's batch in order, then CommitRecords for the last record handled.

go
// Package kafkaafter disables auto-commit and commits only what was handled.
package kafkaafter

import (
	"context"
	"fmt"

	"github.com/twmb/franz-go/pkg/kgo"
)

func Run(ctx context.Context, brokers []string, handle func(*kgo.Record) error) error {
	cl, err := kgo.NewClient(
		kgo.SeedBrokers(brokers...),
		kgo.ConsumerGroup("billing"),
		kgo.ConsumeTopics("orders"),
		kgo.DisableAutoCommit(),
	)
	if err != nil {
		return err
	}
	defer cl.Close()

	for {
		fetches := cl.PollFetches(ctx)
		if fetches.IsClientClosed() || ctx.Err() != nil {
			return ctx.Err()
		}
		if errs := fetches.Errors(); len(errs) > 0 {
			return fmt.Errorf("fetch: %w", errs[0].Err)
		}

		// Commit per partition batch, in order, after every record in it succeeded.
		var failed error
		fetches.EachPartition(func(p kgo.FetchTopicPartition) {
			if failed != nil || len(p.Records) == 0 {
				return
			}
			for _, r := range p.Records {
				if err := handle(r); err != nil {
					failed = fmt.Errorf("%s/%d@%d: %w", r.Topic, r.Partition, r.Offset, err)
					return
				}
			}
			// CommitRecords stores last offset + 1 for each partition it sees.
			last := p.Records[len(p.Records)-1]
			if err := cl.CommitRecords(ctx, last); err != nil {
				failed = err
			}
		})
		if failed != nil {
			// Stop: the uncommitted tail is redelivered after restart or rebalance.
			return failed
		}
	}
}

Redis Streams: XACK after the work, and a reaper built on XAutoClaim that adopts entries whose consumer stopped.

go
// Package redisafter acknowledges with XACK after the work and runs a reaper
// that takes over entries abandoned by crashed consumers.
package redisafter

import (
	"context"
	"log"
	"time"

	"github.com/redis/go-redis/v9"
)

const (
	stream = "orders"
	group  = "billing"
)

// Run reads new entries (">") and acknowledges each one after handling it.
func Run(ctx context.Context, rdb *redis.Client, consumer string, handle func(redis.XMessage) error) error {
	for {
		streams, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
			Group:    group,
			Consumer: consumer,
			Streams:  []string{stream, ">"},
			Count:    50,
			Block:    5 * time.Second,
		}).Result()
		if err == redis.Nil {
			continue
		}
		if err != nil {
			return err
		}
		for _, s := range streams {
			for _, m := range s.Messages {
				if err := handle(m); err != nil {
					// Leave it pending; the reaper will hand it out again.
					log.Printf("entry %s stays pending: %v", m.ID, err)
					continue
				}
				if err := rdb.XAck(ctx, stream, group, m.ID).Err(); err != nil {
					return err
				}
			}
		}
	}
}

// Reap claims entries that have sat unacknowledged for longer than minIdle,
// for example because their consumer crashed, and processes them here.
func Reap(ctx context.Context, rdb *redis.Client, consumer string, minIdle time.Duration, handle func(redis.XMessage) error) error {
	ticker := time.NewTicker(minIdle / 2)
	defer ticker.Stop()

	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-ticker.C:
		}

		start := "0-0"
		for {
			msgs, next, err := rdb.XAutoClaim(ctx, &redis.XAutoClaimArgs{
				Stream:   stream,
				Group:    group,
				Consumer: consumer,
				MinIdle:  minIdle,
				Start:    start,
				Count:    50,
			}).Result()
			if err != nil {
				return err
			}
			for _, m := range msgs {
				if err := handle(m); err != nil {
					continue // still pending, idle clock was reset by the claim
				}
				if err := rdb.XAck(ctx, stream, group, m.ID).Err(); err != nil {
					return err
				}
			}
			if next == "0-0" {
				break
			}
			start = next
		}
	}
}

The Go angle ​

None of the three clients hides acknowledgment, which suits Go: the ack is an ordinary method call at a visible point in your loop. In amqp091-go a Delivery carries Ack(multiple), Nack(multiple, requeue), Reject(requeue), Redelivered and DeliveryTag; Channel.Qos sets prefetch and Channel.Consume takes the autoAck flag. In franz-go the group options choose the policy: the default autocommit commits records from earlier polls, GreedyAutoCommit commits what was just polled ("may result in message loss if your application crashes", per its doc comment), AutoCommitMarks plus MarkCommitRecords lets you mark records as done and have them committed in the background, DisableAutoCommit leaves everything to CommitRecords, and BlockRebalanceOnPoll makes a poll and a rebalance exclusive until you call AllowRebalance. go-redis exposes XReadGroupArgs{NoAck, Claim}, XAck, XPendingExt, XAutoClaim, XInfoConsumers and, for Redis 8.8 or newer, XNack, as one-to-one wrappers. Four Go-specific habits matter: ack on the goroutine and channel that owns the delivery (RabbitMQ acks are per channel); never commit offsets out of order from concurrent workers (franz-go: "you will rewind your commit"); make shutdown wait for in-flight handlers before the connection closes, otherwise every deploy produces redeliveries; and give each outgoing call a context deadline shorter than the broker's stuck-detector.

Laravel ​

Before ​

A job that catches everything. From the worker's point of view handle() returned, so the job is deleted: a success, with no retry, no failed_jobs row and no failed() call.

php
<?php

namespace App\Jobs;

use App\Services\InvoiceGateway;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;
use Throwable;

// Default settings: one attempt, no backoff, no failed() hook.
class SendInvoice implements ShouldQueue
{
    use Queueable;

    public function __construct(public int $orderId) {}

    public function handle(InvoiceGateway $gateway): void
    {
        try {
            $gateway->send($this->orderId);
        } catch (Throwable $e) {
            // The exception never reaches the worker, so handle() "returns
            // normally" and the worker deletes the job as a success. There is
            // no retry and no row in failed_jobs: the failure is invisible.
            Log::warning('invoice failed', ['order' => $this->orderId]);
        }
    }
}

After ​

Tries and Backoff attributes, release() for "not now", fail() for "never", and exceptions left to propagate for everything else.

php
<?php

namespace App\Jobs;

use App\Services\InvoiceGateway;
use App\Services\RateLimitedException;
use App\Services\InvalidOrderException;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Queue\InteractsWithQueue;
use Throwable;

// Five attempts in total; delays of 10s, 30s, 60s between them.
// Keep retry_after in config/queue.php above the longest handle() run.
#[Tries(5)]
#[Backoff([10, 30, 60])]
class SendInvoice implements ShouldQueue
{
    use InteractsWithQueue, Queueable;

    public function __construct(public int $orderId) {}

    public function handle(InvoiceGateway $gateway): void
    {
        try {
            $gateway->send($this->orderId);
        } catch (RateLimitedException $e) {
            // Not an error: put the job back and try again later.
            // A release still counts as an attempt.
            $this->release($e->retryAfterSeconds);

            return;
        } catch (InvalidOrderException $e) {
            // Retrying cannot help. Mark it failed now, so it lands in
            // failed_jobs and failed() runs, instead of burning the attempts.
            $this->fail($e);

            return;
        }

        // Any other exception propagates: the worker releases the job using
        // the backoff above until the attempts run out, then fails it.
        // Returning normally is the acknowledgement: the worker deletes the job.
    }

    public function failed(?Throwable $exception): void
    {
        // Alert, compensate, or notify here.
    }
}

$this->delete() for a job that has become pointless, and the timeout attributes:

php
<?php

namespace App\Jobs;

use App\Models\Order;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;

class ObsoleteReminder implements ShouldQueue
{
    use InteractsWithQueue, Queueable;

    public function __construct(public int $orderId) {}

    public function handle(): void
    {
        $order = Order::find($this->orderId);

        if ($order === null || $order->isPaid()) {
            // Nothing left to do and nothing to retry: this is an
            // acknowledgment of a job we deliberately do not run. It removes
            // the job but, as the docs note, does not stop a surrounding chain.
            $this->delete();

            return;
        }

        // ... send the reminder ...
    }
}
php
<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\FailOnTimeout;
use Illuminate\Queue\Attributes\Timeout;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Queue\InteractsWithQueue;

// The worker kills a run after 120 s (needs the PCNTL extension). With
// FailOnTimeout the job goes straight to failed_jobs instead of being retried.
// retry_after of this connection must be larger than 120, or a second worker
// reserves the same job while the first is still running it.
#[Timeout(120)]
#[FailOnTimeout]
#[Tries(3)]
#[Backoff([30, 120])]
class SlowReport implements ShouldQueue
{
    use InteractsWithQueue, Queueable;

    public function __construct(public int $reportId) {}

    public function handle(): void
    {
        // Give every outgoing call its own timeout as well: blocking IO such as
        // sockets does not always respect the worker's alarm signal.
        // ... build the report ...
    }
}

The connection settings that decide when an unacknowledged job returns:

php
<?php

// config/queue.php (excerpt). The two numbers that decide when an unacknowledged
// job comes back are retry_after here and --timeout on the worker command.
return [
    'default' => env('QUEUE_CONNECTION', 'redis'),

    'connections' => [
        'redis' => [
            'driver' => 'redis',
            'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
            'queue' => env('REDIS_QUEUE', 'default'),
            // A reserved job that is neither deleted nor released within 90 s
            // goes back onto the queue. Must exceed the longest handle().
            'retry_after' => env('REDIS_QUEUE_RETRY_AFTER', 90),
            // Block on BLPOP for up to 5 s instead of polling in a tight loop.
            // 0 would block forever and delay SIGTERM handling.
            'block_for' => 5,
            'after_commit' => false,
        ],

        'database' => [
            'driver' => 'database',
            'connection' => env('DB_QUEUE_CONNECTION'),
            'table' => env('DB_QUEUE_TABLE', 'jobs'),
            'queue' => env('DB_QUEUE', 'default'),
            'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
            'after_commit' => false,
        ],
    ],
];

// php artisan queue:work redis --timeout=60 --tries=3
//   --timeout=60  < retry_after=90   (a frozen job is killed before it is retried)

The Laravel angle ​

The queue docs describe the lifecycle in plain terms. Success is returning from handle(): the worker deletes the job. An uncaught exception releases it: "the job will automatically be released back onto the queue so it may be attempted again" until the maximum attempts, after which it is a failed job. A crash or a hung process is covered by the connection's retry_after: "the job will be released back onto the queue if it has been processing for 90 seconds without being released or deleted". Set --timeout "at least several seconds shorter" than retry_after, or "your jobs may be processed twice". Attempts are consumed by exceptions, by release(), by middleware that releases (WithoutOverlapping, RateLimited) and by timeouts, which is why a job that releases itself needs Tries raised. $this->delete() removes the job; $this->fail() is the explicit negative acknowledgment. In the framework source the redis driver does this with a reserved sorted set: pop moves the payload to queues:<name>:reserved with the score now + retry_after and bumps attempts; delete does ZREM; release does ZREM plus ZADD into delayed; and each pop first migrates expired reserved payloads back to the queue. With block_for the worker waits on a notify list with BLPOP instead of polling. For RabbitMQ with vladimir-yuldashev/laravel-queue-rabbitmq the package maps the same calls onto AMQP: delete becomes basic_ack, release publishes a new delayed message and acks the old one, and a failed job is basic_reject so a dead-letter exchange can take it:

php
<?php

namespace App\Jobs;

use App\Services\InvoiceGateway;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;

// With vladimir-yuldashev/laravel-queue-rabbitmq the Laravel job calls are
// translated into AMQP calls (see the package's RabbitMQJob):
//   handle() returns   -> worker calls delete()  -> basic.ack
//   $this->fail()      -> markAsFailed()         -> basic.reject (requeue=false, so a DLX applies)
//   $this->release(30) -> a NEW message is published with a delay, the old one is acked
//   exception          -> worker releases it     -> same as release()
class SendInvoiceViaRabbit implements ShouldQueue
{
    use InteractsWithQueue, Queueable;

    public function __construct(public int $orderId) {}

    public function handle(InvoiceGateway $gateway): void
    {
        $gateway->send($this->orderId);
    }
}

// Elsewhere (a controller, an action):
//   SendInvoiceViaRabbit::dispatch($order->id)->onConnection('rabbitmq')->onQueue('invoices');
// Worker, with the prefetch of the package's consume command:
//   php artisan rabbitmq:consume rabbitmq --queue=invoices --prefetch-count=10 --tries=3

Broker differences ​

RabbitMQ ​

The primitive is the delivery with a delivery tag: a per-channel, monotonically increasing integer, so a delivery must be acknowledged on the channel that received it (acking elsewhere closes the channel with "unknown delivery tag", and so does acking the same tag twice). Manual mode offers basic.ack, basic.nack (can reject several at once) and basic.reject, with a requeue flag; with requeue=false the message is dead-lettered if a dead-letter exchange is configured, otherwise discarded. multiple=true acknowledges "all outstanding delivery tags up to and including the tag specified". When a channel or connection closes with unacked messages they are requeued automatically and flagged redelivered. Quorum queues add a delivery limit (default 20 since 4.0) and x-delivery-count; basic.reject counts towards it and basic.nack does not (4.3+). Prefetch (basic.qos) caps unacked deliveries and is per consumer in RabbitMQ. consumer_timeout (30 min) returns messages from a consumer that holds an unacked delivery for too long. What breaks: auto-ack with no prefetch, which lets the broker push an unbounded backlog into your heap; requeue loops; acking on the wrong channel; a long handler that outlives the timeout. The Go snippets rabbit_after and rabbit_timing above are the RabbitMQ pattern; for Laravel, the package job above.

Kafka ​

There is no per-message acknowledgment. Each partition has one consumer in a group, so "the position of a consumer in each partition is just a single integer", and the equivalent of an ack is committing that integer, which "makes the equivalent of message acknowledgements very cheap". The committed offset is the next record to read. Defaults matter: enable.auto.commit is true, auto.commit.interval.ms is 5000. Auto-commit is at-least-once only if you finish everything poll returned before the next poll; the Javadoc spells out the failure: "it is possible for the committed offset to get ahead of the consumed position, which results in missing records". Manual commit after processing gives at-least-once, committing before gives at-most-once, per the design doc's two orderings. A failed record cannot be skipped without moving the offset past it, so you stop, retry in place, or republish it to a retry or dead-letter topic (DLQ). Rebalances can redeliver the uncommitted tail to another member, so handlers must be idempotent. Share groups (KIP-932, production-ready in Kafka 4.2) bring queue semantics: records are acquired with a time-limited lock and the consumer can accept, release or reject each one, with delivery attempts counted; Kafka 4.4 adds dead-letter queues for share groups (KIP-1191). The Go snippets kafka_after and kafka_timing are the franz-go versions; for Laravel, the withManualCommit() command:

php
<?php

namespace App\Console\Commands;

use App\Services\OrderProcessor;
use Illuminate\Console\Command;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Contracts\MessageConsumer;
use Junges\Kafka\Facades\Kafka;

// mateusjunges/laravel-kafka. By default the package commits after the handler
// returns EVEN WHEN it failed; withManualCommit() turns that off.
class ConsumeOrders extends Command
{
    protected $signature = 'kafka:orders';

    protected $description = 'Consume orders and commit the offset only after the work succeeded';

    public function handle(OrderProcessor $processor): int
    {
        $consumer = Kafka::consumer(['orders'])
            ->withConsumerGroupId('billing')
            ->withManualCommit()
            // On a failure the exception is rethrown by the handler: retry in
            // place a few times, then stop WITHOUT committing, so the next
            // member of the group starts from the failed record.
            ->retryFailedMessages(3, backoffInMs: 1000)
            ->stopOnFailure()
            ->withHandler(function (ConsumerMessage $message, MessageConsumer $consumer) use ($processor) {
                $processor->process(json_decode($message->getBody(), true));

                // Not reached when process() throws. commit() blocks; commitAsync()
                // does not and may be lost in a crash, which only costs a duplicate.
                $consumer->commit($message);
            })
            ->build();

        $consumer->consume();

        return self::SUCCESS;
    }
}

Redis Streams ​

The primitive is the pending entries list (PEL) of a consumer group. XREADGROUP with > delivers new entries and records them in the PEL as owned by that consumer; XACK removes them. The docs' definition is exact: a pending message "was delivered to some consumer but the server is yet not sure it was processed at least once". Reading with an id of 0 replays that consumer's own pending history. XPENDING inspects the list (summary, or per entry: id, owner, idle time in milliseconds, delivery count, with an IDLE filter). There is no timeout or failure detector: nothing redelivers a pending entry by itself (Redis 8.4 adds XREADGROUP ... CLAIM min-idle-time so a consumer can claim stale entries as part of the read). A crashed consumer's entries sit in the PEL until another consumer takes them with XCLAIM or XAUTOCLAIM, which resets the idle time and increments the delivery counter. NOACK skips the PEL. XNACK (8.8) releases entries immediately. What breaks: forgetting the reaper (the PEL grows for ever) and unbounded retries of a poison entry, for which the delivery count is your retry limit. In Laravel the built-in Redis queue driver does not use streams (it uses lists and sorted sets), so use the Redis facade directly:

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
use Throwable;

// Assumes the phpredis client (REDIS_CLIENT=phpredis, Laravel's default).
// The group must exist: XGROUP CREATE orders billing $ MKSTREAM
class ConsumeOrders extends Command
{
    protected $signature = 'orders:consume {consumer=worker-1} {--min-idle=60000}';

    protected $description = 'Consume the orders stream with XACK and a PEL reaper';

    private const STREAM = 'orders';
    private const GROUP = 'billing';

    public function handle(): int
    {
        $consumer = $this->argument('consumer');
        $minIdle = (int) $this->option('min-idle');
        $lastReap = 0;

        while (true) {
            // 1. Reap entries abandoned by crashed consumers (about once a minute).
            if (time() - $lastReap >= 60) {
                $this->reap($consumer, $minIdle);
                $lastReap = time();
            }

            // 2. Read new entries; ">" means "never delivered to anyone in the group".
            $result = Redis::xreadgroup(self::GROUP, $consumer, [self::STREAM => '>'], 50, 5000);

            foreach ($result[self::STREAM] ?? [] as $id => $fields) {
                $this->process($id, $fields);
            }
        }
    }

    private function reap(string $consumer, int $minIdle): void
    {
        $start = '0-0';

        do {
            // Claiming resets the idle clock and bumps the delivery counter.
            $claimed = Redis::xautoclaim(
                self::STREAM, self::GROUP, $consumer, $minIdle, $start, 50
            );
            [$start, $entries] = $claimed ?: ['0-0', []];

            foreach ($entries as $id => $fields) {
                $this->process($id, $fields);
            }
        } while ($start !== '0-0');
    }

    private function process(string $id, array $fields): void
    {
        try {
            // ... do the work; it must be idempotent, an entry can arrive twice ...
            Redis::xack(self::STREAM, self::GROUP, [$id]);
        } catch (Throwable $e) {
            // No XACK: the entry stays in the PEL until the reaper claims it.
            $this->error("entry {$id} stays pending: {$e->getMessage()}");
        }
    }
}

And a read-only inspector for the pending list:

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

// Assumes the phpredis client. Read-only: safe to run in production.
class StreamInspect extends Command
{
    protected $signature = 'orders:pending {--idle=60000} {--max-deliveries=5}';

    protected $description = 'Show stuck entries of the billing group in the orders stream';

    public function handle(): int
    {
        // XPENDING orders billing: [count, smallest id, greatest id, [[consumer, count], ...]]
        $summary = Redis::xpending('orders', 'billing');
        $this->info('pending: '.($summary[0] ?? 0));

        // XPENDING orders billing - + 100: [[id, consumer, idle ms, deliveries], ...]
        foreach (Redis::xpending('orders', 'billing', '-', '+', 100) ?: [] as [$id, $consumer, $idle, $deliveries]) {
            if ($idle < (int) $this->option('idle')) {
                continue;
            }

            $poison = $deliveries >= (int) $this->option('max-deliveries');
            $this->line("{$id} owner={$consumer} idle={$idle}ms deliveries={$deliveries}".($poison ? ' POISON' : ''));
        }

        return self::SUCCESS;
    }
}

Other brokers, briefly ​

BrokerAck primitiveTimeout and redeliveryDetails
NATS JetStreamconsumer AckPolicy: AckExplicit (default), AckNone, AckAllAckWait, then redelivery; MaxDeliver limits attempts (default -1); Backoff lists delaysOther Brokers
Amazon SQSDeleteMessagevisibility timeout (default 30 s, 0 to 12 h)Other Brokers
Pulsar, Google Pub/Subper-message ackack timeout / ack deadlineOther Brokers
Kafka share groupsper-record accept, release, rejectacquisition lock duration; delivery countingKIP-932, 4.2+

In production systems ​

  • RabbitMQ defaults are documented, not folklore. The prefetch guide gives 100 through 300 as the usual sweet spot, quorum queues cap unlimited prefetch at 2,000 and enforce a delivery acknowledgement timeout, and a consumer that never acks makes the node's memory grow ("Consumers that consume a lot of messages without acknowledging will lead to memory consumption growth on the node they are connected to").
  • Kafka's consumer settings. enable.auto.commit=true with a 5 second interval is the default in the consumer configs; transactional consumers are told to set enable.auto.commit=false and isolation.level=read_committed in the design doc's exactly-once section.
  • Redis recovery is a client job. The XAUTOCLAIM reference describes a cursor-style scan of the PEL (0-0 means the scan finished) and the limit of ten times COUNT entries scanned per call; entries that no longer exist in the stream are dropped from the PEL during the scan (Redis 7.0+). Every Streams consumer library has to run that loop itself.
  • Laravel's retry_after. Each connection in config/queue.php defines it (SQS relies on the queue's Default Visibility Timeout instead), and the docs tie it to --timeout to avoid double processing. laravel-queue-rabbitmq's rabbitmq:consume command defaults to --prefetch-count=1000; check that against your handler time.

In architecture: from a single process to a distributed system ​

Acknowledgment placement is where the delivery guarantee is actually decided: ack after the side effect and you accept duplicates, ack before and you accept loss. An ack is also hop by hop: it says "the next hop took responsibility", never "the business operation succeeded end to end".

Monolith (one process, one database) ​

A Laravel app with QUEUE_CONNECTION=redis or database, one queue:work pool and one MySQL or PostgreSQL database. Ack is the return of handle(). The simplest correct setup: Tries 3 to 5, a Backoff array, --timeout 60 and retry_after 90, jobs idempotent (updateOrCreate, a unique key), and a failed() hook that alerts. A ShouldBeUnique job and the after_commit option keep a job from running before the row it needs is committed (Laravel Queue Internals). An in-process Go equivalent is a buffered channel with a worker pool: the "ack" is the worker's wg.Done() after the work; without a durable queue a crash loses the whole buffer, which is why the broker exists.

Modular monolith / multiple databases ​

One deployable, several modules, each with its own tables (or schema) and its own queue: billing.invoices, shipping.labels. Each module consumes with its own prefetch and its own dead-letter queue, and acks after committing to its own tables, so one module's slow handler does not starve another's. The dedup row lives in the module's schema, in the same transaction as the module's write. A module that publishes an event after its commit uses the outbox; the consuming module acks only after its own commit. The domain-event side is in Domain Events & Integration Events.

Microservices ​

Orders, billing and shipping as three services over Kafka. Orders writes OrderPlaced through the outbox; billing consumes from orders.v1 in group billing, in one database transaction inserts the inbox row, writes the invoice and an InvoiceIssued outbox row, commits, then marks the offset (MarkCommitRecords). Shipping does the same on invoices.v1.

text
1   orders:   BEGIN; INSERT order; INSERT outbox(OrderPlaced); COMMIT
2   relay:    publish OrderPlaced to orders.v1                       (at-least-once)
3   billing:  poll -> BEGIN; INSERT inbox; INSERT invoice; INSERT outbox(InvoiceIssued); COMMIT
4   billing:  MarkCommitRecords -> background commit of offset+1
5   crash between 3 and 4: restart at the old offset -> inbox hit -> skip -> commit

What survives the service boundary: the ack does not. It ends at the broker. "Billing acked" does not mean "the customer was billed", so cross-service success is reported by events (InvoiceIssued) and, when a step fails, compensated in a saga. The patterns of reliable messaging between services are in Designing for Failure: Reliable Messaging and Service Communication.

Distributed data (replicas, caches, multi-region) ​

A lost ack is a normal event, not an edge case: a network partition or a failover between the work and the ack produces a redelivery. RabbitMQ's quorum-queue docs list an intra-cluster network partition (consumer node suspected down) and a consumer timeout as triggers that return a message and raise its acquired count; the consequence is that a consumer on the far side of a partition may still be working on a message that has already been handed to someone else. Kafka stores committed offsets as messages in an internal topic, so they replicate with the cluster like data, but a committed offset is meaningful only for its own cluster and topic: after a failover to another cluster, offsets must be translated or you choose a reset policy (auto.offset.reset). Redis replication is asynchronous (Redis, Replication & Failover): after a failover an XACK that was not replicated reappears as a pending entry (a duplicate), and an XADD that was not replicated is gone. A dedup cache (Redis keys with a TTL) must outlive the longest possible redelivery delay, which is the consumer timeout plus any backoff; a database inbox with a retention period is safer. See Distributed SQL & Consensus for why exactly-once across stores needs coordination.

Scaling path ​

LoadWhat changes in acknowledgment
1x (hundreds per minute)One consumer, prefetch 1 (RabbitMQ), COUNT 10 (Redis), default Kafka poll; ack per message; simplest code
10xPrefetch 50 to 300, ack per message or batched multiple=true; Kafka commits per batch; XACK with many ids; a second consumer, which brings fairness into play
100xMany partitions or streams, commit per partition batch, AutoCommitMarks, consumer lag alarms, XAUTOCLAIM reaper per group, dedup table partitioned by day; consider Kafka share groups or splitting hot queues
Multi-regionPer-region consumer groups; ack stays local; dedup keys must be globally unique (message id, not offset)

Lab ​

Expected output, not run. Goal: kill a consumer mid-process and watch each broker redeliver. Use the Go snippets in a small main, or the Laravel jobs, with a handler that sleeps 30 s and logs the id.

RabbitMQ (Docker rabbitmq:management, queue orders, consumer from rabbit_after):

text
1   publish 3 messages (management UI or a small Go program)
2   start the consumer with prefetch 2, handler sleeps 30 s
3   rabbitmqctl list_queues name messages_ready messages_unacknowledged consumers
    orders  1  2  1                     # expected: 1 ready, 2 unacked, 1 consumer
4   kill -9 the consumer process
5   rabbitmqctl list_queues name messages_ready messages_unacknowledged consumers
    orders  3  0  0                     # expected, after the connection closes: all 3 ready again
6   start the consumer again: logs show Redelivered=true for the 2 that were in flight

Kafka (Apache Kafka 4.x, topic orders with 1 partition, group billing, consumer from kafka_after):

text
1   produce 10 records
2   start the consumer, handler sleeps 5 s per record; after record 4 is committed, kill -9
3   bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group billing
    TOPIC   PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG
    orders  0          4               10              6        # expected: committed 4, lag 6
4   start the consumer again: it resumes at offset 4; the record being handled at the kill is handled again
5   repeat with GreedyAutoCommit and a handler that returns the record to a goroutine: expect committed > handled,
    and records missing after the kill (the "before" snippet)

Redis Streams (Redis 8.x, stream orders, group billing, consumer from redis_after):

text
1   redis-cli XGROUP CREATE orders billing $ MKSTREAM
2   redis-cli XADD orders '*' sku A1
3   start the consumer "worker-1", handler sleeps 30 s, then kill -9
4   redis-cli XPENDING orders billing
    1) (integer) 1   2) "1700-0"   3) "1700-0"   4) 1) 1) "worker-1" 2) "1"
5   wait, then: redis-cli XPENDING orders billing IDLE 20000 - + 10
    1) 1) "1700-0"  2) "worker-1"  3) (integer) 24133  4) (integer) 1      # idle grows, deliveries 1
6   redis-cli XAUTOCLAIM orders billing worker-2 20000 0-0 COUNT 10
    # expected: next cursor 0-0, the entry now owned by worker-2
7   redis-cli XPENDING orders billing IDLE 0 - + 10
    1) 1) "1700-0"  2) "worker-2"  3) (integer) 17  4) (integer) 2         # owner changed, deliveries 2

Laravel (redis driver, job that sleeps 120 s, retry_after 90, --timeout 60):

text
1   php artisan queue:work redis --timeout=60 --tries=3
2   dispatch the job, then kill -9 the worker (the --timeout alarm never gets a chance)
3   redis-cli ZCARD queues:default:reserved          # expected: 1
4   after 90 s the next pop migrates it back; another worker logs attempt 2
5   let the job run to the --timeout: expected a TimeoutExceededException, then release with backoff, attempt 2

Common misconceptions ​

BeliefReality
"Auto-ack is fine, my handler is fast."The message is forgotten when written to the socket; speed does not shorten the crash window, and there is no prefetch limit
"Ack means the work succeeded."It means the consumer took responsibility; a rejected or deleted message is acked by the broker's accounting
"Ack after processing gives exactly-once."It gives at-least-once; exactly-once effect needs an idempotent handler or a dedup row
"Kafka acks each message."It commits a position; committing N acknowledges everything before N
"Not committing a failed Kafka record redelivers it."Only if no later record of the partition is committed
"Redis Streams redelivers unacked entries on its own."Nothing does; use XAUTOCLAIM, XCLAIM or XREADGROUP ... CLAIM
"multiple=true acks only this tag."It acks every outstanding tag up to and including it, on that channel
"Requeue is a retry policy."It is an immediate redelivery; deterministic failures loop and burn CPU
"A bigger prefetch is always faster."Gains flatten after about 100 to 300 and a big window starves other consumers
"redelivered=false means my code never saw it."It means the broker has not delivered it before; it is a boolean, and true does not say whether the earlier attempt finished its side effect
"In Laravel, catching the exception retries the job."handle() returns, the job is deleted: no retry, no failed_jobs
"--timeout and retry_after are the same thing."One kills a run, the other returns a reserved job; the first must be shorter

Cheat sheet ​

TopicWhat to remember
Ack meaningEnds the broker's duty; RabbitMQ deletes, Kafka moves the offset, Redis leaves the PEL
Default timingManual ack after processing, idempotent handler
Side effectsCommit the DB transaction with an inbox row, then ack
RabbitMQbasic.ack, basic.nack, basic.reject, multiple, per-channel tags, redelivered
Quorum queuesdelivery-limit 20, x-delivery-count, use basic.reject to count
Prefetch1 for slow or mixed work, 100 to 300 for fast; per consumer in RabbitMQ
consumer_timeout30 min default; PRECONDITION_FAILED in 4.0; quorum queues only from 4.3
Kafka commitCommit the next offset after the work, per partition, in order
Kafka clockssession.timeout.ms 45 s, heartbeat.interval.ms 3 s, max.poll.interval.ms 5 min, max.poll.records 500
Redis recoveryXPENDING, XAUTOCLAIM, delivery counter; nothing redelivers by itself
Redis newXNACK (8.8), XREADGROUP ... CLAIM (8.4), XACKDEL (8.2)
Laravelreturn = ack, release = retry later, delete = forget, fail = never; --timeout below retry_after
Diagnoseowner, idle time, delivery count, per queue or group
Poisoncount deliveries, then park; do not requeue forever

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 — What does an ack change in RabbitMQ, Kafka and Redis Streams? Must-know ​

Answer

Answer: RabbitMQ deletes the message from the queue, Kafka advances the committed offset of the group for that partition, and Redis removes the id from the group's PEL (the entry remains in the stream).

2 — A consumer acks first and then crashes while processing. What is the delivery semantics, and what is lost? Must-know ​

Answer

Answer: At-most-once: the broker already forgot the message, so the work is lost and nothing is redelivered.

3 — Why does ack-after-side-effects still need an idempotent handler? Must-know ​

Answer

Answer: A crash between the commit and the ack makes the broker redeliver; the dedup row from the first run lets the second run skip the work and just ack.

4 — Delivery tags 5 to 8 are unacked and tag 6 failed. Why is basic.ack(8, multiple=true) wrong? Good to know ​

Answer

Answer: It acknowledges 5, 6, 7 and 8, silently dropping the failed 6. Settle 6 (reject) before acking later tags with multiple=true.

5 — After handling record 9 on a partition, which offset do you commit, and why? Must-know ​

Answer

Answer: 10: the committed offset is the next record to read.

6 — A Redis consumer dies holding an entry. When is it redelivered? Important ​

Answer

Answer: Never by itself. It stays in the PEL until another consumer claims it with XCLAIM, XAUTOCLAIM or XREADGROUP ... CLAIM, or releases with XNACK (8.8+), after min-idle-time.

7 — A quorum queue consumer uses basic.nack with requeue for a poison message on RabbitMQ 4.3. What happens? Good to know ​

Answer

Answer: The nack does not count towards the delivery limit, so the message can loop for ever. Use basic.reject with requeue=true.

8 — What do max.poll.interval.ms and session.timeout.ms each detect? Must-know ​

Answer

Answer: session.timeout.ms (with heartbeats) detects a dead process; max.poll.interval.ms detects a live process that stopped calling poll(). Either triggers a rebalance.

9 — A Laravel job runs 100 s and retry_after is 90. What goes wrong? Must-know ​

Answer

Answer: The job is returned to the queue after 90 s and a second worker runs it while the first is still running: processed twice. Keep --timeout several seconds below retry_after and retry_after above the longest run.

10 — Name the three numbers you alert on for stuck messages. Important ​

Answer

Answer: Unacked or pending count, oldest idle time (or commit age), and maximum delivery count.

11 — Why is redelivered not enough for deduplication? Important ​

Answer

Answer: It is a boolean on RabbitMQ only, it says nothing about whether the earlier attempt finished its side effect, and other brokers do not have it. Use a dedup key.

Glossary ​

TermMeaning
ack / acknowledgmentConsumer-to-broker signal that ends the broker's obligation to redeliver
nackNegative acknowledgment: "could not process" (RabbitMQ basic.nack, extension to AMQP 0-9-1)
rejectRabbitMQ basic.reject: reject one delivery, with requeue
requeuePut a rejected message back in the queue instead of dead-lettering or dropping it
delivery tagPer-channel increasing integer that identifies a RabbitMQ delivery
multipleFlag that makes an ack or nack cover all outstanding tags up to and including this one
auto-ack / no-ackBroker treats the message as handled when it is sent
prefetch / QoSMaximum unacked deliveries (basic.qos)
in-flight windowMessages delivered but not yet acknowledged
redeliveredAMQP boolean set when a message is delivered again
x-delivery-countQuorum-queue header with the number of failed delivery attempts
delivery-limitQuorum-queue limit (default 20) after which a message is dead-lettered or dropped
consumer_timeoutRabbitMQ delivery acknowledgement timeout, default 30 minutes
committed offsetThe position a Kafka group stored for a partition; the next record to read
positionThe offset of the next record poll() returns in a consumer
enable.auto.commitKafka consumer setting for background offset commits (default true)
max.poll.recordsKafka cap on records per poll() (default 500)
max.poll.interval.msKafka limit between polls before the member is considered failed (default 300000)
session.timeout.msKafka limit between heartbeats before the member is removed (default 45000)
CommitFailedExceptionKafka error when a commit comes from a member that already left the group
rebalanceReassignment of partitions among group members
share groupKafka queue-style group with per-record acknowledgment (KIP-932)
PELPending entries list of a Redis consumer group
XACKRemove entry ids from the PEL
XPENDINGInspect the PEL: summary or per entry with owner, idle time, delivery count
XCLAIM / XAUTOCLAIMTransfer ownership of idle pending entries; XAUTOCLAIM scans with a cursor
XNACKRelease pending entries back to the group without acking (Redis 8.8+)
idle timeMilliseconds since an entry was last delivered
retry_afterLaravel connection setting: seconds before a reserved job returns to the queue
--timeoutLaravel worker option: maximum seconds a job may run
block_forLaravel redis option: seconds to block waiting for a job
ack-after-side-effectsAcknowledging only after the database commit that holds the effect and the dedup row
poison messageA message that fails every time it is processed
visibility timeoutSQS equivalent of a reserved-job timeout
AckWait / MaxDeliverNATS JetStream redelivery delay and attempt limit

References ​

Built by Morteza Negahi