Skip to content

Queues and Messaging Interview Guide: Delivery, Ordering, Retries

Master the queue and messaging concepts interviewers probe: delivery guarantees, idempotency, acks, retries, DLQs, ordering, backpressure and the outbox pattern.

15 min read8 conceptsTechnical testsQueues and messaging

Questions about queues are rarely about a specific broker's API. They test whether you understand what happens when things fail: a consumer crashes halfway through a job, a message arrives twice, a partition gets hot, or the database commits but the publish does not. This guide covers the ideas behind strong answers. For each concept you get a short explanation, a TypeScript sketch you can run or adapt, and the traps that catch engineers in production. The examples are broker-neutral. Where behaviour differs between a classic queue such as RabbitMQ or SQS and a log such as Kafka, the guide says so. Work through the study order at the end. Delivery semantics and idempotency come first because almost every situational question reduces to them.

Study order

If time is short, go in this order.

  1. At-most-once, at-least-once and effectively-once

    Nearly every failure scenario question reduces to where the ack happens and what the guarantee covers.

  2. Idempotent consumers and deduplication

    At-least-once delivery is only safe with idempotent processing, and interviewers expect you to name how you dedupe atomically.

  3. Acknowledgements, leases and visibility timeouts

    Explains the mechanics behind redelivery and the common bug of duplicate work from short timeouts.

  4. Retries, backoff and dead-letter queues

    Shows you can handle poison messages and downstream outages without retry storms or silent data loss.

  5. The dual-write problem and the transactional outbox

    The standard answer to keeping a database and a broker consistent, asked often in system design rounds.

  6. Ordering guarantees and partition keys

    Tests whether you understand the trade-off between ordering and parallelism and how keys map to partitions.

  7. Backpressure, prefetch and consumer lag

    Covers operating queues under load: what to monitor, how to scale and where the real bottleneck sits.

  8. Point-to-point queues, pub/sub and logs

    Frames tool choice. Learn it last to tie the other concepts to a concrete broker model.

Point-to-point queues, pub/sub and logs

A point-to-point queue hands each message to exactly one of several competing consumers and removes it once acknowledged. It suits work distribution: rendering invoices, sending emails, resizing images. Pub/sub fans one message out to every subscriber, usually through a copy per subscription. A log, such as a Kafka topic, keeps messages for a retention period. Each consumer group tracks its own offset, so many groups read the same data independently and can rewind.

The practical difference is ownership of position. In a queue the broker tracks per-message state, which makes things like per-message delays and selective redelivery easy. In a log the consumer tracks a single offset per partition, which makes replay and new subscribers cheap but means one slow or broken message blocks everything behind it in that partition.

In an interview, pick the model from the requirement. Do you need replay, independent readers or event sourcing? Choose a log. Do you need a task queue with per-message retries, priorities or delays? Choose a queue. Many real systems use both: a log for domain events and a queue for jobs derived from them.

TypeScript

type Event = { offset: number; type: string; orderId: string };

class Log {
  private entries: Event[] = [];
  private committed = new Map<string, number>();

  append(type: string, orderId: string): number {
    const offset = this.entries.length;
    this.entries.push({ offset, type, orderId });
    return offset;
  }

  poll(group: string, max: number): Event[] {
    const from = this.committed.get(group) ?? 0;
    return this.entries.slice(from, from + max);
  }

  commit(group: string, nextOffset: number): void {
    this.committed.set(group, nextOffset);
  }
}

// Larkspur Pantry: billing and email both read order events
const log = new Log();
log.append("OrderPlaced", "ord-101");
log.append("OrderPlaced", "ord-102");

const batch = log.poll("billing", 10);
log.commit("billing", batch[batch.length - 1].offset + 1);

console.log(log.poll("billing", 10).length); // 0: billing is caught up
console.log(log.poll("email", 10).length);   // 2: email reads independently

log.commit("billing", 0);                    // rewind after a bug fix
console.log(log.poll("billing", 10).length); // 2: replay

A toy log: each consumer group owns an offset, so readers are independent and can replay.

Traps

  • Treating a log like a task queue: one message that always fails blocks its whole partition unless you move it aside to a retry or dead-letter topic.
  • Assuming retention is forever. If a consumer group falls behind beyond the retention window, the unread messages are deleted and its next fetch hits an out-of-range offset, handled by the configured offset reset policy.
  • Using pub/sub with no durable subscription and expecting subscribers that were offline to receive what they missed.

