Decouple the rate at which work arrives from the rate at which it is processed. A buffer absorbs bursts, and a consumer pulls at a steady, configured rate. The protected resource then sees a flat load profile regardless of how spiky the producers are.
Some downstream systems can only absorb work at a fixed rate. A payment provider allows 50 calls per second. A legacy ERP handles 20 writes per second. A GPU pool has a set number of slots. Traffic does not respect any of those limits. Queue-based load leveling puts a durable queue between the services that create work and the one service that performs it. Producers enqueue and return immediately. A consumer drains the queue at a rate the downstream can sustain. Peaks become a backlog that clears over minutes, and the downstream is never overrun. This guide follows one incident at a ferry booking platform from the outage through the redesign, and then covers what interviewers will probe: drain-rate sizing, delivery semantics, queue depth limits and the failure modes that remain after the change.
The problem
A situation where the obvious design starts to hurt.
Ferrymark sells tickets for a regional ferry operator: about 9,000 bookings a day and roughly 300 refunds on a normal day. Refunds go through a payment provider whose contract allows 50 requests per second per merchant account. Above that it returns HTTP 429.
The old design was fully synchronous. When a sailing was cancelled, the disruption service looped over the affected bookings with 120 parallel workers and called the Refund API for each one. The Refund API called the provider inline and retried up to 3 times on failure, holding a Postgres connection from a pool of 40 the whole time. Customers who tapped Request refund in the app reached the same code path.
One February morning a gale warning cancelled 11 sailings at 06:05. Within 90 seconds the disruption service fired 16,800 refund calls, and thousands of anxious passengers tapped the refund button on top of that. The provider started returning 429 on most calls. Inline retries tripled the request volume and made the throttling worse. The connection pool was pinned by requests waiting on the provider, so booking and check-in pages, which shared the database, began timing out. Refund API p99 latency climbed to 28 seconds.
When the dust settled, 2,100 refunds sat in an unknown state. The caller had timed out, but the provider might or might not have processed them. Engineers found 63 passengers refunded twice, because a timed-out call had actually succeeded and the retry succeeded again. The provider's limit had not changed. What broke Ferrymark was presenting 16,800 units of work as 16,800 simultaneous demands.
The solution
What the pattern proposes.
Split accepting a refund from executing it.
The Refund API now does only fast, local work. It validates the request, writes a refund row with status queued and an idempotency key derived from the booking ID, puts a small message on a durable refund-requests queue, and returns 202 Accepted with the refund ID. That takes a few milliseconds and never touches the provider, so the disruption service and the app can hit it as hard as they like.
A refund worker pulls messages in batches of 10 and paces provider calls at 40 per second. That is 80 percent of the contractual 50, which leaves headroom for the manual refunds the support team issues from the provider dashboard. At that rate the 16,800-refund storm drains in 420 seconds, about 7 minutes, well inside the 30-minute refund-initiated promise shown to customers.
Each call passes the idempotency key to the provider, so a redelivered message cannot pay twice. A 429 or 5xx response puts the message back on the queue with exponential backoff (1 s, 2 s, 4 s, capped at 60 s). After 5 attempts, or on a non-retryable error such as card account closed, the message goes to a dead-letter queue and the refund row is marked needs_review. A successful call marks the row completed, and a notification goes out.
The queue absorbs the peak. Queue depth and the age of the oldest message become the operational signals, replacing provider error rate. The booking database no longer holds connections open while waiting on a third party.
An everyday analogy
The same idea, outside software.
Picture a regional mail sorting centre. Trucks arrive whenever they arrive: two an hour overnight, then eight within twenty minutes after the morning ferry docks. Each truck dumps its sacks into a large hopper. The sorting machine at the bottom of the hopper feeds letters at its rated speed, never faster, however full the hopper gets. Drivers unload and leave without waiting for their letters to be sorted. The supervisor watches the hopper level. A full hopper at 7 a.m. is normal. A hopper still full at noon means the machine is too slow for the day's volume, and that is the point to add a second machine or slow down intake.
Structure
The pieces and how they relate.
Participants
- Producers (disruption service, Ferrymark app)
- Create work at whatever rate events happen. They call the Refund API and receive a refund ID and 202 Accepted within milliseconds. They never wait for the provider and never retry against it.
- Refund API (intake)
- Validates input, writes the refund row with status queued and an idempotency key, and enqueues a small message. It does no slow or rate-limited work, so its latency stays flat under load.
- refund-requests queue
- Durable buffer that holds the backlog. It provides at-least-once delivery, a visibility timeout so in-flight messages are not handed out twice, and retention long enough to survive a long provider outage. Its depth and oldest-message age are the key health metrics.
- Refund worker (steady consumer)
- Pulls batches and paces outbound calls to a configured rate below the downstream limit. It acknowledges on success, re-queues with backoff on retryable errors, and dead-letters after the attempt limit.
- Payment provider (protected resource)
- The fixed-capacity dependency the pattern exists to protect. It sees at most 40 requests per second from the worker, whatever the producers are doing.
- Dead-letter queue
- Parks messages that failed 5 times or hit a non-retryable error. Support triages them, and they are never silently dropped.
Pseudocode
The solution to the scenario, language-neutral.
// Intake: fast, local, never touches the provider
handle POST /refunds(bookingId, amount):
key = "refund:" + bookingId
row = db.insertIfAbsent(refunds, key, status = QUEUED, amount)
if row.alreadyExisted:
return 202 { refundId: row.id } // duplicate tap, same answer
queue.send({ refundId: row.id, bookingId, amount, key })
return 202 { refundId: row.id }
// Steady consumer
RATE = 40 per second
interval = 1 / RATE
nextSlot = now()
loop forever:
batch = queue.receive(max = 10, visibilityTimeout = 30s)
if batch is empty:
sleep(100ms)
continue
for msg in batch:
wait until nextSlot
nextSlot = max(now(), nextSlot) + interval
try:
provider.refund(msg.amount, idempotencyKey = msg.key)
db.update(msg.refundId, status = COMPLETED)
queue.ack(msg)
catch RetryableError (429, 5xx, timeout):
if msg.attempts < 5:
queue.release(msg, delay = min(60s, 2^(attempts-1) s))
else:
queue.deadLetter(msg)
db.update(msg.refundId, status = NEEDS_REVIEW)
catch FatalError:
queue.deadLetter(msg)
db.update(msg.refundId, status = NEEDS_REVIEW)
// Ops signals
alert if queue.depth > 50,000 or queue.oldestAge > 20 minutesThe code
The same solution in TypeScript, Python and PHP.
// Steady consumer that drains a queue at a fixed rate into a rate-limited provider.
// The in-memory queue stands in for SQS/RabbitMQ: receive() hides messages,
// release() makes them visible again after a delay, success acts as an ack.
type RefundJob = { refundId: string; bookingId: string; amountCents: number };
type Message<T> = { id: string; body: T; attempts: number };
class RetryableError extends Error {}
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
class InMemoryQueue<T> {
private items: { msg: Message<T>; availableAt: number }[] = [];
private seq = 0;
readonly deadLetters: Message<T>[] = [];
enqueue(body: T): void {
this.seq += 1;
this.items.push({ msg: { id: String(this.seq), body, attempts: 0 }, availableAt: 0 });
}
receive(max: number, now: number): Message<T>[] {
const ready: Message<T>[] = [];
const waiting: { msg: Message<T>; availableAt: number }[] = [];
for (const item of this.items) {
if (item.availableAt <= now && ready.length < max) {
item.msg.attempts += 1;
ready.push(item.msg);
} else {
waiting.push(item);
}
}
this.items = waiting;
return ready;
}
release(msg: Message<T>, delayMs: number, now: number): void {
this.items.push({ msg, availableAt: now + delayMs });
}
deadLetter(msg: Message<T>): void {
this.deadLetters.push(msg);
}
size(): number {
return this.items.length;
}
}
interface PaymentProvider {
refund(job: RefundJob): Promise<void>;
}
class SteadyWorker {
private readonly intervalMs: number;
private nextSlot = 0;
constructor(
private readonly queue: InMemoryQueue<RefundJob>,
private readonly provider: PaymentProvider,
ratePerSec: number,
private readonly maxAttempts = 5,
) {
this.intervalMs = 1000 / ratePerSec;
}
private async pace(): Promise<void> {
const now = Date.now();
const wait = Math.max(0, this.nextSlot - now);
this.nextSlot = Math.max(now, this.nextSlot) + this.intervalMs;
if (wait > 0) await sleep(wait);
}
async drainOnce(batch = 10): Promise<number> {
const messages = this.queue.receive(batch, Date.now());
for (const msg of messages) {
await this.pace();
try {
await this.provider.refund(msg.body);
} catch (err) {
if (err instanceof RetryableError && msg.attempts < this.maxAttempts) {
const backoffMs = Math.min(60_000, 1000 * 2 ** (msg.attempts - 1));
this.queue.release(msg, backoffMs, Date.now());
} else {
this.queue.deadLetter(msg);
}
}
}
return messages.length;
}
}
class FlakyProvider implements PaymentProvider {
calls = 0;
readonly refunded = new Set<string>();
async refund(job: RefundJob): Promise<void> {
this.calls += 1;
if (this.calls % 7 === 0) throw new RetryableError('429 from provider');
this.refunded.add(job.refundId); // a Set mirrors provider-side idempotency
}
}
async function main(): Promise<void> {
const queue = new InMemoryQueue<RefundJob>();
for (let i = 1; i <= 25; i++) {
queue.enqueue({ refundId: `rf-${i}`, bookingId: `bk-${i}`, amountCents: 4500 });
}
const provider = new FlakyProvider();
const worker = new SteadyWorker(queue, provider, 20);
const start = Date.now();
while (queue.size() > 0) {
if ((await worker.drainOnce()) === 0) await sleep(100);
}
const secs = ((Date.now() - start) / 1000).toFixed(1);
console.log(`refunded=${provider.refunded.size} calls=${provider.calls} dlq=${queue.deadLetters.length} in ${secs}s`);
}
main();# Steady consumer that drains a queue at a fixed rate into a rate-limited provider.
# The in-memory queue stands in for SQS/RabbitMQ: receive() hides messages,
# release() makes them visible again after a delay, success acts as an ack.
from __future__ import annotations
import asyncio
import time
from dataclasses import dataclass
from typing import Protocol
@dataclass(frozen=True)
class RefundJob:
refund_id: str
booking_id: str
amount_cents: int
@dataclass
class Message:
id: str
body: RefundJob
attempts: int = 0
class RetryableError(Exception):
pass
class InMemoryQueue:
def __init__(self) -> None:
self._items: list[tuple[Message, float]] = []
self._seq = 0
self.dead_letters: list[Message] = []
def enqueue(self, body: RefundJob) -> None:
self._seq += 1
self._items.append((Message(str(self._seq), body), 0.0))
def receive(self, max_count: int, now: float) -> list[Message]:
ready: list[Message] = []
waiting: list[tuple[Message, float]] = []
for msg, available_at in self._items:
if available_at <= now and len(ready) < max_count:
msg.attempts += 1
ready.append(msg)
else:
waiting.append((msg, available_at))
self._items = waiting
return ready
def release(self, msg: Message, delay_sec: float, now: float) -> None:
self._items.append((msg, now + delay_sec))
def dead_letter(self, msg: Message) -> None:
self.dead_letters.append(msg)
def size(self) -> int:
return len(self._items)
class PaymentProvider(Protocol):
async def refund(self, job: RefundJob) -> None: ...
class SteadyWorker:
def __init__(self, queue: InMemoryQueue, provider: PaymentProvider,
rate_per_sec: float, max_attempts: int = 5) -> None:
self._queue = queue
self._provider = provider
self._interval = 1.0 / rate_per_sec
self._max_attempts = max_attempts
self._next_slot = 0.0
async def _pace(self) -> None:
now = time.monotonic()
wait = max(0.0, self._next_slot - now)
self._next_slot = max(now, self._next_slot) + self._interval
if wait > 0:
await asyncio.sleep(wait)
async def drain_once(self, batch: int = 10) -> int:
messages = self._queue.receive(batch, time.monotonic())
for msg in messages:
await self._pace()
try:
await self._provider.refund(msg.body)
except RetryableError:
if msg.attempts < self._max_attempts:
backoff = min(60.0, 2.0 ** (msg.attempts - 1))
self._queue.release(msg, backoff, time.monotonic())
else:
self._queue.dead_letter(msg)
except Exception:
self._queue.dead_letter(msg)
return len(messages)
class FlakyProvider:
def __init__(self) -> None:
self.calls = 0
self.refunded: set[str] = set() # mirrors provider-side idempotency
async def refund(self, job: RefundJob) -> None:
self.calls += 1
if self.calls % 7 == 0:
raise RetryableError("429 from provider")
self.refunded.add(job.refund_id)
async def main() -> None:
queue = InMemoryQueue()
for i in range(1, 26):
queue.enqueue(RefundJob(f"rf-{i}", f"bk-{i}", 4500))
provider = FlakyProvider()
worker = SteadyWorker(queue, provider, rate_per_sec=20)
start = time.monotonic()
while queue.size() > 0:
if await worker.drain_once() == 0:
await asyncio.sleep(0.1)
elapsed = time.monotonic() - start
print(f"refunded={len(provider.refunded)} calls={provider.calls} "
f"dlq={len(queue.dead_letters)} in {elapsed:.1f}s")
if __name__ == "__main__":
asyncio.run(main())<?php
// Steady consumer that drains a queue at a fixed rate into a rate-limited provider.
// The in-memory queue stands in for SQS/RabbitMQ: receive() hides messages,
// release() makes them visible again after a delay, success acts as an ack.
declare(strict_types=1);
final class RefundJob
{
public function __construct(
public readonly string $refundId,
public readonly string $bookingId,
public readonly int $amountCents,
) {}
}
final class Message
{
public int $attempts = 0;
public function __construct(
public readonly string $id,
public readonly RefundJob $body,
) {}
}
final class RetryableError extends RuntimeException {}
final class InMemoryQueue
{
/** @var list<array{0: Message, 1: float}> */
private array $items = [];
private int $seq = 0;
/** @var list<Message> */
public array $deadLetters = [];
public function enqueue(RefundJob $body): void
{
$this->seq++;
$this->items[] = [new Message((string) $this->seq, $body), 0.0];
}
/** @return list<Message> */
public function receive(int $max, float $now): array
{
$ready = [];
$waiting = [];
foreach ($this->items as [$msg, $availableAt]) {
if ($availableAt <= $now && count($ready) < $max) {
$msg->attempts++;
$ready[] = $msg;
} else {
$waiting[] = [$msg, $availableAt];
}
}
$this->items = $waiting;
return $ready;
}
public function release(Message $msg, float $delaySec, float $now): void
{
$this->items[] = [$msg, $now + $delaySec];
}
public function deadLetter(Message $msg): void
{
$this->deadLetters[] = $msg;
}
public function size(): int
{
return count($this->items);
}
}
interface PaymentProvider
{
public function refund(RefundJob $job): void;
}
final class SteadyWorker
{
private float $interval;
private float $nextSlot = 0.0;
public function __construct(
private InMemoryQueue $queue,
private PaymentProvider $provider,
float $ratePerSec,
private int $maxAttempts = 5,
) {
$this->interval = 1.0 / $ratePerSec;
}
private function pace(): void
{
$now = microtime(true);
$wait = max(0.0, $this->nextSlot - $now);
$this->nextSlot = max($now, $this->nextSlot) + $this->interval;
if ($wait > 0) {
usleep((int) ($wait * 1_000_000));
}
}
public function drainOnce(int $batch = 10): int
{
$messages = $this->queue->receive($batch, microtime(true));
foreach ($messages as $msg) {
$this->pace();
try {
$this->provider->refund($msg->body);
} catch (RetryableError $e) {
if ($msg->attempts < $this->maxAttempts) {
$backoff = min(60.0, 2.0 ** ($msg->attempts - 1));
$this->queue->release($msg, $backoff, microtime(true));
} else {
$this->queue->deadLetter($msg);
}
} catch (Throwable $e) {
$this->queue->deadLetter($msg);
}
}
return count($messages);
}
}
final class FlakyProvider implements PaymentProvider
{
public int $calls = 0;
/** @var array<string, true> mirrors provider-side idempotency */
public array $refunded = [];
public function refund(RefundJob $job): void
{
$this->calls++;
if ($this->calls % 7 === 0) {
throw new RetryableError('429 from provider');
}
$this->refunded[$job->refundId] = true;
}
}
$queue = new InMemoryQueue();
for ($i = 1; $i <= 25; $i++) {
$queue->enqueue(new RefundJob("rf-$i", "bk-$i", 4500));
}
$provider = new FlakyProvider();
$worker = new SteadyWorker($queue, $provider, 20.0);
$start = microtime(true);
while ($queue->size() > 0) {
if ($worker->drainOnce() === 0) {
usleep(100_000);
}
}
printf(
"refunded=%d calls=%d dlq=%d in %.1fs\n",
count($provider->refunded),
$provider->calls,
count($queue->deadLetters),
microtime(true) - $start,
);When to use it
Situations where it pays off.
A downstream has a hard throughput ceiling (contractual rate limit, licence slots, a legacy system) and arrivals are bursty with a much higher peak-to-average ratio.
The queue turns a peak far above the ceiling into a backlog that drains at a safe rate. You size the consumer for the downstream limit instead of the producers' worst day.
The caller does not need the result synchronously and an eventual completion signal (status poll, webhook, push notification) is acceptable.
Load leveling only works if producers can hand off and leave. If the user must see the provider's answer inside the HTTP request, the queue only adds latency.
A shared resource such as a database connection pool is being exhausted by requests that wait on a slow third party.
Moving the slow call to a worker frees request-path resources within milliseconds. Unrelated features stop failing because one dependency is slow.
Bursts are predictable in shape but not in timing: weather cancellations, end-of-month batch jobs, a marketing push at 09:00.
You can compute worst-case drain time from the largest plausible burst and the drain rate, and check it against your completion SLA before the burst happens.
How to implement it
Steps to introduce it in existing code.
Identify the protected resource and its true limit, then pick a drain rate with headroom. Ferrymark uses 40/s against a 50/s contract because support issues manual refunds from the same merchant account.
Make intake cheap and durable: validate, persist the record with an idempotency key, enqueue, return 202 with an ID the caller can poll. Use a transactional outbox if the DB write and the enqueue must not diverge.
Size the backlog. Take the largest credible burst (16,800 refunds) divided by the drain rate (40/s) to get the drain time (7 minutes), and confirm it fits the customer promise (30 minutes). Set queue retention well above your longest plausible downstream outage.
Pace the consumer explicitly with a token bucket or a fixed-interval scheduler. Do not rely on worker count alone. If you run several workers, divide the global rate between them or use a shared limiter.
Set the visibility timeout above the worst-case processing time (provider timeout 10 s, so 30 s) so in-flight messages are not redelivered while still being processed.
Route repeated failures to a dead-letter queue with a bounded attempt count and exponential backoff. Mark the business record as needing review so nothing disappears.
Alert on queue depth and oldest-message age, not just error rate. A growing age means the drain rate is below the sustained arrival rate, and that needs a capacity decision.
Pros and cons
What you gain and what you pay.
Pros
- The downstream sees a flat, configurable load. A 16,800-request spike reaches the provider as 40 requests per second.
- Producer latency stays at a few milliseconds regardless of downstream health, so request-path resources such as DB connections are released quickly.
- Downstream outages become delay instead of data loss. Messages wait in the queue until the provider recovers.
- Capacity planning simplifies: consumers are sized for the average arrival rate plus a drain-time budget, not for the peak.
- Queue depth and age give a clear, single-number view of whether the system is keeping up.
Cons
- Work completes asynchronously, so clients need a status endpoint or notification path, and the UX has to explain processing states.
- Delivery is at least once, so every consumer action needs idempotency. Without it, redelivery causes duplicate side effects such as double refunds.
- Adds infrastructure to operate: the queue itself, a DLQ, alerting on depth and age, and replay tooling for dead letters.
- If the sustained arrival rate exceeds the drain rate, the queue grows without bound. Load leveling smooths peaks but does not create capacity.
- Ordering guarantees are weaker unless you choose a FIFO or partitioned queue, which usually lowers throughput.
Trade-offs
Decisions you'll have to make, each with its price.
Drain at 40/s against a 50/s provider limit instead of running at the full 50/s
You gainRoom for support's manual refunds and for clock jitter between worker instances, so the account is never throttled during a storm.
You payThe 16,800-refund burst takes 420 s instead of 336 s, and 20 percent of contracted capacity sits idle on quiet days.
Return 202 and complete asynchronously instead of keeping the synchronous 200 with the provider result
You gainIntake p99 drops from seconds to single-digit milliseconds, and the DB pool is no longer held while the provider responds.
You payClients must handle a pending state. The app needed a status screen and push notification, and support needed a refund-status lookup tool.
Visibility timeout of 30 s with a 10 s provider call timeout
You gainA crashed worker's messages reappear within 30 s, which keeps recovery quick.
You payA call that hangs past 30 s through a stuck connection gets redelivered while the original may still complete. Only the provider-side idempotency key prevents a double refund.
Max 5 attempts with backoff capped at 60 s before dead-lettering
You gainBounds how long a poison message churns, about 15 s of cumulative delay, and surfaces it to humans quickly.
You payA provider outage longer than about a minute pushes healthy refunds into the DLQ. Pair it with a circuit breaker or a longer cap during known incidents, and build a one-click DLQ redrive.
Single paced worker instead of a horizontally scaled pool
You gainThe rate limit is trivially correct because one process owns the clock, and there is no distributed limiter to run.
You payIt is a throughput ceiling and a single point of slowness. Losing the instance pauses refunds until restart, though no messages are lost.
How it fails
What goes wrong in production and how to prevent it.
Sustained arrivals exceed drain rate, so the queue grows for hours and refunds blow past the 30-minute promise
What to doAlert when oldest-message age exceeds 20 minutes or depth exceeds 50,000. Negotiate a higher provider limit or add a second merchant account. Past a hard depth cap, intake returns 503 with Retry-After so producers back off.
Redelivery after a timeout causes duplicate refunds
What to doDerive the idempotency key from the booking ID, not the message ID, and send it on every provider call. Before calling, check the refund row: if it is already completed, ack and skip.
Intake commits the DB row but crashes before enqueueing, so the refund sits in queued forever
What to doWrite the message to an outbox table in the same transaction and have a relay publish it. Alternatively, run a sweeper that re-enqueues rows stuck in queued for more than 5 minutes.
Autoscaler adds workers on queue depth and multiplies the outbound rate past the provider limit
What to doEnforce the rate globally with a shared token bucket in Redis keyed by merchant account. Alternatively, cap the worker count and split the rate per instance (2 workers at 20/s each), not 40/s each.
Poison message, such as an amount mismatch the provider rejects as a validation error, is retried as if it were transient
What to doClassify errors: 429, 5xx and timeouts are retryable, while 4xx validation errors go straight to the DLQ and the row is marked needs_review with the provider's error code.
Provider outage drains every message into the DLQ within minutes
What to doPut a circuit breaker in the worker. When it opens, stop receiving instead of failing messages, so they stay in the queue with their attempt counts intact until the provider recovers.
In a system design interview
When to bring it up and how to explain it.
Use it when a design has a slow or rate-limited dependency (payment provider, email vendor, ML inference, legacy ERP) and bursty input such as flash sales, batch jobs or incident-driven spikes, and the result does not have to be returned inside the user's request. It is a natural answer when the interviewer asks what happens at 10x traffic or what happens when the vendor throttles you.
What you could say
The core issue is that our refund rate is set by the payment provider, 50 requests per second, while demand is set by the weather. A storm can produce 16,000 refunds in a minute. So I'd split accepting a refund from executing it. The Refund API validates, writes a row with status queued and an idempotency key from the booking ID, enqueues a message and returns 202. That's milliseconds and never touches the provider. A worker drains the queue and paces calls at 40 per second, leaving headroom for manual refunds. At that rate 16,800 refunds clear in about seven minutes, inside our 30-minute promise. Delivery is at least once, so every provider call carries the idempotency key, and a redelivered message can't pay twice. Throttling and 5xx errors re-queue with exponential backoff. After five attempts the message goes to a dead-letter queue and support sees it. Operationally I'd alert on oldest-message age, not error rate, because a growing age means the drain rate is below the sustained arrival rate. That is a capacity problem, and the queue can't fix it.
Likely follow-ups
What if you need more throughput than one worker gives you?
I'd add competing consumers, but the outbound limit is per merchant account, so I'd enforce it with a shared token bucket in Redis rather than per-process pacing. Scaling workers only helps if the downstream limit has headroom. Otherwise I'd negotiate a higher limit or shard across merchant accounts.
How do you stop the queue from growing forever?
I'd set a depth cap derived from the SLA: 30 minutes at 40/s is 72,000 messages. Above that, intake returns 503 with Retry-After, which is backpressure. The disruption service is a batch job, so it can slow down, and the app shows a try-again message instead of accepting work we can't finish in time.
How does the customer know the refund happened?
The 202 response carries a refund ID. The app polls a status endpoint or receives a push notification when the worker marks the row completed, and needs_review rows trigger a support ticket. The UI says processing, not refunded, until the provider confirms.
Why not just retry inline with backoff in the API?
Inline retries hold request threads and DB connections while you wait, which is exactly what took down booking pages here. They also multiply load on an already throttled provider. Re-queuing with a delay releases every request-path resource and keeps the outbound rate fixed.
Relations with other guides
Patterns it's often confused or combined with.
- Competing Consumers: Many Workers, One Queue, No Duplicates
When one paced worker cannot keep up with the sustained rate, several consumers pull from the same queue. The global rate limit must then be shared between them so the protected resource still sees at most its limit.
- Backpressure: Let Slow Consumers Slow Down Fast Producers
Load leveling absorbs bursts. Backpressure tells producers to slow down when the buffer is near capacity. Combine them so a full queue produces 503 with Retry-After at intake instead of unbounded growth.
- Idempotency Keys: Making Retried Writes Safe
At-least-once delivery means the worker will occasionally process a message twice. An idempotency key sent to the provider turns that duplicate into a no-op instead of a second refund.
- Transactional Outbox: Commit State and Events Together
Intake writes a DB row and enqueues a message. An outbox makes those two steps atomic so a crash between them cannot leave a queued refund with no message.
- Rate Limiting: Token Bucket, Sliding Window and Honest 429s
The consumer's pacing is a rate limiter applied to outbound calls. The pattern moves the limit from rejecting callers to scheduling work.
- Retry with Backoff: Exponential Delays, Jitter and Retry Budgets
Retries happen by re-queuing with a delay instead of retrying inline, so a throttled provider is not hit with a retry storm while request threads wait.
Common questions
Short answers to the usual doubts.
Is a queue enough, or do I also need rate limiting in the consumer?
You need both. The queue only stores the backlog. If the consumer pulls as fast as it can, or autoscales on queue depth, it forwards the burst straight to the provider and you are back to 429s. The explicit pacing in the worker is what produces the flat load.
How do I pick the drain rate?
Start from the downstream's hard limit and subtract anything else that shares it, such as manual operations, other services on the same account, or a safety margin. Then check the arithmetic: largest credible burst divided by drain rate must fit your completion SLA, and the drain rate must exceed the sustained average arrival rate, or the backlog never empties.
What should the producer return if the work has not happened yet?
Return 202 Accepted with a durable ID and a way to observe the outcome: a status endpoint, a webhook or a push notification. Ferrymark shows Refund requested, processing in the app and sends a push notification when the row flips to completed.
Kafka, SQS, RabbitMQ or a database table?
For a few hundred messages per second with per-message retries and a DLQ, SQS or RabbitMQ fit naturally because they have visibility timeouts and per-message acks. Kafka suits very high throughput and replay, but per-message retry needs extra topics. A Postgres table with SKIP LOCKED works at Ferrymark's volume and keeps the write transactional, at the cost of polling load on the primary.
Does load leveling help if the downstream is simply down?
Yes, as long as retention outlasts the outage. Messages accumulate and drain once the provider recovers. Pair it with a circuit breaker in the worker so it stops burning attempts and filling the DLQ while the provider is hard down.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- Queues and messagingTake the test
- Massive traffic spikes: live votingSolve the exercise