Skip to content

Backpressure & Flow Control ​

“RabbitMQ will reduce the speed of connections which are publishing too quickly for queues to keep up.” — RabbitMQ documentation, Flow Control

Summary: Backpressure is how a slow part of a pipeline tells faster parts to wait, so queues stay bounded and latency stays honest. Focus: Bounded buffers, Little's law, lag and wait-time signals, prefetch and poll limits, shedding, rate limiting, shutdown, and each broker's real knobs. Learning goal: Given a growing backlog, name the signal, pick block / shed / scale, and set the matching limit in Go, RabbitMQ, Kafka, Redis Streams or Laravel.

This chapter owns the overload path of a messaging system. Competing consumers owns how to add consumers and rebalance; acknowledgment owns the ack primitives that make prefetch meaningful; retry and backoff owns retry schedules; dead-letter queues own terminal failures. System-wide counterparts live in load shedding and rate limiting algorithms. Here the question is narrower: when messages arrive faster than they are finished, who waits, who is refused, and what do you measure?

Page map ​

Looking forGo to
What backpressure is and what it is notBackpressure vs buffering
Why an unbounded queue only hides the problemBounded buffers
How many workers and how big a queueLittle's law
Why pull-based consumers behave differently from pushPull, push and credit
The numbers to alert onLag and signals
RabbitMQ basic.qos and prefetch_countPrefetch, RabbitMQ
Refusing work on purposeShedding and admission
Slowing producers with a token bucketRate limiting
Stopping without losing workGraceful shutdown
Exact broker settingsMechanics, Broker differences
Laravel queue:work flags and HorizonLaravel
A reproducible experimentLab

Everything in one minute ​

QuestionWorking answerFailure if ignored
What is backpressure?A signal from a slow consumer or resource back to its sources: wait, slow down, or stopThe fast side keeps producing; memory, disk or latency absorbs the difference until something breaks
Is a bigger queue a fix?It is a delay: it absorbs bursts, not sustained excessWaiting time grows without limit while every message still “succeeds”
What must be bounded?Queue length, in-flight messages per consumer, worker concurrency, retries, client buffersOne unbounded stage becomes the out-of-memory victim
What do you do when the bound is hit?Choose explicitly: block the producer, reject, drop the oldest, or drop the newestThe default (often blocking forever or growing) is chosen for you
Which number tells you first?Consumer lag, queue depth and age of the oldest message, not CPUCPU stays low while the queue is hours deep
Who sets the pace in a pull broker?The consumer, by how often and how much it pollsAssuming the broker will push less when you are slow
What does Little's law give you?L = λ × W: items in the system equals arrival rate times time in the systemGuessing worker counts and queue sizes
MechanismRabbitMQKafkaRedis StreamsLaravel worker
Consumer-side windowbasic.qos prefetch (per consumer)max.poll.records, fetch sizesCOUNT on each readOne job at a time per process, --sleep when idle
Producer-side signalConnection flow state, connection.blocked, publisher nackClient buffer full: buffer.memory, max.block.ms; broker quotas throttleNone: XADD never blocksDispatch never blocks; check queue size yourself
Bound on stored backlogx-max-length with overflowRetention (time or size), not a consumer-aware limitMAXLEN / MINID trimmingNot built in; limit at dispatch
Lag signalReady and unacknowledged countsConsumer lag per partition, records-lag-maxXINFO GROUPS lag and pendingQueue::size, Horizon wait times
Overload defaultBlock publishers on alarms; head drop when length limit hitProducer blocks then errors; broker throttles by quotaData loss on trim, or memory growthBacklog grows silently

Where it comes from ​

Queueing arithmetic is older than message brokers. John Little proved in 1961 the relation now called Little's law and described it fifty years later as: “the average number of items in a queuing system, denoted L, equals the average arrival rate of items to the system, λ, multiplied by the average waiting time of an item in the system, W”. The relation holds for a long-run average whatever the shape of the arrival and service times, which is why it applies equally to a queue, a thread pool or a whole service.

Flow control in networking and messaging follows the same logic. Apache Kafka's design notes explain why the consumer pulls: “a push-based system has difficulty dealing with diverse consumers as the broker controls the rate at which data is transferred.” RabbitMQ's documentation describes the opposite problem: a node whose components “fall behind particularly fast publishers”, so it applies a back-pressure mechanism to publishing connections “in order to avoid runaway memory usage growth”. This page uses “backpressure” in the broad sense of any feedback from a slow stage to the faster stages feeding it.

Why it exists ​

Every pipeline has a slowest stage. If upstream rates exceed that stage, the difference has to go somewhere. There are only four places: into a buffer, onto the producer (it waits), into the bin (shed), or into more capacity (scale). Backpressure is the discipline of choosing among them deliberately.

Let the buffer absorb itPush the wait back to the producer
Producers stay fast and simpleProducers must handle waiting, timeouts or refusal
Bursts are smoothed without dropsSustained excess is visible immediately
Memory or disk grows; latency grows with depthLatency stays bounded; throughput equals the slowest stage
Failure arrives late and large (out of memory, disk alarm)Failure arrives early and small (a rejected request)
Shed or rejectAdd capacity
Protects the stage and the work that is still usefulKeeps all work, at a cost
Needs a policy: oldest, newest, lowest priorityNeeds headroom, a scalable resource and time to scale
Fine for telemetry, searches, anything that expiresDoes nothing if the bottleneck is a shared database or partner API

Three misunderstandings to remove first: a growing queue is not “healthy buffering” if it never shrinks; backpressure is not an error, it is the system working; and adding consumers helps only when the slow resource is the consumer, not what the consumer calls.

What it is really about ​

Backpressure is a control loop with a sensor, a decision and an actuator. The sensor is a number (depth, lag, wait time, a full buffer, a rejected publish). The decision is the overload policy. The actuator is one of: block the sender, slow the sender, refuse work, or change capacity. A system without a sensor has no backpressure; a system without a bound has a sensor that fires too late.

Producersarrival rate (lambda)Bounded buffercapacity N, depth LConsumersservice rate (mu)Signalsdepth, lag, wait timeOverload policyblock, shed, or rejectScale or slowworkers, rate limitfull or deepslow downdrain fasterLittle: L = lambda x W. If lambda exceeds mu, W and L grow until a bound or a failure.

The loop must be fast relative to the problem and slow relative to noise. A depth reading that flaps around a single threshold makes producers stop and start in bursts; use two thresholds (a high and a low watermark) so the system pauses at one level and resumes at a lower one. The Go snippet's Gate does exactly that.

An everyday picture ​

A restaurant kitchen has a pass where plates wait. If the pass has six slots and they are full, cooks stop plating until a server takes one: that is a bounded buffer with blocking. A host who tells new guests “forty minutes” is admission control. A kitchen that keeps taking orders onto an ever-longer rail of tickets has no backpressure: every guest is “accepted”, and every guest waits two hours. The kitchen did not become faster; the wait just moved from the door to the table, where it is harder to fix.

Concept catalogue ​

Backpressure vs buffering Must-know ​

In plain words: Buffering stores the excess; backpressure refuses to create it. A buffer buys time, backpressure removes the cause.

Common misunderstanding: “Our broker queues messages, so we have backpressure.” A queue that grows is the absence of backpressure: the producer never learned the consumer was slow. Backpressure exists when the producer's behaviour changes because of the consumer's state.

Definition: Backpressure is feedback that makes the rate of a producer depend on the capacity of its consumer or of a shared resource. It can be implicit (a blocking call, a full TCP window, a full channel) or explicit (a nack, a credit, a lag metric that a controller reads).

text
1 t=0   producer 500/s  -> queue (cap 1000) -> consumer 200/s
2 t=3s  queue full (net +300/s)
3 t=3s  producer.send blocks / returns 'full'   <- backpressure starts
4 t=3s+ producer effective rate falls to 200/s, queue stays at 1000
5 no backpressure: queue keeps growing, wait = depth / 200 per second

Real scenarios: A Go service writes events to a channel read by one flusher; a RabbitMQ publisher is throttled during a memory alarm; a Kafka producer blocks because the broker is slow; a Laravel scheduler dispatches 100,000 jobs against a partner API limited to ten requests per second.

FormExampleWho feels it
BlockingFull bounded channel, full producer buffer, TCP windowThe calling thread or request
RefusalPublisher nack, HTTP 429/503, ErrShedThe caller, immediately, with a code to act on
SlowingToken bucket Wait, Kafka quota delay, RabbitMQ connection flowThe producer, as added latency
Pause intakeConsumer stops polling or PauseFetch, Horizon scales downUpstream sees growing lag, not an error

Fix / how to use it: Decide per path whether work is “must not lose” (block or slow) or “fine to drop” (shed). Go and Laravel examples follow in Go and Laravel.

Bounded vs unbounded buffers Must-know ​

In plain words: A bounded buffer has a maximum size and a rule for what happens at the maximum. An unbounded one has neither, so the rule is “run out of memory”.

Common misunderstanding: “Memory is cheap; make the queue huge.” Size does not change the rate equation. A bigger buffer only moves the day of failure and makes every message wait longer first, which is worse for work that expires.

Definition: A buffer is bounded when both its count (or bytes) and its full-buffer behaviour are fixed in configuration. Unbounded in effect includes: a channel with a billion slots, a slice that appends forever, a stream with no MAXLEN, a topic whose retention exceeds disk, a client that retries into an in-memory list, and a prefetch of zero (RabbitMQ treats 0 as no limit).

text
1 arrival 200/s, service 160/s, queue unbounded
2 backlog grows 40/s -> 2,400 after 1 min -> 24,000 after 10 min
3 new message waits depth / 160/s = 150 s after 10 min
4 message TTL is 60 s -> every message is expired before it is served
5 bounded queue (cap 2,000): wait <= 12.5 s, excess is refused at the door

Real scenarios: A reporting job whose results are valid for one minute; chat presence updates where only the newest matters; an order queue where nothing may be lost and the producer can wait; a log pipeline that may drop debug lines but not audit lines.

Overflow policyWhat happensTypical use
Block the producerSender waits for roomLossless internal pipelines
Reject the newestNew item refused, caller informedAdmission control, order intake
Drop the oldestHead of queue discardedLatest-value data, RabbitMQ drop-head default
Drop by priorityLowest class dropped firstMixed traffic with a protected class
Spill to diskBuffer on disk, bounded by diskShort outages only; disk alarm is the next bound

Fix / how to use it: Pick the bound from Little's law (below), pick the policy from the business value of waiting, and make the policy visible in a metric (shed count, rejected publishes). The Go Pipeline exposes Shed, Depth and AvgWait.

Little's law and queueing intuition Must-know ​

In plain words: The number of messages in the system equals how fast they arrive times how long each stays. If you know two, you know the third.

Common misunderstanding: “Utilisation of 90% is fine because we are below 100%.” Waiting time rises sharply as utilisation approaches 1 even when the average rate is sustainable, because bursts have nowhere to go. Capacity planning needs headroom, not equality.

Definition: L = λ × W (Little, 1961). In a stable system, L is the average number of items in the system, λ the average arrival rate, W the average time an item spends in the system, queue plus service. Applied to the service stage only, L_service = λ × service time is the average number of busy workers. Stability requires λ < c × μ where c is the worker count and μ the per-worker service rate.

text
1 arrival lambda = 200 msg/s, service time = 50 ms
2 busy workers needed = 200 x 0.05 = 10  -> MinWorkers(200, 50ms) = 10
3 with 8 workers: capacity = 8 / 0.05 = 160 msg/s < 200  -> unstable
4 with 12 workers: capacity 240/s, utilisation 200/240 = 83%
5 target wait W = 1 s and lambda = 200  -> about L = 200 messages in the system

Real scenarios: Choosing maxProcesses for Horizon; sizing a Go worker pool; deciding whether a 10,000-message queue is acceptable (at 100 msg/s drain it is 100 s of delay); computing how long a recovery backlog takes to clear.

QuantityHow to get itUse
λ (arrival rate)Publish rate metricRequired capacity
Service timeHandler duration histogram, p50 and p99Workers needed = λ × service time
W (time in system)Age of oldest message, consume time minus publish timeSLO check
LQueue depth plus in-flightCross-check: L should equal λ × W
Drain timeBacklog ÷ (capacity − λ)Recovery planning: 1,000,000 ÷ (300 − 100) = 5,000 s

Fix / how to use it: Use pipeline.Occupancy and pipeline.MinWorkers in tests or capacity scripts. In SQL, the same law on a database-backed queue appears as ready jobs ÷ drain rate.