At-most-once, at-least-once and effectively-once

The guarantee you get depends on when the consumer acknowledges relative to doing the work. Ack before processing and a crash loses the message: at-most-once. Ack after processing and a crash causes redelivery, so the work may run twice: at-least-once. Most production systems choose at-least-once because losing a payment or an order is worse than handling a duplicate.

Exactly-once delivery across a network is not achievable in general, because the sender cannot tell a lost message from a lost acknowledgement. What you can build is effectively-once processing: at-least-once delivery combined with an idempotent consumer, or a transaction that covers both the side effect and the consumed position. Kafka transactions give this only when the input, the output and the offsets all live in Kafka. They do not cover a call to an external payment API.

When an interviewer says exactly-once, answer with where the boundary of the guarantee sits and what happens to side effects outside it.

TypeScript

interface Message { id: string; body: string }
interface Broker { ack(id: string): Promise<void> }
type Handler = (m: Message) => Promise<void>;

// At-most-once: a crash between the two lines loses the message
export async function atMostOnce(b: Broker, m: Message, handle: Handler) {
  await b.ack(m.id);
  await handle(m);
}

// At-least-once: a crash between the two lines redelivers it
export async function atLeastOnce(b: Broker, m: Message, handle: Handler) {
  await handle(m);
  await b.ack(m.id);
}

The only difference is the order of two lines, and it decides whether failures lose or duplicate work.

Traps

  • Claiming a broker setting gives end-to-end exactly-once when the consumer writes to a database or calls an HTTP API outside the broker's transaction.
  • Auto-commit modes that acknowledge on receipt or on a timer silently turn at-least-once into at-most-once if processing happens later on another thread.
  • Forgetting the producer side: a publish retried after a timeout can create a duplicate even if the consumer is perfect.

Idempotent consumers and deduplication

Since at-least-once delivery will hand you duplicates, the consumer must make repeated processing harmless. There are two approaches. Make the operation naturally idempotent, for example set status = 'shipped' instead of increment counter. Or record a deduplication key, usually the message id or a business key, and skip messages you have already applied.

The dedup record must be written atomically with the side effect. If you mark the message processed in Redis and then update the database, a crash between the two leaves them inconsistent. In practice you insert into a processed_messages table with a unique constraint inside the same database transaction as the business change, and treat a constraint violation as a duplicate.

For side effects you do not control, such as a payment provider, pass an idempotency key to the provider so it deduplicates on its side. Derive the key from the message, not from a random value generated per attempt.

TypeScript

type PayoutRequested = { messageId: string; employeeId: string; amountCents: number };

// Tallyho Payroll ledger. In production this is one DB transaction
// with a UNIQUE constraint on processed_messages.message_id.
class Ledger {
  private processed = new Set<string>();
  private balances = new Map<string, number>();

  apply(evt: PayoutRequested): "applied" | "duplicate" {
    if (this.processed.has(evt.messageId)) return "duplicate";
    const current = this.balances.get(evt.employeeId) ?? 0;
    this.balances.set(evt.employeeId, current + evt.amountCents);
    this.processed.add(evt.messageId);
    return "applied";
  }

  balance(employeeId: string): number {
    return this.balances.get(employeeId) ?? 0;
  }
}

const ledger = new Ledger();
const evt = { messageId: "pay-7731", employeeId: "emp-42", amountCents: 125000 };
console.log(ledger.apply(evt)); // applied
console.log(ledger.apply(evt)); // duplicate, e.g. after a redelivery
console.log(ledger.balance("emp-42")); // 125000

The dedup check and the balance change must succeed or fail together.

Traps

  • Generating the idempotency key at consume time, so each redelivery gets a fresh key and deduplication never triggers.
  • Keeping dedup keys in a store with a shorter TTL than the maximum redelivery or replay window.
  • Check-then-act without a lock or unique constraint: two consumers receiving the same message concurrently both pass the check.
  • Assuming the broker's dedup feature, such as a short dedup window on a FIFO queue, protects you from duplicates produced hours later by a replay.

Acknowledgements, leases and visibility timeouts

