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 for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
| Why a broker needs acknowledgment at all | Why acknowledgment exists, Where it comes from |
| What "ack" literally does on each broker | Ownership transfer |
Auto ack (auto-ack), NOACK, auto-commit | Auto vs manual |
| Ack before, after, after side effects | Ack timing |
| nack, reject, requeue, poison loops | Negative acknowledgment |
multiple=true, batch commit, XACK with many ids | Batch acknowledgment |
Prefetch, QoS, max.poll.records, COUNT | The in-flight window |
| Committed offset vs position | Kafka offsets |
PEL, XPENDING, XCLAIM, XAUTOCLAIM, XNACK | Redis pending list |
consumer_timeout, max.poll.interval.ms, idle time, retry_after | Consumer timeouts |
Redelivery and the redelivered flag | Redelivery |
| "Why is this message stuck?" | Stuck-message diagnostics |
Laravel release, delete, fail, --timeout, block_for | Laravel outcomes |
| Knobs, defaults, error messages | Mechanics |
| Code for all three timings and manual commit | Solving the classic problems, Go, Laravel |
| Which ack for which workload | Choosing |
| Monolith to multi-region | In architecture |
| Reproduce a crash per broker | Lab |
| Wrong beliefs, cheat sheet, every term | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
What an ack means. Every row is unpacked in the concept catalogue.
| Broker | Primitive that carries the ack | What the ack does | Granularity | If it never comes |
|---|---|---|---|---|
| RabbitMQ | basic.ack for a delivery tag | The message is recorded as delivered and deleted from the queue | One delivery, or all tags up to N with multiple=true | Requeued when the channel closes or the consumer timeout fires; redelivered is set |
| Kafka | Committed offset of (group, partition) | The stored position moves to the next offset to read | A position: everything before it is "done" | The group resumes from the last committed offset after a rebalance or restart |
| Redis Streams | XACK against the consumer group's PEL | The id leaves the PEL (the entry stays in the stream) | One entry, many ids per call | The entry stays in the PEL for ever until another consumer claims it |
| Laravel queue | Returning from handle() (the worker calls delete) | The job is deleted | One job | retry_after seconds later the job becomes available again |
| NATS JetStream | Ack against the consumer with AckExplicit | The message is settled | One message by default | Redelivered after AckWait, up to MaxDeliver |
| Amazon SQS | DeleteMessage | The message is removed | One message | Visible again after the visibility timeout (default 30 s) |
The three timings.
| Timing | Order | A crash in the window causes | Delivery semantics | Use when |
|---|---|---|---|---|
| Ack-before-process | deliver, ack, process | The message is lost | at-most-once | Losing one is cheaper than doing it twice (metrics, cache warm-up) |
| Ack-after-process | deliver, process, ack | The work may be done twice | at-least-once | The default for almost everything, with an idempotent handler |
| Ack-after-side-effects | deliver, process, COMMIT, ack | A redelivery that hits a dedup row and only acks | at-least-once delivery, effectively-once effect | Money, stock, anything with a visible side effect |
The negative outcomes.
| You want to say | RabbitMQ | Kafka | Redis Streams | Laravel |
|---|---|---|---|---|
| "Done" | basic.ack | commit offset N+1 | XACK | return from handle() |
| "Not now, try again" | basic.nack / basic.reject with requeue=true | do not commit, stop or retry in place | do 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 commit | XACK after copying to a dead-letter stream | $this->fail($e) |
| "Nothing to do, forget it" | basic.ack | commit | XACK | $this->delete() |
Three things to do.
| Situation | Do this |
|---|---|
| Any consumer you write | Manual ack after the work, a bounded in-flight window, an idempotent handler |
| Any failure that retrying cannot fix | Do not requeue; send it to the dead-letter queue |
| Any unacked message you cannot explain | Look 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 duplicates | Duplicates after every crash |
| Messages lost on a crash | Nothing lost on a crash |
| Small in-flight window | The unacked window is your backlog and your memory |
| Nothing to redeliver, nothing to time out | Needs a failure detector: channel close, session timeout, idle time, retry_after |
| Simple handler | Handler 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
- "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 abasic.rejecthas 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". - "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.
- "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
XCLAIMorXAUTOCLAIM.
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).
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 removedReal 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".
| Broker | What changes in the broker | What is not changed |
|---|---|---|
| RabbitMQ | The message is removed from the queue (a stream queue is a log and keeps data until retention) | Nothing is written back to the publisher |
| Kafka | One integer in the internal offsets topic for (group, partition) | The record stays in the log until retention deletes it; other groups are unaffected |
| Redis Streams | The id leaves the group's PEL | The 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>:reserved | A 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).
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.
| Product | Auto mode | Default | Safe to use? |
|---|---|---|---|
| RabbitMQ | autoAck=true in Channel.Consume (basic.consume with no-ack) | you choose it per Channel.Consume call | Only for steady, cheap, loss-tolerant consumers |
| Kafka (Java consumer, librdkafka) | enable.auto.commit=true | true | At-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 polled | autocommit on | Default is safe; greedy "may result in message loss if your application crashes" |
| Redis Streams | NOACK on XREADGROUP | off | Same as fire-and-forget |
| Laravel | none: the worker deletes after handle() returns | always on | Safe, but a caught exception counts as success |
| laravel-kafka | auto-commit "after your handler runs, even when it fails" | on | Use 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.
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, ACKReal 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.
| Timing | RabbitMQ | Kafka | Redis Streams | Laravel |
|---|---|---|---|---|
| Before | d.Ack(false) then handle | CommitRecords then handle | XACK then handle (or NOACK) | $this->delete() at the top of handle() |
| After | handle then d.Ack(false) | handle then CommitRecords | handle then XACK | return normally (the default) |
| After side effects | commit the DB transaction, then ack | commit the DB transaction, then MarkCommitRecords | commit the DB transaction, then XACK | DB::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.
// 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:
// 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:
// 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:
-- 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().
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 droppedReal 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 queue | nack/reject with requeue=true | reject with requeue=false | None: you track redelivered yourself, but it is only a boolean |
| RabbitMQ quorum queue | same | same | delivery-limit (default 20 since 4.0, -1 disables it) and the x-delivery-count header; basic.reject counts, basic.nack does not |
| Kafka | do not commit, retry in place or republish to a retry topic | publish to a dead-letter topic, then commit | None (share groups count delivery attempts) |
| Redis Streams | leave in the PEL; XNACK ... FAIL (8.8+) | copy to a dead-letter stream, XACK | The delivery counter in XPENDING; XNACK ... FATAL sets it to the maximum |
| Laravel | release($delay), exception | fail($e) | Tries, MaxExceptions, failed_jobs |
| NATS JetStream | nak or no ack until AckWait (redelivery) | reach MaxDeliver | MaxDeliver (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.
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 pushedReal 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.
| Product | Batch ack | Rule to stay correct |
|---|---|---|
| RabbitMQ | basic.ack and basic.nack with multiple=true (not basic.reject) | Settle failures first, then ack with multiple; tags are per channel |
| Kafka | CommitRecords(lastRecord) / commitSync with the next offset | Commit in order per partition; committing an older offset rewinds the group |
| Redis Streams | XACK key group id1 id2 ... | Only list ids that succeeded; failed ids stay pending |
| Laravel | none: 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.
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=trueReal 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.
| Knob | Product | Default | Scope |
|---|---|---|---|
basic.qos(prefetch_count) | RabbitMQ | 0 (no limit) unless default_consumer_prefetch is configured | per consumer in RabbitMQ; per channel with the deprecated global flag |
rabbit.default_consumer_prefetch | RabbitMQ (advanced.config) | none | applied when a consumer sets no prefetch |
basic.get | RabbitMQ pull API | n/a | prefetch "has no effect" on it |
max.poll.records | Kafka consumer | 500 | per poll() call |
PollRecords(ctx, n) | franz-go | n/a | per call (no max.poll.records option; you choose n) |
COUNT | Redis XREADGROUP | optional; set it | per read |
MAXCOUNT, MAXSIZE | Redis 8.10+ | none | cumulative cap across streams |
--prefetch-count | laravel-queue-rabbitmq rabbitmq:consume | 1000 | per 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.
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.
| Question | Java consumer / librdkafka | franz-go |
|---|---|---|
| Auto-commit default | enable.auto.commit=true, every 5000 ms | on, every 5 s (AutoCommitInterval) |
| What auto-commit commits | the offsets of the last poll when the next poll or close is called; safe only if you finish a poll's records first | records from earlier polls (non-"dirty"); GreedyAutoCommit commits the current poll |
| Manual commit | commitSync(), commitSync(offsets), commitAsync() | DisableAutoCommit() then CommitRecords, CommitUncommittedOffsets |
| Halfway mode | none | AutoCommitMarks() + MarkCommitRecords + CommitMarkedOffsets |
| Commit on rebalance | ConsumerRebalanceListener.onPartitionsRevoked | OnPartitionsRevoked (the default does a blocking commit when autocommit is on) |
| Rewind by committing an old offset | possible | CommitRecords "will rewind your commit" if you go backwards |
| laravel-kafka | withManualCommit(); $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".
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".
| Command | Purpose | Notes |
|---|---|---|
XREADGROUP GROUP g c STREAMS s > | read new entries, add to the PEL | NOACK skips the PEL |
XREADGROUP ... STREAMS s 0 | replay this consumer's own pending history | how a restarted consumer resumes |
XREADGROUP ... CLAIM min-idle-time | claim idle pending entries while reading (Redis 8.4+) | folds the reaper into the read |
XACK s g id [id ...] | remove ids from the PEL | returns the count really removed |
XPENDING s g | summary: count, smallest id, greatest id, per consumer | read-only |
XPENDING s g [IDLE ms] start end count [consumer] | one row per entry: id, owner, idle ms, deliveries | find stuck entries |
XCLAIM s g c min-idle id ... [JUSTID] [RETRYCOUNT n] | take specific ids | JUSTID does not bump the counter |
XAUTOCLAIM s g c min-idle start [COUNT n] [JUSTID] | scan the PEL and claim, cursor style | returns 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 g | per consumer: pending, idle, inactive | find dead consumers |
XACKDEL | ack 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 inrabbitmq.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 aPRECONDITION_FAILEDchannel 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 keyconsumer-timeoutand queue argumentx-consumer-timeout(since 3.12). - Kafka: three separate clocks.
session.timeout.ms(default 45000) withheartbeat.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 withCommitFailedException. The new consumer group protocol (group.protocol=consumer) moves the session timeout to the broker (group.consumer.session.timeout.ms). franz-go has nomax.poll.interval.msoption: heartbeats run in the background, so a hung handler is not detected by poll cadence; the risks there areRebalanceTimeout(default 60 s) while a rebalance waits for you, whichBlockRebalanceOnPollmakes real. - Redis Streams: nothing detects it. Idle time is only a number you read in
XPENDINGand filter withmin-idle-time; the reaper you write is the detector. - Laravel:
retry_afteron the connection (reserved job returns after N seconds), and--timeout(worker kills a run, default 60 s, needs PCNTL). The rule: "your--timeoutvalue should always be at least several seconds shorter than yourretry_after".
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=trueReal 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.
| Product | Detects a dead process | Detects a stuck process | Redelivery trigger | Default |
|---|---|---|---|---|
| RabbitMQ | channel/connection close, heartbeat | consumer_timeout | requeue of all unacked deliveries | 30 min |
| Kafka (Java) | session.timeout.ms | max.poll.interval.ms | rebalance, resume from the committed offset | 45 s / 5 min |
| Kafka (franz-go) | SessionTimeout | none by poll cadence | rebalance | 45 s |
| Redis Streams | none built in | none built in | your XAUTOCLAIM with min-idle-time | n/a |
| Laravel | retry_after | --timeout kills it, then retry_after | job returns to the queue | 90 s / 60 s |
| NATS JetStream | AckWait | AckWait | redelivery, up to MaxDeliver | see NATS docs |
| SQS | visibility timeout | visibility timeout | message visible again | 30 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.
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 20Real 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.
| Product | Signal | Counter | Where to read it |
|---|---|---|---|
| RabbitMQ classic | redelivered boolean | none | Delivery.Redelivered |
| RabbitMQ quorum | redelivered boolean | x-delivery-count, x-acquired-count header | message headers |
| Kafka | none | none (offsets are stable; share groups count attempts) | the record |
| Redis Streams | none | delivery counter in the PEL | XPENDING extended form |
| Laravel | none | attempts() | 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:
| Question | RabbitMQ | Kafka | Redis Streams | Laravel |
|---|---|---|---|---|
| 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 tab | the CONSUMER-ID column of the --describe output | XPENDING s g - + 100 (owner) and XINFO CONSUMERS s g | worker process list, Horizon |
| For how long? | consumer timeout log line on the node | commit age: compare committed offset movement over time | idle ms in XPENDING extended form | the job's score in queues:<q>:reserved (redis driver) and its attempts |
| How many times? | x-delivery-count (quorum), redelivered | not tracked | delivery counter in XPENDING | attempts column / $this->attempts() |
| Release it | close the consumer's channel or connection; basic.nack | restart the member or trigger a rebalance | XAUTOCLAIM, XCLAIM, XNACK (8.8+) | wait for retry_after; queue:retry for failed jobs |
$ 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 # deliveriesThe two Go helpers that print the same answers programmatically are Report for Redis and Report for Kafka lag:
// 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
}// 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".
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:defaultReal 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().
| Concern | Setting | Default | Source of truth |
|---|---|---|---|
| Time before a reserved job is retried | retry_after on the connection | 90 in the sample redis config; SQS uses the queue's Default Visibility Timeout | config/queue.php |
| Time a run may take | --timeout or #[Timeout(n)] | 60 s | worker, needs PCNTL |
| Fail on timeout instead of retrying | #[FailOnTimeout] | off | job class |
| Attempts | --tries or #[Tries(n)] | 1 | worker or job |
| Exceptions before failing | #[MaxExceptions(n)] | none | job class |
| Delay between attempts | #[Backoff([10, 30, 60])] or releaseUsingBackoff() | 0 | job class |
| Block instead of polling (redis) | block_for | null (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
| Knob | Product | Default | Effect on acknowledgment |
|---|---|---|---|
autoAck / no-ack | RabbitMQ | per client call | true means ack on send |
prefetch_count | RabbitMQ | 0 (no limit) | caps unacked deliveries |
consumer_timeout | RabbitMQ rabbitmq.conf | 1800000 ms | max time to hold an unacked delivery |
delivery-limit | RabbitMQ quorum queue policy | 20 (4.0+) | dead-letter or drop after N failed deliveries |
enable.auto.commit | Kafka consumer | true | background commit |
auto.commit.interval.ms | Kafka consumer | 5000 | autocommit cadence |
max.poll.records | Kafka consumer | 500 | records per poll |
max.poll.interval.ms | Kafka consumer | 300000 | max gap between polls |
session.timeout.ms | Kafka consumer (classic protocol) | 45000 | dead-member detection |
heartbeat.interval.ms | Kafka consumer (classic protocol) | 3000 | heartbeat cadence, at most a third of the session timeout |
auto.offset.reset | Kafka consumer | latest | start when there is no committed offset |
isolation.level | Kafka consumer | read_uncommitted | read_committed hides aborted transactional records |
group.instance.id | Kafka consumer | unset | static membership; a timed-out static member is reassigned only after the session timeout |
COUNT, BLOCK, NOACK, CLAIM | Redis XREADGROUP | none | read size, wait, skip the PEL, claim while reading |
min-idle-time | Redis XCLAIM/XAUTOCLAIM | required | which pending entries may be taken |
retry_after, block_for | Laravel connection | 90, null | reserved-job return time, blocking pop |
--timeout, --tries, --backoff | queue:work | 60, 1, released immediately | run limit, attempts, delay |
Error messages and exceptions you will catch Important
| Where | Message or class | Meaning | What to do |
|---|---|---|---|
| RabbitMQ | PRECONDITION_FAILED - unknown delivery tag 100 | you acked the same tag twice, an unknown tag, or acked on another channel | ack once, on the channel that received it |
| RabbitMQ | PRECONDITION_FAILED with "timed out waiting for a consumer acknowledgement of a delivery with delivery tag = N" | consumer_timeout fired | speed up, raise the timeout for the queue, or ack earlier |
| RabbitMQ | channel closed, deliveries requeued | channel or connection died | redelivery with redelivered=true; be idempotent |
| Kafka | CommitFailedException | the member left the group (missed max.poll.interval.ms) before committing | shorten work per poll; accept the redelivery |
| Kafka | rebalance, partitions revoked | another member now owns the partition | commit finished work in the revoke callback |
| Redis | NOGROUP | the stream or group does not exist | XGROUP CREATE ... MKSTREAM |
| Redis | XACK returns 0 | the id was not pending (already acked, or never delivered to the group) | harmless; check for double processing |
| Laravel | Illuminate\Queue\MaxAttemptsExceededException | attempts exhausted (often because of repeated timeouts) | raise Tries, fix the cause |
| Laravel | Illuminate\Queue\TimeoutExceededException | run 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
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Manual ack after the work | autoAck=false, DisableAutoCommit, XACK after the handler | No loss on a crash | Duplicates after a crash |
| Replace greedy autocommit | franz-go default, or AutoCommitMarks | Only finished work is committed | A little code |
| Commit in the revoke callback | OnPartitionsRevoked | Less rework at a rebalance | A 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
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Idempotent handler | upsert, natural key, ON CONFLICT DO NOTHING | Simplest | Only for operations that can be made idempotent |
| Inbox table in the same transaction | the AckAfterSideEffects snippets | Works for any side effect in your own database | One table, one insert per message |
| Idempotency key to the downstream API | pass the message id | Covers external effects | The API must support it |
3. A poison message loops forever Must-know
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Reject without requeue after the first redelivery | d.Redelivered check, basic.reject(false) | Stops the hot loop | A transient error on the second try also dead-letters |
| Quorum queue delivery limit | delivery-limit plus basic.reject(requeue=true) | Broker counts for you | Must use reject, not nack (4.3+) |
| Delivery counter check | XPENDING count versus a limit, then park | Works on Redis | You write the reaper |
| Retry topic and dead-letter topic | publish the record, then commit | Keeps the partition moving | More topics |
Tries, MaxExceptions, fail() | Laravel attributes | Built in | None |
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
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Raise the detector | consumer_timeout per queue; max.poll.interval.ms; retry_after | Fits legitimate long work | A real hang is detected later |
| Shrink the unit of work | lower max.poll.records, prefetch 1 | Each unit fits inside the detector | Lower throughput per round trip |
| Hand work to a pool and ack from the pool | worker pool, then MarkCommitRecords or d.Ack on the owning channel | Poll or heartbeat is never blocked | Ordering and ack-on-the-right-goroutine care |
| Split into steps | durable workflow | No single long delivery | More 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
| Failure | Retry? | Ack decision |
|---|---|---|
| Timeout, 5xx, deadlock, connection lost | Yes, with delay | RabbitMQ reject(requeue=true) or delayed queue; Redis leave pending; Laravel release($delay) or exception |
| Validation error, missing entity, unknown schema | No | RabbitMQ reject(requeue=false); Kafka dead-letter topic then commit; Redis dead-letter stream then XACK; Laravel fail() |
| Handler panic or OOM | Yes (the process is gone) | no ack was sent: the broker redelivers; the delivery count rises |
| The ack call itself fails | Treat as success of the work | the 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
| Workload | Ack timing | Window | Extra technique | Reason |
|---|---|---|---|---|
| Payments, ledger entries, stock | After side effects | Small (prefetch 1 to 10, one poll of tens of records) | Inbox table, per-key ordering | One duplicate or one loss costs money |
| Emails, notifications | After process | 10 to 50 | Idempotency key per recipient | A duplicate email is tolerable, a lost one is not |
| Metrics, logs, cache warm-up | Before process or auto | Large | None | Loss is cheaper than the round trips |
| Mixed fast and slow jobs on one queue | After process | Prefetch 1 for slow consumers | Separate queues per class of work | Fairness |
| High-throughput event pipeline | After process, batched | 100 to 300 (RabbitMQ), 500 (Kafka poll) | Commit per batch, AutoCommitMarks | Fewer ack round trips |
| Long-running work (minutes) | After process, with a raised timeout | 1 | Raise consumer_timeout or split into steps | The default detector is shorter than the work |
| Laravel app with the redis driver | Default (return from handle) | --tries, Backoff | retry_after above --timeout | The defaults are single-attempt |
| Broker | Pick this ack style | Because |
|---|---|---|
| RabbitMQ | Manual ack, prefetch 100 to 300, reject(false) plus DLX for permanent failures | Per-message control and the broker deletes on ack |
| Kafka | Manual commit after processing, per partition, AutoCommitMarks for throughput | One position per partition; a share group when you need per-record ack |
| Redis Streams | XACK after processing plus a reaper | No built-in redelivery |
Go
Before
Every broker has an "ack on receipt" shortcut. RabbitMQ: autoAck=true and no prefetch.
// 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.
// 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.
// 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.
// 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.
// 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.
// 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
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
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
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
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
// 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
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=3Broker 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
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
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
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
| Broker | Ack primitive | Timeout and redelivery | Details |
|---|---|---|---|
| NATS JetStream | consumer AckPolicy: AckExplicit (default), AckNone, AckAll | AckWait, then redelivery; MaxDeliver limits attempts (default -1); Backoff lists delays | Other Brokers |
| Amazon SQS | DeleteMessage | visibility timeout (default 30 s, 0 to 12 h) | Other Brokers |
| Pulsar, Google Pub/Sub | per-message ack | ack timeout / ack deadline | Other Brokers |
| Kafka share groups | per-record accept, release, reject | acquisition lock duration; delivery counting | KIP-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=truewith a 5 second interval is the default in the consumer configs; transactional consumers are told to setenable.auto.commit=falseandisolation.level=read_committedin the design doc's exactly-once section. - Redis recovery is a client job. The
XAUTOCLAIMreference describes a cursor-style scan of the PEL (0-0means the scan finished) and the limit of ten timesCOUNTentries 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 inconfig/queue.phpdefines it (SQS relies on the queue's Default Visibility Timeout instead), and the docs tie it to--timeoutto avoid double processing. laravel-queue-rabbitmq'srabbitmq:consumecommand 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.
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 -> commitWhat 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
| Load | What changes in acknowledgment |
|---|---|
| 1x (hundreds per minute) | One consumer, prefetch 1 (RabbitMQ), COUNT 10 (Redis), default Kafka poll; ack per message; simplest code |
| 10x | Prefetch 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 |
| 100x | Many 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-region | Per-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):
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 flightKafka (Apache Kafka 4.x, topic orders with 1 partition, group billing, consumer from kafka_after):
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):
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 2Laravel (redis driver, job that sleeps 120 s, retry_after 90, --timeout 60):
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 2Common misconceptions
| Belief | Reality |
|---|---|
| "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
| Topic | What to remember |
|---|---|
| Ack meaning | Ends the broker's duty; RabbitMQ deletes, Kafka moves the offset, Redis leaves the PEL |
| Default timing | Manual ack after processing, idempotent handler |
| Side effects | Commit the DB transaction with an inbox row, then ack |
| RabbitMQ | basic.ack, basic.nack, basic.reject, multiple, per-channel tags, redelivered |
| Quorum queues | delivery-limit 20, x-delivery-count, use basic.reject to count |
| Prefetch | 1 for slow or mixed work, 100 to 300 for fast; per consumer in RabbitMQ |
consumer_timeout | 30 min default; PRECONDITION_FAILED in 4.0; quorum queues only from 4.3 |
| Kafka commit | Commit the next offset after the work, per partition, in order |
| Kafka clocks | session.timeout.ms 45 s, heartbeat.interval.ms 3 s, max.poll.interval.ms 5 min, max.poll.records 500 |
| Redis recovery | XPENDING, XAUTOCLAIM, delivery counter; nothing redelivers by itself |
| Redis new | XNACK (8.8), XREADGROUP ... CLAIM (8.4), XACKDEL (8.2) |
| Laravel | return = ack, release = retry later, delete = forget, fail = never; --timeout below retry_after |
| Diagnose | owner, idle time, delivery count, per queue or group |
| Poison | count deliveries, then park; do not requeue forever |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — 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
| Term | Meaning |
|---|---|
| ack / acknowledgment | Consumer-to-broker signal that ends the broker's obligation to redeliver |
| nack | Negative acknowledgment: "could not process" (RabbitMQ basic.nack, extension to AMQP 0-9-1) |
| reject | RabbitMQ basic.reject: reject one delivery, with requeue |
| requeue | Put a rejected message back in the queue instead of dead-lettering or dropping it |
| delivery tag | Per-channel increasing integer that identifies a RabbitMQ delivery |
multiple | Flag that makes an ack or nack cover all outstanding tags up to and including this one |
auto-ack / no-ack | Broker treats the message as handled when it is sent |
| prefetch / QoS | Maximum unacked deliveries (basic.qos) |
| in-flight window | Messages delivered but not yet acknowledged |
redelivered | AMQP boolean set when a message is delivered again |
x-delivery-count | Quorum-queue header with the number of failed delivery attempts |
delivery-limit | Quorum-queue limit (default 20) after which a message is dead-lettered or dropped |
consumer_timeout | RabbitMQ delivery acknowledgement timeout, default 30 minutes |
| committed offset | The position a Kafka group stored for a partition; the next record to read |
| position | The offset of the next record poll() returns in a consumer |
enable.auto.commit | Kafka consumer setting for background offset commits (default true) |
max.poll.records | Kafka cap on records per poll() (default 500) |
max.poll.interval.ms | Kafka limit between polls before the member is considered failed (default 300000) |
session.timeout.ms | Kafka limit between heartbeats before the member is removed (default 45000) |
CommitFailedException | Kafka error when a commit comes from a member that already left the group |
| rebalance | Reassignment of partitions among group members |
| share group | Kafka queue-style group with per-record acknowledgment (KIP-932) |
| PEL | Pending entries list of a Redis consumer group |
XACK | Remove entry ids from the PEL |
XPENDING | Inspect the PEL: summary or per entry with owner, idle time, delivery count |
XCLAIM / XAUTOCLAIM | Transfer ownership of idle pending entries; XAUTOCLAIM scans with a cursor |
XNACK | Release pending entries back to the group without acking (Redis 8.8+) |
| idle time | Milliseconds since an entry was last delivered |
retry_after | Laravel connection setting: seconds before a reserved job returns to the queue |
--timeout | Laravel worker option: maximum seconds a job may run |
block_for | Laravel redis option: seconds to block waiting for a job |
| ack-after-side-effects | Acknowledging only after the database commit that holds the effect and the dedup row |
| poison message | A message that fails every time it is processed |
| visibility timeout | SQS equivalent of a reserved-job timeout |
AckWait / MaxDeliver | NATS JetStream redelivery delay and attempt limit |
References
- RabbitMQ, "Consumer Acknowledgements and Publisher Confirms". rabbitmq.com
- RabbitMQ, "Consumers" (delivery acknowledgement timeout), "Consumer Prefetch", "Negative Acknowledgements", "Quorum Queues" (poison message handling). consumers, prefetch, nack, quorum queues
- Apache Kafka documentation, "Design" (Consumer Position, Message Delivery Semantics). kafka.apache.org
- Apache Kafka documentation, "Consumer Configs";
KafkaConsumerJavadoc, "Automatic Offset Committing"; "Operations" (checking consumer position). kafka.apache.org - Apache Kafka 4.2 and 4.4 release announcements; KIP-932 "Queues for Kafka". KIP-932
- Redis commands: XACK, XPENDING, XCLAIM, XAUTOCLAIM, XREADGROUP, XNACK
- Redis, "Redis Streams" (consumer groups, recovering from failures). redis.io
- Laravel 13 documentation: Queues, Redis; framework source
Illuminate\Queue\RedisQueue,LuaScripts,Worker(13.x branch on GitHub) - Packages: vladimir-yuldashev/laravel-queue-rabbitmq, mateusjunges/laravel-kafka manual commit, phpredis
- NATS, "JetStream Consumers". docs.nats.io; Amazon SQS, "Visibility timeout". docs.aws.amazon.com
- Go packages: amqp091-go, franz-go kgo, go-redis