Pull, push and credit-based flow Must-know ​

In plain words: In a pull system the consumer asks when it is ready. In a push system the broker sends and relies on a limit so the consumer is not flooded. A credit is permission to send a fixed amount more.

Common misunderstanding: “Kafka consumers are pull-based, so they can never be overwhelmed.” Pull protects the consumer's memory; it does not stop the backlog on the broker from growing, and a slow consumer pays with lag and possibly rebalances.

Definition: Credit-based flow control gives the sender a number of credits; each message consumes one; the receiver replenishes credits as it finishes work. RabbitMQ's consumer prefetch is a credit window for push delivery: the broker sends up to prefetch_count unacknowledged messages and then waits for acks. Kafka and Redis Streams invert control: the client requests data (poll, XREADGROUP), so each request is an implicit credit. AMQP 1.0 uses explicit link credit. Inside RabbitMQ, flow control applied by channels, queues and other components “eventually propagates back to publishing connections”, which is what shows up as a connection in flow state.

text
1 broker has 500 ready messages, consumer prefetch = 3
2 broker -> consumer: m1 m2 m3         (3 unacked, window full)
3 consumer -> broker: ack m1
4 broker -> consumer: m4               (window refilled by one)
5 consumer stalls; m2 m3 m4 stay unacked, broker sends nothing more
6 consumer crashes -> m2 m3 m4 returned to the queue, redelivered

Real scenarios: A consumer doing slow image resizing with prefetch 1 for fairness; a Kafka consumer calling poll only after finishing a batch; a Redis consumer using BLOCK so it neither spins nor floods.

ModelWho controls rateTypical windowFailure shape
RabbitMQ push with prefetchBroker, up to the windowprefetch_countWindow too large: one consumer hoards messages; too small: idle consumer
Kafka pullConsumerPoll size and fetch bytesPoll too rarely: max.poll.interval.ms exceeded, rebalance
Redis Streams pullConsumerCOUNT, BLOCKUnacked entries accumulate in the PEL
SQS long pollingConsumerMaxNumberOfMessages (1 to 10), WaitTimeSecondsVisibility timeout shorter than processing
NATS JetStreamServer up to ack windowMaxAckPending (default 1000)Set below batch size: throughput capped

Fix / how to use it: Match the window to throughput × round-trip rather than guessing; see Prefetch.

Consumer lag and the signals that matter Must-know ​

In plain words: Lag is how far behind the consumer is. Alert on how big and how old the backlog is, and on whether it is shrinking.

Common misunderstanding: “Low CPU means the consumers are healthy.” A consumer blocked on a slow database has idle CPU and an exploding backlog. CPU measures the consumer; lag measures the pipeline.

Definition: Consumer lag is the amount of data a consumer group has not yet processed. Kafka: log end offset minus committed (or current) offset, per partition; the consumer metric records-lag-max reports the maximum partition lag in the window and is “based on current offset and not committed offset”. Redis: XINFO GROUPS returns lag, “the number of entries in the stream that are still waiting to be delivered to the group's consumers, or a NULL when that number can't be determined”, plus pending, the length of the PEL. RabbitMQ: messages_ready and messages_unacknowledged per queue. Laravel redis driver: Queue::size.

text
1 signal                 healthy                       trouble
2 depth / lag            flat or falling               rising for longer than one burst
3 age of oldest          below SLO                     above SLO even if depth is small
4 consume rate           >= publish rate               < publish rate
5 in-flight / pending    <= window                     stuck at window for minutes
6 shed / reject count    ~0                            rising: capacity or limit too low

Real scenarios: A Kafka group's records-lag-max climbs after a deploy that doubled handler time; a Redis group shows low lag but pending rising because a worker died holding entries; a RabbitMQ queue has few ready messages but many unacknowledged because prefetch is high and handlers hang.

BrokerBacklogStuck workTime-based
RabbitMQmessages_readymessages_unacknowledgedAdd a timestamp property to measure age
KafkaLag per partition, records-lag-maxRebalances, max.poll.interval.ms breachesCompare record timestamp with now
Redis StreamsXINFO GROUPS lagpending, XPENDING idle timeEntry ID is a millisecond timestamp
LaravelQueue::size, Horizon waitReserved jobs past retry_afterHorizon waits threshold

Fix / how to use it: See LagCheck.php in Laravel and reportLag in the Redis Go consumer. Metric collection and tracing are covered in messaging observability.

Prefetch and in-flight limits Must-know ​

In plain words: Prefetch is how many unfinished messages the broker may hand one consumer at a time.

Common misunderstanding: “Prefetch is the batch size.” RabbitMQ prefetch limits unacknowledged deliveries; it says nothing about how you process them, and it has no effect at all on messages fetched with basic.get. A prefetch that is too large does not make a consumer faster; it makes one consumer hold messages other consumers could be working on.

Definition: In AMQP 0-9-1, basic.qos sets a prefetch count. RabbitMQ deviates from the spec: the count is applied separately to each new consumer on a channel rather than shared across the channel. Channel-wide (global) QoS is deprecated and disabled by default starting with RabbitMQ 4.3. A value of 0 means unlimited. The docs report that values in the 100 to 300 range “usually offer optimal throughput and do not run significant risk of overwhelming consumers”; 1 is the most conservative and reduces throughput when connection latency is high. Quorum queues cap consumer prefetch at 2,000 to limit Raft log growth.

text
1 handler = 5 ms, ack round-trip = 20 ms, prefetch = 1
2 each message occupies a consumer for 25 ms -> 40 msg/s
3 prefetch = 5: broker already has 4 queued at the consumer
4 consumer always busy -> limited by the handler: 200 msg/s
5 rule of thumb: prefetch >= (handler + round trip) / handler = 5

Real scenarios: Prefetch 1 for jobs that take minutes and vary widely (fair dispatch); prefetch 50 to 200 for millisecond handlers; an auto-ack consumer that gets flooded (no window at all); a Laravel RabbitMQ worker using queue:work, which polls with basic_get and therefore never uses prefetch, versus rabbitmq:consume --prefetch-count.

SettingEffectRisk
Small prefetch (1 to 10)Fair dispatch, little in memoryIdle gaps when latency is high
Medium (100 to 300)Usually good throughputLarge redelivery batch when a consumer dies
Large or unlimitedMax delivery rateMemory growth in the consumer and broker, hoarding (head-of-line blocking behind slow messages), unfair load
Auto ackNo windowConsumer can be flooded; crash loses in-flight messages
Global (per channel)One shared windowDeprecated; coordination cost; disabled by default from 4.3

Fix / how to use it: Go ch.Qos(10, 0, false) in the RabbitMQ snippet; Laravel rabbitmq:consume --prefetch-count=10. Kafka and Redis equivalents are PollRecords(ctx, 200) and COUNT 50.

Load shedding and admission control Important ​

In plain words: When you cannot do everything, decide early what you will not do, and tell the caller quickly.

Common misunderstanding: “Dropping work is a failure.” Accepting work you cannot finish before it expires is the failure; refusing it at the door costs microseconds, accepting it costs a full queue slot and a late answer.

Definition: Admission control decides at the entrance whether work may enter (rate, concurrency, queue depth, priority). Load shedding discards or rejects work that is already queued or arriving, because capacity is insufficient. They differ in timing; both keep the stage inside its stable region.

text
1 request arrives -> limiter.Allow()?            no -> 429 / ErrRateLimited
2                -> semaphore slot free?          no -> 503 / ErrOverloaded
3                -> queue has room?               no -> shed (drop or reject)
4                -> enqueue; worker finishes; release slot
5 at every refusal: count it, log it with the reason

Real scenarios: A search endpoint that returns 503 above 200 in-flight requests; telemetry that drops samples when the buffer is full; a payments intake that rejects over a per-merchant limit; an email queue that drops marketing but never password resets.

PolicyDropsProCon
Reject newest (tail drop)Latest arrivalsSimple; caller can retryOld, possibly stale work is served
Drop oldest (head drop)Oldest queuedNewest data wins; RabbitMQ default overflowOld work silently lost
Priority sheddingLowest priorityProtects critical trafficNeeds classification
ProbabilisticRandom shareSmoothHard to reason about per customer
Deadline-basedItems already past their TTLWasted work avoidedNeeds timestamps and a clock

Fix / how to use it: The Go admission.Controller combines a token bucket and a semaphore; Pipeline.TrySubmit sheds on a full queue and Stats.Shed counts it. See also load shedding.

Rate limiting producers: the token bucket Important ​

In plain words: A token bucket gives the producer a steady allowance plus a small burst.

Common misunderstanding: “Rate limiting is only for public APIs.” A producer that fans out 100,000 jobs against a partner API is also a client with a rate; limiting at the producer is cheaper than letting workers retry into 429 responses.

Definition: golang.org/x/time/rate: “A Limiter controls how frequently events are allowed to happen. It implements a "token bucket" of size b, initially full and refilled at rate r tokens per second.” Allow never waits, Wait(ctx) blocks until a token or the context ends, Reserve returns a reservation with a delay. Laravel offers RateLimiter::for with RateLimited job middleware (released back with a delay when exceeded) and RateLimitedWithRedis. Algorithm comparisons live in rate limiting algorithms.

text
1 limiter r = 200/s, burst b = 50 (bucket full: 50 tokens)
2 burst of 80 events: 50 pass at once, 30 wait or are refused
3 tokens refill 200/s -> the 30 pass over the next 150 ms
4 steady 100/s: bucket stays full, no waiting

Real scenarios: Producing 2,000 records per second to Kafka to stay under a quota; limiting webhook deliveries per tenant; throttling a nightly import.

MethodBlocks?ReturnsUse
Allow()NoboolShedding
Wait(ctx)Yes, until token or ctx enderrorBackpressure on the caller
Reserve()No, gives a delayreservationSchedule work yourself
Laravel RateLimitedReleases job with delayjob releasedQueue jobs against a shared limit
Kafka quotaBroker delays responsesthrottle timeMulti-tenant fairness

Fix / how to use it: rate.NewLimiter(200, 50) in the producer; RateLimited('partner-api') in the Laravel job.

Retries amplify overload Important ​

In plain words: When a slow system makes work fail, retries add more work exactly when there is least capacity.

Common misunderstanding: “Retries make the system more reliable.” Unbounded or immediate retries multiply the arrival rate during an incident and can keep a recovered system overloaded.

Definition: A retry storm is retry traffic that sustains overload after the original cause is gone. Controls: bounded attempts, exponential backoff with jitter, a circuit breaker or ThrottlesExceptions, and retry budgets. Schedules belong to retry, backoff and delayed delivery.

text
1 dependency slows -> 30% of calls time out
2 each failure retried 3 times immediately -> arrival x1.9
3 dependency now at 190% of normal load -> more timeouts
4 backoff + breaker: failing calls pause 10 min, load falls, dependency recovers

Real scenarios: Workers hammer a payment API that returned 503; a Kafka consumer re-polls and reprocesses after a timeout; Laravel jobs with $tries = 25 and no backoff.