When a consumer receives a message, the broker does not delete it. It either marks it unacknowledged on that connection, as RabbitMQ does, or hides it for a visibility timeout, as SQS does. If the consumer acks or deletes it, it is gone. If the connection drops or the timeout expires, the message becomes available again for another consumer.

The timeout must exceed your realistic processing time. Suppose Brightwater Utilities renders PDF invoices with a 30 second visibility timeout, but large accounts take 90 seconds. Every large invoice reappears while still being rendered, a second worker picks it up, and customers get two invoices. The fix is to extend the lease with a heartbeat while work is in progress, or to set a timeout based on the slowest job you accept.

Explicit negative acknowledgement, or setting visibility to zero, lets a consumer give a message back immediately instead of waiting for the timeout. Use it when you know you cannot process the message right now.

TypeScript

interface QueueClient {
  extendVisibility(receiptHandle: string, seconds: number): Promise<void>;
  deleteMessage(receiptHandle: string): Promise<void>;
}

export async function processWithHeartbeat(
  q: QueueClient,
  receiptHandle: string,
  work: () => Promise<void>,
): Promise<void> {
  const timeoutSec = 30;
  const timer = setInterval(() => {
    q.extendVisibility(receiptHandle, timeoutSec)
      .catch(err => console.error("lease extension failed", err));
  }, (timeoutSec / 3) * 1000);

  try {
    await work();
    await q.deleteMessage(receiptHandle); // ack only after success
  } finally {
    clearInterval(timer); // on failure, no delete: message reappears later
  }
}

Extend the lease every third of the timeout so one missed heartbeat does not release the message.

Traps

  • Setting the visibility timeout from average processing time instead of the slow tail, which produces duplicate work under load.
  • Heartbeats that keep running after the worker is stuck, holding a message hostage forever. Cap the total extension time.
  • Prefetching many messages per consumer with a short timeout: messages time out while waiting in the local buffer before processing even starts.
  • Acking on a different channel or connection than the one that received the message, which brokers such as RabbitMQ reject.

Retries, backoff and dead-letter queues

Failures split into transient ones, such as timeouts, 503s and lock contention, and permanent ones, such as invalid payloads or a currency code that does not exist. Retry transient failures with exponential backoff and jitter so a downstream outage does not turn into a synchronized retry storm. Send permanent failures, and anything that exhausts its retry budget, to a dead-letter queue.

A message that fails forever is called a poison message. Without a limit it is redelivered endlessly, burning capacity and, in a log, blocking its partition. Brokers count delivery attempts, for example SQS's maxReceiveCount or RabbitMQ's dead-letter exchanges, and move the message aside after N attempts.

A DLQ is only useful if someone watches it. Alert on its depth, keep the original headers and error reason, and have a tool to inspect, fix and redrive messages back to the main queue once the bug is fixed.

TypeScript

class PermanentError extends Error {}

const MAX_ATTEMPTS = 5;
const BASE_MS = 500;
const CAP_MS = 60_000;

function backoffMs(attempt: number): number {
  const ceiling = Math.min(CAP_MS, BASE_MS * 2 ** (attempt - 1));
  return Math.floor(Math.random() * ceiling); // full jitter
}

type Decision =
  | { action: "ack" }
  | { action: "retry"; delayMs: number }
  | { action: "dead-letter"; reason: string };

function decide(err: Error | null, attempt: number): Decision {
  if (err === null) return { action: "ack" };
  if (err instanceof PermanentError) return { action: "dead-letter", reason: err.message };
  if (attempt >= MAX_ATTEMPTS) {
    return { action: "dead-letter", reason: `gave up after ${attempt} attempts: ${err.message}` };
  }
  return { action: "retry", delayMs: backoffMs(attempt) };
}

console.log(decide(new Error("503 from tax service"), 2));
console.log(decide(new PermanentError("unknown currency XQZ"), 1));
console.log(decide(new Error("timeout"), 5));

Classify the error, then retry with jittered backoff or dead-letter it.

Traps

  • Retrying inside the consumer with sleeps while holding the message lease, which blocks throughput and can trigger a visibility timeout mid-retry.
  • Retrying permanent errors such as validation failures, which only delays the inevitable and hides the bug.
  • Retry topics in a log-based system break per-key ordering: later events for the same key can be processed before the retried one.
  • No alert on DLQ depth, so failed orders sit there for weeks.

