Let several independent workers pull from one queue so a backlog drains in parallel. Each message is processed successfully at most once in effect, related messages keep their order, and a message that can never succeed is moved aside instead of blocking or looping.
Competing consumers is the simplest way to scale queue processing: put more workers on the same queue and let each message go to whichever worker asks first. Throughput grows roughly with worker count. The hard part comes after you add the second worker. Messages can be delivered twice, related messages can finish in the wrong order, and one bad message can keep failing and coming back indefinitely. This guide uses one invented system throughout: Ledgerline, a B2B billing platform that renders and emails invoices at month-end. It covers how the pattern works, what broke when Ledgerline scaled out, and the specific settings that fixed it: visibility timeouts with heartbeats, per-account message groups, idempotent processing and a dead-letter queue.
The problem
A situation where the obvious design starts to hurt.
Ledgerline closes billing at 00:00 UTC on the first of each month. The close job publishes about 420,000 render jobs to a queue called invoice-render. Each job renders a PDF, stores it and emails the customer. The run must finish by 06:00 UTC, when the accounting export starts.
One worker process with 8 concurrent slots took about 1.5 s per invoice at p50, which is roughly 5 invoices per second. At that rate the backlog takes about 22 hours. The team scaled to 24 replicas of the same worker on the same queue, 192 slots in flight, about 128 invoices per second. The backlog now drained in under an hour. Three things broke on the first close.
Duplicates. The queue used its default 30 s visibility timeout. Enterprise invoices with 2,000 or more line items took 40 to 110 s to render. Their messages became visible again mid-render, a second worker picked them up, and both workers emailed the customer. About 1,900 accounts got duplicate invoices, and a few got three.
Ordering. When an account had an adjustment, the close job emitted an invoice and then a credit note referencing it. With 24 workers, a small credit note often finished before its large invoice. The accounting sync rejected 312 credit notes that pointed to invoice numbers it had not seen yet.
Poison. A test account had the currency code XBT, which the renderer does not support. That message threw on every attempt. With no receive limit, it came back every 30 s all night, held a slot each time, and paged nobody. Later, when the team added per-account ordering, the same kind of message stopped that account's queue entirely, because nothing behind it in the group could be delivered.
The solution
What the pattern proposes.
Keep the competing consumers, and make each of the three failure points explicit.
Visibility timeout plus heartbeat. A received message is hidden from other workers for a lease of 60 s. A worker processing a long invoice extends the lease every 20 s, between chunks of 500 line items. If the worker dies, the lease runs out and another worker gets the message within about a minute. If it is alive, the lease never expires mid-render. The default timeout no longer needs to cover the worst-case job.
Idempotent processing. Redelivery will still happen, for example after a long GC pause, a crash after sending the email but before the ack, or a lost ack. Every worker checks a processed_docs table, which has a unique key on docId, before doing work, and records the docId after success. The email call also passes docId as the provider's idempotency key. This covers the window between sending and recording.
Ordering by group, not globally. Each message carries a group key equal to accountId. The queue delivers only the oldest unfinished message of a group, so an account's invoice and credit note are processed in order. Different accounts still spread across all 24 workers. Global order is neither needed nor affordable.
Poison handling. Errors are classified. A permanent error, such as a bad currency, a schema violation or an unparseable body, goes straight to invoice-render-dlq. A transient error, such as a timeout or a 503 from the email provider, is released with exponential backoff (5 s times 2 to the power of the receive count, capped at 300 s). A message received more than 5 times is dead-lettered regardless. An alarm fires when the DLQ depth is above 0, and a redrive tool replays fixed messages.
An everyday analogy
The same idea, outside software.
Picture a hospital lab with one rack of sample tubes and six technicians. Any free technician takes the next tube and writes their name and the time on a sign-out board. If the board shows no update for 20 minutes, the supervisor assumes the technician got pulled away and returns the tube to the rack. A technician on a long test updates the time every few minutes. Tubes from the same patient are rubber-banded together and handled in sequence. A tube with an unreadable label goes into a separate tray for a human to sort out. Nobody keeps putting it back on the rack.
Structure
The pieces and how they relate.
Participants
- Producer (billing close job)
- Publishes one message per document with a stable docId and a group key of accountId. It publishes an account's invoice before its credit note, because the queue preserves order only within a group and only in publish order.
- Queue (invoice-render)
- Hands each visible message to one receiver at a time and hides it for the visibility timeout. It delivers only the head message of each group and counts receives per message.
- Workers (24 replicas)
- Identical, stateless consumers that compete for messages. Each one checks the done-store, processes the job, extends its lease during long work, then acks. On failure it either releases the message with backoff or dead-letters it.
- Done-store (processed_docs)
- Shared table with a unique key on docId. It makes redelivery harmless: a worker that finds the docId already recorded acks the message and skips the work.
- Dead-letter queue (invoice-render-dlq)
- Holds messages that failed permanently or exceeded 5 receives, with the failure reason attached. It removes poison from the main queue so it stops holding worker slots and stops blocking its group.
- Redrive tool
- After a fix ships, moves dead-lettered messages back to the main queue, oldest first per account, so replays respect the same ordering rules.
Pseudocode
The solution to the scenario, language-neutral.
constants VISIBILITY = 60s, HEARTBEAT = 20s, MAX_RECEIVES = 5
worker loop:
while not shutting down:
batch = queue.receive(max = free slots, visibility = VISIBILITY)
for each msg in batch: handle(msg)
handle(msg):
if msg.receiveCount > MAX_RECEIVES:
queue.deadLetter(msg, "receive limit")
return
job = parse(msg.body)
if job is invalid:
queue.deadLetter(msg, "unparseable")
return
if doneStore.has(job.docId):
queue.ack(msg) // duplicate delivery, already done
return
touch = every HEARTBEAT: queue.changeVisibility(msg, VISIBILITY)
try:
render(job, touch) // calls touch between chunks
on PermanentError e:
queue.deadLetter(msg, e.reason)
return
on any other error:
queue.changeVisibility(msg, min(300s, 5s * 2^msg.receiveCount))
return
doneStore.add(job.docId) // unique key on docId
queue.ack(msg)
queue.receive rule for groups:
walk messages oldest first
deliver a message only if it is the oldest unfinished one in its group
and it is currently visibleThe code
The same solution in TypeScript, Python and PHP.
type Message = { id: string; groupId: string; body: string; receiveCount: number };
type Job = { kind: "invoice" | "credit_note"; docId: string; accountId: string; currency: string };
type Renderer = (job: Job, touch: () => Promise<void>) => Promise<void>;
class PermanentError extends Error {}
const VISIBILITY_SEC = 60;
const HEARTBEAT_SEC = 20;
const MAX_RECEIVES = 5;
const SUPPORTED = new Set(["EUR", "USD", "GBP"]);
class InMemoryQueue {
private items = new Map<string, { msg: Message; visibleAt: number }>();
readonly dlq: { id: string; reason: string }[] = [];
private seq = 0;
send(job: Job): void {
const id = `m${++this.seq}`;
const msg: Message = { id, groupId: job.accountId, body: JSON.stringify(job), receiveCount: 0 };
this.items.set(id, { msg, visibleAt: 0 });
}
// FIFO per group: only the oldest message of each group is eligible,
// so a group is blocked while its head message is in flight.
async receive(max: number, visibilitySec: number): Promise<Message[]> {
const now = Date.now();
const seenGroups = new Set<string>();
const out: Message[] = [];
for (const entry of this.items.values()) {
if (out.length >= max) break;
if (seenGroups.has(entry.msg.groupId)) continue;
seenGroups.add(entry.msg.groupId);
if (entry.visibleAt > now) continue;
entry.msg.receiveCount += 1;
entry.visibleAt = now + visibilitySec * 1000;
out.push({ ...entry.msg });
}
return out;
}
async changeVisibility(id: string, seconds: number): Promise<void> {
const entry = this.items.get(id);
if (entry) entry.visibleAt = Date.now() + seconds * 1000;
}
async ack(id: string): Promise<void> {
this.items.delete(id);
}
async deadLetter(msg: Message, reason: string): Promise<void> {
this.dlq.push({ id: msg.id, reason });
this.items.delete(msg.id);
}
}
function parseJob(body: string): Job | null {
try {
const job = JSON.parse(body);
return job && typeof job.docId === "string" ? (job as Job) : null;
} catch {
return null;
}
}
// In production `done` is a table with a unique key on docId, shared by all workers.
async function handle(queue: InMemoryQueue, done: Set<string>, msg: Message, render: Renderer): Promise<string> {
if (msg.receiveCount > MAX_RECEIVES) {
await queue.deadLetter(msg, `exceeded ${MAX_RECEIVES} receives`);
return "dead-lettered (receive limit)";
}
const job = parseJob(msg.body);
if (job === null) {
await queue.deadLetter(msg, "unparseable body");
return "dead-lettered (bad body)";
}
if (done.has(job.docId)) {
await queue.ack(msg.id);
return `skipped duplicate ${job.docId}`;
}
let lastExtend = Date.now();
const touch = async (): Promise<void> => {
if (Date.now() - lastExtend >= HEARTBEAT_SEC * 1000) {
await queue.changeVisibility(msg.id, VISIBILITY_SEC);
lastExtend = Date.now();
}
};
try {
await render(job, touch);
} catch (err) {
if (err instanceof PermanentError) {
await queue.deadLetter(msg, err.message);
return `dead-lettered: ${err.message}`;
}
const delay = Math.min(300, 5 * 2 ** msg.receiveCount);
await queue.changeVisibility(msg.id, delay);
return `retry in ${delay}s`;
}
done.add(job.docId);
await queue.ack(msg.id);
return `rendered ${job.kind} ${job.docId}`;
}
const render: Renderer = async (job, touch) => {
if (!SUPPORTED.has(job.currency)) throw new PermanentError(`unsupported currency ${job.currency}`);
for (let chunk = 0; chunk < 3; chunk++) {
// render 500 line items per chunk, then prove we are still alive
await touch();
}
};
async function main(): Promise<void> {
const queue = new InMemoryQueue();
queue.send({ kind: "invoice", docId: "inv-1001", accountId: "acct-1", currency: "EUR" });
queue.send({ kind: "credit_note", docId: "cn-1001", accountId: "acct-1", currency: "EUR" });
queue.send({ kind: "invoice", docId: "inv-1002", accountId: "acct-2", currency: "USD" });
queue.send({ kind: "invoice", docId: "inv-1003", accountId: "acct-3", currency: "XBT" });
queue.send({ kind: "invoice", docId: "inv-1004", accountId: "acct-2", currency: "USD" });
queue.send({ kind: "invoice", docId: "inv-1002", accountId: "acct-2", currency: "USD" });
const done = new Set<string>();
const workers = ["worker-a", "worker-b", "worker-c"];
for (let round = 1; round <= 3; round++) {
const claimed: [string, Message][] = [];
for (const w of workers) {
for (const msg of await queue.receive(2, VISIBILITY_SEC)) claimed.push([w, msg]);
}
for (const [w, msg] of claimed) {
console.log(`round ${round} ${w} ${msg.id}: ${await handle(queue, done, msg, render)}`);
}
}
console.log("DLQ:", queue.dlq);
}
main();import asyncio
import json
import time
from dataclasses import dataclass, replace
from typing import Awaitable, Callable
VISIBILITY_SEC = 60
HEARTBEAT_SEC = 20
MAX_RECEIVES = 5
SUPPORTED = {"EUR", "USD", "GBP"}
Touch = Callable[[], Awaitable[None]]
Renderer = Callable[[dict, Touch], Awaitable[None]]
class PermanentError(Exception):
pass
@dataclass
class Message:
id: str
group_id: str
body: str
receive_count: int = 0
@dataclass
class Entry:
msg: Message
visible_at: float = 0.0
class InMemoryQueue:
def __init__(self) -> None:
self._items: dict[str, Entry] = {}
self.dlq: list[tuple[str, str]] = []
self._seq = 0
def send(self, job: dict) -> None:
self._seq += 1
mid = f"m{self._seq}"
self._items[mid] = Entry(Message(mid, job["account_id"], json.dumps(job)))
async def receive(self, max_n: int, visibility_sec: int) -> list[Message]:
# FIFO per group: only the oldest message of each group is eligible,
# so a group is blocked while its head message is in flight.
now = time.monotonic()
seen: set[str] = set()
out: list[Message] = []
for entry in self._items.values():
if len(out) >= max_n:
break
if entry.msg.group_id in seen:
continue
seen.add(entry.msg.group_id)
if entry.visible_at > now:
continue
entry.msg.receive_count += 1
entry.visible_at = now + visibility_sec
out.append(replace(entry.msg))
return out
async def change_visibility(self, msg_id: str, seconds: float) -> None:
entry = self._items.get(msg_id)
if entry:
entry.visible_at = time.monotonic() + seconds
async def ack(self, msg_id: str) -> None:
self._items.pop(msg_id, None)
async def dead_letter(self, msg: Message, reason: str) -> None:
self.dlq.append((msg.id, reason))
self._items.pop(msg.id, None)
def parse_job(body: str) -> dict | None:
try:
job = json.loads(body)
except json.JSONDecodeError:
return None
return job if isinstance(job, dict) and isinstance(job.get("doc_id"), str) else None
# In production `done` is a table with a unique key on doc_id, shared by all workers.
async def handle(queue: InMemoryQueue, done: set[str], msg: Message, render: Renderer) -> str:
if msg.receive_count > MAX_RECEIVES:
await queue.dead_letter(msg, f"exceeded {MAX_RECEIVES} receives")
return "dead-lettered (receive limit)"
job = parse_job(msg.body)
if job is None:
await queue.dead_letter(msg, "unparseable body")
return "dead-lettered (bad body)"
if job["doc_id"] in done:
await queue.ack(msg.id)
return f"skipped duplicate {job['doc_id']}"
last_extend = time.monotonic()
async def touch() -> None:
nonlocal last_extend
if time.monotonic() - last_extend >= HEARTBEAT_SEC:
await queue.change_visibility(msg.id, VISIBILITY_SEC)
last_extend = time.monotonic()
try:
await render(job, touch)
except PermanentError as err:
await queue.dead_letter(msg, str(err))
return f"dead-lettered: {err}"
except Exception:
delay = min(300, 5 * 2 ** msg.receive_count)
await queue.change_visibility(msg.id, delay)
return f"retry in {delay}s"
done.add(job["doc_id"])
await queue.ack(msg.id)
return f"rendered {job['kind']} {job['doc_id']}"
async def render(job: dict, touch: Touch) -> None:
if job["currency"] not in SUPPORTED:
raise PermanentError(f"unsupported currency {job['currency']}")
for _chunk in range(3):
# render 500 line items per chunk, then prove we are still alive
await touch()
async def main() -> None:
queue = InMemoryQueue()
for job in [
{"kind": "invoice", "doc_id": "inv-1001", "account_id": "acct-1", "currency": "EUR"},
{"kind": "credit_note", "doc_id": "cn-1001", "account_id": "acct-1", "currency": "EUR"},
{"kind": "invoice", "doc_id": "inv-1002", "account_id": "acct-2", "currency": "USD"},
{"kind": "invoice", "doc_id": "inv-1003", "account_id": "acct-3", "currency": "XBT"},
{"kind": "invoice", "doc_id": "inv-1004", "account_id": "acct-2", "currency": "USD"},
{"kind": "invoice", "doc_id": "inv-1002", "account_id": "acct-2", "currency": "USD"},
]:
queue.send(job)
done: set[str] = set()
workers = ["worker-a", "worker-b", "worker-c"]
for rnd in range(1, 4):
claimed: list[tuple[str, Message]] = []
for w in workers:
for msg in await queue.receive(2, VISIBILITY_SEC):
claimed.append((w, msg))
for w, msg in claimed:
print(f"round {rnd} {w} {msg.id}: {await handle(queue, done, msg, render)}")
print("DLQ:", queue.dlq)
asyncio.run(main())<?php
declare(strict_types=1);
const VISIBILITY_SEC = 60;
const HEARTBEAT_SEC = 20;
const MAX_RECEIVES = 5;
const SUPPORTED = ['EUR', 'USD', 'GBP'];
final class PermanentError extends RuntimeException {}
final class Message
{
public function __construct(
public readonly string $id,
public readonly string $groupId,
public readonly string $body,
public int $receiveCount = 0,
) {}
}
final class InMemoryQueue
{
/** @var array<string, array{msg: Message, visibleAt: float}> */
private array $items = [];
/** @var list<array{string, string}> */
public array $dlq = [];
private int $seq = 0;
public function send(array $job): void
{
$id = 'm' . ++$this->seq;
$body = json_encode($job, JSON_THROW_ON_ERROR);
$this->items[$id] = ['msg' => new Message($id, $job['accountId'], $body), 'visibleAt' => 0.0];
}
// FIFO per group: only the oldest message of each group is eligible,
// so a group is blocked while its head message is in flight.
/** @return list<Message> */
public function receive(int $max, int $visibilitySec): array
{
$now = microtime(true);
$seen = [];
$out = [];
foreach (array_keys($this->items) as $id) {
if (count($out) >= $max) {
break;
}
$msg = $this->items[$id]['msg'];
if (isset($seen[$msg->groupId])) {
continue;
}
$seen[$msg->groupId] = true;
if ($this->items[$id]['visibleAt'] > $now) {
continue;
}
$msg->receiveCount++;
$this->items[$id]['visibleAt'] = $now + $visibilitySec;
$out[] = clone $msg;
}
return $out;
}
public function changeVisibility(string $id, float $seconds): void
{
if (isset($this->items[$id])) {
$this->items[$id]['visibleAt'] = microtime(true) + $seconds;
}
}
public function ack(string $id): void
{
unset($this->items[$id]);
}
public function deadLetter(Message $msg, string $reason): void
{
$this->dlq[] = [$msg->id, $reason];
unset($this->items[$msg->id]);
}
}
function parseJob(string $body): ?array
{
try {
$job = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException) {
return null;
}
return is_array($job) && is_string($job['docId'] ?? null) ? $job : null;
}
// In production $done is a table with a unique key on docId, shared by all workers.
function handle(InMemoryQueue $queue, array &$done, Message $msg, callable $render): string
{
if ($msg->receiveCount > MAX_RECEIVES) {
$queue->deadLetter($msg, 'exceeded ' . MAX_RECEIVES . ' receives');
return 'dead-lettered (receive limit)';
}
$job = parseJob($msg->body);
if ($job === null) {
$queue->deadLetter($msg, 'unparseable body');
return 'dead-lettered (bad body)';
}
if (isset($done[$job['docId']])) {
$queue->ack($msg->id);
return "skipped duplicate {$job['docId']}";
}
$lastExtend = microtime(true);
$touch = function () use ($queue, $msg, &$lastExtend): void {
if (microtime(true) - $lastExtend >= HEARTBEAT_SEC) {
$queue->changeVisibility($msg->id, VISIBILITY_SEC);
$lastExtend = microtime(true);
}
};
try {
$render($job, $touch);
} catch (PermanentError $e) {
$queue->deadLetter($msg, $e->getMessage());
return 'dead-lettered: ' . $e->getMessage();
} catch (Throwable) {
$delay = min(300, 5 * 2 ** $msg->receiveCount);
$queue->changeVisibility($msg->id, $delay);
return "retry in {$delay}s";
}
$done[$job['docId']] = true;
$queue->ack($msg->id);
return "rendered {$job['kind']} {$job['docId']}";
}
$render = function (array $job, callable $touch): void {
if (!in_array($job['currency'], SUPPORTED, true)) {
throw new PermanentError("unsupported currency {$job['currency']}");
}
for ($chunk = 0; $chunk < 3; $chunk++) {
// render 500 line items per chunk, then prove we are still alive
$touch();
}
};
$queue = new InMemoryQueue();
$queue->send(['kind' => 'invoice', 'docId' => 'inv-1001', 'accountId' => 'acct-1', 'currency' => 'EUR']);
$queue->send(['kind' => 'credit_note', 'docId' => 'cn-1001', 'accountId' => 'acct-1', 'currency' => 'EUR']);
$queue->send(['kind' => 'invoice', 'docId' => 'inv-1002', 'accountId' => 'acct-2', 'currency' => 'USD']);
$queue->send(['kind' => 'invoice', 'docId' => 'inv-1003', 'accountId' => 'acct-3', 'currency' => 'XBT']);
$queue->send(['kind' => 'invoice', 'docId' => 'inv-1004', 'accountId' => 'acct-2', 'currency' => 'USD']);
$queue->send(['kind' => 'invoice', 'docId' => 'inv-1002', 'accountId' => 'acct-2', 'currency' => 'USD']);
$done = [];
$workers = ['worker-a', 'worker-b', 'worker-c'];
for ($round = 1; $round <= 3; $round++) {
$claimed = [];
foreach ($workers as $w) {
foreach ($queue->receive(2, VISIBILITY_SEC) as $msg) {
$claimed[] = [$w, $msg];
}
}
foreach ($claimed as [$w, $msg]) {
$result = handle($queue, $done, $msg, $render);
echo "round {$round} {$w} {$msg->id}: {$result}" . PHP_EOL;
}
}
echo 'DLQ: ' . json_encode($queue->dlq) . PHP_EOL;When to use it
Situations where it pays off.
A backlog of independent jobs arrives faster than one process can drain it, as with 420,000 invoices in a 6-hour window.
Throughput scales with worker count until a downstream limit is reached, and you add or remove capacity by changing a replica count, not by changing code.
Jobs vary widely in duration, from 1 s for a two-line invoice to 110 s for an enterprise one.
Pull-based consumption balances load on its own. A worker stuck on a long job just stops asking, so nobody needs to predict job sizes or partition work in advance.
You need ordering only within an entity, such as an account, an order or a device, and not across the whole stream.
Message groups or partition keys keep per-entity order while different entities still spread across all workers. Global ordering would cap throughput at a single consumer.
Some messages will fail for reasons code cannot fix at runtime, such as bad reference data or schema drift from an older producer.
Competing consumers combined with a receive limit and a DLQ isolates those messages instead of letting them consume capacity on every retry.
How to implement it
Steps to introduce it in existing code.
Give every message a stable business id (docId) and a group key (accountId) at publish time. Retries and replays must carry the same id, or idempotency cannot work.
Set the visibility timeout to a short lease, 60 s here, and have workers extend it every 20 s during long work. Do not size the timeout to the worst-case job.
Create a shared done-store with a unique constraint on the business id. Check it before processing and record the id after success. Pass the same id as an idempotency key to any external side effect, such as email or payments.
Use message groups or key-based partitions for anything that must stay ordered. Publish dependent messages, like an invoice and then its credit note, in order from a single producer.
Classify errors. Dead-letter permanent ones immediately. Release transient ones with exponential backoff capped at 300 s. Dead-letter anything received more than 5 times.
Alarm on DLQ depth above 0 and on the age of the oldest message in the main queue. Build a redrive tool that replays per group, oldest first.
On SIGTERM, stop receiving, finish in-flight jobs within the shutdown grace period (90 s at Ledgerline), and set visibility to 0 for anything not started so another worker picks it up immediately.
Pros and cons
What you gain and what you pay.
Pros
- Throughput grows with replicas: going from 8 to 192 slots took Ledgerline's close from about 22 hours to under 1 hour with no code change to the rendering itself.
- Load balances by pull, so long and short jobs mix without manual partitioning or a coordinator.
- A crashed worker loses nothing: its leased messages reappear within one visibility timeout and another worker takes them.
- Workers are stateless and identical, so autoscaling on queue depth or oldest-message age is straightforward.
Cons
- Delivery is at-least-once. Every handler must be idempotent, which adds a shared store and an extra round trip per message.
- Ordering is limited to groups, and a slow or poisoned head message stalls its whole group until it succeeds or is dead-lettered.
- More workers shift the bottleneck downstream. 192 concurrent renders can exceed the email provider's send rate or the database's connection limit unless you cap concurrency.
- Retries, backoff, receive limits and DLQ redrive add moving parts that need dashboards and runbooks.
Trade-offs
Decisions you'll have to make, each with its price.
Message groups keyed by accountId instead of a standard unordered queue
You gainEach account's invoice is processed before its credit note, which removed the 312 rejected credit notes, while different accounts still run in parallel.
You payThroughput per account drops to one message at a time. An account with 9,000 invoices at 1.5 s each needs about 3.75 hours, which takes up most of the 6-hour window by itself.
60 s visibility with a 20 s heartbeat instead of a static 600 s timeout
You gainA crashed worker's messages come back within 60 s instead of 10 minutes, and long renders never expire while their worker is alive.
You payAbout 3 extra queue API calls per minute per in-flight message, roughly 576 calls per minute at 192 slots, plus code in the renderer that has to call touch between chunks.
maxReceiveCount of 5 instead of 2
You gainA message survives a short blip such as a 90 s email provider outage, given backoff delays of 10, 20, 40 and 80 s, without being dead-lettered.
You payA poison message that is misclassified as transient holds a slot 5 times and blocks its group for about 2.5 minutes before it moves to the DLQ.
Receiving in batches of up to 8 instead of 1
You gainUp to 8 times fewer receive calls and lower per-message latency on short jobs.
You payThe visibility clock starts at receive for all 8. Messages waiting behind a slow job in the same batch can expire unless the worker only receives as many messages as it has free slots.
Checking a shared done-store on every message
You gainDuplicate deliveries become harmless, and the duplicate-email incident cannot recur from a visibility expiry.
You payOne extra database read and one write per message, about 256 queries per second at peak, plus a table to prune, for example rows older than 90 days.
How it fails
What goes wrong in production and how to prevent it.
A worker pauses longer than the lease (a 70 s GC pause or a hung DNS lookup), the message reappears, and two workers render the same invoice.
What to doCheck processed_docs before rendering, insert the docId with a unique constraint after success, and pass docId as the email provider's idempotency key so the second send is dropped. Alert when the duplicate-skip count rises above its baseline.
A poison message sits at the head of an account's group and blocks every later document for that account.
What to doDead-letter permanent errors on the first attempt and anything received more than 5 times. Alarm on DLQ depth above 0 and on the oldest message age per group above 10 minutes, so on-call sees the blocked account before the 06:00 export.
The email provider is down for 20 minutes and every message burns its 5 receives, sending thousands of good invoices to the DLQ.
What to doPut a circuit breaker on the provider client. When the error rate exceeds 50% over 30 s, workers stop receiving instead of failing messages. Treat provider 5xx responses as transient, and redrive the DLQ in bulk once the provider recovers.
A redrive replays an old credit note after a newer invoice for the same account has already been processed, so state goes backwards.
What to doThe redrive tool sorts by original publish time within each account and re-publishes into the same group. Handlers compare a per-account sequence number and skip anything older than the last applied one.
An autoscaler scales from 24 to 6 replicas mid-close, killing workers in the middle of renders.
What to doOn SIGTERM, stop receiving, finish in-flight jobs within a 90 s grace period, and set visibility to 0 on anything not yet started so another worker picks it up immediately instead of waiting out the lease.
In a system design interview
When to bring it up and how to explain it.
Use it whenever a design has a queue with a backlog to drain: background jobs, notification fan-out, media or document processing, webhook delivery. Bring it up when the interviewer asks how you would scale the consumers, or what happens if a worker crashes mid-job.
What you could say
I'd put the render jobs on a queue and run N identical workers that compete for messages. That scales linearly until we hit a downstream limit: 24 workers with 8 slots each at 1.5 s per invoice gives about 128 per second, so 420,000 invoices clear in under an hour. Three things need explicit design. First, visibility: I'd use a 60 s lease and have workers extend it every 20 s, so long jobs don't get redelivered while their worker is alive, and a crashed worker's messages come back within a minute. Second, delivery is at-least-once, so every handler checks a done-store keyed by document id, and side effects like email carry that id as an idempotency key. Third, ordering: I'd only promise it per account, using the account id as the message group. Different accounts still run in parallel, and an invoice always lands before its credit note. For poison messages, I'd dead-letter permanent errors immediately and anything received more than 5 times, and alarm on DLQ depth above zero, because in a grouped queue a poison head blocks its whole account.
Likely follow-ups
What happens if a worker sends the email and then crashes before acking?
The message reappears after the lease runs out and another worker picks it up. The done-store doesn't have the docId yet, so it renders again. The email provider sees the same idempotency key and drops the second send. Without that key you'd get a duplicate email. That's why the dedupe has to reach the side effect, not stop at the database.
How would you handle one huge account that dominates the backlog?
Per-account grouping serializes it, so I'd check whether full per-account order is really needed. If only an invoice and its credit notes must stay ordered, I'd group by accountId plus billing entity or invoice id, which spreads the account across many groups. I'd also have the close job publish that account first so it starts at 00:00.
How do you choose the number of workers?
Work back from the deadline and the downstream limits. 420,000 jobs in a 4-hour target is about 30 per second, and 1.5 s per job means about 45 slots, so I'd allow 2 to 4 times that for headroom. Then I'd cap total concurrency at what the email provider and the database pool can absorb, and autoscale on the age of the oldest message, not on CPU.
Why not retry inside the worker instead of releasing the message?
In-process retries hold a slot while sleeping, and they disappear if the worker crashes. Releasing with a visibility delay frees the slot, survives crashes, and lets the queue count receives, which is what drives the poison cutoff. I'd only retry inside the worker for very short blips, such as a single 100 ms retry on a connection reset.
Relations with other guides
Patterns it's often confused or combined with.
- Queue-Based Load Leveling: Absorbing a Refund Burst
Load leveling puts a queue between the producer and the slow work. Competing consumers is how you drain that queue fast enough, by adding workers behind it.
- Idempotency Keys: Making Retried Writes Safe
At-least-once delivery means a docId can arrive twice. Idempotency keys in the done-store and on the email call turn duplicate deliveries into no-ops.
- Retry with Backoff: Exponential Delays, Jitter and Retry Budgets
Transient failures are released with exponential backoff through the visibility timeout, instead of being retried immediately in a tight loop inside the worker.
- Backpressure: Let Slow Consumers Slow Down Fast Producers
Workers pull only as many messages as they have free slots, so a slow downstream naturally slows consumption instead of piling up in-memory work.
- Circuit breaker: fail fast when a dependency is down
When the email provider is down, a breaker that pauses receiving stops every message from burning its 5 receives and flooding the DLQ.
- Sharding: Splitting Data Across Nodes by Key
Group keys and partition keys follow the same idea as sharding: route by entity so related work stays together while unrelated work spreads out.
Common questions
Short answers to the usual doubts.
Is competing consumers the same as publish-subscribe?
No. In competing consumers each message goes to exactly one of the workers. In publish-subscribe each subscriber gets its own copy. Ledgerline uses both: one subscription feeds invoice-render, which 24 workers compete on, and a separate subscription feeds an analytics consumer that sees every event.
Why not set the visibility timeout to 15 minutes and skip heartbeats?
Because the timeout is also your crash-recovery delay. With 15 minutes, a worker that dies takes its 8 in-flight invoices with it for 15 minutes before anyone retries. With a 60 s lease and a 20 s heartbeat, recovery takes at most a minute, and long jobs stay protected as long as the worker is alive.
Can I get exactly-once processing from the queue?
Not end to end. Some queues deduplicate on publish within a time window, but a worker can still crash after sending an email and before acking. Plan for at-least-once delivery, and make the effect exactly-once with a done-store and idempotency keys on side effects.
How do message groups differ from Kafka-style partitions?
Both keep order per key. Groups are scheduled dynamically: any free worker can take the next available group, and a blocked group affects only itself. Partitions are assigned to consumers, so a slow message stalls every key on that partition, and parallelism is capped by the partition count.
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