ControlEffect
Max attempts (#[Tries], delivery-limit)Bounds total retry work
Backoff with jitter (#[Backoff])Spreads retries
ThrottlesExceptionsPauses a job type after N exceptions
Circuit breakerStops calls to a failing dependency
Pause consumersStops reading; backlog waits safely in the broker

Fix / how to use it: Combine RateLimited, ThrottlesExceptions and #[Backoff] (see SyncContact.php). In Go, stop calling Submit while a Gate is paused.

Graceful shutdown Important ​

In plain words: Stop taking new work, finish or hand back what you hold, then exit.

Common misunderstanding: “Closing the connection is a clean shutdown.” Closing with unacked messages returns them to the queue (RabbitMQ) or leaves them in the PEL (Redis); work done but not acknowledged runs again. Clean shutdown makes that window as small as possible.

Definition: Order of operations: stop intake (cancel the consumer, stop polling), let in-flight handlers finish within a deadline, acknowledge or commit what finished, then close. If the deadline expires, cancel handlers via context and report what was abandoned. The Go Pipeline.Shutdown(ctx) does this and returns ErrShutdownTimeout.

text
1 SIGTERM received
2 stop admission: Submit returns ErrClosed; blocked submitters are woken
3 close the queue; workers drain accepted items
4 deadline reached? cancel handler context; queued items are abandoned (counted)
5 ack/commit finished work, close client, exit
6 orchestrator grace period must exceed the shutdown deadline

Real scenarios: A Kubernetes pod terminated during a rolling deploy; a Supervisor stop with stopwaitsecs shorter than the longest job; queue:restart after deploy.

PlatformMechanismDetail
Gosignal.NotifyContext, Shutdown(ctx)Cancel consumer first, then drain
RabbitMQbasic.cancel, then ack in-flightUnacked messages are requeued on close
KafkaStop polling, commit processed, Close the clientNever commit records you did not finish
Redis StreamsStop XREADGROUP, XACK finishedRemaining PEL entries are reclaimed by others
Laravelqueue:restart, --max-jobs, --max-timeWorker finishes the current job; Supervisor stopwaitsecs must exceed the longest job

Mechanics and exact controls ​

RabbitMQ: prefetch, flow, alarms and limits Must-know ​

Publishing path: a connection reads bytes, a channel parses methods, a queue process stores messages. Any stage that falls behind applies flow control that “eventually propagates back to publishing connections”. Connection flow is visible to operators: a flow-controlled connection shows state flow in rabbitmqctl, the management UI and the HTTP API; it blocks and unblocks several times a second and, from the client's view, “should just look like the network bandwidth to the server is lower than it actually is”. No configuration is required.

Publisherconfirms onConnectionstate: flowChannelcredit flowQueue processx-max-lengthpublishing path: each hop slows the one before itResource alarmsmemory 0.6, disk 50 MBconnection.blockedpublishers stop readingConsumerbasic.qos prefetch 10blocksprefetch windowAck frees a prefetch slot. A full queue drops the head or rejects the publish, by overflow setting.

Resource alarms are harder stops. A node raises a memory alarm when its footprint exceeds vm_memory_high_watermark; by default about 60% of available RAM (vm_memory_high_watermark.relative = 0.6), or an absolute limit (vm_memory_high_watermark.absolute = 4Gi). A disk alarm is raised when free disk space drops below disk_free_limit (50 MB by default). While an alarm is active all publishing connections are blocked; clients that advertise the connection.blocked capability receive connection.blocked and later connection.unblocked. The Go NotifyBlocked channel exposes them. Setting the watermark to 0 blocks all publishing, which is a documented way to pause publishing globally.

SettingWhereDefaultNotes
vm_memory_high_watermark.relativerabbitmq.conf0.6 of detected RAMPrefer an absolute value in containers
vm_memory_high_watermark.absoluterabbitmq.confnoneUnits such as 4Gi, 1024MiB
rabbitmqctl set_vm_memory_high_watermarkCLIn/aUntil node restart only
disk_free_limit.absoluterabbitmq.conf50MBAlarm blocks all publishers
connection.blocked / unblockedAMQP extensionon for supporting clientsSent on the first alarm only
quorum_commands_soft_limitadvanced.configsee docsUnconfirmed messages a channel accepts before entering flow
rabbit.default_consumer_prefetchadvanced.confignoneApplied when a consumer sets no prefetch

Queue limits: x-max-length (messages) and x-max-length-bytes (body bytes), set by policy (max-length, recommended) or queue arguments; if both are set the minimum applies. For classic queues only ready messages count; unacknowledged messages do not count toward the limit. overflow (x-overflow) chooses behaviour: drop-head (default) drops or dead-letters the oldest message; reject-publish discards the newest and, with publisher confirms, sends basic.nack; reject-publish-dlx also dead-letters the rejected message (not supported by quorum queues). Quorum queues also count delayed messages and messages awaiting at-least-once dead-lettering.

Memory behaviour: classic queues no longer have a lazy mode (“RabbitMQ no longer supports the lazy mode”); the current implementation behaves like the old lazy mode. Quorum queues never keep message bodies in memory and keep an in-memory index of at least 32 bytes per message, so at least 1 MB per 30,000 messages. The documentation's advice is that “keeping the queues short is the best way to maintain low memory usage” and that a maximum length on all queues limits total memory. Message TTL adds 16 bytes per message of overhead on quorum queues; TTL removes expired messages but is no substitute for a length bound, because expiry is not a rate limit.

Consumer side: manual acks with a bounded prefetch limit in-flight work; with automatic acks there is no limit and consumers can be overwhelmed. Quorum queues enforce consumer timeouts (available from RabbitMQ 4.3): messages held unacknowledged past the timeout are returned to the queue.

Kafka: pull knobs, producer buffers and quotas Must-know ​

Consumer: the consumer pulls. max.poll.records (default 500) bounds records returned by one poll(), and “does not impact the underlying fetching behavior”: the consumer caches records from each fetch and returns them incrementally. fetch.min.bytes (default 1) lets the broker wait for more data; fetch.max.wait.ms (default 500) caps that wait; fetch.max.bytes (default 50 MiB) and max.partition.fetch.bytes (default 1 MiB) cap response sizes, though a first oversized batch is still returned so the consumer can progress. max.poll.interval.ms (default 5 minutes) is the maximum delay between polls; if it passes, the consumer is considered failed and the group rebalances. The rule: max.poll.records × worst-case time per record must stay below max.poll.interval.ms.

Producer: buffer.memory (default 32 MiB) is the total memory for records waiting to be sent; when sending outpaces delivery, “the producer will block for max.block.ms after which it will fail with an exception” (default 60,000 ms). linger.ms (default 5 since Kafka 4.0, previously 0) trades a little latency for larger batches; batch.size (default 16,384 bytes) is the per-partition batch upper bound. The batch.size documentation notes that “broker backpressure can result in a higher effective linger time than this setting”.

Broker: client quotas protect brokers from clients that “monopolize broker resources”. Two kinds apply to a (user, client-id) group: byte-rate quotas (producer_byte_rate, consumer_byte_rate, per broker) and request-rate quotas (request_percentage, a share of network and I/O threads). On violation the broker “computes the amount of delay needed”, returns the response with the delay and mutes the channel; throttled clients are blocked from both sides. Throttling is visible in client metrics such as produce-throttle-time-avg and fetch-throttle-time-avg.

KnobSideDefaultEffect on flow
max.poll.recordsConsumer500Bounds work per poll
max.poll.interval.msConsumer300000Deadline between polls before rebalance
fetch.min.bytesConsumer1Larger: fewer, bigger fetches, more latency
fetch.max.wait.msConsumer500Longest the broker holds a fetch
fetch.max.bytesConsumer52428800Cap per fetch response
max.partition.fetch.bytesConsumer1048576Cap per partition per response
buffer.memoryProducer33554432Total unsent bytes
max.block.msProducer60000How long send() blocks on a full buffer or metadata
linger.msProducer5Batching delay
batch.sizeProducer16384Per-partition batch bytes
producer_byte_rate / consumer_byte_rateBroker quotaunlimitedThrottle by delaying responses
request_percentageBroker quotaunlimitedThrottle by thread time
records-lag-maxConsumer metricn/aMax partition lag in the window
Kafka partition loglog-end offset (producer side)Committed offsetmoves after workLagend minus committedRedis streamentries, trimmed by MAXLEN or MINIDPELdelivered, not ackedXINFO lagentries not deliveredconsumer pollsXREADGROUP COUNT n BLOCK msPull: the consumer sets the pace; the broker simply keeps what is not fetched.

Redis Streams: trimming, the PEL and memory Must-know ​

XADD never blocks and never refuses: nothing in Redis tells a producer that consumers are behind. The only built-in bound is trimming. XADD key MAXLEN ~ 1000 * adds an entry and evicts old ones so the stream holds about 1,000 entries “or at most a few tens more”. MAXLEN trims by count, MINID by age (entries with IDs lower than the threshold; IDs begin with a millisecond timestamp). Exact trimming (=) is the default; ~ is more efficient because it removes whole internal nodes. LIMIT count caps the entries evicted per call. From Redis 8.2, XTRIM/XADD take a reference policy: KEEPREF (default) trims regardless of consumer groups and keeps the PEL references, DELREF removes references too, ACKED trims only entries acknowledged by all groups.

The consequence is blunt: a cap bounds memory by deleting data, which is data loss for a slow group, not backpressure. Entries still pending can be trimmed from the stream while their IDs remain in the PEL. Real flow control is the producer reading XLEN or group lag and slowing down, as in the Go produce function. XREADGROUP ... COUNT n BLOCK ms STREAMS key > reads a bounded batch of never-delivered entries, BLOCK waits server-side, and entries stay in the PEL until XACK. XINFO GROUPS key returns per group consumers, pending, last-delivered-id, entries-read and lag; lag is NULL when it cannot be determined (for example after deletions). The docs say high lag can be addressed by adding consumers to the group.

CommandPurposeFlow-control use
XADD ... MAXLEN ~ nAppend and capMemory ceiling; deletes oldest
XADD ... MINID ~ idAppend and age outRetention by time
XTRIMTrim without addingScheduled cleanup
XLENEntries in streamProducer-side gate
XINFO GROUPSlag, pending per groupConsumer lag metric
XINFO STREAMStream detailsLength, first/last IDs
XPENDINGPEL summary and detailFind stuck work
XREADGROUP COUNT/BLOCKBounded readConsumer batch size and idle wait
XACKRemove from PELFrees the in-flight slot

Laravel: workers and Horizon Important ​

A queue:work process handles one job at a time; concurrency is the number of worker processes. Flags that bound a worker: --max-jobs (exit after N jobs), --max-time (exit after N seconds), --memory (megabytes at which the worker exits, default 128, or a percentage of PHP's memory_limit), --sleep (seconds to wait when no job is ready), --timeout (maximum seconds per job; needs the PCNTL extension; must be less than retry_after), --tries, --stop-when-empty. php artisan queue:restart gracefully restarts all workers after a deploy. The redis connection option block_for makes the driver wait for a job instead of polling; 0 blocks indefinitely and delays signal handling until the next job.

Laravel does not bound the queue: dispatch always succeeds. Bounds belong in job middleware (RateLimited, RateLimitedWithRedis, WithoutOverlapping, ThrottlesExceptions), in worker counts, and in the dispatcher (check Queue::size). RateLimited releases a job back with a delay when the limit is exceeded; ->releaseAfter(60) sets the delay and ->dontRelease() discards instead. ThrottlesExceptions(10, 5 * 60) delays further attempts after 10 exceptions for 300 seconds; ->backoff(5) delays by 5 minutes between attempts while below the threshold. WithoutOverlapping uses an atomic lock; set expireAfter so a crashed job cannot hold the lock forever.

Horizon (redis only): each supervisor has balance (auto, simple, false), and under auto an autoScalingStrategy of time (estimated time to clear) or size (job count), minProcesses, maxProcesses (total ceiling across queues), balanceMaxShift and balanceCooldown (how many processes are added or removed, and how often). memory (default 128) and maxTime recycle workers; timeout at the supervisor must exceed every job timeout. waits sets the seconds after which a queue counts as a “long wait”, which can notify you.

SettingScopeEffect
--max-jobs, --max-time, --memoryqueue:workRecycle workers to limit leaks
--sleep, block_forqueue:work, connectionIdle polling cost vs latency
--timeout < retry_afterWorker, connectionAvoid duplicate execution
balance, autoScalingStrategyHorizon supervisorHow workers follow load
minProcesses, maxProcessesHorizon supervisorFloor and hard ceiling on concurrency
balanceMaxShift, balanceCooldownHorizon supervisorScaling speed
RateLimited('name')Job middlewareShared rate limit, jobs released
ThrottlesExceptions(n, seconds)Job middlewarePause after repeated failures
WithoutOverlapping($key)Job middlewareOne job per key

Other brokers in one table ​

Other brokers expose the same ideas under different names. The table lists documented controls only; see other brokers for the survey.

BrokerConsumer windowProducer or backlog boundNote
NATS JetStreamMaxAckPending (default 1000): un-acked messages the server hands out before it waits for acksStream limits (outside this page's scope)Setting it far below your fetch batch caps throughput
Apache PulsarAcknowledgement and backlog per subscriptionBacklog quota with policies producer_request_hold, producer_exception, consumer_backlog_evictionA hard limit on the logical backlog size of a topic
Amazon SQSMaxNumberOfMessages 1 to 10 per receive, WaitTimeSeconds for long pollingQueue depth is unbounded by design; scale consumers on ApproximateNumberOfMessagesPull model; the visibility timeout is the in-flight window
Google Pub/SubFlow control settings in client librariesRetentionNot covered in the sources used here

Solving classic problems ​

The consumer is slow and the backlog grows ​

Measure before tuning: λ, service time, and where the time goes. If handler time is dominated by a dependency, adding consumers moves the queue into the dependency. If the handler is CPU-bound or I/O-bound on its own resources, add workers up to MinWorkers. Otherwise reduce work per message (batching, caching), or accept shedding.

CauseCheckFixCost
Too few consumersUtilisation near 100%, lag risingScale to λ × service time plus headroomMore connections, rebalances
Slow dependencyHandler waits; consumers idle on CPURate-limit, circuit-break, pause consumersBacklog stays in the broker
Big messagesFetch or prefetch bytes highSmaller windows, claim checkExtra storage hop
Hot partition or keyOne partition laggingSee ordering and partitioningRepartitioning
Poison messageSame message retriedSee dead-letter queueParking-lot ownership

The producer outruns the consumer ​

Choose a policy per message class. Lossless: block with a deadline, rate-limit at the source, or gate on lag (the Redis produce function and the Laravel dispatcher both do). Lossy: shed with a counter. Never rely on a retry loop alone.

Draining a backlog after an outage ​

Drain time is backlog ÷ (capacity − λ). With one million messages and capacity 300/s against live traffic of 100/s, the drain takes 5,000 seconds, about 83 minutes. During the drain the oldest messages are the most likely to be stale; decide whether to process, skip or expire them. Raising consumers helps only if the downstream can take the load; pair it with a rate limit.

sql
-- Database-backed queue (Laravel's jobs table shape): the numbers to watch.
SELECT queue,
       count(*) AS ready,
       now() - to_timestamp(min(available_at)) AS oldest
FROM jobs
WHERE reserved_at IS NULL
  AND available_at <= extract(epoch FROM now())
GROUP BY queue;

-- Claim a bounded batch without blocking other workers (illustration only).
UPDATE jobs
SET reserved_at = extract(epoch FROM now())::int, attempts = attempts + 1
WHERE id IN (
  SELECT id FROM jobs
  WHERE queue = 'default' AND reserved_at IS NULL
    AND available_at <= extract(epoch FROM now())
  ORDER BY id
  LIMIT 10
  FOR UPDATE SKIP LOCKED
)
RETURNING id;

A dependency is down ​

Stop consuming (pause), do not fail every message into retries or the dead-letter queue. The broker is the safest place to keep the backlog while the dependency is unavailable, provided its own limits (disk, x-max-length, retention) outlast the outage. Resume gradually.

Choosing a response ​

Backlog or wait time rising?Brief burstabsorb in the bufferSustained, still valuableslow input, add consumersSustained, work expiresshed or reject earlyAlert on depth, lag, agenot on CPUBound everythingqueue, workers, retriesDependency down?pause consumers, not drop
SituationRecommended responseExtra techniqueReason
Short burst, work still valuableAbsorb in a bounded queueAlert on depth ageSmoothing is exactly what a buffer is for
Sustained excess, work valuableSlow producers, add consumersToken bucket; autoscale on lagCapacity or rate must change
Sustained excess, work expiresShed earlyTTL, deadline checksLate answers are useless
Downstream dependency limits throughputRate-limit at the edge of the dependencyRateLimited, rate.LimiterScaling consumers makes it worse
Dependency completely downPause consumersCircuit breaker, ThrottlesExceptionsKeep backlog in the broker
Multi-tenant noisy neighbourPer-tenant limitsKafka quotas, per-key rate limitFairness
Telemetry or metricsDrop oldest or sampledrop-head, MAXLEN ~Loss is acceptable
Money or ordersBlock or reject with a clear errorPublisher confirms, reject-publishLoss is not acceptable

Go ​

Before ​

An unbounded queue between a fast producer and a slow consumer: append never refuses, the producer never learns anything, and both memory and wait time grow with the backlog. It is intentionally bad design, not broken code; go run it and watch the backlog counter.

go
// Package main shows a producer with no feedback from its consumer. The
// "queue" is a slice that grows without limit, which is what an unbounded
// buffer, a huge channel or a never-trimmed stream amounts to.
package main

import (
	"fmt"
	"sync"
	"time"
)

type event struct {
	ID      int
	Payload [1024]byte
}

type unboundedQueue struct {
	mu    sync.Mutex
	items []event
}

func (q *unboundedQueue) push(e event) {
	q.mu.Lock()
	q.items = append(q.items, e) // never refuses, never blocks, never slows the caller
	q.mu.Unlock()
}

func (q *unboundedQueue) pop() (event, bool) {
	q.mu.Lock()
	defer q.mu.Unlock()
	if len(q.items) == 0 {
		return event{}, false
	}
	e := q.items[0]
	q.items = q.items[1:]
	return e, true
}

func (q *unboundedQueue) len() int {
	q.mu.Lock()
	defer q.mu.Unlock()
	return len(q.items)
}

func main() {
	q := &unboundedQueue{}
	deadline := time.Now().Add(3 * time.Second)

	// Producer: about 10,000 events per second.
	go func() {
		for i := 0; time.Now().Before(deadline); i++ {
			q.push(event{ID: i})
			time.Sleep(100 * time.Microsecond)
		}
	}()

	// Consumer: about 100 events per second. The backlog (and memory) only
	// grows, and every new event waits longer than the previous one.
	for time.Now().Before(deadline) {
		if e, ok := q.pop(); ok {
			time.Sleep(10 * time.Millisecond)
			if e.ID%50 == 0 {
				fmt.Println("handled", e.ID, "backlog", q.len())
			}
		}
	}
}

After: a bounded worker pipeline ​

pipeline.Pipeline has a queue of fixed size, a fixed worker count, and two ways in: TrySubmit sheds when full and counts it; Submit(ctx, item) blocks with a deadline. Stats reports accepted, shed, processed, failed, abandoned, depth, in-flight and average queue wait, the inputs to Little's law. Shutdown(ctx) stops admission, wakes blocked submitters, drains accepted work, and on deadline cancels the handlers' context and counts leftovers as abandoned. The file little.go holds Occupancy, MinWorkers and a two-threshold Gate.

go
// Package pipeline is a bounded worker pipeline: a fixed-size queue, a fixed
// number of workers, an explicit overload policy and counters that expose the
// state an operator needs (depth, wait time, shed, abandoned).
package pipeline

import (
	"context"
	"errors"
	"sync"
	"sync/atomic"
	"time"
)

var (
	// ErrShed means the queue was full and the item was refused immediately.
	ErrShed = errors.New("pipeline: queue full, item shed")
	// ErrClosed means Shutdown has started; no new work is admitted.
	ErrClosed = errors.New("pipeline: closed")
	// ErrShutdownTimeout means workers did not finish before the deadline.
	ErrShutdownTimeout = errors.New("pipeline: shutdown deadline exceeded")
)

// Handler processes one item. It must honour ctx: after a forced shutdown
// the context is cancelled.
type Handler[T any] func(ctx context.Context, item T) error

type entry[T any] struct {
	item     T
	enqueued time.Time
}

// Stats is a point-in-time snapshot of the counters.
type Stats struct {
	Accepted  int64         // items placed in the queue
	Shed      int64         // items refused because the queue was full
	Processed int64         // handler returned nil
	Failed    int64         // handler returned an error
	Abandoned int64         // dequeued after forced shutdown, handler not run
	Depth     int           // items waiting right now
	Capacity  int           // queue bound
	InFlight  int64         // handlers running right now
	AvgWait   time.Duration // mean time an item spent in the queue
}

// Pipeline is safe for concurrent use.
type Pipeline[T any] struct {
	handler Handler[T]
	items   chan entry[T]
	closing chan struct{}

	mu         sync.RWMutex
	closed     bool
	submitters sync.WaitGroup // Submit calls that passed the closed check
	workers    sync.WaitGroup

	workCtx    context.Context
	cancelWork context.CancelFunc

	accepted, shed, processed, failed, abandoned, inFlight atomic.Int64
	waitNanos, waitCount                                   atomic.Int64
}

// New starts workers goroutines reading from a queue of queueSize items.
func New[T any](queueSize, workers int, h Handler[T]) *Pipeline[T] {
	if queueSize < 1 || workers < 1 {
		panic("pipeline: queueSize and workers must be >= 1")
	}
	ctx, cancel := context.WithCancel(context.Background())
	p := &Pipeline[T]{
		handler:    h,
		items:      make(chan entry[T], queueSize),
		closing:    make(chan struct{}),
		workCtx:    ctx,
		cancelWork: cancel,
	}
	p.workers.Add(workers)
	for i := 0; i < workers; i++ {
		go p.worker()
	}
	return p
}

func (p *Pipeline[T]) worker() {
	defer p.workers.Done()
	// The channel is closed only after every Submit has returned, so range
	// drains whatever is left and then exits.
	for e := range p.items {
		if p.workCtx.Err() != nil {
			p.abandoned.Add(1)
			continue
		}
		p.waitNanos.Add(int64(time.Since(e.enqueued)))
		p.waitCount.Add(1)
		p.inFlight.Add(1)
		err := p.handler(p.workCtx, e.item)
		p.inFlight.Add(-1)
		if err != nil {
			p.failed.Add(1)
		} else {
			p.processed.Add(1)
		}
	}
}

func (p *Pipeline[T]) enter() error {
	p.mu.RLock()
	defer p.mu.RUnlock()
	if p.closed {
		return ErrClosed
	}
	p.submitters.Add(1)
	return nil
}

// TrySubmit never waits: it sheds the item when the queue is full.
func (p *Pipeline[T]) TrySubmit(item T) error {
	if err := p.enter(); err != nil {
		return err
	}
	defer p.submitters.Done()
	select {
	case p.items <- entry[T]{item, time.Now()}:
		p.accepted.Add(1)
		return nil
	default:
		p.shed.Add(1)
		return ErrShed
	}
}

// Submit applies backpressure: it waits for room, but never longer than ctx
// allows, and it wakes up when Shutdown starts.
func (p *Pipeline[T]) Submit(ctx context.Context, item T) error {
	if err := p.enter(); err != nil {
		return err
	}
	defer p.submitters.Done()
	select {
	case p.items <- entry[T]{item, time.Now()}:
		p.accepted.Add(1)
		return nil
	case <-ctx.Done():
		return ctx.Err()
	case <-p.closing:
		return ErrClosed
	}
}

// Stats returns a snapshot; the fields are individually consistent only.
func (p *Pipeline[T]) Stats() Stats {
	s := Stats{
		Accepted:  p.accepted.Load(),
		Shed:      p.shed.Load(),
		Processed: p.processed.Load(),
		Failed:    p.failed.Load(),
		Abandoned: p.abandoned.Load(),
		Depth:     len(p.items),
		Capacity:  cap(p.items),
		InFlight:  p.inFlight.Load(),
	}
	if n := p.waitCount.Load(); n > 0 {
		s.AvgWait = time.Duration(p.waitNanos.Load() / n)
	}
	return s
}

// Shutdown stops admission, lets workers drain the queue, and waits until ctx
// ends. When ctx ends first it cancels the handlers' context, counts what is
// left as abandoned and returns ErrShutdownTimeout.
func (p *Pipeline[T]) Shutdown(ctx context.Context) error {
	p.mu.Lock()
	first := !p.closed
	p.closed = true
	p.mu.Unlock()
	if first {
		close(p.closing)
		p.submitters.Wait() // no sender can touch the channel after this
		close(p.items)
	}

	done := make(chan struct{})
	go func() { p.workers.Wait(); close(done) }()
	select {
	case <-done:
		p.cancelWork()
		return nil
	case <-ctx.Done():
		p.cancelWork() // tell running handlers to stop; queued items are abandoned
		<-done
		return ErrShutdownTimeout
	}
}
go
package pipeline

import (
	"math"
	"time"
)

// Occupancy is Little's law, L = lambda * W: the average number of items in
// a stable system equals the arrival rate times the average time each item
// spends in it.
func Occupancy(arrivalsPerSecond float64, timeInSystem time.Duration) float64 {
	return arrivalsPerSecond * timeInSystem.Seconds()
}

// MinWorkers is Little's law applied to the service stage only: the number
// of handlers that must run at once to keep up with the arrival rate when
// each item takes serviceTime. Fewer workers means the queue grows without
// bound, whatever its size.
func MinWorkers(arrivalsPerSecond float64, serviceTime time.Duration) int {
	return int(math.Ceil(Occupancy(arrivalsPerSecond, serviceTime)))
}

// Gate turns one noisy signal (queue depth, consumer lag) into a stable
// pause/resume decision with two thresholds, so the caller does not flap
// around a single limit.
type Gate struct {
	High, Low int64
	paused    bool
}

// Update feeds the latest reading and reports whether intake should be paused.
func (g *Gate) Update(depth int64) bool {
	switch {
	case !g.paused && depth >= g.High:
		g.paused = true
	case g.paused && depth <= g.Low:
		g.paused = false
	}
	return g.paused
}

The tests are deterministic (no sleeps decide outcomes except a short settle delay): shedding at a full queue, blocking until the context ends, draining on shutdown, waking a blocked submitter, peak concurrency never above the worker count, Little's-law arithmetic, and gate hysteresis. Run with go test -race ./....

go
package pipeline

import (
	"context"
	"errors"
	"sync"
	"sync/atomic"
	"testing"
	"time"
)

// blockingHandler parks every call until release is closed or ctx ends.
func blockingHandler(started chan<- struct{}, release <-chan struct{}) Handler[int] {
	return func(ctx context.Context, _ int) error {
		started <- struct{}{}
		select {
		case <-release:
			return nil
		case <-ctx.Done():
			return ctx.Err()
		}
	}
}

func TestTrySubmitShedsWhenFull(t *testing.T) {
	started := make(chan struct{}, 8)
	release := make(chan struct{})
	p := New(2, 1, blockingHandler(started, release))

	if err := p.TrySubmit(1); err != nil {
		t.Fatal(err)
	}
	<-started // the single worker now holds item 1; the queue is empty
	for i := 2; i <= 3; i++ {
		if err := p.TrySubmit(i); err != nil {
			t.Fatalf("item %d: %v", i, err)
		}
	}
	if err := p.TrySubmit(4); !errors.Is(err, ErrShed) {
		t.Fatalf("want ErrShed, got %v", err)
	}
	s := p.Stats()
	if s.Accepted != 3 || s.Shed != 1 || s.Depth != 2 || s.Capacity != 2 {
		t.Fatalf("unexpected stats %+v", s)
	}
	close(release)
	if err := p.Shutdown(context.Background()); err != nil {
		t.Fatal(err)
	}
	if got := p.Stats().Processed; got != 3 {
		t.Fatalf("processed %d, want 3", got)
	}
}

func TestSubmitBlocksUntilContextEnds(t *testing.T) {
	started := make(chan struct{}, 8)
	release := make(chan struct{})
	p := New(1, 1, blockingHandler(started, release))
	_ = p.TrySubmit(1)
	<-started
	_ = p.TrySubmit(2) // queue is now full

	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
	defer cancel()
	if err := p.Submit(ctx, 3); !errors.Is(err, context.DeadlineExceeded) {
		t.Fatalf("want deadline exceeded, got %v", err)
	}
	if p.Stats().Accepted != 2 {
		t.Fatalf("blocked submit must not count as accepted")
	}
	close(release)
	_ = p.Shutdown(context.Background())
}

func TestShutdownDrainsAcceptedWork(t *testing.T) {
	var done atomic.Int64
	p := New(50, 4, func(_ context.Context, _ int) error {
		time.Sleep(time.Millisecond)
		done.Add(1)
		return nil
	})
	for i := 0; i < 50; i++ {
		if err := p.Submit(context.Background(), i); err != nil {
			t.Fatal(err)
		}
	}
	if err := p.Shutdown(context.Background()); err != nil {
		t.Fatal(err)
	}
	if done.Load() != 50 {
		t.Fatalf("handled %d of 50 accepted items", done.Load())
	}
	if err := p.TrySubmit(1); !errors.Is(err, ErrClosed) {
		t.Fatalf("want ErrClosed after shutdown, got %v", err)
	}
	if err := p.Shutdown(context.Background()); err != nil {
		t.Fatalf("second Shutdown must be harmless, got %v", err)
	}
}

func TestShutdownWakesBlockedSubmitter(t *testing.T) {
	started := make(chan struct{}, 8)
	p := New(1, 1, blockingHandler(started, nil)) // nil release: only ctx frees it
	_ = p.TrySubmit(1)
	<-started
	_ = p.TrySubmit(2)

	errc := make(chan error, 1)
	go func() { errc <- p.Submit(context.Background(), 3) }()
	time.Sleep(20 * time.Millisecond) // let the submitter block

	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
	defer cancel()
	if err := p.Shutdown(ctx); !errors.Is(err, ErrShutdownTimeout) {
		t.Fatalf("want ErrShutdownTimeout, got %v", err)
	}
	if err := <-errc; !errors.Is(err, ErrClosed) {
		t.Fatalf("blocked submitter got %v, want ErrClosed", err)
	}
	s := p.Stats()
	if s.Abandoned != 1 || s.Failed != 1 {
		t.Fatalf("want 1 failed (cancelled) and 1 abandoned, got %+v", s)
	}
}

func TestConcurrencyNeverExceedsWorkers(t *testing.T) {
	const workers = 3
	var cur, peak atomic.Int64
	p := New(10, workers, func(_ context.Context, _ int) error {
		n := cur.Add(1)
		for {
			old := peak.Load()
			if n <= old || peak.CompareAndSwap(old, n) {
				break
			}
		}
		time.Sleep(2 * time.Millisecond)
		cur.Add(-1)
		return nil
	})
	var wg sync.WaitGroup
	for g := 0; g < 8; g++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for i := 0; i < 20; i++ {
				_ = p.Submit(context.Background(), i)
			}
		}()
	}
	wg.Wait()
	_ = p.Shutdown(context.Background())
	if peak.Load() > workers {
		t.Fatalf("peak concurrency %d exceeds %d workers", peak.Load(), workers)
	}
	if got := p.Stats().Processed; got != 160 {
		t.Fatalf("processed %d, want 160", got)
	}
}

func TestLittlesLaw(t *testing.T) {
	cases := []struct {
		rate float64
		w    time.Duration
		want float64
	}{
		{200, 50 * time.Millisecond, 10},
		{1000, 2 * time.Second, 2000},
		{0, time.Second, 0},
	}
	for _, c := range cases {
		if got := Occupancy(c.rate, c.w); got != c.want {
			t.Errorf("Occupancy(%v,%v)=%v want %v", c.rate, c.w, got, c.want)
		}
	}
	if got := MinWorkers(200, 50*time.Millisecond); got != 10 {
		t.Errorf("MinWorkers=%d want 10", got)
	}
	if got := MinWorkers(201, 50*time.Millisecond); got != 11 {
		t.Errorf("MinWorkers=%d want 11 (round up)", got)
	}
}

func TestGateHysteresis(t *testing.T) {
	g := Gate{High: 100, Low: 40}
	steps := []struct {
		depth int64
		want  bool
	}{{10, false}, {99, false}, {100, true}, {70, true}, {41, true}, {40, false}, {70, false}}
	for _, s := range steps {
		if got := g.Update(s.depth); got != s.want {
			t.Fatalf("depth %d: paused=%v want %v", s.depth, got, s.want)
		}
	}
}

After: admission control ​

admission.Controller pairs a rate.Limiter token bucket with a counting semaphore built from a buffered channel. Admit refuses at once (ErrRateLimited, ErrOverloaded); AdmitWait waits within a context. golang.org/x/sync/semaphore offers a weighted semaphore if requests have different costs; a buffered channel is enough for equal-weight slots.

go
// Package admission decides whether work may enter at all. Two independent
// checks: a token bucket bounds the arrival rate, a counting semaphore bounds
// how many requests are being served at once. Refusing early is cheaper than
// accepting work that will time out in a queue.
package admission

import (
	"context"
	"errors"

	"golang.org/x/time/rate"
)

var (
	ErrRateLimited = errors.New("admission: rate limit exceeded")
	ErrOverloaded  = errors.New("admission: too many requests in flight")
)

// Controller combines a token bucket and an in-flight limit.
type Controller struct {
	limiter *rate.Limiter
	slots   chan struct{} // buffered channel used as a counting semaphore
}

// New allows ratePerSecond sustained arrivals with bursts up to burst, and at
// most maxInFlight concurrent holders.
func New(ratePerSecond float64, burst, maxInFlight int) *Controller {
	return &Controller{
		limiter: rate.NewLimiter(rate.Limit(ratePerSecond), burst),
		slots:   make(chan struct{}, maxInFlight),
	}
}

// Admit refuses immediately (shedding). On success the caller must call the
// returned release exactly once when the work is done.
func (c *Controller) Admit() (release func(), err error) {
	if !c.limiter.Allow() {
		return nil, ErrRateLimited
	}
	select {
	case c.slots <- struct{}{}:
		return func() { <-c.slots }, nil
	default:
		return nil, ErrOverloaded
	}
}

// AdmitWait delays instead of refusing (backpressure on the caller). It waits
// for a token and then for a slot, and gives up when ctx ends.
func (c *Controller) AdmitWait(ctx context.Context) (release func(), err error) {
	if err := c.limiter.Wait(ctx); err != nil {
		return nil, err
	}
	select {
	case c.slots <- struct{}{}:
		return func() { <-c.slots }, nil
	case <-ctx.Done():
		return nil, ctx.Err()
	}
}

The Go angle ​

A buffered channel is Go's bounded queue: make(chan T, n) blocks the sender at n, and select with default turns blocking into shedding. The Go blog's pipelines article shows how a buffer can be sized when the number of values is known; in a service, size it from Little's law and make the full-queue behaviour an explicit branch, not an accident. Always pass a context.Context so a blocked send can end. Never close a channel that senders may still use (the pipeline closes only after every submitter has returned). Goroutines are cheap but not free: a goroutine per message is an unbounded buffer in disguise, so cap concurrency with a worker pool or semaphore.

Laravel ​

Before ​

One command dispatches a job per contact in a single burst. Nothing limits how fast jobs are consumed, how many run at once, or how the partner API copes.

php
<?php

namespace App\Console\Commands;

use App\Jobs\SyncContact;
use App\Models\Contact;
use Illuminate\Console\Command;

class SyncAllContacts extends Command
{
    protected $signature = 'contacts:sync-all';

    public function handle(): void
    {
        // 100k jobs pushed in one burst. Nothing limits how fast they are
        // consumed, so the partner API is hammered, the Redis list grows
        // without bound, and every other job on "default" waits behind them.
        foreach (Contact::query()->cursor() as $contact) {
            SyncContact::dispatch($contact->id);
        }
    }
}

After ​

The job carries its own limits as middleware (RateLimited, ThrottlesExceptions, WithoutOverlapping) and bounded attempts through attributes (#[Tries], #[Timeout], #[Backoff]). The dispatcher is the producer half: it checks Queue::size with a high and low mark before pushing more.

php
<?php

namespace App\Jobs;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\Timeout;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Queue\Middleware\RateLimited;
use Illuminate\Queue\Middleware\ThrottlesExceptions;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\RateLimiter;

/**
 * Defined once, for example in AppServiceProvider::boot(): at most 600 calls
 * per minute against the partner API, shared by every worker process.
 */
function registerPartnerLimiter(): void
{
    RateLimiter::for('partner-api', fn (object $job) => Limit::perMinute(600));
}

#[Tries(8)]
#[Timeout(30)]
#[Backoff([10, 30, 60])]
class SyncContact implements ShouldQueue
{
    use Dispatchable, Queueable;

    public function __construct(public int $contactId) {}

    /** @return array<int, object> */
    public function middleware(): array
    {
        return [
            // Over the limit: the job is released back with a delay, not failed.
            (new RateLimited('partner-api'))->releaseAfter(30),
            // After 5 exceptions stop calling the partner for 10 minutes.
            (new ThrottlesExceptions(5, 10 * 60))->backoff(1),
            // One sync per contact at a time, across all workers.
            (new WithoutOverlapping((string) $this->contactId))->releaseAfter(30)->expireAfter(120),
        ];
    }

    public function handle(): void
    {
        Http::timeout(10)
            ->post('https://partner.example/api/contacts/sync', ['id' => $this->contactId])
            ->throw();
    }
}
php
<?php

namespace App\Console\Commands;

use App\Jobs\SyncContact;
use App\Models\Contact;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Queue;

/**
 * The producer half of backpressure: look at the backlog before pushing more.
 * The queue is a buffer, and a buffer with no bound is a latency bomb.
 */
class SyncAllContacts extends Command
{
    protected $signature = 'contacts:sync-all {--high=5000} {--low=1000}';

    public function handle(): int
    {
        $high = (int) $this->option('high');
        $low = (int) $this->option('low');
        $paused = false;

        foreach (Contact::query()->select('id')->lazyById(500) as $contact) {
            // Hysteresis: pause above $high, resume only below $low.
            while (true) {
                $size = Queue::connection('redis')->size('partner-sync');
                $paused = $paused ? $size > $low : $size >= $high;
                if (! $paused) {
                    break;
                }
                $this->line("backlog {$size}, waiting");
                sleep(2);
            }

            SyncContact::dispatch($contact->id)->onConnection('redis')->onQueue('partner-sync');
        }

        return self::SUCCESS;
    }
}

Horizon's supervisor settings are the consumer half: a hard maxProcesses, gradual scaling, and recycling.

php
<?php

// config/horizon.php (fragment). Worker processes are the consumer-side
// bound: maxProcesses caps concurrency whatever the backlog looks like.
return [
    // Seconds a queue may wait before Horizon reports a "long wait".
    'waits' => [
        'redis:partner-sync' => 120,
        'redis:default' => 60,
    ],

    'environments' => [
        'production' => [
            'partner-sync' => [
                'connection' => 'redis',
                'queue' => ['partner-sync'],
                'balance' => 'auto',
                'autoScalingStrategy' => 'time',
                'minProcesses' => 1,
                'maxProcesses' => 8,      // hard ceiling on parallel partner calls
                'balanceMaxShift' => 1,   // add or remove at most one process ...
                'balanceCooldown' => 3,   // ... every three seconds
                'tries' => 8,
                'timeout' => 60,          // greater than any job-level timeout
                'memory' => 128,
                'maxTime' => 3600,        // recycle workers hourly
            ],
            'default' => [
                'connection' => 'redis',
                'queue' => ['default'],
                'balance' => 'simple',
                'maxProcesses' => 10,
                'tries' => 3,
            ],
        ],
    ],
];

A scheduled command can turn the backlog into one number per broker for an alert:

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Redis;
use Symfony\Component\Process\Process;

/**
 * One backlog number per broker, so a scheduler or alert can compare it with
 * a threshold. Lag is the signal; CPU usually is not.
 */
class LagCheck extends Command
{
    protected $signature = 'messaging:lag {broker : redis-queue|rabbitmq|kafka|redis-stream}';

    protected $description = 'Print the current backlog for a broker';

    public function handle(): int
    {
        $backlog = match ($this->argument('broker')) {
            // Laravel's redis driver: ready list + delayed + reserved.
            'redis-queue' => Queue::connection('redis')->size('default'),

            // RabbitMQ management HTTP API: messages_ready is the backlog.
            'rabbitmq' => (int) Http::withBasicAuth(config('rabbit.user'), config('rabbit.pass'))
                ->get(config('rabbit.api').'/api/queues/%2F/jobs')
                ->throw()
                ->json('messages_ready'),

            'kafka' => $this->kafkaLag('billing'),

            // XINFO GROUPS reports lag per consumer group. The reply shape is
            // client-specific; this assumes the phpredis extension.
            'redis-stream' => $this->streamLag('events', 'billing'),

            default => throw new \InvalidArgumentException('unknown broker'),
        };

        $this->line((string) $backlog);

        return $backlog > (int) config('messaging.lag_alert', 10000) ? self::FAILURE : self::SUCCESS;
    }

    private function kafkaLag(string $group): int
    {
        $p = new Process([
            'kafka-consumer-groups.sh', '--bootstrap-server', config('kafka.brokers'),
            '--describe', '--group', $group,
        ]);
        $p->mustRun();

        // Columns: GROUP TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG ...
        $total = 0;
        foreach (explode("\n", $p->getOutput()) as $line) {
            $cols = preg_split('/\s+/', trim($line));
            if (count($cols) >= 6 && ctype_digit($cols[5])) {
                $total += (int) $cols[5];
            }
        }

        return $total;
    }

    private function streamLag(string $stream, string $group): int
    {
        foreach (Redis::xinfo('GROUPS', $stream) as $g) {
            if (($g['name'] ?? null) === $group) {
                // lag is null when Redis cannot compute it (for example after deletions).
                return (int) ($g['lag'] ?? $g['pending'] ?? 0);
            }
        }

        return 0;
    }
}
bash
# Supervisor-managed workers: recycle often, bound each job, never run unbounded.
php artisan queue:work redis --queue=partner-sync --sleep=3 --tries=8 \
  --timeout=30 --max-jobs=1000 --max-time=3600 --memory=128
# After deploys: ask every worker to exit after its current job.
php artisan queue:restart

The Laravel angle ​

Laravel 13 documents “database, Amazon SQS, Redis, and Beanstalkd drivers”; none of them bounds the queue for you. The bounds are worker count and flags, job middleware, and a producer that checks Queue::size. A job's --timeout must be shorter than the connection's retry_after (default 90 seconds for redis), otherwise a second worker can pick up a job that is still running. Horizon requires Redis. RabbitMQ and Kafka are not built in: use vladimir-yuldashev/laravel-queue-rabbitmq and mateusjunges/laravel-kafka. For Redis Streams use the Redis facade, because Laravel's redis driver uses lists and sorted sets, not streams. A short PHP comparison with Go: Go bounds with a channel and a semaphore inside one process; Laravel bounds with process counts and middleware across processes.

Broker differences ​

RabbitMQ ​

RabbitMQ pushes, so the control is the prefetch window and the broker's own flow control. The consumer snippet declares a bounded quorum queue (x-max-length, x-overflow: reject-publish), sets Qos(10, 0, false) for a per-consumer window, cancels its consumer on SIGTERM and drains the deliveries already in its channel. The publisher snippet watches NotifyBlocked, uses deferred publisher confirms, and turns a nack from reject-publish into a growing pause. Prefer a policy over hardcoded arguments when you need to change limits without redeclaring the queue.

go
// Package main consumes from a bounded RabbitMQ quorum queue with a small
// per-consumer prefetch and manual acks, so the broker never pushes more
// unacknowledged messages than this process can hold, and it shuts down by
// cancelling the consumer before it closes the channel.
package main

import (
	"context"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

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

const (
	queueName   = "jobs"
	consumerTag = "worker-1"
	prefetch    = 10 // per consumer, RabbitMQ semantics of basic.qos
)

func main() {
	url := os.Getenv("AMQP_URL")
	if url == "" {
		log.Println("AMQP_URL not set, exiting")
		return
	}
	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)
	}

	// The queue is bounded on the broker: with reject-publish, publishers
	// using confirms receive a basic.nack once 100000 messages are ready.
	if _, err := declareBoundedQueue(ch); err != nil {
		log.Fatal(err)
	}

	// global=false: the limit applies to each consumer on this channel. The
	// RabbitMQ 4.4 docs mark channel-wide (global) prefetch deprecated.
	if err := ch.Qos(prefetch, 0, false); err != nil {
		log.Fatal(err)
	}
	deliveries, err := ch.Consume(queueName, consumerTag, false, false, false, false, nil)
	if err != nil {
		log.Fatal(err)
	}

	go func() {
		<-ctx.Done()
		// Stop new deliveries; messages already prefetched stay in the
		// deliveries channel and are handled below before we return.
		if err := ch.Cancel(consumerTag, false); err != nil {
			log.Println("cancel:", err)
		}
	}()

	for d := range deliveries {
		if err := handle(d); err != nil {
			// Requeue once; the broker redelivers it, possibly to another worker.
			_ = d.Nack(false, !d.Redelivered)
			continue
		}
		if err := d.Ack(false); err != nil {
			log.Println("ack:", err) // channel is gone; unacked messages are requeued
			return
		}
	}
	log.Println("drained, exiting")
}

func declareBoundedQueue(ch *amqp.Channel) (amqp.Queue, error) {
	return ch.QueueDeclare(queueName, true, false, false, false, amqp.Table{
		"x-queue-type": "quorum",
		"x-max-length": int64(100000),
		"x-overflow":   "reject-publish",
	})
}

func handle(d amqp.Delivery) error {
	time.Sleep(50 * time.Millisecond) // the real work
	return nil
}
go
package main

import (
	"context"
	"errors"
	"log"
	"time"

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

var errRejected = errors.New("broker rejected the publish (queue full)")

// watchBlocked logs connection.blocked / connection.unblocked. The broker
// sends them when a memory or disk alarm stops publishers.
func watchBlocked(conn *amqp.Connection) {
	ch := conn.NotifyBlocked(make(chan amqp.Blocking, 4))
	go func() {
		for b := range ch {
			log.Printf("connection blocked=%v reason=%q", b.Active, b.Reason)
		}
	}()
}

// publishConfirmed sends one persistent message and waits for the broker's
// verdict. A nack means the bounded queue refused it; that is the signal to
// slow down, not to retry in a tight loop.
func publishConfirmed(ctx context.Context, ch *amqp.Channel, body []byte) error {
	ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()

	dc, err := ch.PublishWithDeferredConfirmWithContext(ctx, "", queueName, false, false, amqp.Publishing{
		DeliveryMode: amqp.Persistent,
		ContentType:  "application/octet-stream",
		Body:         body,
	})
	if err != nil {
		return err
	}
	acked, err := dc.WaitContext(ctx)
	if err != nil {
		return err // unknown outcome: the caller must treat it as possibly delivered
	}
	if !acked {
		return errRejected
	}
	return nil
}

// publishWithBackoff retries rejections with a growing pause; every pause is
// backpressure applied to whoever is calling us.
func publishWithBackoff(ctx context.Context, ch *amqp.Channel, body []byte) error {
	pause := 50 * time.Millisecond
	for {
		err := publishConfirmed(ctx, ch, body)
		if !errors.Is(err, errRejected) {
			return err
		}
		select {
		case <-time.After(pause):
		case <-ctx.Done():
			return ctx.Err()
		}
		if pause < 2*time.Second {
			pause *= 2
		}
	}
}

For Laravel with vladimir-yuldashev/laravel-queue-rabbitmq, queue:work fetches with basic_get and does not use prefetch (the broker documents that QoS has no effect on basic.get). The package's rabbitmq:consume uses basic_consume, is documented as about twice as fast, handles one queue, and in the inspected source accepts --prefetch-count (default 1000 there) and --prefetch-size.

php
<?php

// config/queue.php (fragment) for vladimir-yuldashev/laravel-queue-rabbitmq.
return [
    'connections' => [
        'rabbitmq' => [
            'driver' => 'rabbitmq',
            'queue' => env('RABBITMQ_QUEUE', 'jobs'),
            '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' => [],
            'worker' => env('RABBITMQ_WORKER', 'default'),
        ],
    ],
];

// Prefetch is a consumer-command option, not a connection option:
//
//   php artisan rabbitmq:consume rabbitmq --prefetch-count=10   # basic_consume + basic.qos
//   php artisan queue:work rabbitmq                              # basic_get, one at a time
//
// Queue length limits are broker policy, not application code:
//
//   rabbitmqctl set_policy jobs-limit '^jobs$' \
//     '{"max-length":100000,"overflow":"reject-publish"}' --apply-to queues
bash
# Policy-based bound; expected, not run.
rabbitmqctl set_policy jobs-limit '^jobs$' \
  '{"max-length":100000,"overflow":"reject-publish"}' --apply-to queues
rabbitmqctl set_vm_memory_high_watermark 0.5     # until restart

Kafka ​

Kafka consumers pull, so a slow consumer slows itself only: the broker keeps the data and lag grows. The consumer snippet polls at most 200 records (like max.poll.records), commits exactly what finished, uses a time budget well below max.poll.interval.ms, and logs group lag through the admin API. The producer file bounds the client buffer (MaxBufferedRecords, MaxBufferedBytes), lets Produce wait for a deadline (the counterpart of max.block.ms), and paces production with a token bucket. franz-go option names differ from Java property names; the comments map them.

go
// Package main polls Kafka in bounded batches. A consumer that does not call
// poll applies backpressure by itself: the broker holds the data, and the
// committed offset only moves after the work is done. Lag is how far behind
// that leaves the group.
package main

import (
	"context"
	"log"
	"os"
	"os/signal"
	"strings"
	"syscall"
	"time"

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

const (
	group       = "billing"
	topic       = "orders"
	maxRecords  = 200              // like max.poll.records
	batchBudget = 30 * time.Second // keep far below max.poll.interval.ms (default 5 min)
)

func main() {
	brokers := os.Getenv("KAFKA_BROKERS")
	if brokers == "" {
		log.Println("KAFKA_BROKERS not set, exiting")
		return
	}
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	cl, err := kgo.NewClient(
		kgo.SeedBrokers(strings.Split(brokers, ",")...),
		kgo.ConsumerGroup(group),
		kgo.ConsumeTopics(topic),
		kgo.DisableAutoCommit(),
		kgo.BlockRebalanceOnPoll(),             // no rebalance between poll and commit
		kgo.FetchMaxBytes(5<<20),               // fetch.max.bytes, one response
		kgo.FetchMaxPartitionBytes(1<<20),      // max.partition.fetch.bytes
		kgo.FetchMinBytes(1<<10),               // fetch.min.bytes
		kgo.FetchMaxWait(500*time.Millisecond), // fetch.max.wait.ms
	)
	if err != nil {
		log.Fatal(err)
	}
	defer cl.Close()

	adm := kadm.NewClient(cl)
	lastLag := time.Now()

	for ctx.Err() == nil {
		fetches := cl.PollRecords(ctx, maxRecords)
		if fetches.IsClientClosed() {
			return
		}
		fetches.EachError(func(t string, p int32, err error) {
			log.Printf("fetch %s/%d: %v", t, p, err)
		})

		batchCtx, cancel := context.WithTimeout(context.Background(), batchBudget)
		var done []*kgo.Record
		fetches.EachRecord(func(r *kgo.Record) {
			if batchCtx.Err() != nil {
				return // out of time budget: leave the rest uncommitted
			}
			time.Sleep(5 * time.Millisecond) // the real work
			done = append(done, r)
		})
		// Commit exactly what was processed; unprocessed records are fetched again.
		if len(done) > 0 {
			if err := cl.CommitRecords(batchCtx, done...); err != nil {
				log.Println("commit:", err)
			}
		}
		cancel()
		cl.AllowRebalance()

		if time.Since(lastLag) > 10*time.Second {
			lastLag = time.Now()
			logLag(ctx, adm)
		}
	}
}

// logLag prints the group's total lag: the number to alert on and to scale by.
func logLag(ctx context.Context, adm *kadm.Client) {
	lags, err := adm.Lag(ctx, group)
	if err != nil {
		log.Println("lag:", err)
		return
	}
	for _, g := range lags {
		log.Printf("group=%s total lag=%d", g.Group, g.Lag.Total())
	}
}
go
package main

import (
	"context"
	"errors"
	"log"
	"strings"
	"time"

	"github.com/twmb/franz-go/pkg/kgo"
	"golang.org/x/time/rate"
)

// newProducer bounds what the client may buffer. When the buffer is full,
// Produce waits (the counterpart of buffer.memory plus max.block.ms) and
// TryProduce fails at once with kgo.ErrMaxBuffered.
func newProducer(brokers string) (*kgo.Client, error) {
	return kgo.NewClient(
		kgo.SeedBrokers(strings.Split(brokers, ",")...),
		kgo.MaxBufferedRecords(10_000),
		kgo.MaxBufferedBytes(32<<20),
		kgo.ProducerLinger(5*time.Millisecond), // linger.ms (default 5 since Kafka 4.0)
		kgo.ProducerBatchMaxBytes(1<<20),       // largest batch, like a bigger batch.size
	)
}

// send waits at most blockFor for buffer space, like max.block.ms.
func send(ctx context.Context, cl *kgo.Client, key, value []byte, blockFor time.Duration) error {
	ctx, cancel := context.WithTimeout(ctx, blockFor)
	defer cancel()
	errc := make(chan error, 1)
	cl.Produce(ctx, &kgo.Record{Topic: topic, Key: key, Value: value}, func(_ *kgo.Record, err error) {
		errc <- err
	})
	return <-errc
}

// produceLoop paces the producer with a token bucket and treats a full
// buffer as a reason to pause rather than to drop.
func produceLoop(ctx context.Context, cl *kgo.Client) {
	limiter := rate.NewLimiter(rate.Limit(2000), 200)
	for ctx.Err() == nil {
		if err := limiter.Wait(ctx); err != nil {
			return
		}
		err := send(ctx, cl, nil, []byte("x"), 2*time.Second)
		switch {
		case err == nil:
		case errors.Is(err, context.DeadlineExceeded):
			log.Println("buffer full for 2s: broker or quota is slower than we produce")
		default:
			log.Println("produce:", err)
		}
	}
}

Laravel uses mateusjunges/laravel-kafka over php-rdkafka and librdkafka. Careful with names: librdkafka's fetch.wait.max.ms is Java's fetch.max.wait.ms, and its max.poll.records applies only to share consumers, so an ordinary consumer cannot set it; bound batches in the application with withMaxMessages and withMaxTime, and bound prefetch with queued.max.messages.kbytes.

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Junges\Kafka\Facades\Kafka;

/**
 * mateusjunges/laravel-kafka wraps php-rdkafka, which wraps librdkafka.
 * librdkafka has no max.poll.records for ordinary consumers (the option
 * exists only for share consumers), so the batch bound is applied here:
 * stop after N messages or T seconds and let the supervisor restart us.
 */
class ConsumeOrders extends Command
{
    protected $signature = 'orders:consume';

    public function handle(): void
    {
        $consumer = Kafka::consumer(['orders'])
            ->withBrokers(config('kafka.brokers'))
            ->withConsumerGroupId('billing')
            ->withManualCommit()
            ->withMaxMessages(10_000)
            ->withMaxTime(3600)
            ->withOptions([
                // Must exceed the slowest handler, or the group rebalances.
                'max.poll.interval.ms' => 300000,
                // librdkafka names; there is no fetch.max.wait.ms here.
                'fetch.wait.max.ms' => 500,
                'fetch.min.bytes' => 1024,
                // Local prefetch bound: kilobytes of queued messages.
                'queued.max.messages.kbytes' => 16384,
            ])
            ->withHandler(function ($message, $consumer): void {
                // The real work, then commit only what is finished.
                $consumer->commit($message);
            })
            ->build();

        $consumer->consume();
    }
}
bash
# Quotas are broker-side; expected, not run.
kafka-configs.sh --bootstrap-server localhost:9092 --alter \
  --add-config 'producer_byte_rate=1048576,consumer_byte_rate=2097152,request_percentage=50' \
  --entity-type clients --entity-name partner-importer
kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group billing

Redis Streams ​

Redis does not push back at all. The consumer snippet reads with COUNT 50 BLOCK 2s, acknowledges per entry and reports XINFO GROUPS lag, pending and XLEN. The producer uses MAXLEN ~ as a ceiling and a high and low watermark gate on XLEN as the control, so it pauses before the cap deletes unread entries. Remember that trimming can delete entries still referenced by the PEL (default KEEPREF).

go
// Package main reads a Redis Stream through a consumer group with COUNT and
// BLOCK, so each read is a bounded batch and an idle consumer waits on the
// server instead of spinning. Work stays in the group's pending entries list
// (PEL) until it is acknowledged.
package main

import (
	"context"
	"errors"
	"log"
	"os"
	"os/signal"
	"strings"
	"syscall"
	"time"

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

const (
	stream   = "events"
	group    = "billing"
	consumer = "worker-1"
	batch    = 50 // COUNT: records per read
)

func main() {
	addr := os.Getenv("REDIS_ADDR")
	if addr == "" {
		log.Println("REDIS_ADDR not set, exiting")
		return
	}
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	rdb := redis.NewClient(&redis.Options{Addr: addr})
	defer rdb.Close()

	err := rdb.XGroupCreateMkStream(ctx, stream, group, "$").Err()
	if err != nil && !strings.HasPrefix(err.Error(), "BUSYGROUP") {
		log.Fatal(err)
	}

	lastReport := time.Now()
	for ctx.Err() == nil {
		res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
			Group:    group,
			Consumer: consumer,
			Streams:  []string{stream, ">"},
			Count:    batch,
			Block:    2 * time.Second, // wait on the server, no busy loop
		}).Result()
		if errors.Is(err, redis.Nil) {
			continue // block timeout, nothing new
		}
		if err != nil {
			if ctx.Err() != nil {
				break
			}
			log.Println("xreadgroup:", err)
			time.Sleep(time.Second)
			continue
		}
		for _, s := range res {
			for _, m := range s.Messages {
				time.Sleep(5 * time.Millisecond) // the real work
				if err := rdb.XAck(context.Background(), stream, group, m.ID).Err(); err != nil {
					log.Println("xack:", err)
				}
			}
		}
		if time.Since(lastReport) > 10*time.Second {
			lastReport = time.Now()
			reportLag(ctx, rdb)
		}
	}
	log.Println("stopped; unacknowledged entries remain in the PEL for another consumer")
}

// reportLag prints the numbers an operator needs: entries not yet delivered
// (lag), entries delivered but not acknowledged (pending) and stream length.
func reportLag(ctx context.Context, rdb *redis.Client) {
	groups, err := rdb.XInfoGroups(ctx, stream).Result()
	if err != nil {
		log.Println("xinfo groups:", err)
		return
	}
	n, _ := rdb.XLen(ctx, stream).Result()
	for _, g := range groups {
		log.Printf("group=%s lag=%d pending=%d xlen=%d", g.Name, g.Lag, g.Pending, n)
	}
}
go
package main

import (
	"context"
	"time"

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

	"academy/backpressure-flow-control/after/pipeline"
)

const (
	approxCap  = 100_000 // MAXLEN ~ : memory ceiling, deletes the oldest entries
	highMark   = 80_000  // pause producing before the cap starts deleting unread data
	lowMark    = 40_000
	checkEvery = 100
)

// produce is the producer half of backpressure on Redis Streams. XADD never
// blocks and MAXLEN trims silently, so the producer must watch the backlog
// itself. The approximate cap is a safety net (data loss), the gate is the
// control (no data loss).
func produce(ctx context.Context, rdb *redis.Client, total int) error {
	gate := pipeline.Gate{High: highMark, Low: lowMark}
	for i := 0; i < total; i++ {
		err := rdb.XAdd(ctx, &redis.XAddArgs{
			Stream: stream,
			MaxLen: approxCap,
			Approx: true,
			Values: map[string]any{"n": i},
		}).Err()
		if err != nil {
			return err
		}
		if i%checkEvery != 0 {
			continue
		}
		for {
			n, err := rdb.XLen(ctx, stream).Result()
			if err != nil {
				return err
			}
			if !gate.Update(n) {
				break
			}
			select {
			case <-time.After(500 * time.Millisecond):
			case <-ctx.Done():
				return ctx.Err()
			}
		}
	}
	return nil
}
php
<?php

namespace App\Services;

use Illuminate\Support\Facades\Redis;

/**
 * Redis Streams through the Redis facade (Laravel's redis queue driver uses
 * lists and sorted sets, not streams). Written against phpredis semantics.
 */
class RedisStream
{
    private const STREAM = 'events';
    private const GROUP = 'billing';

    /** Producer: approximate MAXLEN is a ceiling, the XLEN check is the control. */
    public function publish(array $fields): ?string
    {
        if (Redis::xlen(self::STREAM) >= 80_000) {
            return null; // shed or retry later; the caller decides
        }

        return Redis::xadd(self::STREAM, '*', $fields, 100_000, true);
    }

    /** Consumer: one bounded batch, blocking up to 2 s on the server. */
    public function consume(string $consumer, callable $handle): int
    {
        $reply = Redis::xreadgroup(self::GROUP, $consumer, [self::STREAM => '>'], 50, 2000);
        $done = 0;

        foreach ($reply[self::STREAM] ?? [] as $id => $fields) {
            $handle($id, $fields);
            Redis::xack(self::STREAM, self::GROUP, [$id]);
            $done++;
        }

        return $done;
    }
}
bash
# Bounded batch, then observe; expected, not run.
redis-cli XADD events MAXLEN '~' 100000 '*' n 1
redis-cli XREADGROUP GROUP billing worker-1 COUNT 50 BLOCK 2000 STREAMS events '>'
redis-cli XINFO GROUPS events

In production systems ​

  • RabbitMQ documents the full chain in its own guides: flow state on connections, memory and disk alarms that block publishers, and connection.blocked notifications. Monitoring should alert on alarm state and on flow connections before users notice slow publishes.
  • Kafka documents broker-side quotas with throttling by delayed responses and per-client throttle-time metrics, and consumer lag metrics (records-lag-max) published by the consumer. A group whose lag rises while poll intervals approach max.poll.interval.ms is about to rebalance.
  • Redis documents XINFO GROUPS lag and the trimming options; the docs themselves suggest adding consumers when lag is high and warn that lag can be unknown (NULL).
  • Laravel Horizon documents balance, autoScalingStrategy, maxProcesses, balanceCooldown and long-wait notifications (waits); Laravel queue docs document RateLimited, ThrottlesExceptions and worker recycle flags.

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

Monolith: one process, one database ​

A web request writes an order and enqueues a confirmation email in the same process. The simplest correct backpressure is a bounded in-process queue and a worker pool, as the Pipeline: TrySubmit for “nice to have” work, Submit with a deadline for work that must happen. If the queue is the jobs table, the SQL above gives depth and age; a command refuses to enqueue past a limit. One database means one capacity; protect it first.

Modular monolith: explicit owners ​

Billing and notification modules share a queue worker fleet. Without per-module limits a notification flood starves billing. Use separate queues and supervisors (Horizon partner-sync versus default), separate maxProcesses, and per-module rate limiters. The owner of each queue owns its alert on age.

Microservices: signals cross service boundaries ​

Orders publishes OrderPlaced; Billing consumes it and calls a payment provider limited to 50 requests per second. If Billing simply scales consumers, the provider returns 429s and retries amplify. Billing rate-limits calls to the provider, pauses consumption when the provider is down, and surfaces lag. Orders does not need to know; the broker holds the backlog. Where Orders must know (it can refuse checkout when Billing is far behind), publish a health or lag signal and make the front door shed with a clear 503, not accept orders that will not be billed for hours. The outbox keeps the publish reliable; acknowledgment keeps in-flight work correct.

Distributed data: replicas, caches and regions ​

Replica lag is also lag: a consumer reading a lagging replica may see old state and fail, making retries pile up. A cache stampede after an outage turns into a thundering herd of recomputation jobs; rate-limit recompute and coalesce duplicates. Across regions, backlog per region is separate; failover moves consumers but not the backlog, so drain estimates must use the target region's capacity. Kafka quotas and per-tenant limits keep one tenant from consuming a shared cluster.

Scaling path ​

LoadDesignExample
1×One bounded queue, a few workers, an alert on queue ageLaravel queue:work under Supervisor, --max-jobs, --max-time
10×Per-queue limits, rate-limited external calls, lag-based autoscalingHorizon auto balance, maxProcesses, RateLimited
100×Partition by tenant or key, quotas, load shedding with priorities, drain runbooksKafka quotas, per-tenant token buckets, shed low-priority classes first

At every step the bound moves outward, but it never disappears. The question to ask of any queue is: when it is full, who waits and who is told?

Lab ​

All broker labs below are expected, not run; the Go labs are real commands you can run locally.

1. See an unbounded queue grow (Go, runs locally) ​

bash
cd docs/snippets/messaging/backpressure-flow-control/go
go run ./before | tail -3
# measured once on this machine: backlog about 7,000 after 1.5 s, 17,000 after 3 s; numbers vary

2. Run the pipeline and admission tests (Go, runs locally) ​

bash
go test -race -count=1 ./after/pipeline ./after/admission
# ok  academy/backpressure-flow-control/after/pipeline
# ok  academy/backpressure-flow-control/after/admission

3. RabbitMQ bounded queue (expected, not run) ​

bash
rabbitmqctl set_policy jobs-limit '^jobs$' '{"max-length":5,"overflow":"reject-publish"}' --apply-to queues
# publish 10 persistent messages with confirms enabled
# expected: 5 acks, 5 nacks; messages_ready = 5
# start one consumer with prefetch 2 and sleep 10 s per message
# expected: messages_unacknowledged = 2, messages_ready = 3

4. Kafka lag and quota (expected, not run) ​

bash
kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group billing
# expected: LAG column grows while the consumer sleeps 1 s per record and the producer runs
kafka-configs.sh --bootstrap-server localhost:9092 --alter \
  --add-config 'producer_byte_rate=1024' --entity-type clients --entity-name lab
# expected: producer metric produce-throttle-time-avg rises for client-id lab

5. Redis Streams trimming and lag (expected, not run) ​

bash
redis-cli XGROUP CREATE events billing '$' MKSTREAM
for i in $(seq 1 200); do redis-cli XADD events MAXLEN '~' 100 '*' n $i >/dev/null; done
redis-cli XLEN events
# expected: a value close to 100, possibly a few tens above; entries older than that were deleted
redis-cli XINFO GROUPS events
# expected: lag reflects entries not yet delivered to billing, or NULL if it cannot be determined

6. Laravel worker and Horizon (expected, not run) ​

bash
php artisan queue:work redis --queue=partner-sync --max-jobs=50 --max-time=60 --memory=128
# expected: the worker exits after 50 jobs or 60 s; Supervisor restarts it
php artisan horizon
# expected: with maxProcesses 8 the supervisor never exceeds 8 workers however large the backlog

Common misconceptions ​

BeliefReality
A bigger queue solves overloadIt only delays failure and increases waiting time; sustained excess still overflows
Pull-based consumers cannot be overwhelmedThey cannot be flooded, but the backlog and lag still grow, and slow polling triggers rebalances
Prefetch is the batch sizeIt limits unacknowledged deliveries; large values cause hoarding and memory growth
basic.qos applies to basic.getIt has no effect on messages fetched with basic.get
Global QoS is the normal wayIn RabbitMQ it is deprecated and disabled by default from 4.3; use per-consumer prefetch
max.poll.records limits what is fetchedIt limits what one poll() returns; fetching is governed by the fetch settings
MAXLEN on a stream is backpressureIt deletes data; the producer must still watch XLEN or lag
Low CPU means healthy consumersWaiting on a dependency leaves CPU idle while lag explodes
Adding consumers always helpsIf the bottleneck is a shared dependency, it makes things worse
Dropping messages is always a failureDropping expired or low-value work early is how a system stays stable
Retries make a system more reliableUnbounded or immediate retries amplify overload
Closing the connection is graceful shutdownUnacked or uncommitted work is redelivered; stop intake and drain first

Cheat sheet ​

TopicRemember
Bound everythingQueue length, in-flight window, workers, retries, client buffers
Little's lawL = λ × W; workers needed = λ × service time
StabilityNeed λ < workers ÷ service time, plus headroom
Drain timebacklog ÷ (capacity − λ)
RabbitMQ windowbasic.qos per-consumer prefetch; 100 to 300 is typical; 0 means unlimited
RabbitMQ stopsMemory alarm at vm_memory_high_watermark (0.6), disk alarm at disk_free_limit (50 MB)
RabbitMQ limitsx-max-length plus overflow (drop-head default, reject-publish)
Kafka consumermax.poll.records × time per record below max.poll.interval.ms
Kafka producerbuffer.memory and max.block.ms; linger.ms, batch.size shape batches
Kafka quotasByte-rate and request-rate; broker delays responses
Redis StreamsCOUNT and BLOCK per read; MAXLEN ~ caps memory but deletes data
Redis lagXINFO GROUPS lag and pending; lag can be NULL
Laravel worker--max-jobs, --max-time, --memory, --timeout below retry_after
Laravel middlewareRateLimited, ThrottlesExceptions, WithoutOverlapping
Horizonbalance, maxProcesses, balanceCooldown, waits
ShutdownStop intake, drain with a deadline, cancel, ack finished work

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why does a larger buffer not fix sustained overload? Must-know ​

Answer

Answer: Arrival exceeds service, so the backlog grows at the difference. A larger buffer only postpones the overflow and increases waiting time for every message.

2 — A queue receives 200 messages per second and each message takes 50 ms. How many workers keep it stable? Must-know ​

Answer

Answer: Little's law gives 200 × 0.05 = 10 busy workers at 100% utilisation, so at least 11 and preferably 12 or more for headroom.

3 — With 8 workers in the same case, how fast does the backlog grow and how long does a new message wait after 10 minutes? Important ​

Answer

Answer: Capacity is 160/s, so it grows 40/s, reaching 24,000 messages after 10 minutes; a new message waits 24,000 ÷ 160 = 150 seconds.

4 — What does RabbitMQ prefetch limit, and what does it not affect? Important ​

Answer

Answer: The number of unacknowledged deliveries per consumer. It has no effect on basic.get, and 0 means unlimited.

5 — What happens when a RabbitMQ node hits vm_memory_high_watermark? Important ​

Answer

Answer: A memory alarm blocks all publishing connections; clients that support it get connection.blocked and later connection.unblocked when alarms clear.

6 — What is the difference between drop-head and reject-publish? Important ​

Answer

Answer: drop-head (default) discards or dead-letters the oldest message; reject-publish discards the newest and, with publisher confirms, nacks the publisher.

7 — Why can a Kafka consumer be kicked out of its group even though it is healthy? Must-know ​

Answer

Answer: If time between polls exceeds max.poll.interval.ms (for example 500 records at 1 s each), the group considers it failed and rebalances.

8 — Why is MAXLEN on a Redis stream not backpressure? Must-know ​

Answer

Answer: It deletes old entries instead of slowing the producer; unread data can be lost. The producer must watch XLEN or group lag and slow down.

9 — What does a pause with two thresholds (high and low watermark) prevent? Important ​

Answer

Answer: Flapping: with one threshold the system stops and starts repeatedly around it; hysteresis pauses at the high mark and resumes only at the low mark.

10 — Why should --timeout be shorter than retry_after in Laravel? Must-know ​

Answer

Answer: Otherwise the queue may release a still-running job to another worker, executing it twice concurrently.

11 — When is shedding better than scaling? Must-know ​

Answer

Answer: When the work expires before it can be served, when the bottleneck is a shared dependency, or when capacity cannot grow in time.

Glossary ​

TermMeaning
BackpressureFeedback from a slow stage that makes faster stages wait, slow down, or stop
Flow controlMechanisms (windows, credits, blocking) that match sender rate to receiver capacity
Credit-based flow controlSender may send only as many items as the receiver has granted credit for
Bounded bufferQueue with a fixed capacity and a defined full-buffer behaviour
Unbounded queueQueue with no effective size limit
Little's lawL = λ × W for a stable system
Arrival rate (λ)Average items entering per unit time
Service timeTime a worker needs per item
UtilisationShare of capacity in use: λ ÷ (workers ÷ service time)
Consumer lagHow far a consumer group is behind the end of the data
records-lag-maxKafka consumer metric: maximum partition lag in the window
PrefetchNumber of unacknowledged messages a broker may deliver to a consumer
basic.qosAMQP method that sets prefetch count (and size)
prefetch_countRabbitMQ's per-consumer unacknowledged-delivery limit
Connection flowRabbitMQ state of a publishing connection that is being slowed
connection.blockedAMQP extension notifying clients that alarms block publishing
vm_memory_high_watermarkRabbitMQ memory threshold that raises the memory alarm
disk_free_limitRabbitMQ free-disk threshold that raises the disk alarm
x-max-lengthRabbitMQ queue length limit argument (max-length as policy key)
overflowWhat a full RabbitMQ queue does: drop-head, reject-publish, reject-publish-dlx
drop-headOverflow mode that discards the oldest message
reject-publishOverflow mode that rejects the newest publish
Quorum queueReplicated RabbitMQ queue type with a bounded in-memory index
Lazy queueFormer classic-queue mode; no longer supported, behaviour is now default
TTLMessage or queue time-to-live; expiry, not a rate limit
max.poll.recordsKafka: maximum records returned by one poll()
max.poll.interval.msKafka: maximum time between polls before rebalance
fetch.min.bytesKafka: minimum data the broker returns per fetch
fetch.max.wait.msKafka: longest the broker waits to satisfy fetch.min.bytes
buffer.memoryKafka producer: memory for unsent records
max.block.msKafka producer: how long send() blocks before failing
linger.msKafka producer: batching delay
batch.sizeKafka producer: per-partition batch size in bytes
QuotaKafka limit on a client's byte rate or request time, enforced by delayed responses
MAXLENRedis stream trim by entry count
MINIDRedis stream trim by minimum entry ID (age)
XINFORedis commands for stream and group introspection
PELPending entries list: delivered, unacknowledged entries of a Redis consumer group
Load sheddingDiscarding or rejecting work to protect capacity
Admission controlDeciding at the entrance whether work may enter
Rate limitingBounding the rate of events
Token bucketLimiter with a refill rate and a burst size
SemaphoreCounter that bounds concurrent holders
golang.org/x/time/rateGo token-bucket limiter package
HysteresisTwo thresholds so pause and resume do not flap
Graceful shutdownStop intake, drain in-flight work within a deadline, then exit
queue:workLaravel command that runs a queue worker
HorizonLaravel's Redis queue dashboard and supervisor-based autoscaler
RateLimitedLaravel job middleware that releases jobs over a named limit
ThrottlesExceptionsLaravel job middleware that pauses a job after repeated exceptions
WithoutOverlappingLaravel job middleware that serialises jobs by key
Retry stormRetries that sustain overload after the cause has gone

References ​

Built by Morteza Negahi