Ordering guarantees and partition keys

Global ordering and parallelism are at odds. Brokers give you ordering within a partition or message group, never across the whole topic once you scale out. You choose a partition key so that messages that must stay in order share a partition. For Quayside Bank, keying account events by account id keeps AccountOpened, Deposit and Withdrawal for acc-9001 in sequence while different accounts are processed in parallel.

The number of partitions caps consumer parallelism in a consumer group: with 12 partitions, a 13th consumer sits idle. Within one partition, the consumer must also process in order. If it hands messages to a thread pool, ordering is lost unless it routes by key to a fixed worker.

Plain competing-consumer queues give no ordering at all once there is more than one consumer or any redelivery. If you need it there, use FIFO queues with message group ids, or design consumers to tolerate reordering with version numbers or timestamps and discard stale updates.

TypeScript

function partitionFor(key: string, partitions: number): number {
  let h = 0;
  for (const ch of key) h = (h * 31 + ch.charCodeAt(0)) >>> 0;
  return h % partitions;
}

const events = [
  { account: "acc-9001", type: "AccountOpened" },
  { account: "acc-3150", type: "AccountOpened" },
  { account: "acc-9001", type: "Deposit" },
  { account: "acc-9001", type: "Withdrawal" },
];

const partitions = new Map<number, string[]>();
for (const e of events) {
  const p = partitionFor(e.account, 6);
  partitions.set(p, [...(partitions.get(p) ?? []), `${e.account}:${e.type}`]);
}
console.log(partitions); // all acc-9001 events land in one partition, in order

Same key, same partition, same order. Different keys spread across partitions.

Traps

  • Hot keys: one huge tenant keyed by tenant id overloads a single partition while others idle.
  • Adding partitions changes the key-to-partition mapping, so events for one key can be split across old and new partitions during the transition.
  • Producer retries with several in-flight requests can reorder messages unless the producer is idempotent or limited to one in-flight request.
  • Assuming ordering survives a DLQ redrive or a retry topic.

Backpressure, prefetch and consumer lag

A queue absorbs bursts, but only if consumers eventually catch up. The signals to watch are queue depth and, more usefully, the age of the oldest message, or consumer lag in a log: the latest offset minus the committed offset per partition. Age tells you directly how stale processing is. Depth alone can look fine for small messages and terrible for a harmless backlog of tiny ones.

Backpressure means consumers take only what they can handle. Limit prefetch, the number of unacked messages a broker pushes to a consumer, and bound concurrency inside the consumer. Fernhill Labs sends SMS through a provider that allows 50 requests per second. Scaling to 40 consumers would just multiply 429 errors. The real limit is downstream capacity, not consumer count.

Autoscale consumers on lag or oldest-message age, cap the scale at what the downstream and the partition count allow, and decide upfront what happens when lag keeps growing: shed low-priority work, degrade, or alert.

TypeScript

async function runPool<T>(
  items: AsyncIterable<T>,
  concurrency: number,
  handle: (item: T) => Promise<void>,
): Promise<void> {
  const inFlight = new Set<Promise<void>>();
  for await (const item of items) {
    const p: Promise<void> = handle(item)
      .catch(err => console.error("failed", err))
      .finally(() => inFlight.delete(p));
    inFlight.add(p);
    if (inFlight.size >= concurrency) await Promise.race(inFlight);
  }
  await Promise.all(inFlight);
}

async function* fakeQueue(n: number) {
  for (let i = 0; i < n; i++) yield `sms-${i}`;
}

const sleep = (ms: number) => new Promise<void>(r => setTimeout(r, ms));

runPool(fakeQueue(20), 4, async id => {
  await sleep(100);
  console.log("sent", id);
});

The consumer stops pulling when four messages are in flight, so it never takes more than it can process.

Traps

  • Unbounded prefetch: one consumer grabs thousands of messages, others starve, and a crash returns them all at once.
  • Scaling consumers beyond the partition count in a log-based system, which adds cost but no throughput.
  • Alerting on depth instead of oldest-message age or lag, which misses a backlog that is small but hours old.
  • Scaling consumers without checking the downstream database or API, moving the bottleneck and causing cascading failures.

The dual-write problem and the transactional outbox

