Competing Consumers & Scaling Consumers
"Create multiple Competing Consumers on a single channel so that the consumers can process multiple messages concurrently." — Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, "Competing Consumers" (enterpriseintegrationpatterns.com)
Summary: adding consumers is how a messaging system scales its work, and each broker has a different unit that limits it: a message in RabbitMQ, a partition in Kafka, an entry in a Redis Streams group, a process in Laravel. Focus: the four scaling dimensions (consumers per queue, partitions, concurrency inside a consumer, batch size), prefetch and fair dispatch, Kafka consumer groups and rebalancing (eager, cooperative, static, KIP-848, share groups), RabbitMQ single active consumer and priorities, Redis dead-consumer recovery, Go worker pools with graceful shutdown, Laravel workers and Horizon, autoscaling on lag with KEDA. Learning goal: size a consumer fleet with arithmetic instead of guessing, pick the right prefetch and partition count, deploy without rebalance storms or lost work, and know which signal to autoscale on for each broker.
This page owns scaling the consumer side. Several neighbours hold the pieces it builds on, and each gets one sentence here plus a link. Acks, basic.qos semantics and offset commits are taught in Message Acknowledgment. Per-key ordering and partition keys are in Ordering & Partitioning, and lag as a flow-control signal is in Backpressure & Flow Control. Duplicates after a rebalance are handled by Idempotent Consumers & the Inbox Pattern, and poison messages that block a worker go to the Dead-Letter Queue. The EIP endpoint patterns around this one (Polling vs Event-Driven Consumer, Message Dispatcher) are in Consumer & Endpoint Patterns.
Page map
| If you are looking for | Go to |
|---|---|
| The whole topic in three tables | Everything in one minute |
| Why one consumer is not enough, and what scaling costs | Why competing consumers exist |
| EIP 2003, KIP-62, KIP-429, KIP-345, KIP-848, KIP-932 | Where it comes from |
| Competing consumers, scaling dimensions, prefetch, consumer groups, rebalancing, static membership, KIP-848, share groups, single active consumer, Redis groups, worker pools, shutdown, autoscaling | Concept catalogue |
| Timers, assignors, error names, PEL internals, Laravel flags | Mechanics |
| How many workers, what prefetch, how many partitions, how long to drain | Capacity math |
| Bounded pool, per-key pool, errgroup, SIGTERM in Go | Go |
queue:work, Supervisor, Horizon balancing | Laravel |
| The same mechanism on RabbitMQ, Kafka and Redis Streams | Broker differences |
| Prefetch too high, too many partitions, deploy storms, duplicates, hot keys | Solving the classic problems |
| Which design for which workload | Choosing |
| From one Laravel app to a multi-region fleet | In architecture |
| Scale 1 → 8 consumers on each broker (expected, not run) | Lab |
| Beliefs to drop, one-line rules, every term | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
Table 1: what each broker hands out, and the ceiling it implies.
| Broker | Unit handed to one consumer | Who decides | Max useful consumers | Order kept |
|---|---|---|---|---|
| RabbitMQ classic / quorum queue | One message (delivery) | Broker, round-robin among consumers with free prefetch | Queue, node and downstream capacity | Only with one consumer, or single active consumer |
| Kafka consumer group | A whole partition | Group leader (classic) or group coordinator (KIP-848) | Number of partitions | Per partition |
| Kafka share group (KIP-932) | Batches of records, each acked alone | Broker, with an acquisition lock | Not bound to partitions | No |
| Redis Streams consumer group | One entry, recorded in the group's PEL | Whoever calls XREADGROUP first | One stream lives on one shard; downstream capacity | No (with more than one consumer) |
Laravel queue:work (redis, database, sqs) | One job | First worker to pop or lock it | Processes you run | No |
| NATS JetStream | Batch requested by shared pull subscribers | Server and shared consumer state | Outstanding request and ack limits | Parallel handlers have no completion-order guarantee |
| Pulsar | Message in Shared; key in Key_Shared | Subscription dispatcher | Broker capacity; key distribution for Key_Shared | Shared unordered; Key_Shared serial per key with appropriate batching |
| SQS | Receive batch, hidden during visibility timeout | Service | Service quotas, downstream capacity; FIFO group count | FIFO orders within MessageGroupId; standard does not |
Table 2: the four scaling dimensions.
| Dimension | Knob | Raises | Cost / limit |
|---|---|---|---|
| Consumers per queue/group | Replicas, numprocs, Horizon maxProcesses | Throughput, availability | Kafka: capped by partitions; more connections; more downstream load |
| Partitions (Kafka) / streams (Redis) | --partitions, number of stream keys | The ceiling for consumers | Hard to change later (key mapping moves); more files, more rebalance work |
| Concurrency inside one consumer | Goroutines, threads, prefetch | Throughput per process | Ordering per partition, memory, shared resources |
| Batch size | max.poll.records, COUNT, prefetch | Fewer round trips | Longer redelivery on crash; longer time between polls |
Table 3: the knobs that matter most.
| Knob | Broker / tool | Default | Rule of thumb |
|---|---|---|---|
basic.qos prefetch count | RabbitMQ | 0 = unlimited (per consumer) | 1 for slow uneven jobs; concurrency × (1 + RTT/service time) for fast ones; docs: 100–300 usually optimal for throughput |
x-single-active-consumer | RabbitMQ | off | Ordered processing with automatic failover |
x-priority | RabbitMQ | 0 | Prefer local or bigger consumers |
session.timeout.ms | Kafka classic protocol | 45000 | Raise with static membership to survive restarts |
heartbeat.interval.ms | Kafka classic protocol | 3000 | No more than 1/3 of the session timeout |
max.poll.interval.ms | Kafka | 300000 | Larger than the slowest batch |
max.poll.records | Kafka Java client | 500 | Lower it when records are slow |
group.instance.id | Kafka | null (dynamic) | Stable pod name for static membership |
group.protocol | Kafka 4.x clients | classic | consumer for the KIP-848 protocol (broker 4.0+) |
XAUTOCLAIM min-idle-time | Redis Streams | none | Longer than the slowest normal job |
--max-jobs, --max-time, --memory | Laravel queue:work | unlimited, unlimited, 128 MB | Recycle long-lived PHP workers |
balance | Laravel Horizon | auto in the default config | auto scales per queue between minProcesses and maxProcesses |
Why competing consumers exist
A producer can publish faster than one consumer can process, and the gap grows a backlog. EIP addresses this by putting several readers on the same point-to-point channel: the messaging system decides who receives each item. A publish-subscribe channel has a different purpose: separate subscriptions receive separate copies rather than dividing one workload.
Scaling the consumer side is a trade, not a free lunch:
| One consumer | Many competing consumers |
|---|---|
| Serial handler preserves initial delivery order; retries still matter | Order only per key (partition, lane) or with a single active consumer |
| No coordination | Broker or group coordinator must assign work; rebalances happen |
| Throughput capped by one process | Throughput scales until the broker's unit of parallelism or a downstream runs out |
| A crash stops everything | A crash redelivers that consumer's in-flight work to the others |
| No multi-member reassignment; crash duplicates still possible | Reassignment during a rebalance or a crash produces duplicates: handlers must be idempotent |
| Simple capacity question | Capacity becomes arithmetic: Little's law, prefetch, partitions |
The everyday picture used through this page. A supermarket with one queue of shoppers and several tills. Opening tills is competing consumers. One shared queue that sends the next shopper to whichever till frees up is RabbitMQ with prefetch 1. Letting each till pull five shoppers into its own lane is prefetch 5: faster when shoppers are quick, unfair when one has a full trolley. Assigning shoppers to tills by surname initial is Kafka: no till can steal from another, but all of one family's items go through one till in order. Closing a till and making every shopper re-sort themselves is an eager rebalance; moving only that till's shoppers is cooperative.
Three common misunderstandings, up front
- "Doubling consumers doubles throughput." Only until the ceiling: Kafka partitions, the database pool, a third-party rate limit, a hot key that serialises everything on one lane.
- "The queue is FIFO, so processing is ordered." Delivery is ordered; completion is not. Two consumers finish in any order.
- "A rebalance means something crashed." Deploys, scaling and handlers that exceed their progress budget can trigger one. The question is how long the pause is and how much work is redone.
Where it comes from
EIP, 2003. Hohpe and Woolf place Competing Consumers among Messaging Endpoints. Several receivers share one point-to-point channel; the messaging implementation assigns each delivery to a receiver.
The Kafka note. Their later Kafka example explains why the name can be misleading: assignment happens at partition granularity before reading begins. An idle member cannot steal individual records from a busy member, and useful membership is bounded by the assigned partitions.
KIP-62 (Kafka 0.10.1). Background heartbeats separated process liveness from application progress. The Java consumer uses max.poll.interval.ms as its processing and rebalance budget, so a live but stalled handler can still lose group membership.
KIP-429 (Kafka 2.4). Incremental cooperative rebalancing lets members retain unchanged assignments instead of revoking all partitions during each group change.
KIP-345. Static membership gives a returning instance a stable identity, reducing unnecessary partition movement and state reconstruction during short interruptions.
KIP-848 (GA in Kafka 4.0). The new consumer protocol moves assignment coordination to the broker and reconciles members incrementally through heartbeats. It is distinct from selecting cooperative-sticky in the classic protocol.
KIP-932 (production-ready in Kafka 4.2). Share groups add queue-style acquisition and individual acknowledgement of records. This enables independent work-item concurrency beyond the partition count without over-partitioning for worker count alone.
RabbitMQ and Redis. RabbitMQ's work-queue tutorial demonstrates round-robin dispatch and prefetch-based fairness; its Consumers guide covers single active consumer and priority. Redis added XAUTOCLAIM in 6.2.0. Laravel scales queue execution by running additional worker processes.
Concept catalogue
Competing consumers on one queue Must-know
In plain words: several identical workers read the same queue; each message is handed to exactly one of them.
Common misunderstanding: "Each consumer gets a copy." That is publish-subscribe (fan-out). Competing consumers split the stream of work; fan-out duplicates it. On RabbitMQ the difference is one queue with N consumers versus N queues bound to one exchange; on Kafka it is N members of one group versus N groups.
Definition: N consumers attached to a single point-to-point channel; the messaging system delivers each message to one of them and redelivers it to another if the first does not acknowledge it.
The picture shows the RabbitMQ shape. Messages 1 to 4 have gone round-robin. Consumer 1 is at its prefetch limit, so the broker skips it. Consumer 3 crashed with message 3 unacked, and closing its channel requeued that message for someone else.
Queue "invoices" Consumer C1 (prefetch 1) Consumer C2 (prefetch 1)
1 m1 m2 m3 m4 m5
2 deliver m1 -> C1 handle m1 (2 s)
3 deliver m2 -> C2 handle m2 (50 ms)
4 ack m2
5 deliver m3 -> C2 handle m3, ack
6 deliver m4 -> C2 handle m4, ack
7 ack m1
8 deliver m5 -> C1 handle m5
-- prefetch 1: the fast consumer takes the work the slow one cannotReal scenarios: invoice PDF rendering behind a checkout; image thumbnails after upload; e-mail and SMS sending; webhook delivery to customers; nightly report generation split into one message per tenant; search-index updates.
Which primitive provides it:
| Broker | Primitive | What decides the receiver |
|---|---|---|
| RabbitMQ | Several basic.consume on one queue | Round-robin among consumers that are not blocked by prefetch; priorities change it |
| Kafka | Several members with the same group.id | Partition assignment (one owner per partition) |
| Kafka 4.2+ | Several members of a share group | Broker acquisition locks per record batch |
| Redis Streams | Several XREADGROUP callers with different consumer names | Whoever reads first; the group's last-delivered ID advances |
| Laravel | Several queue:work processes | Atomic pop (redis Lua script) or row lock (database driver) |
| SQS | Several ReceiveMessage callers | Visibility timeout hides a message from others |
Fix / how to use it: the shared database table is the simplest competing-consumer queue, and it is what Laravel's database driver does; see Laravel Queue Internals. Go and Laravel versions for each broker are in Go, Laravel and Broker differences.
-- PostgreSQL teaching schema with timestamp columns, not Laravel's exact jobs schema.
-- The caller binds $1 to the selected ID before committing the claim.
BEGIN;
SELECT id, payload
FROM jobs
WHERE queue = 'invoices' AND reserved_at IS NULL AND available_at <= now()
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED;
UPDATE jobs SET reserved_at = now(), attempts = attempts + 1 WHERE id = $1;
COMMIT;
-- worker processes the job, then: DELETE FROM jobs WHERE id = $1;Scaling dimensions Must-know
In plain words: there are four dials: how many consumers, how many partitions (or streams), how much concurrency inside each consumer, and how many messages each fetch brings. Throughput is the product, up to whichever dial hits its limit first.
Common misunderstanding: "Scaling means more pods." Often the cheapest step is more concurrency inside an I/O-bound Go consumer, or a larger batch. The dangerous step is the one that silently breaks ordering: concurrency inside a Kafka partition.
Definition: consumer throughput ≈ min(instances × concurrency per instance / service time, broker ceiling, downstream ceiling), where the broker ceiling is partitions for Kafka and the queue's own dispatch rate for RabbitMQ.
Change Before After What moved the ceiling
1 1 pod, 1 goroutine, 50 ms/msg 20 msg/s
2 1 pod, 16 goroutines 20 ~300 concurrency (I/O-bound work)
3 4 pods x 16 300 ~1,200 instances
4 Kafka: 4 pods, 6 partitions -> 12 pods 1,200 ~1,800 only 6 pods get partitions
5 Postgres pool = 50 connections ~1,800 ~1,000 downstream: pool wait dominatesReal scenarios: a CPU-bound image resize (more pods, not more goroutines); an HTTP-bound webhook sender (more goroutines); a Kafka topic created with 3 partitions that now needs 12 consumers; a PHP worker fleet that saturates MySQL's max_connections.
| Dimension | RabbitMQ | Kafka | Redis Streams | Laravel |
|---|---|---|---|---|
| Instances | Consumers on the queue | Group members ≤ partitions | Consumer names in the group | queue:work processes |
| Partitioning | Several queues + consistent-hash exchange | Partitions per topic | Several stream keys | Several named queues |
| Concurrency inside | Prefetch + goroutines/threads | Goroutines per partition, or ordered per key | COUNT + goroutines | One job per process |
| Batch | Prefetch | max.poll.records, fetch.min.bytes | COUNT | One job per pop |
Fix: decide the ceiling first. For Kafka, choose partitions for the peak consumer count you will need (capacity math). For everything else, cap the downstream (database pool, rate limit) and size the fleet to it.
Prefetch and fair dispatch Must-know
In plain words: prefetch is how many unacknowledged messages the broker may push to one consumer before waiting. Small prefetch is fair; large prefetch is fast but can leave one consumer holding a pile of work while others are idle.
Common misunderstanding: "Prefetch 1000 is just a performance setting." For a PHP worker that runs one job at a time, it parks 999 messages in a busy process. If that process crashes, all 1000 are redelivered (duplicates for any it had half-processed), and during a slow job the other workers starve. The rabbitmq:consume command of the Laravel RabbitMQ package defaults to --prefetch-count=1000.
Definition: RabbitMQ applies basic.qos(prefetch_count) separately to consumers created on that channel when global=false; AMQP 0-9-1 originally defines a shared channel limit. Zero removes this limit. RabbitMQ 4.3 deprecates global QoS and disables it by default.
Round-robin distribution alone does not account for handler duration. Prefetch 1 makes the next delivery wait for the previous acknowledgement, which improves fairness for uneven jobs but leaves a worker waiting during network round trips. RabbitMQ recommends benchmarking and notes that counts around 100–300 often suit throughput-oriented workloads; that range is not a universal setting for serial, slow PHP jobs.
Two consumers, prefetch 10, jobs alternate heavy (10 s) and light (10 ms)
1 C1 receives m1 m3 m5 ... m19 (all heavy) C2 receives m2 m4 ... m20 (all light)
2 C1 busy for 100 s C2 done in 0.1 s, then idle
3 queue empty, C2 idle, C1 still has 9 heavy jobs buffered
-- same jobs with prefetch 1: each takes the next job when free, total ~50 sReal scenarios: mixed short and long jobs on one queue (PDF reports next to e-mails); a consumer across a WAN with 80 ms round trips (prefetch 1 leaves the worker waiting between jobs); a Go consumer with 32 goroutines and prefetch 1 (31 idle goroutines).
| Broker | Equivalent of prefetch | Default |
|---|---|---|
| RabbitMQ | basic.qos prefetch count per consumer | 0 (unlimited) unless default_consumer_prefetch is set |
| Kafka | max.poll.records per poll, plus fetch.max.bytes / max.partition.fetch.bytes buffers | 500 records (Java client) |
| Redis Streams | COUNT on XREADGROUP | Unlimited when omitted |
| Laravel redis/database | One job per pop | Fixed |
| SQS | MaxNumberOfMessages per receive (1–10) | 1 |
Fix: match prefetch to the concurrency of the consumer, plus enough to cover the round trip (the formula is in capacity math). In Go: ch.Qos(workers, 0, false); in Laravel with RabbitMQ: rabbitmq:consume --prefetch-count=1 for slow jobs.
Consumer groups and the partition ceiling Must-know
In plain words: in Kafka a group of consumers splits a topic's partitions among themselves, and a partition belongs to one member at a time. More members than partitions means idle members.
Common misunderstanding: "Kafka load-balances messages like RabbitMQ." It assigns partitions. An idle partition owner cannot consume a different member's hot partition; adding processes cannot split that partition's ordered workload.
Definition: consumers with the same group.id form a consumer group; a group coordinator (a broker) tracks membership, and an assignor maps each partition to exactly one member. Each group keeps its own committed offsets, so two groups on one topic each see every record (fan-out between groups, competition within one).
Topic "orders": 6 partitions. Group "billing".
1 members: A -> A: P0..P5
2 + B -> A: P0 P1 P2 B: P3 P4 P5
3 + C -> A: P0 P1 B: P2 P3 C: P4 P5
4 + D E F -> one partition each
5 + G -> G: (nothing) -- idle, but still part of every rebalanceReal scenarios: a billing service that needs 12 consumers on a 6-partition topic; a topic with 3 partitions where one key (a big tenant) is 70% of the traffic; KEDA scaling a deployment to 20 replicas on a 10-partition topic (it will not, by default).
What provides it: Kafka consumer groups; Redis Streams has groups but no partitions, so any consumer can take any entry; RabbitMQ has no groups (the queue itself is the shared cursor); Pulsar's Shared and Key_Shared subscriptions and NATS JetStream pull consumers are not partition-bound.
Fix: plan partitions for peak consumers with headroom; when a workload is really a queue of independent tasks, use a Kafka share group (below) or RabbitMQ instead of over-partitioning.
Rebalancing: eager vs cooperative Must-know
In plain words: when a member joins or leaves, the group reshuffles partitions. The old way stops everybody while it reshuffles; the cooperative way only moves the partitions that change owner.
Common misunderstanding: "Cooperative rebalancing means no pause." Partitions that move still pause from revocation until the new owner starts, and the new owner restarts from the last committed offset, so work whose offset was not committed before handoff may replay.
Definition: with the classic protocol, members send JoinGroup, a leader runs the assignor, and SyncGroup distributes the result. Under the eager protocol (Range, RoundRobin, Sticky assignors) every member revokes all partitions before rejoining. Under the cooperative protocol (CooperativeSticky, KIP-429) members keep the partitions they will still own and give up only the ones that move, which can take a second rebalance round. Under KIP-848 the coordinator computes the target assignment and revokes and assigns incrementally per member through heartbeats.
The picture compares whole-group revocation with incremental handoff. Only P2 and P5 move in the incremental example. KIP-429 uses classic group rounds and a member-side assignor; KIP-848 uses broker coordination and heartbeats. Their shared incremental property does not make them the same protocol.
Rebalance storm during a rolling deploy of 6 pods, eager protocol, dynamic members
1 pod-1 stops -> rebalance #1 (all partitions revoked, 5 members)
2 pod-1' starts -> rebalance #2 (all revoked again, 6 members)
3 pod-2 stops -> rebalance #3
4 ... -> 12 stop-the-world rebalances for one deploy
5 a handler that takes 6 min > max.poll.interval.ms (5 min) -> member evicted -> rebalance #13
-- fix: cooperative-sticky + static membership + bounded batchesReal scenarios: consumer lag graph shows a sawtooth at every deploy; Kafka Streams applications with large state stores re-restoring after each rebalance; a consumer that logs CommitFailedException because its partitions were reassigned while it was processing.
Assignors:
| Assignor | Protocol | Behaviour | Note |
|---|---|---|---|
RangeAssignor | Eager | Per topic, contiguous ranges | Default first choice in the Java client list; uneven across topics |
RoundRobinAssignor | Eager | Partitions dealt round-robin | Even counts, moves many partitions |
StickyAssignor | Eager | Balanced, keeps existing assignments | Still revokes all during the rebalance |
CooperativeStickyAssignor | Cooperative | Sticky + incremental | Java client default list is [RangeAssignor, CooperativeStickyAssignor] to allow a rolling upgrade |
Server-side uniform / range | KIP-848 (group.protocol=consumer) | Coordinator assigns | Chosen with group.remote.assignor |
The Java client lists RangeAssignor before CooperativeStickyAssignor by default. After compatible members are deployed, removing RangeAssignor lets the group select cooperative-sticky. librdkafka defaults to range,roundrobin; franz-go supports eager and cooperative balancers. Check every member's assignor list before a rolling migration.
Fix: cooperative-sticky everywhere you can (kgo.CooperativeStickyBalancer(), RebalanceStrategy::COOPERATIVE_STICKY), commit before giving partitions up, and keep batches short enough to finish within the rebalance timeout.
Static membership Important
In plain words: give each consumer a fixed name. If it restarts quickly, Kafka keeps its partitions waiting for it instead of reshuffling the whole group.
Common misunderstanding: "Static membership removes rebalances." It removes the rebalances caused by short restarts. A member that stays away longer than the session timeout is removed, and scaling out still rebalances. It also delays failover: a dead static member's partitions sit unconsumed for the whole session timeout.
Definition: group.instance.id identifies a static member independently of its transient connection. A unique, stable identity plus an adequate session timeout can preserve assignment across a brief restart. Concurrent instances must not reuse it: a duplicate identity can produce FENCED_INSTANCE_ID.
Static member billing-2, session.timeout.ms = 120000
1 t=0 pod billing-2 receives SIGTERM, commits, closes (no LeaveGroup for static members)
2 t=0..40 P2 P3 are not consumed; lag on them grows; others unaffected
3 t=40 s new pod billing-2 joins with the same group.instance.id
4 coordinator hands back P2 P3; no rebalance for the group
-- if the pod had not returned by t=120 s, the coordinator would remove it and rebalanceReal scenarios: StatefulSet consumers whose pod names are stable (billing-0, billing-1); Kafka Streams with big local state; rolling deploys of 50-member groups.
Fix: set group.instance.id from the pod name (StatefulSet ordinals are stable; Deployment pod names are not), raise the session timeout to cover a restart, and alert on per-partition lag so a dead static member is noticed.
KIP-848: the broker-side group protocol Important
In plain words: in Kafka 4.0+ the broker, not the client, computes who owns which partition, and changes roll out member by member with no group-wide pause.
Common misunderstanding: "It is on by default." For the Java client and librdkafka, group.protocol still defaults to classic; you opt in with group.protocol=consumer. franz-go opts in with kgo.ServerSideBalancer(), and its docs recommend Kafka 4.3+ for it.
Definition: the consumer group protocol uses ConsumerGroupHeartbeat to coordinate member state and incremental assignment. The broker coordinator determines the target assignment. With group.protocol=consumer, client session.timeout.ms and heartbeat.interval.ms do not configure these timers; broker group.consumer.session.timeout.ms and group.consumer.heartbeat.interval.ms do.
KIP-848, member C joins a group of A (P0 P1 P2) and B (P3 P4 P5)
1 C heartbeats with its subscription
2 coordinator computes target: A {P0 P1} B {P3 P4} C {P2 P5}
3 A's next heartbeat response: revoke P2 (A keeps consuming P0 P1)
4 B's next heartbeat response: revoke P5 (B keeps consuming P3 P4)
5 A and B ack the revocation in later heartbeats
6 C's heartbeat response: assigned P2 P5Fix: upgrade brokers to 4.x, set group.protocol=consumer on clients, and tune timers on the broker (group.consumer.*), not the client.
Share groups (KIP-932) Important
In plain words: a Kafka group that behaves like a queue. Any member can get records from any partition, each record is acked or released on its own, and you can have more members than partitions.
Common misunderstanding: "Share groups replace consumer groups." They give up per-partition ordering and offset-based replay positions per member to get queue semantics. Event processing that needs order stays on consumer groups.
Definition: share-group members acquire records under time-limited locks and settle them individually. delivery.count.limit bounds delivery attempts. franz-go exposes kgo.ShareGroup and per-record Ack(kgo.AckAccept / AckRelease / AckReject / AckRenew). This is a separate delivery model, not a new partition assignor.
Share group "thumbnail-workers", topic with 2 partitions, 6 members
1 member 1 acquires P0 offsets 100-109 (lock 30 s)
2 member 2 acquires P0 offsets 110-119
3 member 3 acquires P1 offsets 40-49
4 member 1 acks 100-108 ACCEPT, 109 RELEASE (transient error)
5 offset 109 becomes available again, delivery count = 2
6 member 4 acquires 109 and accepts itFix: use share groups for independent work items on Kafka 4.2+ (thumbnails, notifications, crawl jobs) instead of creating 200 partitions; keep consumer groups for ordered event streams. The franz-go version is in Broker differences: Kafka.
Single active consumer and consumer priorities (RabbitMQ) Important
In plain words: several consumers register on a queue, but only one receives; the rest wait as hot standbys. Priorities decide who is preferred.
Common misunderstanding: "An exclusive consumer does the same." An exclusive consumer refuses others; when it dies, nobody is waiting, and a new consumer must notice and subscribe. Single active consumer keeps the standbys registered and fails over automatically.
Definition: set x-single-active-consumer: true when declaring a classic or quorum queue. Registered standbys replace a disconnected or cancelled active consumer; SAC cannot be enabled through a policy. Ordinary x-priority consumers receive work before lower-priority consumers while eligible. With quorum SAC, a higher-priority newcomer can take over after the active consumer drains its unacknowledged deliveries; classic SAC does not offer that priority takeover rule.
Queue ledger.postings (quorum, x-single-active-consumer), prefetch 1
1 C1 (prio 0) registers -> active
2 C2 (prio 0) registers -> waiting
3 C3 (prio 10, same zone as the leader) registers -> queue stops delivering to C1
4 C1 acks its last message -> C3 becomes active
5 C3's pod is killed -> C1 or C2 becomes active, processing continues in orderReal scenarios: ledger postings per account queue that must stay ordered; a sequence of state updates to one external system that cannot handle concurrency; preferring consumers in the same availability zone as the queue leader.
Fix: Go code in Broker differences: RabbitMQ; for ordered parallelism, many SAC queues behind a consistent-hash exchange (see Ordering & Partitioning).
Redis Streams consumer groups and dead consumers Important
In plain words: a Redis consumer group gives each entry to one named consumer and remembers it in a pending list until acked. If that consumer dies, the entry stays pending until someone claims it.
Common misunderstanding: "Redis redelivers unacked entries automatically, like RabbitMQ." It does not. A dead consumer's entries stay in its pending entries list (PEL) until explicitly recovered or removed. This chapter uses the Redis 6.2+ XAUTOCLAIM recovery path; see Redis Streams for newer version-specific claim options.
Definition: XREADGROUP divides new stream entries between group members and tracks unacknowledged ownership in the PEL. XAUTOCLAIM scans for entries idle beyond min-idle-time and transfers them to the caller, resetting idle time and normally increasing the delivery counter. XINFO CONSUMERS reports pending entries and interaction timestamps; Redis 7.2 adds inactive. One stream key remains on one Redis Cluster shard, so more readers do not partition its storage.
Stream jobs, group workers, consumers w-1 and w-2
1 w-1: XREADGROUP ... > -> 1700-0, 1700-1 (PEL: w-1 holds both)
2 w-1 is OOM-killed
3 w-2 keeps reading new entries; 1700-0 and 1700-1 stay pending, idle grows
4 reaper: XAUTOCLAIM jobs workers reaper 60000 0-0 COUNT 100
5 -> 1700-0, 1700-1 now owned by reaper, delivery count 2, processed and XACKed
6 XINFO CONSUMERS shows w-1 with pending 0 -> XGROUP DELCONSUMER jobs workers w-1Real scenarios: workers named by random IDs leave hundreds of stale consumer names; a deploy kills consumers mid-batch and entries are stuck; a single hot stream on one Redis Cluster shard saturates that shard's CPU.
Fix: stable consumer names, a reaper with XAUTOCLAIM (Go and Laravel below), a delivery-count cap that parks poison entries, and N stream keys (jobs:{0} … jobs:{N-1}) when one shard is not enough.
Concurrency inside a consumer and per-key serialisation Must-know
In plain words: one consumer process can run many messages at once, but it needs a bound, and if order matters per customer or per order, messages with the same key must run one after another.
Common misunderstanding: "go handle(msg) per message is fine, goroutines are cheap." With no bound, a backlog turns into a million concurrent database calls; with no key affinity, two updates for the same order race.
Definition: a bounded worker pool caps active handlers using a semaphore or errgroup.SetLimit; submitting more work waits for a slot. A keyed pool hashes each message key to one of N lanes and runs one handler at a time per lane. Different keys may collide and share a lane, trading throughput for bounded memory and concurrency.
Keyed pool, 4 lanes; messages for order-7 hash to lane 2
1 lane 2: order-7 "created" lane 0: order-3 "paid" lane 1: order-9 "created"
2 lane 2: order-7 "paid" (waits behind "created")
3 lane 2: order-7 "shipped" lane 3: order-12 "created"
-- order-7 events run in order; other orders proceed in parallel
-- a slow order-7 blocks only lane 2 (and any other key hashed there)Real scenarios: a Kafka consumer owning 2 partitions but needing 64-way I/O concurrency; a webhook sender that must not deliver "shipped" before "paid" for one order; a consumer committing offsets only after every record below them is done.
Fix: pool.Go (semaphore), keyed.Pool (per-key lanes) and errgroup with SetLimit in Go. For Kafka, commit an offset only when every lower offset in that partition is done (process a batch, Wait, then commit).
Graceful shutdown Must-know
In plain words: when the platform says "stop", stop taking new messages, finish or hand back the ones in hand, record what was finished, then exit before you are killed.
Common misunderstanding: "At-least-once means I do not need a clean shutdown." With durable messages and retention sufficient for recovery, unacknowledged work can be redelivered, but an unclean stop replays work in flight (duplicates, double e-mails), triggers a session-timeout rebalance on Kafka, and leaves Redis entries pending until a reaper finds them.
Definition: the shutdown order is (1) stop fetching (basic.cancel, stop polling, stop XREADGROUP), (2) give back buffered but unstarted messages (Nack with requeue, or simply do not commit them), (3) wait for in-flight handlers with a deadline, (4) ack / commit / XACK, (5) leave the group and close the connection. In Go, signal.NotifyContext turns SIGTERM into a cancelled context. In Kubernetes the deadline must be shorter than terminationGracePeriodSeconds (30 s by default), after which the kubelet sends SIGKILL.
The diagram shows both halves. The top row is the steady state: the fetch loop blocks on the semaphore, which is the backpressure. The bottom row is the shutdown order and the two deadlines.
Pod receives SIGTERM, terminationGracePeriodSeconds = 60, drain deadline = 45 s
1 t=0 ctx cancelled; fetch loop exits; ch.Cancel(tag) / stop polling
2 t=0 3 buffered deliveries nacked with requeue -> other pods get them
3 t=0..12 8 in-flight handlers finish and ack
4 t=12 Kafka: commit offsets, leave group; Redis: XACK, DELCONSUMER if PEL empty
5 t=12 connection closed, exit 0
-- a handler still running at t=45 is abandoned; its message is redeliveredFix: the RabbitMQ consumer in Go implements this order. Laravel workers do it for you: on SIGTERM queue:work finishes the current job, php artisan queue:restart asks every worker to exit after its current job, and Supervisor's stopwaitsecs must exceed the longest job.
Autoscaling signals Important
In plain words: scale consumers on how much work is waiting, not on CPU. An I/O-bound consumer with a huge backlog can show 5% CPU.
Common misunderstanding: "HPA on CPU works for workers." It scales the wrong way for I/O-bound consumers and cannot scale from zero. Queue depth, consumer lag and the age of the oldest message are the signals.
Definition: three signals, each per broker:
| Signal | Meaning | RabbitMQ | Kafka | Redis Streams | Laravel |
|---|---|---|---|---|---|
| Depth / lag | Work waiting | messages_ready (+ unacked) | Consumer lag = log-end offset − committed offset, per partition | Group lag (XINFO GROUPS), PEL size | Redis list length, jobs table rows |
| Rate | Arrival vs completion | Publish rate vs deliver/get rate | Records-in rate vs records-consumed rate | XADD rate vs XACK rate | Horizon throughput |
| Age of oldest message | Latency the user feels | Head message timestamp (needs a header) | Timestamp of the record at the committed offset ("time lag") | Entry ID is a millisecond timestamp | Horizon wait time |
KEDA has a scaler per broker. Kafka uses lagThreshold as a target backlog per replica and normally caps replicas at the partition count. RabbitMQ supports QueueLength, MessageRate, DeliverGetRate, PublishedToDeliveredRatio and ExpectedQueueConsumptionTime; including unacked messages requires the HTTP API. Redis Streams exposes pendingEntriesCount, streamLength or lagCount. Laravel's redis driver stores ready jobs in lists and uses the Redis list scaler with listLength. A list-only signal misses delayed and reserved jobs, so monitor wait time and active work too.
KEDA kafka scaler, lagThreshold 1000, topic with 24 partitions
1 total lag 3,500 -> desired replicas ceil(3500/1000) = 4
2 total lag 40,000 -> 40, capped at 24 partitions -> 24
3 lag 0 for the cooldown period -> scale to minReplicaCount
-- each scale step changes group membership: expect a (cooperative) rebalanceFix: KEDA ScaledObjects for all three brokers and for Laravel are in Broker differences. Inside Laravel, Horizon balance => 'auto' does the same job per queue within one host.
Mechanics
RabbitMQ: how a delivery is chosen Important
A RabbitMQ queue selects eligible consumers, distributing messages round-robin within the highest eligible priority. Consumers whose finite prefetch window is full receive no more deliveries until settlement frees capacity. Closing a channel or connection makes its unsettled deliveries available for redelivery. RabbitMQ 4.3 acknowledgement timeouts apply to quorum queues: the default is 30 minutes; timeout recovery cancels the consumer, or closes the channel with PRECONDITION_FAILED when cancel notification is unsupported. Since 4.0 quorum queues default to a delivery limit of 20; configure dead lettering so repeatedly failing messages have a recoverable destination.
Channels: RabbitMQ recommends avoiding excessive channel counts and generally keeping per-connection counts small. One connection per Go process and one AMQP channel per consumer is a useful starting point. The pool supplies application concurrency; acknowledgements retain the original delivery channel. Ack(false) settles only that delivery, whereas a cumulative ack could settle another worker's unfinished message.
| RabbitMQ knob / message | Where | Effect |
|---|---|---|
basic.qos(prefetch_count, global=false) | Channel, before basic.consume | Per-consumer unacked limit |
default_consumer_prefetch | advanced.config | Prefetch for consumers that set none |
x-single-active-consumer | Queue argument at declare | One active consumer, automatic failover |
x-priority | Consumer argument | Prefer this consumer |
consumer_timeout / consumer-timeout policy | Node config / policy (quorum queues) | Max time a delivery may stay unacked |
x-delivery-limit / delivery-limit | Queue argument / policy (quorum) | Dead-letter or drop after N deliveries |
PRECONDITION_FAILED (406) | Channel close | E.g. ack timeout, or declaring a queue with different arguments |
basic.cancel / consumer cancel notification | Client → broker / broker → client | Stop a consumer cleanly / queue deleted or failover |
Kafka: group coordination and its timers Must-know
Two failure detectors run independently in a classic consumer group. Background heartbeats demonstrate liveness; missing them for session.timeout.ms permits removal. max.poll.interval.ms detects stalled application progress. With static membership, exceeding the poll limit stops heartbeats but does not immediately redistribute partitions: the session timeout must expire. Client-specific APIs and KIP-848 broker timers still matter; the table distinguishes them.
| Setting | Protocol | Java client default | librdkafka default | Meaning |
|---|---|---|---|---|
session.timeout.ms | classic (client) | 45000 | 45000 | No heartbeat for this long → removed, rebalance |
heartbeat.interval.ms | classic (client) | 3000 | 3000 | At most roughly 1/3 of the session timeout |
group.consumer.session.timeout.ms | consumer (broker) | broker config | broker config | Replaces the client setting under KIP-848 |
group.consumer.heartbeat.interval.ms | consumer (broker) | broker config | broker config | Replaces the client setting under KIP-848 |
max.poll.interval.ms | both | 300000 | 300000 | Max time between polls; also the Java rebalance timeout |
max.poll.records | both | 500 | n/a (no such librdkafka property) | Records per poll |
partition.assignment.strategy | classic | [RangeAssignor, CooperativeStickyAssignor] | range,roundrobin | Client-side assignor |
group.remote.assignor | consumer | null (broker's first group.consumer.assignors) | – | Server-side assignor |
group.instance.id | both | null | null | Static membership |
group.protocol | both | classic | classic | consumer = KIP-848 |
rebalance.timeout.ms (franz-go RebalanceTimeout) | classic | = max.poll.interval.ms | = max.poll.interval.ms | franz-go default 60 s |
Errors you will see during rebalances: REBALANCE_IN_PROGRESS (commit during a rebalance), UNKNOWN_MEMBER_ID and ILLEGAL_GENERATION (the member was removed or is from an old generation), FENCED_INSTANCE_ID (another process uses the same group.instance.id), STALE_MEMBER_EPOCH and FENCED_MEMBER_EPOCH (KIP-848 epochs), and in the Java client CommitFailedException when a commit arrives after the partition was reassigned.
Redis Streams: PEL, idle and delivery count Important
Each group stores a last-delivered ID and a PEL: for every delivered, unacked entry, the owning consumer, the last delivery time and a delivery counter. XREADGROUP ... > hands out new entries and adds them to the reader's PEL; XREADGROUP ... 0 re-reads the caller's own pending entries (recovery after a restart with the same consumer name). XPENDING lists pending entries with idle time and delivery count; XCLAIM moves specific IDs; XAUTOCLAIM scans the PEL with a cursor and moves everything idle longer than min-idle-time, returning the next cursor (0-0 when the scan is complete). XGROUP DELCONSUMER deletes a consumer; any entries it still owned become unclaimable, so claim or ack first. XINFO CONSUMERS idle means time since the last attempted interaction since Redis 7.2.0 (before that, last successful interaction), with inactive added for the successful one.
| Redis command | Use in scaling |
|---|---|
XGROUP CREATE key group $ MKSTREAM | Create the group once (BUSYGROUP error if it exists) |
XREADGROUP GROUP g c COUNT n BLOCK ms STREAMS key > | Read new entries as consumer c |
XACK key group id | Remove from the PEL |
XPENDING key group - + 10 [consumer] | Inspect stuck entries, delivery counts |
XAUTOCLAIM key group c min-idle start COUNT n | Take over dead consumers' entries |
XINFO GROUPS key | Group lag, pending, entries-read |
XINFO CONSUMERS key group | Per-consumer pending, idle, inactive |
XGROUP DELCONSUMER key group c | Remove a stale consumer name |
Laravel: processes, Supervisor and Horizon Important
A Laravel worker executes one job at a time per PHP process. Supervisor's numprocs maintains the process count. Horizon manages processes per supervisor: auto distributes capacity according to autoScalingStrategy (time estimates drain duration, size counts jobs, log dampens queue-size differences logarithmically). balanceMaxShift limits each adjustment and balanceCooldown spaces adjustments. Auto balancing does not promise strict queue priority; simple allocates processes evenly, while false reads queues in their configured order. Set both minProcesses and maxProcesses to control the operating range.
queue:work flag | Meaning |
|---|---|
--queue=high,default | Queue list, in priority order |
--max-jobs=1000 | Exit after this many jobs |
--max-time=3600 | Exit between jobs once this runtime budget expires |
--memory=128 | Memory threshold in MB, checked between jobs |
--timeout=60 | Kill a job after N seconds; leave several seconds below retry_after |
--tries=3 | Attempts before failed_jobs |
--sleep=3 | Wait when the queue is empty |
--stop-when-empty | Exit when no ready job remains (batch-style containers) |
queue:restart | All workers exit after their current job; the process manager restarts them with new code |
Capacity math
All four answers come from Little's law, L = λ × W: the average number of items in a system equals arrival rate times the time each spends there. The general method is in Back-of-the-Envelope Capacity Estimation. The numbers below are produced by the small program in the snippets (go run ./capacity), so the text and the code agree.
// Package main is the capacity arithmetic used on the page. Every figure is
// Little's law, L = lambda x W, applied to a different question.
package main
import (
"fmt"
"math"
)
// workers: how many concurrent handlers keep up with an arrival rate.
func workers(arrivalPerSec, serviceSec, targetUtil float64) int {
busy := arrivalPerSec * serviceSec // L = lambda x W
return int(math.Ceil(busy / targetUtil))
}
// prefetch: in-flight messages one consumer needs so that `conc` handlers
// never wait for the broker. Each message is unacked for service + one round
// trip, and the consumer finishes conc/service messages per second.
func prefetch(conc int, serviceSec, rttSec float64) int {
rate := float64(conc) / serviceSec
return int(math.Ceil(rate * (serviceSec + rttSec)))
}
// partitions: Kafka parallelism ceiling for a target rate, given what one
// member can do on one partition, with headroom for peaks and catch-up.
func partitions(targetPerSec, perConsumerPerSec, headroom float64) int {
return int(math.Ceil(targetPerSec / perConsumerPerSec * headroom))
}
// drainSeconds: how long a backlog takes to clear when consumers outpace
// producers. Infinite when they do not.
func drainSeconds(lag, consumePerSec, producePerSec float64) float64 {
if consumePerSec <= producePerSec {
return math.Inf(1)
}
return lag / (consumePerSec - producePerSec)
}
func main() {
fmt.Println("1. Laravel workers: 600 jobs/min, 1.2 s each, 70% target utilisation")
fmt.Printf(" busy=%.0f processes=%d\n", 10*1.2, workers(10, 1.2, 0.7))
fmt.Println("2. RabbitMQ prefetch: 8 goroutines, 20 ms per message, 5 ms round trip")
fmt.Printf(" prefetch=%d\n", prefetch(8, 0.020, 0.005))
fmt.Println(" same consumer across regions, 80 ms round trip")
fmt.Printf(" prefetch=%d\n", prefetch(8, 0.020, 0.080))
fmt.Println("3. Kafka partitions: 20000 rec/s target, 1500 rec/s per member, x2 headroom")
fmt.Printf(" partitions=%d\n", partitions(20000, 1500, 2))
fmt.Println("4. Lag drain: 1.2M lag, consume 25000/s, produce 20000/s")
fmt.Printf(" drain=%.0f s (%.0f min)\n", drainSeconds(1.2e6, 25000, 20000), drainSeconds(1.2e6, 25000, 20000)/60)
}$ go run ./capacity # expected output, not run as a broker lab
1. Laravel workers: 600 jobs/min, 1.2 s each, 70% target utilisation
busy=12 processes=18
2. RabbitMQ prefetch: 8 goroutines, 20 ms per message, 5 ms round trip
prefetch=10
same consumer across regions, 80 ms round trip
prefetch=40
3. Kafka partitions: 20000 rec/s target, 1500 rec/s per member, x2 headroom
partitions=27
4. Lag drain: 1.2M lag, consume 25000/s, produce 20000/s
drain=240 s (4 min)| Question | Formula | Worked example | Decision |
|---|---|---|---|
| How many Laravel processes? | busy = λ × service time; processes = busy / target utilisation | 10 jobs/s × 1.2 s = 12 busy; / 0.7 = 18 | Horizon maxProcesses 18–20; check the DB pool can take 20 more connections |
| What prefetch? | in-flight = rate × (service + RTT), rate = concurrency / service | 8 / 0.02 = 400 msg/s × 0.025 s = 10 | Qos(10); cross-region (80 ms RTT) needs 40 |
| How many partitions? | target / per-member rate × headroom | 20,000 / 1,500 × 2 = 27 | Create 32 (a round number with room); partitions are hard to add later |
| How long to drain a backlog? | lag / (consume rate − produce rate) | 1.2 M / 5,000 = 240 s | Acceptable if the SLO for "age of oldest message" is above 4 min; otherwise scale out first |
| When is scaling pointless? | utilisation ρ = λ / (consumers × μ) ≥ 1 | 30 jobs/s arriving, 20 workers at 1 job/s each | Backlog grows forever; add workers or make jobs faster |
| Why 70%, not 100%? | Queueing delay grows sharply as ρ → 1 | At 95% a small burst adds minutes of wait | Leave headroom for bursts, retries and rebalances |
Go
Before
One auto-acked consumer, no prefetch, one goroutine per message and nothing listening for SIGTERM. The backlog is pulled into memory, concurrency is unbounded, and a deploy loses every in-flight message.
// Package main is the naive consumer: one process, one auto-acked consumer,
// one goroutine per message, and nothing that reacts to SIGTERM.
package main
import (
"log"
"time"
amqp "github.com/rabbitmq/amqp091-go"
)
func main() {
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
if err != nil {
log.Fatal(err)
}
ch, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
// autoAck=true: the broker forgets the message the moment it is written to
// the socket. No prefetch is set, so the broker pushes the whole backlog
// into this process's memory.
msgs, err := ch.Consume("jobs", "", true, false, false, false, nil)
if err != nil {
log.Fatal(err)
}
for d := range msgs {
// Unbounded concurrency: 1M queued messages means 1M goroutines
// hammering the database at once.
go func(body []byte) {
time.Sleep(2 * time.Second) // stand-in for real work
log.Printf("done %s", body)
}(d.Body)
}
// On SIGTERM the process dies here: in-flight goroutines vanish, and since
// the messages were auto-acked they are lost for good.
}After
A small pool built from a semaphore channel and a WaitGroup. Go blocks while the pool is full, so the consumer stops pulling work. RabbitMQ and Redis use it; Kafka uses an error-propagating batch coordinator below.
// Package pool is a bounded worker pool built from a semaphore channel and a
// WaitGroup. It is shared by the three broker examples.
package pool
import (
"context"
"sync"
)
// Pool limits how many tasks run at once.
type Pool struct {
sem chan struct{}
wg sync.WaitGroup
}
// New returns a pool that runs at most n tasks concurrently.
func New(n int) *Pool {
return &Pool{sem: make(chan struct{}, n)}
}
// Go blocks until a slot is free, then runs fn in its own goroutine. It returns
// ctx.Err() instead of starting fn when the context ends first, so the caller
// stops pulling new work while the pool is full or shutting down.
func (p *Pool) Go(ctx context.Context, fn func()) error {
select {
case p.sem <- struct{}{}:
case <-ctx.Done():
return ctx.Err()
}
p.wg.Add(1)
go func() {
defer func() {
<-p.sem
p.wg.Done()
}()
fn()
}()
return nil
}
// Wait blocks until every started task has returned. Call it after the last
// Go to drain in-flight work.
func (p *Pool) Wait() {
p.wg.Wait()
}The RabbitMQ consumer: manual acks, per-consumer prefetch equal to the pool size, signal.NotifyContext, then Cancel the consumer and drain with a deadline before closing.
// Package main consumes a RabbitMQ queue with a bounded pool, manual acks,
// per-consumer prefetch and a graceful shutdown.
package main
import (
"context"
"log"
"os"
"os/signal"
"syscall"
"time"
"academy/competing-consumers-scaling/after/pool"
amqp "github.com/rabbitmq/amqp091-go"
)
const workers = 8
func main() {
url := os.Getenv("AMQP_URL")
if url == "" {
log.Fatal("AMQP_URL is not set")
}
// ctx is cancelled on SIGINT or SIGTERM.
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
conn, err := amqp.Dial(url)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
// Per-consumer prefetch (global=false). Equal to the pool size, so every
// worker has one message and the broker holds the rest for other consumers.
// Use 1 when jobs are long and uneven; larger when jobs are tiny and the
// round trip per ack dominates.
if err := ch.Qos(workers, 0, false); err != nil {
log.Fatal(err)
}
const tag = "worker-1"
msgs, err := ch.Consume("jobs", tag, false, false, false, false, nil)
if err != nil {
log.Fatal(err)
}
p := pool.New(workers)
settlementErrors := make(chan error, workers)
loop:
for {
select {
case <-ctx.Done():
break loop
case err := <-settlementErrors:
log.Printf("settlement failed; close connection for recovery: %v", err)
return
case d, ok := <-msgs:
if !ok {
break loop
}
if err := p.Go(ctx, func() {
if err := handle(d); err != nil {
settlementErrors <- err
}
}); err != nil {
// Shutting down: give the message back untouched.
if err := d.Nack(false, true); err != nil {
log.Printf("nack failed; connection close will recover: %v", err)
return
}
break loop
}
}
}
// Stop new deliveries, then wait for in-flight handlers to ack.
if err := ch.Cancel(tag, false); err != nil {
log.Printf("consumer cancel failed: %v", err)
return
}
done := make(chan struct{})
go func() { p.Wait(); close(done) }()
select {
case <-done:
select {
case err := <-settlementErrors:
log.Printf("ack failed while draining: %v", err)
default:
}
case <-time.After(30 * time.Second):
log.Print("drain timeout: unacked messages will be redelivered")
}
}
func handle(d amqp.Delivery) error {
time.Sleep(time.Second) // stand-in for real work
// Individual ack on the ORIGINAL channel; multiple=true could acknowledge
// another goroutine's unfinished delivery. Ack errors imply uncertain state.
return d.Ack(false)
}When order matters per key, a keyed pool: each key always lands in the same lane, so one order's events run in sequence while different orders run in parallel. Its test (go test -race ./after/keyed/) submits interleaved messages for seven keys and checks per-key order.
// Package keyed is a worker pool that runs messages with the same key one at a
// time and in arrival order, while messages with different keys run in
// parallel. It is the in-process version of a partition key.
package keyed
import (
"context"
"hash/fnv"
"sync"
)
// Task is one unit of work tagged with an ordering key (order id, account id).
type Task struct {
Key string
Run func()
}
// Pool owns a fixed number of lanes. A key always hashes to the same lane, so
// two tasks for one key never overlap, and a lane's buffered channel bounds
// how much work can queue up behind a slow key.
type Pool struct {
lanes []chan Task
wg sync.WaitGroup
}
// New starts n lanes, each with a buffer of depth tasks.
func New(n, depth int) *Pool {
p := &Pool{lanes: make([]chan Task, n)}
for i := range p.lanes {
ch := make(chan Task, depth)
p.lanes[i] = ch
p.wg.Add(1)
go func() {
defer p.wg.Done()
for t := range ch {
t.Run()
}
}()
}
return p
}
func (p *Pool) lane(key string) chan Task {
h := fnv.New32a()
_, _ = h.Write([]byte(key))
return p.lanes[h.Sum32()%uint32(len(p.lanes))]
}
// Submit blocks while the key's lane is full (backpressure) and gives up when
// ctx ends, so a shutting-down consumer stops pulling new messages.
func (p *Pool) Submit(ctx context.Context, t Task) error {
select {
case p.lane(t.Key) <- t:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// Close stops accepting work and waits until every queued task has run.
// Call it once, after the last Submit.
func (p *Pool) Close() {
for _, ch := range p.lanes {
close(ch)
}
p.wg.Wait()
}When a fetched batch must succeed or fail as a whole before it is committed, errgroup with SetLimit bounds concurrency and returns the first error. The program needs no broker; expected behavior is bounded parallel processing and an error when the poison record is encountered. Completed effects are not rolled back by errgroup.
// Package main processes one fetched batch with errgroup.SetLimit: bounded
// concurrency, the first error cancels the rest, and Wait is the drain point
// before the batch is acknowledged or its offsets are committed.
package main
import (
"context"
"errors"
"fmt"
"log"
"time"
"golang.org/x/sync/errgroup"
)
type message struct {
ID int
Body string
}
func handle(ctx context.Context, m message) error {
select {
case <-time.After(20 * time.Millisecond): // stand-in for real work
case <-ctx.Done():
return ctx.Err()
}
if m.Body == "poison" {
return errors.New("cannot parse body")
}
return nil
}
// processBatch returns nil only if every message succeeded, so the caller may
// commit the whole batch. On error it returns the first failure; the caller
// commits nothing and lets the broker redeliver (handlers are idempotent).
func processBatch(ctx context.Context, batch []message, limit int) error {
g, gctx := errgroup.WithContext(ctx)
g.SetLimit(limit) // at most `limit` handlers at once; Go blocks when full
for _, m := range batch {
g.Go(func() error {
if err := handle(gctx, m); err != nil {
return fmt.Errorf("message %d: %w", m.ID, err)
}
return nil
})
}
return g.Wait()
}
func main() {
batch := make([]message, 40)
for i := range batch {
batch[i] = message{ID: i, Body: "ok"}
}
start := time.Now()
err := processBatch(context.Background(), batch, 8)
// 40 messages x 20 ms / 8 workers = about 100 ms.
log.Printf("batch of %d done in %s, err=%v", len(batch), time.Since(start).Round(10*time.Millisecond), err)
batch[17].Body = "poison"
err = processBatch(context.Background(), batch, 8)
log.Printf("with a poison message: err=%v (commit nothing, redeliver)", err)
}The Go angle
Go has no consumer framework; the pieces are context, os/signal, sync, golang.org/x/sync/errgroup and a client. signal.NotifyContext turns SIGTERM into a cancelled context, the one signal every loop and handler should watch. The shutdown order never changes: stop taking new work, give back what has not started, let in-flight handlers finish within a deadline, ack or commit, then close. Skip the deadline and deployments hang until SIGKILL. Skip the drain and nearly finished work is redelivered. Three practical rules follow. First, the bound on concurrency is a semaphore (chan struct{} or errgroup.SetLimit), and prefetch (or COUNT, or max.poll.records) should be sized to it. Second, ack from the goroutine that did the work: amqp091-go's Delivery.Ack is safe to call from any goroutine. Third, for Kafka, commit only offsets whose predecessors are all done, which requires waiting for every handler to succeed, not merely to finish. The Kafka example exits on batch failure to avoid later commits skipping a failed offset. Go-specific background lives in Worker Pools & Pipelines and OS Processes, Signals & Graceful Shutdown.
Laravel
Before
A single hand-started queue:work. One job at a time, no restart on crash, no memory recycling, no job timeout.
<?php
namespace App\Jobs;
use App\Models\Invoice;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
// Before: run by hand, one process, default settings:
//
// php artisan queue:work
//
// One worker means one job at a time. There is no process monitor, so a
// crash, a deploy or a closed terminal stops all processing. There is no
// --max-jobs or --max-time, so the process leaks memory until the OS kills
// it, and no --tries or --timeout on the job, so a hung HTTP call blocks the
// only worker indefinitely.
class RenderInvoicePdf implements ShouldQueue
{
use Queueable;
public function __construct(public int $invoiceId) {}
public function handle(): void
{
$invoice = Invoice::findOrFail($this->invoiceId);
$invoice->renderPdf(); // slow, sometimes hangs
}
}After
A job that bounds its own attempts and runtime and is safe to run twice, so any number of workers can compete for it.
<?php
namespace App\Jobs;
use App\Models\Invoice;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
// After: safe to run on any number of workers. The job is idempotent
// enough to survive a retry, and it bounds its own runtime.
class RenderInvoicePdf implements ShouldQueue
{
use Queueable;
// Attempts before the job lands in failed_jobs.
public int $tries = 3;
// Seconds before the worker kills the job; must stay below the
// connection's retry_after, and below the Horizon supervisor timeout.
public int $timeout = 60;
// Treat a timeout as a failure instead of releasing the job again.
public bool $failOnTimeout = true;
public function __construct(public int $invoiceId) {}
public function handle(): void
{
$invoice = Invoice::findOrFail($this->invoiceId);
// Re-rendering an already rendered invoice is harmless.
if ($invoice->pdf_path === null) {
$invoice->renderPdf();
}
}
}Without Horizon, Supervisor runs N plain workers with the memory-hygiene flags:
; Without Horizon: Supervisor itself runs N plain queue:work processes.
[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
; --max-jobs and --max-time make each worker exit cleanly so Supervisor
; restarts it with fresh memory.
command=php /var/www/app/artisan queue:work redis --sleep=3 --tries=3 --timeout=60 --max-jobs=1000 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=8
redirect_stderr=true
stdout_logfile=/var/www/app/storage/logs/worker.log
stopwaitsecs=3600With Horizon, Supervisor keeps one process alive and Horizon manages the workers:
; Supervisor keeps ONE process alive: Horizon itself. Horizon then forks and
; scales the queue workers according to config/horizon.php.
[program:horizon]
process_name=%(program_name)s
command=php /var/www/app/artisan horizon
autostart=true
autorestart=true
user=www-data
redirect_stderr=true
stdout_logfile=/var/www/app/storage/logs/horizon.log
; Must exceed the longest job so a stop does not kill a job mid-run.
stopwaitsecs=3600The Horizon supervisor with balance => 'auto':
<?php
// config/horizon.php (excerpt)
return [
'defaults' => [
'supervisor-1' => [
'connection' => 'redis',
'queue' => ['default', 'invoices'],
// Scale processes between min and max by queue load.
'balance' => 'auto',
'autoScalingStrategy' => 'time',
'minProcesses' => 1,
'maxProcesses' => 10,
// At most one process added or removed every 3 seconds.
'balanceMaxShift' => 1,
'balanceCooldown' => 3,
'tries' => 3,
// Greater than any job-level $timeout, and a few seconds shorter
// than retry_after in config/queue.php.
'timeout' => 75,
// Memory hygiene: recycle workers that grow or age.
'memory' => 128,
'maxJobs' => 1000,
'maxTime' => 3600,
],
],
'environments' => [
'production' => [
'supervisor-1' => ['maxProcesses' => 10],
],
'local' => [
'supervisor-1' => ['maxProcesses' => 3],
],
],
];The Laravel angle
Laravel concurrency comes from processes: Supervisor numprocs, Horizon maxProcesses, or worker replicas. Recycle long-lived PHP workers with --max-jobs, --max-time and --memory. During deployment, queue:restart or horizon:terminate lets current jobs finish before process-manager restart. A job's $timeout can override the worker timeout; keep the effective timeout below the connection's retry_after. Horizon's supervisor timeout should exceed the job timeout while remaining below retry_after, and Supervisor stopwaitsecs / Kubernetes grace must accommodate the longest permitted job plus shutdown. SQS uses its visibility timeout instead of Laravel retry_after. Horizon scales processes within its deployment; additional hosts require explicit infrastructure scaling. See Laravel Queue Internals for driver mechanics.
Broker differences
RabbitMQ
Multiple RabbitMQ consumers can subscribe to the same queue without a special group declaration. Prefetch and priority govern eligibility; unacknowledged deliveries recover when their channel closes. A hot queue still has one leader, so horizontal capacity may require several queues. For ordered buckets, consistent-hash routing plus SAC is one design. The Laravel RabbitMQ package uses polling (basic_get) for queue:work and push delivery (basic_consume) for rabbitmq:consume; the latter consumes one queue and defaults to prefetch 1000. Set prefetch deliberately and measure your workload rather than assuming a fixed speedup. KEDA can adjust replicas from queue length.
The ordered queue with failover and priorities (Go):
// Package main declares a quorum queue with single active consumer and joins
// it with a consumer priority. Run it N times: one instance receives, the rest
// are hot standbys that take over in order when the active one goes away.
package main
import (
"context"
"log"
"os"
"os/signal"
"strconv"
"syscall"
amqp "github.com/rabbitmq/amqp091-go"
)
func main() {
url := os.Getenv("AMQP_URL")
if url == "" {
log.Fatal("AMQP_URL is not set")
}
prio, _ := strconv.Atoi(os.Getenv("CONSUMER_PRIORITY")) // e.g. 10 in the main zone, 0 elsewhere
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
conn, err := amqp.Dial(url)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
// x-single-active-consumer can only be set at declaration, never by policy.
_, err = ch.QueueDeclare("ledger.postings", true, false, false, false, amqp.Table{
"x-queue-type": "quorum",
"x-single-active-consumer": true,
})
if err != nil {
log.Fatal(err)
}
// Ordered processing: one message in flight at a time.
if err := ch.Qos(1, 0, false); err != nil {
log.Fatal(err)
}
// x-priority: on a quorum queue a higher-priority consumer that registers
// later takes over once the current active consumer's messages are acked.
msgs, err := ch.Consume("ledger.postings", "", false, false, false, false, amqp.Table{
"x-priority": prio,
})
if err != nil {
log.Fatal(err)
}
for {
select {
case <-ctx.Done():
return // closing the channel hands the queue to the next consumer
case d, ok := <-msgs:
if !ok {
return
}
log.Printf("posting %s", d.Body)
if err := d.Ack(false); err != nil {
log.Printf("ack failed; close for redelivery: %v", err)
return
}
}
}
}The Laravel connection and the worker program:
<?php
// config/queue.php (excerpt): the RabbitMQ connection added by the
// vladimir-yuldashev/laravel-queue-rabbitmq package.
return [
'connections' => [
'rabbitmq' => [
'driver' => 'rabbitmq',
'queue' => env('RABBITMQ_QUEUE', 'default'),
'connection' => 'default',
'hosts' => [
[
'host' => env('RABBITMQ_HOST', '127.0.0.1'),
'port' => env('RABBITMQ_PORT', 5672),
'user' => env('RABBITMQ_USER', 'guest'),
'password' => env('RABBITMQ_PASSWORD', 'guest'),
'vhost' => env('RABBITMQ_VHOST', '/'),
],
],
'options' => [],
// "horizon" lets Horizon supervise these workers.
'worker' => env('RABBITMQ_WORKER', 'default'),
],
],
];; RabbitMQ through the package's rabbitmq:consume (basic.consume, push).
; Its --prefetch-count defaults to 1000; a PHP worker runs ONE job at a time,
; so 1000 means 999 messages parked in a busy process while other workers idle.
; Set it to 1 for slow or uneven jobs (fair dispatch), a few more for tiny ones.
[program:rabbitmq-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/app/artisan rabbitmq:consume rabbitmq --queue=invoices --prefetch-count=1 --tries=3 --timeout=60 --max-jobs=1000 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=8
redirect_stderr=true
stdout_logfile=/var/www/app/storage/logs/rabbitmq-worker.log
stopwaitsecs=120# Scale a RabbitMQ worker Deployment on queue depth (KEDA rabbitmq scaler).
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: invoice-workers
spec:
scaleTargetRef:
name: invoice-workers # the Deployment running the consumers
minReplicaCount: 1
maxReplicaCount: 20
triggers:
- type: rabbitmq
metadata:
protocol: http # only the HTTP API counts unacked messages
mode: QueueLength
value: "50" # target messages per replica
activationValue: "1"
queueName: invoices
hostFromEnv: RABBITMQ_MGMT_URLKafka
The primitive is the consumer group, and the parallelism ceiling is the partition count. Concurrency inside a member must respect per-partition order (keyed pool) or commit carefully. Rebalances are the operational cost; cooperative-sticky, static membership and KIP-848 shrink them, and bounded batches keep members inside max.poll.interval.ms. When the workload is a queue of independent tasks, a share group removes the partition ceiling. The franz-go group consumer uses cooperative-sticky, static membership and batch-then-commit for independent records only. It does not preserve per-partition completion order. All tasks must succeed before committing; any failure closes the consumer for replay, so completed side effects need idempotency. A 20-second processing context and separate 5-second commit context bound the drain, provided handlers honor cancellation. Rebalance blocking protects ownership only within the configured rebalance budget; it cannot survive an expired session or network loss:
// Package main consumes a Kafka topic as part of a consumer group, using the
// cooperative-sticky balancer, static membership and bounded batch processing.
package main
import (
"context"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/twmb/franz-go/pkg/kgo"
"golang.org/x/sync/errgroup"
)
const workers = 8
func main() {
broker := os.Getenv("KAFKA_BROKER")
if broker == "" {
log.Fatal("KAFKA_BROKER is not set")
}
// A stable per-pod name, for example the StatefulSet ordinal.
instanceID := os.Getenv("POD_NAME")
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
opts := []kgo.Opt{
kgo.SeedBrokers(broker),
kgo.ConsumerGroup("billing-workers"),
kgo.ConsumeTopics("invoices"),
// Cooperative rebalancing (KIP-429): only moved partitions are revoked.
kgo.Balancers(kgo.CooperativeStickyBalancer()),
// Static membership (KIP-345): a restart within SessionTimeout keeps
// its partitions and triggers no rebalance.
kgo.SessionTimeout(45 * time.Second),
// Kafka's rebalance.timeout.ms (franz-go default 60s): how long members
// may take to finish work and commit once a rebalance has begun. The
// Java client has no separate knob; it uses max.poll.interval.ms.
kgo.RebalanceTimeout(2 * time.Minute),
// Commit after processing, never before.
kgo.DisableAutoCommit(),
// Hold rebalances until we call AllowRebalance, so a batch is never
// half-processed when its partitions move.
kgo.BlockRebalanceOnPoll(),
}
if instanceID != "" {
opts = append(opts, kgo.InstanceID(instanceID))
}
cl, err := kgo.NewClient(opts...)
if err != nil {
log.Fatal(err)
}
defer cl.Close()
for ctx.Err() == nil {
// max.poll.records analogue: at most 100 records per batch.
fetches := cl.PollRecords(ctx, 100)
if fetches.IsClientClosed() {
return
}
fetches.EachError(func(t string, part int32, err error) {
log.Printf("fetch %s/%d: %v", t, part, err)
})
var batch []*kgo.Record
fetches.EachRecord(func(r *kgo.Record) {
batch = append(batch, r)
})
// Independent drain budget: SIGTERM stops polling but lets this batch
// finish. Real handlers MUST honor this context, including network I/O.
batchCtx, cancelBatch := context.WithTimeout(context.Background(), 20*time.Second)
err := processBatch(batchCtx, batch, process, func(records []*kgo.Record) error {
commitCtx, cancelCommit := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelCommit()
return cl.CommitRecords(commitCtx, records...)
})
cancelBatch()
cl.AllowRebalance()
if err != nil {
// Stop this consumer. Continuing would allow a later batch to commit
// past a failed record. Successful effects may replay: use an inbox.
log.Printf("batch failed; closing for replay: %v", err)
return
}
}
}
// processBatch is for independent records, NOT ordered per-partition effects.
// A successful batch commits only after every handler succeeds. Failure does
// not roll back completed effects; it prevents advancing the committed offset.
func processBatch(ctx context.Context, records []*kgo.Record, handle func(context.Context, *kgo.Record) error, commit func([]*kgo.Record) error) error {
g, workCtx := errgroup.WithContext(ctx)
g.SetLimit(workers)
for _, record := range records {
g.Go(func() error { return handle(workCtx, record) })
}
if err := g.Wait(); err != nil {
return err
}
if err := ctx.Err(); err != nil {
return err
}
if len(records) == 0 {
return nil
}
return commit(records)
}
func process(ctx context.Context, r *kgo.Record) error {
timer := time.NewTimer(100 * time.Millisecond) // stand-in for real work
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
}
log.Printf("%s[%d]@%d", r.Topic, r.Partition, r.Offset)
return nil
}The share-group consumer (Kafka 4.2+, franz-go ShareGroup), where each record is accepted or released on its own:
// Package main reads a topic through a Kafka share group (KIP-932, "queues for
// Kafka"): members are not bound to partitions, so there can be more members
// than partitions, and every record is acknowledged on its own.
package main
import (
"context"
"log"
"os"
"os/signal"
"syscall"
"github.com/twmb/franz-go/pkg/kgo"
)
func main() {
broker := os.Getenv("KAFKA_BROKER")
if broker == "" {
log.Fatal("KAFKA_BROKER is not set")
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
cl, err := kgo.NewClient(
kgo.SeedBrokers(broker),
kgo.ConsumeTopics("thumbnails"),
kgo.ShareGroup("thumbnail-workers"),
)
if err != nil {
log.Fatal(err)
}
defer cl.Close()
for ctx.Err() == nil {
fetches := cl.PollRecords(ctx, 50)
if fetches.IsClientClosed() {
return
}
fetches.EachRecord(func(r *kgo.Record) {
if err := render(r); err != nil {
// Release: the broker hands it to some member again and
// counts the delivery (delivery.count.limit caps it).
r.Ack(kgo.AckRelease)
return
}
r.Ack(kgo.AckAccept)
})
// Send the acknowledgements now instead of with the next poll.
if err := cl.FlushAcks(ctx); err != nil {
log.Printf("flush acks: %v", err)
}
}
}
func render(r *kgo.Record) error {
log.Printf("%s[%d]@%d", r.Topic, r.Partition, r.Offset)
return nil
}Laravel has no built-in Kafka driver. With mateusjunges/laravel-kafka a long-running Artisan command is one group member; withRebalanceStrategy(RebalanceStrategy::COOPERATIVE_STICKY) selects the assignor, withOptions passes librdkafka settings such as group.instance.id, and withManualCommit plus $consumer->commit($message) commits after the side effect. Scale it with replicas up to the partition count:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Junges\Kafka\Config\RebalanceStrategy;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Contracts\MessageConsumer;
use Junges\Kafka\Facades\Kafka;
// One process = one Kafka group member. Scale by running more processes
// (Supervisor numprocs or Deployment replicas), never beyond the partition
// count of the topic: extra members get no partitions and sit idle.
class ConsumeOrderEvents extends Command
{
protected $signature = 'kafka:consume-orders';
protected $description = 'Consume order events as a member of the billing consumer group';
public function handle(): void
{
$consumer = Kafka::consumer(['orders'])
->withConsumerGroupId('billing')
// Only partitions that must move are revoked on a rebalance.
->withRebalanceStrategy(RebalanceStrategy::COOPERATIVE_STICKY)
->withOptions([
// Static membership: a restart inside session.timeout.ms keeps
// its partitions. POD_NAME must be stable AND unique per replica.
// The PID fallback avoids collisions but is not stable across restarts.
'group.instance.id' => (string) env('POD_NAME', gethostname().'-'.getmypid()),
'session.timeout.ms' => '45000',
// Longest time between polls before the member is evicted.
'max.poll.interval.ms' => '300000',
])
// Commit only after the handler finished its side effects.
->withManualCommit()
// Recycle the PHP process, like queue:work --max-time.
->withMaxTime(3600)
->withHandler(function (ConsumerMessage $message, MessageConsumer $consumer): void {
$body = $message->getBody();
// ... idempotent side effect keyed by $body['order_id'] ...
$consumer->commit($message);
})
->build();
// The package traps SIGTERM/SIGINT when ext-pcntl is loaded and stops
// after the current message.
$consumer->consume();
}
}# Scale a Kafka consumer Deployment on consumer-group lag (KEDA kafka scaler).
# By default KEDA never exceeds the partition count, because extra members
# would sit idle.
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: billing-consumers
spec:
scaleTargetRef:
name: billing-consumers
minReplicaCount: 1
maxReplicaCount: 24 # = partitions of "orders"
triggers:
- type: kafka
metadata:
bootstrapServers: kafka.svc:9092
consumerGroup: billing
topic: orders
lagThreshold: "1000" # target lag per replica
activationLagThreshold: "10"
allowIdleConsumers: "false"
excludePersistentLag: "true" # a stuck poison partition must not scale us outRedis Streams
A consumer group splits a stream among named consumers, any of which can take any new entry, so there is no partition ceiling. What is missing is automatic redelivery: entries of a dead consumer stay in the PEL until claimed, so every deployment needs a reaper (XAUTOCLAIM) and a cap on delivery count. Consumer names are state, and a worker named by PID leaves a stale name on each restart; XINFO CONSUMERS and XGROUP DELCONSUMER clean up, but only after the consumer is fenced and its PEL is empty. One stream key lives on one Redis Cluster shard, so scaling beyond one shard means several streams. The consumer removes only its own name after bounded drain and an empty PEL check. Deleting another consumer from an XINFO snapshot has a race: it could read again between inspection and deletion. Fence that process first, recover pending work, then administratively remove its name:
// Package main reads a Redis Streams consumer group with named consumers, a
// bounded pool, graceful shutdown and safe cleanup of its own consumer name.
package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"academy/competing-consumers-scaling/after/pool"
"github.com/redis/go-redis/v9"
)
const (
stream = "jobs"
group = "workers"
workers = 8
)
func main() {
addr := os.Getenv("REDIS_ADDR")
if addr == "" {
log.Fatal("REDIS_ADDR is not set")
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
rdb := redis.NewClient(&redis.Options{
Addr: addr, ContextTimeoutEnabled: true,
DialTimeout: 3 * time.Second, ReadTimeout: 3 * time.Second, WriteTimeout: 3 * time.Second,
})
defer rdb.Close()
// Each process needs its own consumer name inside the group. A random or
// per-run name leaves dead entries behind, which is why cleanup exists.
host, _ := os.Hostname()
name := fmt.Sprintf("%s-%d", host, os.Getpid())
err := rdb.XGroupCreateMkStream(ctx, stream, group, "$").Err()
if err != nil && err.Error() != "BUSYGROUP Consumer Group name already exists" {
log.Fatal(err)
}
p := pool.New(workers)
for ctx.Err() == nil {
res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: group,
Consumer: name,
Streams: []string{stream, ">"},
Count: workers, // batch size, not a total in-flight bound
Block: 2 * time.Second,
}).Result()
if err == redis.Nil || ctx.Err() != nil {
continue
}
if err != nil {
log.Printf("xreadgroup: %v", err)
time.Sleep(time.Second)
continue
}
for _, s := range res {
for _, m := range s.Messages {
if err := p.Go(ctx, func() {
time.Sleep(100 * time.Millisecond) // bounded stand-in; real I/O needs deadlines
ackCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if err := rdb.XAck(ackCtx, stream, group, m.ID).Err(); err != nil {
log.Printf("xack %s failed; leave for recovery: %v", m.ID, err)
}
}); err != nil {
// Fetched but unstarted records remain pending for the reaper.
break
}
}
}
}
// Drain in-flight work, then remove ourselves if nothing is pending.
done := make(chan struct{})
go func() { p.Wait(); close(done) }()
select {
case <-done:
case <-time.After(10 * time.Second):
log.Print("drain expired; pending entries require recovery")
return
}
bg, cancelCleanup := context.WithTimeout(context.Background(), 3*time.Second)
defer cancelCleanup()
// Check THIS consumer's pending entries, not the group-wide summary.
mine, err := rdb.XPendingExt(bg, &redis.XPendingExtArgs{
Stream: stream, Group: group, Start: "-", End: "+", Count: 1, Consumer: name,
}).Result()
if err == nil && len(mine) == 0 {
if err := rdb.XGroupDelConsumer(bg, stream, group, name).Err(); err != nil {
log.Printf("delete own consumer: %v", err)
}
}
}
// Do not delete another consumer from an XINFO snapshot alone: it can read
// again between inspection and deletion. Fence that process first, recover its
// pending entries, then remove its name through an administrative workflow.The reaper that takes over a dead consumer's entries and parks poison ones:
// Package main is the Redis Streams reaper: it takes over entries that a dead
// or stuck consumer left in the group's pending entries list (PEL), using
// XAUTOCLAIM, and parks entries that were delivered too many times.
package main
import (
"context"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/redis/go-redis/v9"
)
const (
stream = "jobs"
group = "workers"
minIdle = 60 * time.Second // longer than the slowest normal job
maxDelivery = 5 // then park it instead of retrying forever
)
func main() {
addr := os.Getenv("REDIS_ADDR")
if addr == "" {
log.Fatal("REDIS_ADDR is not set")
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
rdb := redis.NewClient(&redis.Options{Addr: addr})
defer rdb.Close()
host, _ := os.Hostname()
me := "reaper-" + host
t := time.NewTicker(15 * time.Second)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
if err := sweep(ctx, rdb, me); err != nil {
log.Printf("sweep: %v", err)
}
}
}
}
// sweep walks the whole PEL with the cursor XAUTOCLAIM returns. Claimed
// entries now belong to `me`; their idle time resets and their delivery
// counter goes up by one.
func sweep(ctx context.Context, rdb *redis.Client, me string) error {
start := "0-0"
for {
msgs, next, err := rdb.XAutoClaim(ctx, &redis.XAutoClaimArgs{
Stream: stream,
Group: group,
Consumer: me,
MinIdle: minIdle,
Start: start,
Count: 100,
}).Result()
if err != nil {
return err
}
for _, m := range msgs {
if tooManyDeliveries(ctx, rdb, m.ID) {
park(ctx, rdb, m)
continue
}
process(m)
rdb.XAck(ctx, stream, group, m.ID)
}
if next == "0-0" {
return nil // full pass over the PEL done
}
start = next
}
}
func tooManyDeliveries(ctx context.Context, rdb *redis.Client, id string) bool {
p, err := rdb.XPendingExt(ctx, &redis.XPendingExtArgs{
Stream: stream, Group: group, Start: id, End: id, Count: 1,
}).Result()
return err == nil && len(p) == 1 && p[0].RetryCount > maxDelivery
}
// park copies the entry to a dead-letter stream and acks the original, in one
// MULTI/EXEC so the entry is never in neither place.
func park(ctx context.Context, rdb *redis.Client, m redis.XMessage) {
_, err := rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
p.XAdd(ctx, &redis.XAddArgs{Stream: stream + ":dead", Values: m.Values})
p.XAck(ctx, stream, group, m.ID)
return nil
})
if err != nil {
log.Printf("park %s: %v", m.ID, err)
}
}
func process(m redis.XMessage) {
log.Printf("reclaimed %s %v", m.ID, m.Values)
}Laravel's redis queue driver does not use streams, so queue:work cannot read one. A long-running command with the Redis facade (phpredis) does both jobs, claiming then reading:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
// A Redis Streams consumer group member written against the Redis facade
// (phpredis). Laravel's built-in redis queue driver uses lists and sorted
// sets, not streams, so queue:work cannot do this.
class ConsumeStream extends Command
{
protected $signature = 'stream:consume {stream=jobs} {group=workers}';
protected $description = 'Read a Redis stream as one competing consumer';
private bool $shouldKeepRunning = true;
public function handle(): void
{
$stream = $this->argument('stream');
$group = $this->argument('group');
// Set a unique POD_NAME per replica; fallback is unique per process.
// Group must already exist. Reaper scans recover earlier consumer names.
$me = (string) env('POD_NAME', gethostname().'-'.getmypid());
$cursor = '0-0';
$this->trap([SIGTERM, SIGINT], fn () => $this->shouldKeepRunning = false);
while ($this->shouldKeepRunning) {
// 1. Take over entries a dead consumer left idle for 60 s.
$claimed = Redis::xautoclaim($stream, $group, $me, 60000, $cursor, 10);
$cursor = (string) ($claimed[0] ?? '0-0');
$this->work($stream, $group, $claimed[1] ?? []);
// 2. New entries: at most 10, block up to 2 s.
$batch = Redis::xreadgroup($group, $me, [$stream => '>'], 10, 2000);
// phpredis may return prefixed stream keys; only one stream was requested.
foreach (($batch ?: []) as $entries) {
$this->work($stream, $group, $entries);
}
}
// The loop exits between batches. Bound every real side effect and Redis
// socket timeout so a batch finishes within the process-manager grace.
}
/** @param array<string, array<string, string>> $entries */
private function work(string $stream, string $group, array $entries): void
{
foreach ($entries as $id => $fields) {
// ... idempotent side effect ...
Redis::xack($stream, $group, [$id]);
}
}
}# Two Redis triggers. Use the one that matches how the workers read.
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: stream-workers
spec:
scaleTargetRef:
name: stream-workers
minReplicaCount: 1
maxReplicaCount: 10
triggers:
# Redis Streams consumer group: scale on entries not yet delivered (lag).
- type: redis-streams
metadata:
addressFromEnv: REDIS_ADDR
stream: jobs
consumerGroup: workers
lagCount: "100"
activationLagCount: "1"
---
# Laravel's redis queue driver keeps pending jobs in a LIST named
# "queues:<name>" (plus the connection prefix from config/database.php).
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: laravel-workers
spec:
scaleTargetRef:
name: laravel-queue-worker
minReplicaCount: 1
maxReplicaCount: 20
triggers:
- type: redis
metadata:
addressFromEnv: REDIS_ADDR
listName: laravel-database-queues:default
listLength: "20" # target jobs waiting per replica
activationListLength: "1"Solving the classic problems
| Problem | Symptom | Solution | How | Cost / limitation |
|---|---|---|---|---|
| Prefetch too high | One worker busy with a pile, others idle; many duplicates after a crash | Prefetch ≈ concurrency (+ RTT cover) | Qos(n), --prefetch-count=1, COUNT n | More round trips |
| Prefetch too low | Low throughput, idle goroutines, high-latency links worst | Raise to the Little's law value | Capacity formula; docs' 100–300 for throughput | Less fairness |
| Too few partitions | Pods beyond N idle, lag on all partitions | Create topics with headroom; share groups for task queues | 2× peak consumers | Adding partitions remaps keys |
| Too many partitions | Slow rebalances, many idle consumers, more open files and replication | Partition for 1–2 years of peak, not forever | Measure per-member rate first | Re-partitioning means a new topic |
| Rebalance during deploy | Lag sawtooth, duplicates, restarts of state | Cooperative-sticky + static membership; KIP-848 on 4.x | group.instance.id = pod name, session timeout > restart time | Slower detection of real death |
| Slow handler evicted | CommitFailedException, member leaves, rebalance loop | Smaller batches, longer max.poll.interval.ms, offload work | max.poll.records 50, pause partitions | Lower throughput per poll |
| Duplicate processing during rebalance | Same record processed by old and new owner | Inbox / idempotent handler; commit before revoke | Dedup table keyed by message ID | One extra write per message |
| Hot key | One partition / lane lags, others idle | Better key, key salting for commutative work, split the hot tenant | tenant:shard keys | Loses per-key order for salted keys |
| Poison message | One lane or SAC queue stuck forever | Delivery limit + DLQ | Quorum delivery-limit, Redis delivery count, Kafka retry topic | Needs a replay tool |
| Downstream saturation | Scaling out makes p99 worse | Cap concurrency to the downstream, not the backlog | Pool size ≤ DB pool, rate limiter | Backlog grows; alert on age |
| Dead Redis consumer | Entries pending forever, stale names | Reaper with XAUTOCLAIM, stable names | Snippets above | Reaper must be idempotent too |
Duplicate processing during rebalances and crashes is unavoidable with at-least-once delivery. The fix lives in the handler, not in the scaling logic. Record the message ID in the same transaction as the side effect (see Idempotent Consumers & the Inbox Pattern):
-- PostgreSQL: processed-message inbox; the side effect and the mark commit together.
CREATE TABLE inbox (
consumer text NOT NULL,
message_id text NOT NULL,
processed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (consumer, message_id)
);
BEGIN;
WITH claimed AS (
INSERT INTO inbox (consumer, message_id) VALUES ('billing', 'orders-3-18342')
ON CONFLICT DO NOTHING RETURNING 1
)
UPDATE invoices SET status = 'issued'
WHERE order_id = 7781 AND EXISTS (SELECT 1 FROM claimed);
COMMIT; -- then ack / commit the offsetHot keys deserve a word: hashing a key to a partition or lane serialises that key, which is the point, but a tenant with 70% of the traffic turns 24 partitions into one. Options are a finer key (order ID instead of tenant ID), splitting the hot tenant onto its own topic or queue, or salting the key (tenant-42#0..7) when the work is commutative and order does not matter. See Ordering & Partitioning.
Choosing
| Workload | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Independent background jobs inside one Laravel app | Laravel redis or database queue, Horizon auto | --max-jobs, --max-time, idempotent jobs | No new infrastructure; process-level scaling is enough |
| Slow, uneven tasks across services | RabbitMQ quorum queue, many consumers, prefetch 1 | Delivery limit + DLX, KEDA on queue length | Fair dispatch, per-message retry |
| Fast, uniform tasks at high rate | RabbitMQ with prefetch from the capacity formula (tens to low hundreds) | Go pool sized to prefetch | Throughput without unbounded buffers |
| Ordered per entity, parallel overall | Kafka consumer group with a good key, or RabbitMQ consistent-hash + SAC queues | Keyed pool inside the consumer | Order per key, parallel across keys |
| Strictly ordered stream with failover | RabbitMQ SAC queue, or Kafka with one partition | Consumer priorities, static member | One active reader, automatic takeover |
| Event stream with many independent readers | Kafka, one consumer group per service | Cooperative-sticky, static membership, KIP-848 | Fan-out between groups, competition within |
| Queue semantics but Kafka is the platform | Kafka 4.2+ share group | delivery.count.limit, AckRelease | No over-partitioning |
| Already on Redis, moderate volume | Redis Streams consumer group | Reaper with XAUTOCLAIM, stable names | No new broker; accept manual recovery |
| Spiky load, cost-sensitive | Any broker + KEDA, scale to zero | Activation thresholds, cooldown | Pay only when work waits |
In production systems
- Kafka group ceiling and timers. Members beyond the partition count receive no assignment (EIP's Kafka note; KEDA documents the same reason for not exceeding partitions).
session.timeout.ms(45 s) andmax.poll.interval.ms(5 min) are separate failure detectors, documented side by side in the consumer configs, and undergroup.protocol=consumerthe session and heartbeat settings move to the broker. - RabbitMQ prefetch scope and limits. Prefetch is per consumer in RabbitMQ (a documented deviation from AMQP 0-9-1); global QoS is deprecated and disabled by default from 4.3; quorum queues default to a delivery limit of 20 since 4.0 and are the only queues with delivery acknowledgement timeouts from 4.3.
- Redis consumer bookkeeping.
XINFO CONSUMERSchanged the meaning ofidlein 7.2.0 and addedinactive;XAUTOCLAIMexists since 6.2.0;XGROUP DELCONSUMERdiscards a consumer's pending entries. - Laravel workers.
--max-jobs,--max-time,--memory,queue:restartand Horizon'sbalance/autoScalingStrategy/balanceMaxShift/balanceCooldownare documented levers; therabbitmq:consumecommand's source sets--prefetch-count=1000as its default.
In architecture: from a single process to a distributed system
Monolith (one process, one database)
A Laravel app with the database or redis queue driver already has competing consumers: every queue:work process competes for the same jobs. The simplest correct setup is Supervisor with numprocs sized by Little's law, idempotent jobs, nested timeouts and queue:restart in the deploy script. Example: an online shop renders invoice PDFs; 600 orders per minute at 1.2 s each needs about 18 workers (capacity math), and the database pool must admit 18 more connections. A Go monolith does the same in-process with a bounded pool reading from a channel or a SKIP LOCKED table.
Modular monolith (several modules, maybe several databases)
Give each module its own queue (billing, notifications, search-index) and its own worker pool, so a flood of notifications cannot starve billing. With Horizon, one supervisor per module with its own minProcesses/maxProcesses is the bulkhead. Example: the notifications module sends 50,000 e-mails after a campaign. With a shared queue, billing jobs wait behind them for 20 minutes. With separate queues, Horizon's auto strategy shifts processes to notifications and billing keeps its minimum.
Microservices
Each service owns a consumer group (Kafka) or a queue (RabbitMQ) and scales its own replicas. What survives across the boundary is the contract: at-least-once delivery, idempotent handlers, per-key ordering when needed. What does not survive is any assumption about who processes what. Example flow: orders publishes OrderPlaced (key = order ID) to Kafka through an outbox. billing (group billing, 12 replicas on 24 partitions, cooperative-sticky, static members) issues invoices with an inbox table. shipping (group shipping, 4 replicas) reserves stock. Both scale on lag with KEDA, and a deploy of billing causes no rebalance in shipping because the groups are independent. See Service Communication, Domain Events vs Integration Events and Designing for Failure & Reliable Messaging.
Distributed data (replicas, clusters, regions)
Scaling consumers multiplies load on everything they touch. The database becomes the cap: 40 pods × 16 goroutines = 640 connections against a primary that allows 200, so size goroutines to a connection pool and put PgBouncer in front. Reads that consumers do after a write elsewhere may hit a lagging replica (Replication & Failover). Broker-side, a quorum queue's leader and a Kafka partition leader live on one node; consumers in other zones pay cross-zone latency (raise prefetch, or prefer local consumers with x-priority / Kafka rack-aware fetching). A Redis stream is on one shard of a cluster, so N streams spread work across shards. Across regions, consume locally and replicate the stream (MirrorMaker, federation, shovels) rather than stretching one consumer group over a WAN.
Scaling path (1×, 10×, 100×)
| Load | Design | What changes |
|---|---|---|
| 1× (tens of msg/s) | One queue, 2–4 workers, Supervisor, prefetch 1 | Idempotent jobs, timeouts, queue:restart on deploy |
| 10× (hundreds to thousands/s) | Horizon auto or KEDA on depth; Go pools sized by Little's law; RabbitMQ prefetch from the formula | Separate queues per module; DB pool budget per worker type; lag and age-of-oldest alerts |
| 100× (tens of thousands/s and more) | Kafka with partitions planned for peak, cooperative-sticky + static membership or KIP-848; share groups for task-style topics; keyed pools for per-key order | Multiple streams/queues to spread broker leaders; per-region consumption; rebalance and lag dashboards per partition |
Lab
Goal: scale from 1 to 8 consumers and observe throughput and lag. Expected, not run: no brokers or containers were started. Use disposable broker endpoints already available to you, create the named queues/groups with appropriate credentials, and run commands from the snippet Go module. The 50 ms service time below is a hypothetical configuration: change the RabbitMQ sample's workers to 1 and its one-second stand-in delay to 50 ms before comparing those formulas. Original snippets deliberately use different delays to expose concurrency.
RabbitMQ, prefetch 1, 1 → 8 consumers. Publish 10,000 messages to
jobs, start the Go consumer withworkers=1, then 8 processes.bashAMQP_URL=amqp://guest:guest@localhost:5672/ go run ./after/rabbitmq & # x1, then x8 watch -n1 'rabbitmqctl list_queues name messages_ready messages_unacknowledged consumers' # expected: 1 consumer -> ~20 msg/s, ready falls slowly, unacked 1 # expected: 8 consumers -> ~160 msg/s, unacked 8, consumers 8RabbitMQ, uneven jobs, prefetch 1 vs 100. Make every 10th job take 5 s. With prefetch 100 one consumer holds a batch of slow jobs while others finish early (unacked stays high on one consumer in the management UI); with prefetch 1 the total time drops and per-consumer unacked is 1.
Kafka, 6 partitions, 1 → 8 members.
bashkafka-topics.sh --create --topic invoices --partitions 6 --bootstrap-server localhost:9092 KAFKA_BROKER=localhost:9092 POD_NAME=billing-0 go run ./after/kafka & # then billing-1 .. billing-7 kafka-consumer-groups.sh --describe --group billing-workers --bootstrap-server localhost:9092 # expected with 8 members: 6 rows with a CONSUMER-ID, 2 members own nothing # expected throughput: rises up to 6 members, flat from 6 to 8 # expected LAG column: falls on every partition; restarting billing-3 within 45 s leaves its # partitions unassigned briefly but triggers no rebalance (static membership)Kafka, eager vs cooperative. Swap
kgo.CooperativeStickyBalancer()forkgo.RangeBalancer()and add a member while watching lag: with range, lag rises on all six partitions during the rebalance; with cooperative-sticky, only on the two that move.Redis Streams, 1 → 8 consumers, then kill one.
bashREDIS_ADDR=localhost:6379 go run ./after/redis & # x8 redis-cli XINFO GROUPS jobs # expected: lag falls; pending ~= 8 x COUNT while busy kill -9 <pid of one consumer> redis-cli XPENDING jobs workers # expected: that consumer's entries remain pending REDIS_ADDR=localhost:6379 go run ./after/reclaim # after 60 s idle: entries claimed, ackedLaravel, Horizon auto balancing. Dispatch 5,000
RenderInvoicePdfjobs toinvoicesand 100 todefault, runphp artisan horizon, and watch the dashboard: processes move towardinvoicesone every 3 s (balanceMaxShift1,balanceCooldown3) up tomaxProcesses, then back down as the queue drains. This is an expected pattern; actual adjustments depend on measured runtime, minimum process counts and workload.
Common misconceptions
| Belief | Reality |
|---|---|
| More consumers always means more throughput | Not past Kafka's partition count, a single active consumer, a hot key, or the downstream's capacity |
| A FIFO queue gives ordered processing with many consumers | Delivery is ordered; completion is not. Order needs one consumer, SAC, or per-key routing |
| Prefetch is only a performance setting | It decides fairness and how much work is redelivered after a crash |
| Prefetch 1 is always safest | It is fair but can sharply reduce throughput on high-latency links and idles a concurrent consumer |
| Kafka balances messages across consumers | It balances partitions; a slow member's partitions wait for it |
| Cooperative rebalancing has no pause | Moving partitions pause and restart from the last commit |
| Static membership removes rebalances | It removes restart-caused ones and delays detection of real failures |
| KIP-848 is on by default | Java and librdkafka clients default to group.protocol=classic |
| Redis redelivers unacked entries | Entries stay in the dead consumer's PEL until claimed |
| Autoscale workers on CPU | I/O-bound consumers look idle with a huge backlog; scale on lag, depth or age |
| A goroutine per message is fine in Go | Unbounded concurrency floods memory and downstreams; use a bounded pool |
| Graceful shutdown is optional with at-least-once | Unclean stops cause duplicates, rebalances and stuck entries |
Cheat sheet
| Topic | Remember |
|---|---|
| The pattern | Many consumers, one point-to-point channel, each message to one consumer (EIP) |
| Ceilings | RabbitMQ: queue/node; Kafka: partitions; Redis: shard per stream; Laravel: processes and DB pool |
| Prefetch | Per consumer in RabbitMQ; = rate × (service + RTT); 1 for slow uneven jobs |
| Laravel RabbitMQ | rabbitmq:consume defaults to prefetch 1000: set --prefetch-count |
| Kafka timers | Heartbeat ≤ 1/3 session; max.poll.interval.ms > slowest batch |
| Assignors | Cooperative-sticky over range/roundrobin/sticky |
| Static membership | group.instance.id = stable pod name + session timeout > restart |
| KIP-848 | group.protocol=consumer, broker 4.0+, timers on the broker |
| Share groups | Kafka 4.2+, queue semantics, per-record ack, no partition ceiling |
| SAC | x-single-active-consumer at declare; ordered with failover |
| Redis recovery | XAUTOCLAIM reaper + delivery cap + stable names |
| Go pool | Semaphore or errgroup.SetLimit; keyed lanes for per-key order |
| Shutdown | Stop fetch → nack unstarted → drain with deadline → ack/commit → close |
| Laravel | numprocs/Horizon auto; --max-jobs, --max-time, --memory; queue:restart |
| Autoscale | KEDA on lag/depth/age; Kafka capped at partitions by default |
| Duplicates | Inevitable with rebalances: inbox table or idempotent handler |
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 — A RabbitMQ queue has 4 consumers with prefetch 50, and jobs take between 10 ms and 30 s. Two consumers are idle while the queue still has messages. Why, and what do you change? Important
Answer
Answer: Each consumer was pushed up to 50 unacked messages when they arrived; a consumer holding several 30 s jobs works through its buffer while the others have drained theirs and the queue's remaining messages are already assigned. Lower the prefetch to 1 (or to the consumer's real concurrency) so the broker only hands work to consumers that are free.
2 — A Kafka topic has 8 partitions and the group has 12 replicas. What do the extra 4 do? Must-know
Answer
Answer: Nothing useful: each partition has one owner, so 4 members get no assignment. They still join every rebalance. Add partitions (with care for key mapping), reduce replicas to 8, or use a share group if the work is independent tasks.
3 — A consumer takes up to 7 minutes on some batches and keeps getting kicked out of the group. Which setting is involved and what are two fixes? Must-know
Answer
Answer: max.poll.interval.ms (default 300000, 5 minutes): if poll() is not called within it, the member is considered failed. Fix by lowering max.poll.records so a batch finishes sooner, raising max.poll.interval.ms above the slowest batch, or moving slow work off the poll thread (pausing partitions meanwhile).
4 — What does group.instance.id change during a rolling deploy, and what is the price? Important
Answer
Answer: A restarted member with the same ID rejoins within the session timeout and gets its partitions back without a group rebalance. The price is slower failover: if the member is really dead, its partitions are unconsumed until the session timeout expires.
5 — Under group.protocol=consumer, you set session.timeout.ms=120000 on the client. What happens? Good to know
Answer
Answer: It is not supported for that protocol; the session timeout is the broker's group.consumer.session.timeout.ms. Tune it on the broker.
6 — When would you pick a Kafka share group over a consumer group? Good to know
Answer
Answer: When records are independent work items that need per-record ack/retry and more parallelism than partitions, and ordering does not matter (Kafka 4.2+ where share groups are production-ready). Keep consumer groups for ordered event processing and replay.
7 — A Redis Streams worker was OOM-killed. Its entries never come back. Why, and how do you fix it permanently? Important
Answer
Answer: Redis does not redeliver: the entries stay in that consumer's PEL. Run a reaper that calls XAUTOCLAIM with a min-idle-time above the slowest normal job, cap delivery count to park poison entries, use stable consumer names, and delete stale consumers only after their PEL is empty.
8 — How many Laravel workers do you need for 900 jobs per minute averaging 2 s, at 70% target utilisation? Must-know
Answer
Answer: λ = 15 jobs/s; busy = 15 × 2 = 30; 30 / 0.7 ≈ 43 processes. Then check the database and any API those jobs call can take 43 concurrent clients.
9 — Why is CPU a poor autoscaling signal for consumers, and what do you use per broker? Important
Answer
Answer: I/O-bound consumers wait on databases and HTTP and show low CPU even with a huge backlog, and CPU cannot scale from zero. Use queue length (RabbitMQ, KEDA QueueLength over HTTP to count unacked), consumer-group lag (Kafka, KEDA lagThreshold), stream lag or pending entries (Redis, KEDA lagCount / pendingEntriesCount), list length for Laravel's redis queue, plus the age of the oldest message as the SLO.
10 — Write the five steps of a graceful consumer shutdown in order. Must-know
Answer
Answer: Stop fetching (cancel the consumer / stop polling); give back buffered unstarted messages; wait for in-flight handlers with a deadline shorter than the grace period; ack / commit offsets / XACK; leave the group and close the connection.
11 — A Go Kafka consumer processes records of one partition with 16 goroutines and commits the highest offset seen. What can go wrong? Must-know
Answer
Answer: Per-partition order is lost, and committing the highest offset can mark records below it as done while they are still running or have failed; after a crash they are skipped. Process a batch, verify all handlers succeeded, then commit, or use a keyed pool and commit only contiguous completed offsets.
Glossary
| Term | Meaning |
|---|---|
| Competing Consumers | EIP pattern: several consumers on one point-to-point channel, each message to one of them |
| Point-to-Point Channel | One receiver per delivery; recovery may redeliver to another receiver |
Prefetch (basic.qos) | RabbitMQ limit on unacked deliveries per consumer |
| Fair dispatch | Giving the next message to a consumer that is free, achieved with prefetch 1 |
| Round-robin dispatch | Rotating among eligible consumers; finite prefetch excludes full consumers |
| Single active consumer (SAC) | RabbitMQ queue feature: one consumer receives, others stand by and fail over |
Consumer priority (x-priority) | RabbitMQ consumer argument; higher-priority unblocked consumers receive first |
| Quorum queue | RabbitMQ replicated (Raft) queue type with delivery limit and consumer timeout |
| Delivery limit | Max redeliveries before a quorum queue dead-letters or drops a message (default 20 since 4.0) |
| Consumer group | Kafka members sharing a group.id; each partition assigned to one member |
| Partition | Kafka's ordered log shard and its unit of consumer parallelism |
| Group coordinator | The broker that manages a group's membership and offsets |
| Rebalance | Reassignment of partitions when membership or subscriptions change |
| Eager rebalancing | Every member revokes all partitions before reassignment (stop-the-world) |
| Cooperative rebalancing | Only partitions that change owner are revoked (KIP-429) |
| Assignor | Algorithm mapping partitions to members: Range, RoundRobin, Sticky, CooperativeSticky, server-side uniform/range |
| Static membership | Member with a fixed group.instance.id whose short restart can avoid a rebalance (KIP-345) |
session.timeout.ms | Classic-protocol liveness timeout without heartbeats |
heartbeat.interval.ms | Classic-protocol heartbeat period |
max.poll.interval.ms | Max time between polls before a member is considered failed |
max.poll.records | Max records returned by one poll (Java client) |
| KIP-848 | Kafka 4.0 broker-side consumer group protocol (group.protocol=consumer) |
| Share group | Kafka 4.2+ group type with queue semantics and per-record acks (KIP-932) |
| Acquisition lock | Time-limited lock a share-group member holds on fetched records |
| Consumer lag | Log-end offset minus committed offset, per partition; the main Kafka scaling signal |
| Age of oldest message | Time the oldest unprocessed message has waited; the user-facing latency signal |
| Pending entries list (PEL) | Redis Streams record of delivered, unacked entries per group and consumer |
XAUTOCLAIM | Redis command that transfers idle pending entries to another consumer (since 6.2.0) |
XINFO CONSUMERS | Redis command showing per-consumer pending, idle and inactive |
| Worker pool | Fixed number of goroutines or processes processing messages |
| Semaphore | Counter that bounds concurrency; a buffered channel in Go |
errgroup.SetLimit | Go x/sync method bounding active goroutines in a group |
| Keyed pool / per-key serialisation | Hashing a key to a lane so same-key messages run in order |
| Head-of-line blocking | A slow message delays the ones queued behind it in the same lane or partition |
| Hot key | A key with disproportionate traffic that overloads its partition or lane |
| Graceful shutdown | Stop fetching, drain, ack/commit, close before SIGKILL |
signal.NotifyContext | Go helper returning a context cancelled on given signals |
terminationGracePeriodSeconds | Kubernetes time between SIGTERM and SIGKILL (30 s default) |
queue:work | Laravel worker process; one job at a time |
| Horizon | Laravel dashboard and supervisor for Redis queues with balancing strategies |
balance / autoScalingStrategy | Horizon worker allocation: auto (time, size, log), simple, false |
queue:restart | Laravel command that makes workers exit after their current job |
| KEDA | Kubernetes event-driven autoscaler with scalers per broker |
| HPA | Kubernetes Horizontal Pod Autoscaler, which KEDA drives |
| Little's law | L = λ × W: items in system = arrival rate × time in system |
| Inbox | Message IDs committed atomically with an effect, preventing that effect on duplicate delivery |
SKIP LOCKED | SQL clause that lets workers claim different rows without waiting |
| Cooperative-sticky | KIP-429 classic-protocol assignor retaining unchanged partitions |
| SIGTERM / SIGKILL | Cooperative stop request / immediate process termination |
| --max-jobs / --max-time | Laravel limits for recycling long-lived workers between jobs |
| KIP-62 / KIP-429 / KIP-345 | Background heartbeats / incremental rebalancing / static membership |
| XGROUP DELCONSUMER | Remove consumer state only after fencing and resolving pending entries |
| group.protocol / group.remote.assignor | Kafka group protocol selection / broker-side assignor choice |
| group.consumer.session.timeout.ms / group.consumer.heartbeat.interval.ms | Broker-controlled session and heartbeat timers for KIP-848 |
| RebalanceTimeout / rebalance.timeout.ms | franz-go group handoff budget; distinct from Java poll API |
| BlockRebalanceOnPoll / AllowRebalance | franz-go ownership hold / release around processing a fetched batch |
| REBALANCE_IN_PROGRESS / UNKNOWN_MEMBER_ID / ILLEGAL_GENERATION | Commit conflicts with group transition or obsolete membership |
| FENCED_INSTANCE_ID / STALE_MEMBER_EPOCH / FENCED_MEMBER_EPOCH | Duplicate static identity or invalid consumer-protocol epoch |
| CommitFailedException | Java exception for an unrecoverable offset commit, often after reassignment |
| PRECONDITION_FAILED / UNKNOWN_DELIVERY_TAG | AMQP channel precondition failure / acknowledgement of an invalid tag |
| delivery.count.limit | Share-group maximum delivery attempts for one record |
| AckAccept / AckRelease / AckReject / AckRenew | Share record success / retry / reject / extend acquisition |
| COUNT / XPENDING / XCLAIM / XACK | Redis batch bound / pending inspection / ownership transfer / settlement |
| idle / inactive | Redis consumer time since attempted / successful interaction (7.2+) |
| retry_after / visibility timeout | Reservation expiry before another worker may receive unfinished work |
| stopwaitsecs / horizon:terminate | Supervisor stop grace / graceful Horizon restart request |
| minProcesses / maxProcesses | Horizon minimum allocation / supervisor process ceiling |
| balanceMaxShift / balanceCooldown | Horizon change limit per adjustment / interval between adjustments |
| lagThreshold / listLength / lagCount / pendingEntriesCount | KEDA targets for Kafka backlog / Redis list / stream lag / stream pending |
| MaxAckPending / MaxNumberOfMessages / MessageGroupId | JetStream shared in-flight ceiling / SQS receive size / SQS FIFO ordering group |
| Shared / Key_Shared | Pulsar subscriptions sharing messages / preserving key affinity |
References
Hohpe & Woolf, "Competing Consumers", Enterprise Integration Patterns. enterpriseintegrationpatterns.com
RabbitMQ, "Work Queues" tutorial (Go). rabbitmq.com
RabbitMQ, Consumer Prefetch. rabbitmq.com
RabbitMQ, Consumer Acknowledgements and Publisher Confirms (prefetch and throughput). rabbitmq.com
RabbitMQ, Consumers (single active consumer, priority, acknowledgement timeout). rabbitmq.com
RabbitMQ, Consumer Priorities. rabbitmq.com
RabbitMQ, Channels. rabbitmq.com
RabbitMQ, Quorum Queues. rabbitmq.com
Apache Kafka, Consumer Configs (4.2). kafka.apache.org
KIP-62: Allow consumer to send heartbeats from a background thread. cwiki.apache.org
KIP-345: Introduce static membership protocol to reduce consumer rebalances. cwiki.apache.org
KIP-429: Kafka Consumer Incremental Rebalance Protocol. cwiki.apache.org
KIP-848: The Next Generation of the Consumer Rebalance Protocol. cwiki.apache.org
KIP-932: Queues for Kafka. cwiki.apache.org
Apache Kafka 4.0.0 and 4.2.0 release announcements. 4.0, 4.2
librdkafka, CONFIGURATION.md. github.com
Redis, Streams, XAUTOCLAIM, XINFO CONSUMERS, XGROUP DELCONSUMER
Laravel 13: Queues, Horizon, Artisan signal handling
vladimir-yuldashev/laravel-queue-rabbitmq. github.com
mateusjunges/laravel-kafka, Consumer groups and consumer options. laravelkafka.com
KEDA scalers: RabbitMQ Queue, Apache Kafka, Redis Streams, Redis Lists
Go: amqp091-go, franz-go kgo, go-redis, errgroup
AWS SQS ReceiveMessage, NATS JetStream consumers, Pulsar Messaging concepts.
Apache Kafka Java CommitFailedException source.
Kubernetes Pod termination lifecycle, AWS SQS FIFO queues.