A service that writes to its database and then publishes an event performs two writes with no shared transaction. If the commit succeeds and the publish fails, other services never hear about the order. If you publish first and the commit fails, they react to an order that does not exist. Wrapping both in a try/catch does not fix this, because the process can die between the two calls.

The outbox pattern makes the event part of the same database transaction: insert the business row and an outbox row together. A separate relay reads unpublished outbox rows, publishes them and marks them sent. Alternatively, change data capture tails the database's transaction log and publishes outbox rows, avoiding polling.

The relay is itself at-least-once: it can publish and then crash before marking the row. So consumers still need idempotency, which is why the outbox and the idempotent consumer, sometimes implemented as an inbox table, usually appear together.

TypeScript

interface Tx {
  query<R = unknown>(sql: string, params: unknown[]): Promise<{ rows: R[] }>;
}
interface Db { transaction<T>(fn: (tx: Tx) => Promise<T>): Promise<T> }
interface Publisher { publish(topic: string, key: string, payload: string): Promise<void> }
type OutboxRow = { id: number; aggregate_id: string; topic: string; payload: string };

export async function placeOrder(db: Db, orderId: string, totalCents: number) {
  await db.transaction(async tx => {
    await tx.query(
      "INSERT INTO orders (id, total_cents, status) VALUES ($1, $2, 'placed')",
      [orderId, totalCents]);
    await tx.query(
      "INSERT INTO outbox (aggregate_id, topic, payload) VALUES ($1, $2, $3)",
      [orderId, "orders.placed", JSON.stringify({ orderId, totalCents })]);
  });
}

export async function relayOnce(db: Db, pub: Publisher, batch = 100) {
  await db.transaction(async tx => {
    const { rows } = await tx.query<OutboxRow>(
      "SELECT id, aggregate_id, topic, payload FROM outbox " +
      "WHERE published_at IS NULL ORDER BY id LIMIT $1 FOR UPDATE SKIP LOCKED",
      [batch]);
    for (const r of rows) {
      await pub.publish(r.topic, r.aggregate_id, r.payload);
      await tx.query("UPDATE outbox SET published_at = now() WHERE id = $1", [r.id]);
    }
  });
}

The order and its event commit atomically. The relay publishes later and may publish twice.

Traps

  • Running several relays with SKIP LOCKED and assuming per-order ordering still holds: two relays can publish events for the same aggregate out of sequence.
  • Letting the outbox table grow forever. Delete or archive published rows on a schedule.
  • Calling the broker inside the business transaction to save a step, which brings the dual-write problem back and holds database locks during network calls.
  • Forgetting that the relay delivers at-least-once, so consumers without idempotency will double-process.

Common questions

Short answers to the usual doubts.

Should I say exactly-once is impossible in an interview?

Say that exactly-once delivery over an unreliable network is not achievable in general, then explain what is: effectively-once processing through at-least-once delivery plus idempotent consumers, or broker transactions when input, output and offsets all live in the same system. Naming the boundary of the guarantee is what earns credit.

When should I pick Kafka over RabbitMQ or SQS?

Pick a log like Kafka when you need replay, many independent consumer groups, high throughput with per-key ordering, or long retention. Pick a queue like RabbitMQ or SQS for task distribution where you want per-message retries, delays, priorities or simple routing, and where replaying history is not a requirement.

How do I explain a growing backlog during an incident?

Start from the metrics: oldest-message age or lag per partition, consumer error rate and processing latency. Then separate causes: a poison message blocking a partition, a slow downstream dependency, too few consumers, or a hot key. Each has a different fix, and scaling consumers only helps the third.

Is a database table a reasonable queue?

For modest volume, yes. A table with FOR UPDATE SKIP LOCKED gives transactional enqueueing with your business data and simple operations. It becomes a problem at high throughput because of row churn, vacuum or index bloat and polling load, which is when a dedicated broker pays off.

What belongs in a message, the full data or just an id?

Sending the full state makes consumers independent of the producer's database and safe to replay, at the cost of larger messages and schema evolution work. Sending only an id keeps messages small but forces consumers to call back, which couples availability and may read a newer state than the event describes. Many teams send the state relevant to the event plus a version number.

Now, practise it

Put it to work straight away.

Tests, exercises and problems that use what you've just read.

Next guide3 of 4 · Distributed systemsConcurrency and Race Conditions: Interview Guide for EngineersRead the next one