Skip to content
Tech Interview Prep
Technical interview guide

Message Queues & Async Processing

Decoupling a slow or unreliable step from the request path by handing it to a queue and processing it separately.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v7
Editorial status
Reviewed

Scope: Vendor-neutral distributed-systems principles; current AWS architecture guidance.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-17

What is the difference between an event and a command, and why does it matter?

Answer

A command instructs a specific consumer to do something: SendWelcomeEmail. It has one intended handler, it expresses the producer's intention about what should happen, and the producer knows who will act on it.

An event states that something happened: UserRegistered. It has no intended handler, it is a fact, and the producer need not know or care who is listening.

The difference matters most for coupling. A producer emitting commands must know what should happen, so adding 'also create a trial subscription' means changing the producer. A producer emitting events does not: a new consumer subscribes and the producer is untouched. That is the property that makes event-driven architectures extensible, and it is the main reason to prefer events at boundaries between teams or services.

It also matters for naming and evolution. Events are past tense and immutable facts: OrderPlaced was true when emitted and remains true. Commands are imperative and may become inappropriate: a ChargeCard command sitting in a queue for an hour may no longer be right if the order was cancelled meanwhile. Events do not have that problem, because a fact does not expire.

And for replay. Replaying events reconstructs what happened, which is coherent. Replaying commands re-executes intentions that may no longer be appropriate, which is not, and that is a real difference when you need to reprocess history after a bug.

Commands are still legitimate. Task distribution is genuinely command-shaped: 'resize this image' has one handler and is an instruction, and pretending it is an event by calling it ImageUploaded when only one consumer will ever act on it adds indirection without benefit.

The failure I would look for is an event that is really a command in disguise: OrderPlaced published to a queue with exactly one consumer that must handle it, with the producer depending on that consumer's behaviour. That has the coupling of a command and the indirection of an event, and being honest about which it is makes the design clearer.

The practical guidance: commands within a bounded context, events across boundaries. Inside a service, instructing is fine and simpler. Between services, events keep them independently evolvable, which is usually why they were separated at all.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-1

Explain what a message queue gives you and what it costs.

Answer

A queue is a durable buffer plus an acknowledgement protocol. Everything else (the decoupling, the duplicate handling, the operational burden) falls out of those two pieces.

What it buys. Time decoupling: the producer doesn't need the consumer running. SQS holds an unconsumed message 4 days by default, 14 max. Load leveling: a burst lands in the buffer and drains at the consumer's rate. Failure isolation: a consumer crash delays work instead of losing it, as long as the ack hasn't gone out.

What it costs. The caller's operation is no longer atomic with the work. The HTTP 200 leaves before the email is sent, so the caller can't report the outcome and errors surface where the user isn't looking. Three consequences:

  • Delivery is at-least-once. SQS standard queues redeliver after a crash between processing and delete; Kafka consumers with enable.auto.commit=true (the default, auto.commit.interval.ms=5000) redeliver after a crash between processing and commit. Consumers must be idempotent.
  • You now own a stateful component: its retention, its dead-letter queue, its lag.
  • A request's story spans two systems and two log streams.

Worked arithmetic: burst absorption. Producer spikes to 5,000 msg/s for 10 s: 50,000 messages. Consumer sustains 500 msg/s. Backlog peaks at 50,000 − (500 × 10) = 45,000 messages and the queue empties at t = 50,000 / 500 = 100 s. At 2 KB per message that's ~90 MB of backlog: nothing for the broker, but the final message is handled at t = 100 s, 90 s after it was produced. If a user is waiting on that message, the queue didn't absorb the spike, it converted it into 90 s of latency.

Worked trace: the duplicate window. SQS visibility timeout defaults to 30 s.

  1. t=0: consumer A receives the message; ApproximateNumberOfMessagesNotVisible goes to 1.
  2. t=0–45 s: A does the work; it takes 45 s.
  3. t=30 s: the visibility timeout expires and the message becomes visible again.
  4. t=30 s: consumer B receives the same message and starts the same work.
  5. t=45 s: A finishes and deletes the message. B's delete is a no-op, but B already charged the card.

Two workers, one message, one duplicate side effect. Detect it with ApproximateNumberOfMessagesNotVisible staying above zero longer than p99 processing time, or duplicate rows in the consumer's output. Fix it by setting the visibility timeout above p99 processing time, or calling ChangeMessageVisibility on a heartbeat.

Idempotency, concretely. Key on a business ID, not the message ID:

Python
# Python 3.12, boto3 1.35
def handle(msg):
    body = json.loads(msg["Body"])
    key = body["order_id"]              # stable across redeliveries
    if not db.claim(key):               # INSERT ... ON CONFLICT DO NOTHING
        return                          # already handled: ack and move on
    charge(body)

The claim and the charge can't share a transaction when charge is an external call, so a crash between them loses the charge. Either give the claim a status column and sweep for stuck rows, or pass an idempotency key to the payment provider.

Alternatives. SQS FIFO gives exactly-once processing inside a 5-minute deduplication window, at 300 TPS per queue per API action without batching: a real throughput ceiling. Kafka with acks=all, min.insync.replicas=2 and a replication factor of 3 survives one broker loss but still delivers at-least-once unless you add transactions, and those only cover Kafka-to-Kafka.

When not to use one. If the caller needs the result (login, price quote, payment authorization) a queue turns a fast failure into a slow, invisible one. Use it for genuinely asynchronous work: email, thumbnails, report generation, webhook fan-out.

The first question I'd ask is not which broker but what the user sees between enqueue and completion. If nobody has designed that, the queue moved the problem somewhere less visible.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Compare a queue broker with a log-based system like Kafka.

Answer

Core answer. The difference is what a message is, and every other difference follows from it.

A queue broker (RabbitMQ, SQS) treats a message as a unit of work. The broker delivers it to one consumer, the consumer acks it, the broker deletes it. Delivery state lives in the broker: per-message ack/nack, redelivery, visibility timeout. SQS's visibility timeout defaults to 30 s (max 12 h) and message retention defaults to 4 days (max 14): the message is gone once it is done.

A log (Kafka) treats a record as an entry in an append-only log retained independently of reads. Nothing is deleted on ack; log.retention.ms defaults to 604800000 (7 days) and cleanup.policy defaults to delete. The consumer owns a position, an offset per partition, and can move it. That is replayability, and it is the property a queue structurally cannot offer: reprocess history after a bug fix, add a consumer group that catches up from offset 0, rebuild a derived store.

Queue brokerLog (Kafka)
Unitmessage = unit of workrecord = log entry
Removaldeleted on ackretention policy, not ack
Positionbroker tracks per-message deliveryconsumer tracks offset per partition
Redeliverybasic.nack/requeue; SQS visibility timeoutseek() to any offset, any range
Orderingper queue (FIFO queues: per message group)per partition only
Parallelismadd consumers; RabbitMQ basic.qos prefetch_count default 0 = unlimitedbounded by partition count
Fan-outexchange copies to N queues, one consumer eachN consumer groups read the same log independently

Worked trace: parallelism ceiling. Topic orders, 3 partitions, group billing. With 2 consumers the assignment is 2/1. Scale to 5 and 3 consumers hold one partition each while 2 sit idle: max useful parallelism is 3. Going wider means repartitioning, and partition count can only increase: raising 3 to 12 rehashes key % partitions, so records for one key land on a different partition and per-key ordering is lost across the change.

Worked trace: offset commit. With enable.auto.commit=true (the default) and auto.commit.interval.ms=5000, the client commits the offset of the last poll, not the last record processed. Poll returns offsets 100–599; the consumer processes 300 of them and dies. The commit at t=5 s already recorded 600, so the unprocessed tail is skipped: silent loss. Commit manually after processing instead and you get at-least-once: a crash between processing and commit replays the batch, so duplicates. Exactly-once needs a transactional producer (transactional.id) plus isolation.level=read_committed, or an idempotent consumer keyed on a business ID.

Failure modes. max.poll.interval.ms defaults to 300000 (5 min); a batch that takes longer evicts the consumer from the group, triggers a rebalance, and the batch is reprocessed elsewhere: duplicates. On the queue side, a consumer that acks before doing the work loses the message on crash; one that never acks and holds prefetch_count=0 can pull an unbounded backlog into memory. RabbitMQ's replicated option is quorum queues (Raft, since 3.8); classic mirrored queues were removed in RabbitMQ 4.0. RabbitMQ Streams (3.9+) is the log-shaped structure inside RabbitMQ if you want replay without running Kafka.

Selection heuristic. Is this work to be done, or an event that happened? Work has one owner and is finished once done: queue. Events may interest several consumers, now and later, and their history has value: log. The practical tell is someone asking "could we also do X when Y happens?" If that keeps recurring, a stream several groups subscribe to independently is the shape you want; a queue per consumer becomes unwieldy.

Third option. A database table is legitimate at moderate throughput. Its advantage, enqueue transactionally with your business data, is one neither broker gives you without an outbox pattern, and that is a real simplification worth weighing against its throughput ceiling.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How do partitions, partition keys, and consumer groups decide which consumer processes a given message, and what happens to in-flight work when the group rebalances?

Answer

Core mechanism (Kafka). A topic is divided into partitions, each an ordered log. When a producer sends a message with a key, the default partitioner computes murmur2(key) % numPartitions to pick a partition. Without a key, it round-robins or uses a sticky partitioner. Consumers that share a group.id form a consumer group. The group coordinator assigns each partition to exactly one consumer in the group. So the path is: key → partition → consumer. If you have 12 partitions and 4 consumers, each consumer gets 3 partitions. A message with key user-42 always lands on the same partition, and that partition is owned by one consumer, so all messages for that key are processed in order by that consumer.

Rebalance. When a consumer joins, leaves, or crashes, or when partitions are added, the group rebalances. In the classic eager protocol, all consumers stop consuming, revoke their partitions, and the coordinator reassigns. This is a stop-the-world pause. With the cooperative sticky assignor (Kafka 2.4+), consumers only revoke partitions that need to move, so most continue processing. During rebalance, in-flight work: offsets are committed after processing. If a consumer dies mid-batch, the partition is reassigned to another consumer, which resumes from the last committed offset. Messages processed but not committed are reprocessed: at-least-once duplicates. If using auto-commit, the window is larger. Also, a consumer that takes too long between polls can be kicked out (max.poll.interval.ms, default 5 minutes), triggering a rebalance and duplicate work.

Alternatives. SQS FIFO uses a message group ID instead of a partition key. Messages with the same group ID are delivered in order to one consumer at a time. There is no partition assignment to consumers; multiple consumers poll the queue, but SQS ensures only one consumer processes a group at a time. Visibility timeout (default 30s) acts like a lease: if the consumer doesn't delete the message in time, it becomes visible again and another consumer can process it. Duplicates. RabbitMQ has no partitions; a queue's messages are distributed round-robin to competing consumers, so ordering is not guaranteed across consumers.

Failure modes. Hot keys: one key gets most traffic, so one partition and one consumer become the bottleneck. Rebalance storms: frequent consumer restarts cause repeated pauses and duplicate processing. Stuck consumer: a long-running task exceeds max.poll.interval.ms, gets evicted, and its partitions are reassigned, causing duplicates. Detection: monitor consumer lag per partition, rebalance rate, and duplicate processing rate.

SystemPartitioning unitOrdering guaranteeRebalance effect
KafkaPartition (key hash)Per partitionEager: stop-the-world; cooperative: minimal pause; uncommitted work reprocessed
SQS FIFOMessage group IDPer groupNo rebalance; visibility timeout causes redelivery
RabbitMQNone (queue)None across consumersNo rebalance; competing consumers

Trace. Consumer A owns partition 3, processing offset 100-110, commits offset 100. A crashes. Coordinator reassigns partition 3 to consumer B. B starts at offset 101, reprocessing 101-110. If processing is not idempotent, duplicates cause double charges.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

What is fan-out and what problems does it introduce?

Answer

Fan-out is one event delivered to N independent consumers, each receiving its own copy. The producer publishes once and holds no list of who consumes it. Register a user, and the same user.registered event goes to the welcome-email sender, the analytics writer, the trial-subscription creator and the CRM sync: four copies, four independent lifecycles.

The property that makes it worth doing is decoupling: adding a fifth consumer is a subscription, not a producer change.

The mechanism matters more than the word. The unit that receives a copy has to be per-consumer:

BrokerUnit that gets a copyUnit that splits workOrdering
Kafkaconsumer group (group.id)consumers inside one group, one partition eachper partition only
SNSsubscription (typically one SQS queue each)none: every subscription gets every messagenone; SQS standard is at-least-once
RabbitMQqueue bound to a fanout exchangecompeting consumers on one queueper queue
Pub/Subsubscriptionsubscribers within a subscriptionnone

Get this wrong and it fails quietly: several consumers sharing one queue or group compete for messages instead of each getting all of them. With 6 partitions and one group, 12 consumers means 6 sit idle and each message goes to exactly one of the other 6.

Trace it. Two groups on one topic:

kafka-topics.sh --bootstrap-server localhost:9092 --create \
  --topic orders --partitions 6 --replication-factor 3

kafka-console-consumer.sh --bootstrap-server localhost:9092 \
  --topic orders --group email --from-beginning
kafka-console-consumer.sh --bootstrap-server localhost:9092 \
  --topic orders --group analytics --from-beginning

kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group email

Illustrative output: the numbers are made up, the shape is what the tool prints:

GROUP  TOPIC   PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG  CONSUMER-ID
email  orders  0          1042            1042            0    email-1
email  orders  1          998             1042            44   email-1
email  orders  2          1042            1042            0    email-1
email  orders  3          1042            1042            0    email-2
email  orders  4          1042            1042            0    email-2
email  orders  5          1042            1042            0    email-2

Both groups read all 6 partitions. The analytics group has its own offsets and its own lag; the email group falling 44 behind on partition 1 does not slow analytics at all. That independence is the whole point, and the source of every problem below.

Partial failure. Email commits, CRM crashes. No rollback spans them. Detect it per group: Kafka records-lag-max (JMX) or the LAG column above; on SQS, ApproximateNumberOfMessagesVisible and ApproximateAgeOfOldestMessage in CloudWatch. A rising oldest-age with flat throughput is a stuck consumer, not a spike.

Duplicates. Delivery is at-least-once. Kafka's enable.auto.commit defaults to true with auto.commit.interval.ms 5000, so a crash between processing and committing replays the batch. SQS standard queues are at-least-once; FIFO queues deduplicate within a 5-minute window. Consumers have to be idempotent.

Ordering. Kafka orders within a partition, not across them. Six partitions means the email can land before the analytics row. If one consumer's output feeds another, they are not independent.

Debugging. One event, several outcomes, several places to look. A correlation ID stamped by the producer and carried in the event header is what lets you join the four consumer logs into one story.

No completion signal. The producer cannot know when everything has happened. If something must, that is a saga or an orchestrator, not fan-out.

Amplification. One event, eight consumers, each making three downstream calls, is 24 calls per event. At 2,000 events/s that is 48,000 calls/s downstream, and a 3× event spike is a 3× spike on every one of them.

Judgement: fan-out fits genuinely independent reactions to a fact. If one consumer must precede another, or the outcome depends on all of them succeeding, the coupling is real: events make it invisible rather than removing it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Explain delivery guarantees and why broker-level exactly-once does not automatically cover external side effects.

Answer

The 60-second answer. The three guarantees are defined by when the consumer acknowledges, not by what the broker promises. At-most-once acks before processing (a crash loses the message). At-least-once acks after processing (a crash before the ack causes redelivery). Exactly-once means the effect happens once, and a broker can only deliver that for effects inside its own transaction boundary. Kafka's transactions make the output record and the offset commit atomic; they say nothing about your UPDATE accounts. So the consumer owns idempotency, and once it has it, at-least-once is sufficient.

GuaranteeAck timingFailure modeWhere you meet it
At-most-oncebefore processingcrash loses the messagemetric samples, best-effort logs
At-least-onceafter processingcrash before ack → redeliveryKafka, SQS, RabbitMQ, Pulsar defaults
Exactly-onceinside one transactionnone, but only within that boundaryKafka transactions, Flink two-phase-commit sinks

Why the window is unavoidable. The consumer does two things: perform the effect, and record that it did. Without a shared transaction these are separate operations, so there is always an instant where one has happened and the other has not. The ack is itself an operation that can fail after the work succeeded, and it can be lost in transit: the broker cannot distinguish "not processed" from "processed but I did not hear". That is the two-generals problem, and no retry policy removes it.

What exactly-once actually buys. Kafka's transactional producer, checked against Kafka 3.6:

Java
props.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "orders-enricher-1");
props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, "true"); // default since 3.0
producer.initTransactions();
while (true) {
  var records = consumer.poll(Duration.ofMillis(500));
  producer.beginTransaction();
  for (var r : records) producer.send(new ProducerRecord<>("orders.enriched", r.key(), enrich(r.value())));
  producer.sendOffsetsToTransaction(currentOffsets(records), consumer.groupMetadata());
  producer.commitTransaction(); // output records and offsets land together, or neither
}

Consumers must set isolation.level=read_committed (default is read_uncommitted) or they will read records from aborted transactions. The guarantee is bounded: the producer's dedupe window is capped by transaction.timeout.ms (default 60000 ms), and a producer restart gets a new producer ID, so dedupe does not survive it. And the moment enrich() writes to Postgres or calls a payment API, that work is outside the transaction. Kafka Streams' processing.guarantee=exactly_once_v2 and Flink's two-phase-commit sinks have the same shape: exactly-once within the boundary, which is why Flink requires a transactional sink and a replayable source.

The consumer-side fix. A stable key from the producer plus a conditional write, with the effect and the record in one local transaction:

SQL
CREATE TABLE processed_messages (
  consumer_group text NOT NULL,
  message_id     text NOT NULL,
  processed_at   timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (consumer_group, message_id)
);

BEGIN;
INSERT INTO processed_messages (consumer_group, message_id)
VALUES ('billing', 'evt-7f3a') ON CONFLICT DO NOTHING;   -- 0 rows ⇒ duplicate
UPDATE accounts SET balance = balance - 2500 WHERE id = 'acct-91';  -- hypothetical amount
COMMIT;

Trace it. First delivery: the insert affects 1 row, the debit runs, the transaction commits, then the offset is committed. A rebalance follows, the consumer exceeded max.poll.interval.ms (default 300000 ms), and the broker redelivers evt-7f3a. Second attempt: ON CONFLICT DO NOTHING affects 0 rows, so the debit is skipped and the offset is committed. The account is debited once. Set enable.auto.commit=false and commit after the transaction, or the offset can advance past work that never committed.

Failure modes to name. A key built from a timestamp or a fresh UUID (evt-7f3a-1717171717) makes every retry look new and defeats the whole mechanism: the key must identify the operation, not the attempt. Committing the offset before the effect transaction reopens the window. For effects you cannot enlist in a transaction, an external API, write an intent row, call the API with an idempotency key, then mark it done; or use the outbox pattern, writing the business row and an outbox row in one local transaction and letting CDC (Debezium) publish from the WAL.

Scale of the problem. Hypothetically, 2M events/day at a 0.05% redelivery rate is 1000 duplicates/day; at a $25 double debit each, that is $25k/day. Idempotency is not a workaround for a broker deficiency: it is the correct design given the physics, and it is why at-least-once plus an idempotent consumer is the answer in practice.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Walk me through every point where a message can be lost between producer and consumer, and explain how each stage is made durable.

Answer

There are four places a message disappears, and the rule at each one is the same: it is lost wherever you stopped waiting for a confirmation.

StageWhat loses itWhat makes it durable
Producer → brokerfire-and-forget send; acks=1; publish with no confirmacks=all + min.insync.replicas=2 + RF=3 (Kafka); publisher confirms + durable queue + persistent messages (RabbitMQ); the SendMessage response (SQS)
Broker at restnon-durable queue, transient messages, unclean leader election, retention expiryreplication or quorum commit; unclean.leader.election.enable=false; retention longer than the longest consumer outage you will tolerate
Broker → consumerautoAck=true; Kafka auto-commit before processingmanual ack/commit after the side effect commits; visibility timeout above p99 handler time
Consumer side effectacking before the DB transaction commitscommit the write, then ack

Producer. Kafka's acks=all means the leader waited for every in-sync replica: it does not mean the record hit disk. Durability comes from replication, not fsync. With RF=3 and min.insync.replicas=2, a write is acked once two of three replicas hold it, so losing one broker does not lose acked data. With acks=1 the leader acks before replication; kill it in that window and the write is gone even though the producer saw success. The window is replication latency: single-digit milliseconds on a healthy cluster, which is exactly why it survives testing and shows up in an incident. Since Kafka 3.0 the producer defaults are acks=all and enable.idempotence=true; older clients, and anyone who set acks=1 for throughput, are the ones at risk. delivery.timeout.ms bounds retries so a failure surfaces instead of hanging.

The producer's own buffer is the stage people forget: records sitting in the accumulator when the process dies are gone, and a send() future nobody checks is fire-and-forget. That is the dual-write boundary, and the outbox pattern is what closes it.

Broker. SQS stores copies of your messages on multiple servers for redundancy, so you get AZ-level durability for free, but retention is a real loss point: default 4 days, maximum 14. A consumer down for five days loses everything queued, silently. No error, the messages simply are not there. Alarm on ApproximateAgeOfOldestMessage approaching retention. In Kafka, unclean.leader.election.enable=true lets a lagging replica become leader and truncate committed data; leave it false.

Consumer. Kafka's enable.auto.commit=true commits every 5 seconds whether or not you processed anything: crash in between and those offsets are skipped. Set it false and commit after handling. SQS has no offsets: the message reappears after the visibility timeout (default 30 seconds), so delete it only after the work is done, and set the timeout above your p99 handler time. A timeout that fires mid-processing gives you a duplicate, not a loss, unless the handler deleted at the start.

The side effect. Ack after the commit, never before. Ack first and a crash loses the message with the work undone. Ack after and a crash between the two gives a duplicate, which is why the end-to-end guarantee is at-least-once plus an idempotent consumer, not exactly-once.

Detection. Loss is invisible by default; you find it by comparing counts. Producer record-error-rate and outbox rows with no published marker catch stage one. Offset gaps and consumer lag catch stage two. A consumed-count versus side-effect-count reconciliation catches stages three and four. A DLQ does not lose messages but it does hide them: a DLQ with no alarm on its depth is a graveyard.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Explain the dual-write problem and how the outbox pattern solves it.

Answer

A database write and a message publish are two systems with no shared transaction. Whichever you do first, there is a window where one lands and the other does not. Publish first and a rollback leaves consumers acting on an order that never existed. Commit first and a crash before publishing leaves an order nobody downstream knows about. No ordering of the two is safe: that is a property of writing to two systems, not a bug you avoid by being careful.

The outbox pattern removes the second system from the critical path. The business change and a row describing the message go into the same local transaction, so they commit or roll back together. A separate publisher reads unpublished rows, publishes them, and marks them sent. Two-system atomicity becomes one-system atomicity plus a retry loop.

SQL
CREATE TABLE outbox (
  id           bigserial PRIMARY KEY,
  aggregate_id text        NOT NULL,
  event_type   text        NOT NULL,
  payload      jsonb       NOT NULL,
  created_at   timestamptz NOT NULL DEFAULT now(),
  published_at timestamptz
);

-- partial index: only unpublished rows are indexed, so the poller's
-- index scan stays small even after the table has held billions of rows
CREATE INDEX outbox_unpublished ON outbox (id) WHERE published_at IS NULL;
Python
while True:
    with db.transaction():
        rows = db.query("""
            SELECT id, aggregate_id, payload FROM outbox
            WHERE published_at IS NULL
            ORDER BY id LIMIT 500
            FOR UPDATE SKIP LOCKED          -- Postgres 9.5+
        """)
        for r in rows:
            broker.publish(r.aggregate_id, r.payload)   # blocks on broker ack
            db.execute("UPDATE outbox SET published_at = now() WHERE id = %s", r.id)
    time.sleep(0.1)

Trace the two crash windows for order 42, committed at t0 with its outbox row:

teventoutbox row 42brokerconsumer
t0COMMIT (order + outbox row)unpublished——
t1poller takes row 42, FOR UPDATElocked——
t2publish returns, broker ackslockedhas event—
t3process dies before UPDATEunpublished, lock releasedhas event—
t4restart, poller takes row 42 againlockedhas event againsees duplicate
t5UPDATE published_atpublished—dedupes on event_id

Crash between t0 and t1 instead: the row is simply unpublished, the next poll picks it up, nothing is lost. So the pattern is at-least-once, and the only new obligation is consumer idempotency, which a broker delivering at-least-once already imposes. Note the ordering in the loop: publish, then mark. Mark first and a crash between the two loses the message permanently.

Operational details that decide whether this holds up:

  • Latency. A 100 ms poll interval with a 500-row batch adds roughly 100 ms median to event publication. If that is too slow, poll on a LISTEN/NOTIFY signal instead of a timer.
  • Table growth. At 500 events/s a 200-byte row is ~43M rows and ~8.6 GB per day. Delete or archive published rows on a schedule, or the partial index stops helping.
  • Lock hold time. The transaction above stays open across the broker round trip, so row locks are held for the network call. Keep batches small, or publish in one transaction and mark in a second: accepting more duplicates in exchange for shorter locks.
  • Ordering. SKIP LOCKED with several publishers gives you no per-key order. If consumers need it, partition the outbox by aggregate_id and run one publisher per partition.

Change data capture is the alternative: tail the database's replication log (Postgres logical decoding, MySQL binlog) and emit events from the committed changes. No polling, no application code, and it captures every change including ones written by other services. The costs are a replication slot to monitor, coupling to the log format, and that it captures row changes rather than intentions: the event shape is the table shape, so a column rename becomes a breaking API change.

Default to the outbox: the events are designed, the failure modes are local, and the only infrastructure is a table you already have. Reach for CDC when the polling load is real or when you need coverage of writes your service does not make.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

How would you make a consumer idempotent?

Answer

Idempotent means processing the same message twice produces the same end state. There are three approaches, and which fits depends on what the work does.

Natural idempotency. If the operation is a set rather than a change ('set status to shipped', 'store this document') repeating it is already harmless. Where the operation can be expressed this way, that is the cheapest answer and needs no bookkeeping at all.

Conditional write. An upsert keyed on a stable identifier from the producer: INSERT ... ON CONFLICT (external_id) DO NOTHING, or an update guarded by a version so an older message cannot overwrite a newer state. The database's unique constraint does the deduplication atomically, which is what makes it correct under concurrency.

A processed-messages table. Record the message identifier, and check it before processing. The essential detail is that the check, the work and the record must be in one transaction: otherwise two concurrent deliveries both check, both find nothing, and both process. That is check-then-act, and it is a race that will pass every sequential test.

The key itself matters as much as the mechanism. It must identify the operation, not the delivery. If the producer supplies a stable identifier, use it. If not, derive one deterministically from the payload's meaningful fields, and specifically exclude timestamps and generated identifiers, which change between attempts.

Two details often missed. The processed-messages table needs a retention policy, or it grows forever; a TTL sized to comfortably exceed the maximum redelivery window is usually right. And side effects must be inside the idempotency boundary, if the consumer sends an email, deduplication must cover that too, otherwise the database write is idempotent and the customer gets three emails.

That last one is the failure I would look for in review, because the deduplication usually protects the part that was easy to protect.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

How do you handle message ordering requirements?

Answer

What I'd say first. Ordering is a per-key property, not a global one, and it costs throughput. So the first move is to find the smallest unit that must be ordered (almost always an entity ID, not the whole stream) and then decide whether I need ordered delivery at all, or only ordered effect.

Ordering and parallelism are opposed. Every mechanism buys ordering by serialising the ordered unit: Kafka orders within a partition, SQS FIFO within a MessageGroupId. Ordering everything means one consumer, which caps throughput at a single core. Partitioning by entity gives the ordering that matters and keeps parallelism across entities. The partition key is the whole design.

Then make consumers order-insensitive anyway, because ordered delivery does not give ordered processing. A retry reorders: the failed message, redelivered after backoff, lands behind messages that were already processed. A version guard on the consumer tolerates that.

MechanismOrdering unitThroughput capWhere reorder sneaks in
Kafka partitionpartition, by offsetone consumer per partitionproducer retries when max.in.flight.requests.per.connection > 1 without idempotence; consumer-side concurrency inside a poll batch
SQS FIFOMessageGroupIdone in-flight message per group; 300 TPS per API action per queue, 3,000 with 10-message batchesvisibility timeout (default 30 s) expiring while a later message is processed
Single global consumerwhole streamone corenone, but you pay for it

Kafka's idempotent producer (enable.idempotence=true, default since 3.0) preserves order with up to 5 in-flight requests, so the producer side is usually safe on a current client. The consumer side is where people break it: max.poll.records defaults to 500, and handing that batch to a thread pool reorders within it.

Version guard, with a trace. Python 3.12; store.get returns version 0 for an unseen key.

Python
def apply(event, store):
    cur = store.get(event["account_id"])          # version, 0 if absent
    if event["version"] <= cur:
        return "stale, dropped"                    # duplicate or reordered
    if event["version"] > cur + 1:
        return "gap, park"                         # predecessor missing
    store.put(event["account_id"], event["version"], event["payload"])
    return "applied"

Delivery order for account A is v1, v3, v2: v2 was retried after a backoff.

deliveryversioncheckactionstored
1v11 > 0+1? noapply1
2v33 > 1+1? yespark1
3v22 > 1+1? noapply2
4drain v33 > 2+1? noapply3

All three applied in order v1, v2, v3 despite the delivery order. The parked set needs a bound: cap it and alert, or a permanently missing v2 grows it without limit.

Failure modes I'd name. A hot partition key: 12 partitions, one account at 60% of traffic, and that partition's consumer does 60% of the work while 11 sit idle. The ordering guarantee and the load distribution come from the same key and can conflict. Lag arithmetic: a partition at 5,000 msg/s against a consumer doing 2,000 msg/s grows 3,000/s, so 180,000 messages of lag in a minute (example figures). And SQS FIFO's 5-minute dedup window means a redelivery after that window is a new message, not a duplicate.

When order genuinely cannot be relaxed, a state machine with illegal transitions, the options are an ordered partition, or a consumer that detects the gap and waits or fetches what it missed. The second keeps throughput but adds a timeout policy for gaps that never fill.

So: establish the true granularity, partition by it, make consumers tolerant anyway, and check the key distributes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design the failure handling for a message consumer.

Answer

Clarify first, then answer. Two things decide the design: is the failure transient or permanent, and is the handler idempotent? If it isn't idempotent, retry is unsafe and making it so is the first job: a dedupe key on the message ID, or an upsert instead of an insert. Everything below assumes at-least-once delivery, which is what SQS, Kafka and RabbitMQ all give you.

Classify before you retry. Retrying a permanent failure burns capacity and delays real work.

FailureExampleAction
transienttimeout, 503, connection reset, 429 throttlingretry with backoff
permanent400, schema validation, missing referenced entitydead-letter immediately, no retry
poisondeserialisation error, handler bug on one payloaddead-letter after the cap

Retry with exponential backoff and full jitter. Immediate retries hit a dependency when it is least able to take load; synchronised retries across consumers produce a thundering herd that prevents recovery. Full jitter, sleeping uniform(0, min(cap, base * 2**attempt)), is what decorrelates them.

Python
# Python 3.12
import random, time

TRANSIENT = (TimeoutError, ConnectionResetError)

def backoff(attempt, base=0.5, cap=30.0):
    return random.uniform(0, min(cap, base * 2 ** attempt))

def handle(msg, process, max_receives=5):
    for attempt in range(max_receives):
        try:
            process(msg)
            return "ack"
        except TRANSIENT:
            if attempt == max_receives - 1:
                return "dead-letter"
            time.sleep(backoff(attempt))
        except Exception:
            return "dead-letter"      # permanent: no retry
    return "dead-letter"

Trace it with a handler that always raises TimeoutError:

attemptoutcomesleep, uniform in
0TimeoutError[0, 0.5)
1TimeoutError[0, 1.0)
2TimeoutError[0, 2.0)
3TimeoutError[0, 4.0)
4TimeoutError, last attemptnone → dead-letter

Four sleeps, five receives. Worst-case wall clock 0.5+1+2+4 = 7.5 s, expected 3.75 s. That is the number that matters operationally: the visibility timeout must exceed it, or the message becomes visible mid-retry and a second consumer starts the same work. SQS's default visibility timeout is 30 s, which covers 7.5 s comfortably; raise the cap and you raise the timeout with it, or call ChangeMessageVisibility as a heartbeat.

Bound the attempts, then dead-letter. On SQS that is maxReceiveCount in the redrive policy: set it to 5 to match the loop. It counts receives, not in-process attempts, so the two must agree. On Kafka there is no DLQ: consume, and on failure produce to a retry topic with a delay, then after N hops to a .DLT topic. Watch max.poll.interval.ms (default 300000 ms), if processing plus backoff exceeds it the consumer is evicted and the partition rebalances, a retry storm you did not ask for. On RabbitMQ quorum queues, set x-delivery-limit explicitly and route to a dead-letter exchange; the x-death header then carries the count and reason for free.

The DLQ needs an operational contract, and this is where most implementations stop too early:

  • Alarm on depth. CloudWatch ApproximateNumberOfMessagesVisible on the DLQ, threshold ≥ 1 for 5 minutes. Any arrival is worth knowing about; a step change means a systemic problem, not a bad message.
  • Retention long enough to triage. SQS defaults to 4 days; set the DLQ to 14 (the max) so evidence does not expire over a weekend.
  • Failure metadata on the message. SQS has no headers, so wrap the payload: {"original": ..., "attempts": 5, "last_error": "TimeoutError", "first_seen": "..."}. Without the reason, triage is guesswork.
  • A replay path. Once the bug is fixed, re-drive the DLQ back to the source queue rather than hand-recreating messages.

An unmonitored DLQ is a silent data-loss mechanism.

Circuit-break on a failing dependency. If a downstream service is down, every message fails and dead-letters, turning a 10-minute outage into a large backlog of dead work. Track a rolling failure rate; above a threshold, stop consuming and let messages accumulate in the queue. They are durable there and process when the dependency recovers.

Make partial failures safe. If the handler writes to two stores, a crash between them leaves a state a retry must repair: the idempotency requirement again. Order the writes so the retryable one is last, or wrap both in a transaction where you have one.

Test the failure paths deliberately. They run rarely and break quietly. Inject a permanent error, a transient error and a crash mid-handler in staging, and confirm each lands where you expect.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

What is a poison message and how do you handle one?

Answer

A poison message is one that fails every time it is processed: malformed content, a reference to a deleted row, an unhandled edge case, or a bug triggered by a specific payload. The single failure is not the problem. The problem is what the queue does next.

Without containment, the broker redelivers it forever. In an ordered queue (SQS FIFO message group, RabbitMQ single active consumer, Kafka partition) it is worse: the message must be processed before anything behind it, so one poison message blocks its entire group or partition. A malformed record for one account stops all processing for that account.

Containment is a receive counter plus a dead-letter queue. After a bounded number of attempts the message is moved aside and the queue continues. The settings differ by broker:

BrokerReceive counterDead-letter mechanismDefault / recommended
RabbitMQ quorum queuex-delivery-limitx-dead-letter-exchange + x-dead-letter-routing-keydefault 20; x-death header records reason and count
SQS standard/FIFOmaxReceiveCount in RedrivePolicyDLQ ARN in RedrivePolicyAWS recommends 3–5; DLQ retention max 14 days
Kafkanone nativeretry topic + DLQ topicmax.poll.interval.ms 300000, max.poll.records 500
DB-backedattempts columnstate='failed' or separate tableset max_attempts per job type

A database-backed queue makes the mechanism explicit. Postgres 9.5+ (or MySQL 8.0+) with FOR UPDATE SKIP LOCKED:

SQL
CREATE TABLE jobs (
  id           bigserial PRIMARY KEY,
  payload      jsonb NOT NULL,
  attempts     int NOT NULL DEFAULT 0,
  max_attempts int NOT NULL DEFAULT 5,
  state        text NOT NULL DEFAULT 'ready',  -- ready | failed
  last_error   text,
  visible_at   timestamptz NOT NULL DEFAULT now()
);

-- claim one job
UPDATE jobs
SET attempts = attempts + 1,
    visible_at = now() + interval '30 seconds'
WHERE id = (
  SELECT id FROM jobs
  WHERE state = 'ready' AND visible_at <= now()
  ORDER BY id
  FOR UPDATE SKIP LOCKED
  LIMIT 1
)
RETURNING id, payload, attempts;

-- on failure
UPDATE jobs
SET state = CASE WHEN attempts >= max_attempts THEN 'failed' ELSE 'ready' END,
    last_error = $2
WHERE id = $1;

Trace: row id=1, payload {"acct":"42","amount":"abc"}, attempts=0, max_attempts=5, state='ready'. Worker claims it: attempts becomes 1, visible_at is pushed 30 s out. Processing fails with invalid input syntax for type numeric: "abc"; last_error is set. attempts(1) < max_attempts(5), so state stays 'ready'. After 30 s it is visible again. The cycle repeats. On the fifth claim attempts=5; the failure update sets state='failed' because 5 >= 5. SELECT count(*) FROM jobs WHERE state='failed' returns 1. If the worker crashes after claiming, attempts is already incremented and visible_at is pushed out: the job is retried after 30 s with one attempt consumed. That is the at-least-once trade-off.

Detection: alarm on DLQ depth. SQS: CloudWatch ApproximateNumberOfMessagesVisible on the DLQ, alarm when > 0 for one datapoint. RabbitMQ: rabbitmq_queue_messages_ready on the DLQ. Kafka: consumer lag on the DLQ topic via kafka-consumer-groups.sh --describe --group dlq-monitor. DB: SELECT count(*) FROM jobs WHERE state='failed'. A single arrival is usually a data problem; a sudden rise is systemic: a deployment introducing a bug, or a schema change consumers cannot handle.

Diagnosis needs the failure reason recorded with the message. RabbitMQ's x-death header carries reason (rejected, expired, maxlen), count, queue, exchange, routing-keys, time. SQS has no native metadata; write to a side table or use message attributes. Kafka: produce to the DLQ topic with headers x-original-topic, x-original-partition, x-original-offset, x-exception. DB: the last_error column.

Resolution depends on cause. SQS has StartMessageMoveTask to move messages from a DLQ back to the source queue, and ListMessageMoveTasks to check status. RabbitMQ: the shovel plugin or rabbitmqadmin to move messages. Kafka: a consumer that reads the DLQ topic and produces back to the original topic. DB: UPDATE jobs SET state='ready', attempts=0 WHERE state='failed' AND id = .... A replay path must exist; manually re-creating messages is error-prone and often impossible.

Prevention: validate at the boundary. Kafka with Confluent Schema Registry and auto.register.schemas=false rejects malformed records at the producer. SQS: validate a JSON schema before processing. RabbitMQ: validate in the consumer before the expensive work. A malformed message is dead-lettered immediately rather than after five expensive retries, and the failure reason is precise rather than a stack trace from deep in the logic.

Finally, check that a message failing on a transient dependency outage is not misclassified as poison. Use a separate retry queue with exponential backoff and a longer maxReceiveCount, or distinguish by error type. Otherwise a database outage dead-letters a large volume of perfectly good messages: a bigger problem than the poison message this mechanism exists for.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

How would you handle a consumer that needs to call an unreliable external service?

Answer

What a strong candidate says first. Two questions decide the design: is the call on the critical path of the message's effect, and is the failure transient or sustained? Then the shape is fixed: timeout every call, retry only transient failures with backoff and jitter, put a circuit breaker in front of the client, and when the breaker opens, pause the consumer rather than draining the queue into a dead-letter topic. Make the call idempotent at the boundary so a retry after a timeout can't double-charge.

The client. Resilience4j 2.x, wrapping the HTTP call:

Java
TimeLimiterConfig timeLimiter = TimeLimiterConfig.custom()
        .timeoutDuration(Duration.ofSeconds(2))
        .build();

RetryConfig retry = RetryConfig.custom()
        .maxAttempts(3)
        .intervalFunction(IntervalFunction.ofExponentialRandomBackoff(
                Duration.ofMillis(200), 2.0, 0.5))   // 200ms, x2, +/-50% jitter
        .retryExceptions(IOException.class, TimeoutException.class)
        .ignoreExceptions(HttpClientErrorException.class) // Spring's 4xx: permanent
        .build();

CircuitBreakerConfig breaker = CircuitBreakerConfig.custom()
        .slidingWindowType(SlidingWindowType.COUNT_BASED)
        .slidingWindowSize(20)
        .minimumNumberOfCalls(10)
        .failureRateThreshold(50)                     // % -> OPEN
        .waitDurationInOpenState(Duration.ofSeconds(30))
        .permittedNumberOfCallsInHalfOpenState(3)
        .build();

And the Kafka consumer loop, Java client:

Java
if (breaker.getState() == CircuitBreaker.State.OPEN) {
    consumer.pause(consumer.assignment());  // stop fetching; offsets stay put
    Thread.sleep(1_000);
    continue;
}
consumer.resume(consumer.assignment());

Why pausing beats dead-lettering. Consumer at 500 msg/s, dependency down 5 minutes, 3 attempts per message, no breaker: 150,000 messages x 3 = 450,000 outbound calls, all failing, all dead-lettered. Replaying 150,000 DLQ messages by hand is the incident. With the breaker above it opens after 10 failures inside the 20-call window, so ~10 calls are wasted, then the consumer pauses; the 150,000 messages sit in the topic and drain when the dependency returns.

The poll-interval trap. Timeout 2s, backoff 200ms then 400ms, so a fully failing message costs 2 + 0.2 + 2 + 0.4 + 2 = 6.6s. Kafka's max.poll.records defaults to 500; processed on one thread that batch takes 500 x 6.6s ~ 55 minutes. max.poll.interval.ms defaults to 300000 (5 min), so the broker evicts the consumer, the group rebalances, and the same 500 messages are reprocessed forever. Fix: cap max.poll.records (50 is plenty) or hand the batch to a worker pool and keep polling on the main thread.

Failure modes and what detects them.

FailureDetectionResponse
Dependency hangsread timeout at 2sretry with jitter; breaker counts it
Sustained 5xxfailure rate > 50% over 20 callsbreaker OPEN, pause consumer
Bad message (400)ignoreExceptionsno retry; DLQ immediately
Throttling (429)status code / Retry-Aftertoken bucket or concurrency cap, not retries
Timeout after successduplicate effect downstreamIdempotency-Key header

Idempotency and throttling. A timeout is ambiguous: the call may have succeeded and the response been lost. Stripe's Idempotency-Key header makes the retry safe and Stripe retains keys for 24 hours; if the dependency has no such mechanism, you must tolerate duplicates or read-before-write. For throttling, a Guava RateLimiter or a Resilience4j BulkheadConfig.maxConcurrentCalls cap is the right lever: retrying a 429 makes it worse.

Isolation. One consumer handling several dependencies should use separate queues per dependency, so a dead payment provider doesn't consume the capacity needed for email. Alert on breaker state and queue depth together: "queue backing up" and "payment provider down" are one incident, and joining them is most of the response time.

When not to. If the call is on the critical path of a synchronous user request, a queue doesn't help: you need a fallback response or a degraded mode. If messages are worthless after 60 seconds, retries and a breaker only delay the drop; discard and alert instead.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Explain how you would scale message consumers.

Answer

The 90-second answer. Before adding consumers, find out what they are waiting on. If the handler is CPU-bound, more consumers help until you hit the partition cap. If it is blocked on a downstream call, the common case, more consumers multiply load on the thing that is already the constraint, and the queue existed to protect that thing. So measure three numbers first: consumer CPU, downstream p99, and consumer lag (or queue age). Then pick a lever, because "more consumers" is only one of five and often not the best one.

The hard ceiling in a partitioned log. In Kafka a partition is assigned to exactly one consumer in a group. A topic with 12 partitions supports 12 active consumers; the 13th sits idle. You can raise the count with kafka-topics.sh --alter --partitions, but you cannot lower it, and the default partitioner maps a key as murmur2(key) % numPartitions, so every key can land on a different partition after the change. Per-key ordering breaks across the transition. Treat partition count as a capacity decision made up front, not a knob you turn during an incident.

SQS standard has no such cap. SQS FIFO defaults to 300 msg/s per queue, 3,000 with batches of 10, and ordering is per MessageGroupId, so parallelism is bounded by the number of distinct group IDs, not by consumer count. High-throughput FIFO mode raises the per-group limit, but the group is still the unit of ordering.

Worked trace: the rebalance storm. Topic orders, 12 partitions, group order-processor, defaults max.poll.records=500 and max.poll.interval.ms=300000. Each record makes a synchronous pricing call at 700 ms p50.

  1. poll() returns 500 records. Processing them takes 500 × 0.7 s = 350 s.
  2. Heartbeats run on a separate thread (KIP-62), so session.timeout.ms=45000 does not save you: the broker still sees a live member.
  3. The coordinator evicts the consumer at 300 s for exceeding max.poll.interval.ms, and triggers a rebalance.
  4. Offsets were never committed, so all 500 records are redelivered to another consumer, which repeats the cycle. Net progress: zero. Duplicate pricing calls: 500 per cycle.

Fix: max.poll.records=50 → 50 × 0.7 s = 35 s per poll, comfortably inside the interval. Or keep the batch large and move the call off the poll loop with pause()/resume(). Raising max.poll.interval.ms only delays the storm.

Python
from confluent_kafka import Consumer

c = Consumer({
    "bootstrap.servers": "broker:9092",
    "group.id": "order-processor",
    "enable.auto.commit": False,
    "max.poll.interval.ms": 300000,        # coordinator evicts you past this
    "max.poll.records": 50,                # 50 x 0.7s = 35s per poll
    "partition.assignment.strategy": "cooperative-sticky",  # no stop-the-world rebalance
})

Levers, ranked by how often they beat adding consumers.

LeverWins whenConstraint
Bigger batchesPer-message overhead dominates; bulk DB writesBatch must finish inside the visibility timeout (SQS default 30 s, max 12 h) or max.poll.interval.ms
Faster handlerA slow query, an N+1, a serialization costNeeds profiling, not guessing
In-consumer concurrencyI/O-bound work, partition cap already reachedOffset commit and ordering get harder; commit only the contiguous prefix
Remove the dependencyEvery message triggers a downstream callCache or batch the calls; may delete the bottleneck outright
More consumersCPU-bound handler, partitions > consumersCapped by partitions (log) or group IDs (FIFO)

Autoscale on lag, not CPU. Consumers blocked on I/O show low CPU while the backlog grows, so CPU-based scaling does nothing. Scale on Kafka consumer lag or SQS ApproximateNumberOfMessagesVisible divided by in-flight capacity per instance: target tracking on backlog-per-instance, or KEDA. And watch the downstream the whole time: scaling consumers is one of the fastest ways to take down a dependency that was coping, which is the exact failure the queue was built to prevent.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Explain backpressure and how you would apply it.

Answer

What a strong candidate says first

Backpressure is a consumer telling a producer to slow down, and the producer obeying. The signal has to travel upstream and change the producer's rate. If it only changes what the consumer does with work already accepted, that's buffering or shedding, not backpressure.

Two things I'd clarify before designing: is the producer something I control (an internal service) or something I don't (a browser, a partner's API)? And is the work droppable, or must every item be processed? Those answers pick the mechanism.

Assumptions I'll state: internal producer, at-least-once delivery, work is not droppable, and the bottleneck is a downstream database that cannot be scaled out.

The mechanism

Every backpressure scheme is a bounded buffer plus a rule for what happens when it's full. The bound is what makes the signal possible: an unbounded buffer never says "full", so the producer never learns.

Java's Executors.newFixedThreadPool(n) is the classic trap: a fixed thread count paired with an unbounded LinkedBlockingQueue, so under sustained overload the queue grows until the heap dies. The explicit form:

Java
// Java 21
var pool = new ThreadPoolExecutor(
    8, 8, 0L, TimeUnit.MILLISECONDS,
    new ArrayBlockingQueue<>(200),              // bound: 200 queued tasks
    new ThreadPoolExecutor.CallerRunsPolicy()); // full -> caller runs it

Trace: 8 workers busy, 200 tasks queued. The 209th execute() finds the queue full and the pool saturated, so CallerRunsPolicy runs the task on the submitting thread. If that thread is the HTTP request handler, the request now blocks for the task's duration: the producer is physically slowed. That is backpressure. Caveat: CallerRunsPolicy checks isShutdown() and silently discards the task if the pool is shutting down, so it is not a delivery guarantee.

Arithmetic

Arrivals 1,000 msg/s, consumers drain 800 msg/s. Backlog grows at 200 msg/s; after 10 minutes that's 120,000 messages. Drain time at full capacity: 120,000 / 800 = 150 s. With a 10,000-message bound, worst-case queueing delay is 10,000 / 800 = 12.5 s: that's the number to put in the SLO, because it's the latency a message accumulates before it is even started.

Choosing the rule

MechanismSignalAt the limitFails when
Block / caller-runsThread blocksProducer slowsProducer is user-facing; latency becomes the user's
Reject (429/503 + Retry-After)Error to producerProducer retries or gives upRetries without jitter amplify the load
Shed low-value workDropCapacity goes to current workYou can't classify value up front
Age-based expiryDrop by timestampStale work never runsClock skew, or nothing is stale
Autoscale consumersAdd capacityMore drainBottleneck is downstream, not consumer CPU

Named systems

TCP is the original: the receiver advertises a window (65,535 bytes without the RFC 7323 window-scale option), and the sender cannot have more than that unacknowledged. HTTP/2 does the same per stream with a 65,535-byte initial window. Reactive Streams makes it explicit with Subscription.request(n): the consumer asks for exactly n items. Kafka inverts it: the consumer pulls, so there is no broker-side push to throttle; the signal is consumer lag, and the failure mode is a consumer that exceeds max.poll.interval.ms (default 300,000 ms) and gets evicted from the group, triggering a rebalance and reprocessing.

Failure modes and detection

  • Unbounded queue → OOM. Detect: pool.getQueue().size() climbing monotonically.
  • Backpressure reaching a user: 429s. Detect: rate of 429/503 by endpoint.
  • Autoscaling on queue depth when the DB is the bottleneck: more consumers, more contention. Detect: queue depth falls while DB p99 rises.
  • Retry storm. Detect: request rate exceeds arrival rate.

The design decision

Something must give: drop, slow, or grow latency without bound. Not choosing means choosing the third. Decide the shedding policy and the 429 contract before the incident, and make the producer's failure visible: an immediate 429 beats an operation that silently never completes.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

What monitoring would you put on a queue-based system?

Answer

The 90-second answer

Four signals carry the weight: age of the oldest unprocessed message, consumer lag per partition, dead-letter arrivals, and end-to-end latency. Depth is a fifth, and only useful as a trend: a deep queue draining fast is healthy.

Age beats depth because it maps to user impact without arithmetic. "The oldest unprocessed signup is 40 minutes old" is actionable; "there are 18,000 messages" is not until you divide by throughput.

Concrete signals, by system

SignalMetricWhere it comes fromAlert
Oldest message ageApproximateAgeOfOldestMessage (seconds)SQS → CloudWatch> 30 s for 3 min
Consumer lagkafka_consumergroup_lag, per partitionkafka_exporter, or Burrowlag_seconds > 60 for 5 min
DLQ arrivalsApproximateNumberOfMessagesVisible on the DLQCloudWatch≥ 1, no for clause
Redelivery loopNumberOfMessagesReceived − NumberOfMessagesDeletedCloudWatchratio > 1.5 for 10 min
Idle pollingNumberOfEmptyReceivesCloudWatchsustained > 0
Broker backlograbbitmq_queue_messages_ready, rabbitmq_queue_messages_unackedrabbitmq_prometheus pluginready rising for 15 min
Handler durationhistogram_quantile(0.99, ...) over the consumer handlerapp Prometheusp99 > 2× baseline

Per-partition lag matters: one stuck partition is invisible in a group aggregate.

Lag in seconds, not messages

A fixed message-count threshold is wrong because the same count means different things at different production rates. Divide lag by the production rate:

PROMQL
# lag expressed as seconds of production backed up
sum by (consumergroup) (kafka_consumergroup_lag)
  /
sum by (consumergroup) (rate(kafka_topic_partition_current_offset[5m]))
YAML
- alert: ConsumerLagOverOneMinuteOfProduction
  expr: |
    sum by (consumergroup) (kafka_consumergroup_lag)
      / sum by (consumergroup) (rate(kafka_topic_partition_current_offset[5m])) > 60
  for: 5m

Worked arithmetic. Producer at 130 msg/s, four consumers at 25 msg/s each = 100 msg/s drain. Net +30 msg/s, so after 10 minutes the backlog is 18,000 and lag_seconds = 18000 / 130 ≈ 138 s. A "depth > 10,000" alarm fires at about 5.5 minutes here. Run a batch job at 260 msg/s against the same 100 msg/s drain and that identical alarm fires in 62 seconds: same threshold, two very different situations. The lag-in-seconds rule fires at 60 s of production in both.

Also alert on the sign of the drain: if rate(NumberOfMessagesDeleted) < rate(NumberOfMessagesSent) for 15 minutes, the queue never catches up no matter how large it gets.

Failure modes worth naming

  • Alive but stuck. Kafka's max.poll.interval.ms defaults to 300000 ms (5 minutes). A handler that blocks longer is evicted from the group and triggers a rebalance, so a process-up check passes while nothing progresses. Alert on lag, not on liveness.
  • Visibility timeout shorter than the handler. SQS redelivers, so NumberOfMessagesReceived climbs while NumberOfMessagesDeleted stays flat. The default visibility timeout is 30 s; set it above the p99 handler time.
  • Poison message. One bad payload retried forever. Cap maxReceiveCount in the redrive policy so it lands in the DLQ, and alarm on DLQ depth ≥ 1.
  • DLQ nobody watches. Silent data loss. Alarm on any arrival, and check the DLQ's own retention: SQS defaults to 4 days, maximum 14.

Tracing across the boundary

Propagate the W3C traceparent header as a message attribute, and mark the span with OpenTelemetry's messaging semantic conventions (messaging.system, messaging.destination.name, messaging.operation) so the producer and consumer spans join. Without it, debugging means correlating two log streams by timestamp: exactly when you have least time for it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

How does asynchronous processing change debugging and observability?

Answer

What a strong candidate says first

Assume a queue between producer and consumer: SQS, Kafka, RabbitMQ. The mechanics differ; the observability problem doesn't. The change is that the unit of work, the unit of failure, and the unit of observation stop coinciding. A synchronous call gives you one stack trace, one latency number, one error. An async hop gives you a publish that succeeded, a consumer that ran somewhere else seconds or hours later, and no caller left to notice when it failed.

Three things fix most of it: a correlation ID that survives the hop, trace context propagated in the message metadata, and a way to answer "where is this message right now".

Carrying trace context across the hop

Python
# Python 3.12, opentelemetry-api 1.27
from opentelemetry import trace
from opentelemetry.propagate import inject, extract

tracer = trace.get_tracer("orders")

def publish(order, sqs):
    with tracer.start_as_current_span("orders.publish") as span:
        span.set_attribute("messaging.system", "aws_sqs")
        span.set_attribute("messaging.destination.name", "orders")
        carrier = {}
        inject(carrier)                      # writes carrier["traceparent"]
        sqs.send_message(
            QueueUrl=ORDERS_QUEUE,
            MessageBody=json.dumps(order),
            MessageAttributes={
                "traceparent":    {"DataType": "String", "StringValue": carrier["traceparent"]},
                "correlation_id": {"DataType": "String", "StringValue": order["order_id"]},
            },
        )

def handle(message):
    attrs = {k: v["StringValue"] for k, v in message["MessageAttributes"].items()}
    ctx = extract(attrs)                     # reads attrs["traceparent"]
    with tracer.start_as_current_span("orders.consume", context=ctx) as span:
        span.set_attribute("messaging.message.id", message["MessageId"])
        span.set_attribute("sqs.receive_count",
                           int(message["Attributes"]["ApproximateReceiveCount"]))
        process(json.loads(message["Body"]))

inject writes the W3C traceparent value (00-<32 hex trace-id>-<16 hex span-id>-<flags>) into a plain dict; extract reads it back and returns a Context you pass as the parent of the consumer span. The consumer's work then hangs off the publishing request in the same trace. ApproximateReceiveCount is a system attribute: you must request it (AttributeNames=['All'] or MessageSystemAttributeNames) or it won't be in the message. OpenTelemetry's messaging conventions (messaging.system, messaging.destination.name, messaging.message.id, messaging.operation) give the spans consistent names so a backend can group by destination without custom parsing.

A worked trace: hypothetical, SQS, default 30 s visibility timeout, maxReceiveCount=5

elapsedhoplog fieldsrules out
0.0 sAPI orders.publishtrace_id=9f1c…0a15, span=3a7f…6081, order_id=8842, destination=orders—
2.5 sconsumer orders.consumetrace_id=9f1c…0a15, parent=3a7f…6081, receive_count=1"never published"
2.6 spayment callchild span, 180 ms—
2.8 sconsume failserror.type=Timeout"consumer succeeded"
32.5 sredeliveryreceive_count=2—
122.5 s5th delivery failsreceive_count=5"still queued"
~152.5 sDLQbody + receive_count=5 + last error—

The whole investigation is one query on order_id=8842. Without the ID you are matching timestamps across machines with skewed clocks.

Failure modes and how you actually detect them

  • Silent failure. No 5xx, no user-visible error. Detect with a DLQ depth alarm, consumer error rate, and ApproximateAgeOfOldestMessage on the queue. Consumer lag alone misses this: a consumer that receives and fails fast keeps lag near zero while every message lands in the DLQ.
  • Duplicate delivery. At-least-once means duplicates are normal. Log messaging.message.id and compare distinct IDs processed against messages published.
  • Poison message. One bad payload blocks a Kafka partition and lag climbs monotonically. Detect with lag plus the first failure log for that partition.
  • Ordering. Kafka orders within a partition only; SQS standard queues don't guarantee order at all (FIFO queues do, per message group ID). "Out of order" may be by design, so write down the expected guarantee before calling it a bug.
  • Retention as a deadline. SQS keeps messages 4 days by default, 14 max; Kafka's log.retention.hours defaults to 168 (7 days). Past that the message is gone and the only evidence is the DLQ copy, if you kept one.

When not to do this

If the caller needs the result to continue, keep the call synchronous. You get the stack trace, the error and the latency for free, and no correlation apparatus. Async buys decoupling and burst absorption; it costs you everything above.

The practical investment

Correlation ID on every message; trace context propagated in message attributes; DLQ retention with the payload and the failure reason; alarms on DLQ depth and message age; and a documented way to answer "where is this message now" from the correlation ID alone. That last one is the question every investigation starts with.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

A queue is backing up in production. Walk through your response.

Answer

First, establish the shape. Is production up or consumption down? Comparing the producer rate against the consumption rate answers it immediately and routes everything that follows. A spike in production is a different incident from consumers slowing.

If consumption has dropped: are consumers running, and are they actually processing? A consumer that is alive but stuck (blocked on a dependency, deadlocked, waiting on a lock) is the common case and passes liveness checks. Check error rates: a failing dependency causes every message to retry, so effective throughput collapses while consumers look busy. Check whether processing duration has risen, which points at a slow dependency or a data change.

If production has risen: is it legitimate traffic, a retry storm from an upstream failure, or a bug producing duplicates? A retry storm is self-inflicted and the fix is upstream, not here.

Mitigate while diagnosing. Scale consumers out if the bottleneck is consumer capacity: noting the cap: in a partitioned log, parallelism is bounded by partition count, so adding consumers beyond that does nothing. If a dependency is the bottleneck, more consumers make it worse, not better, and the right move is to slow down. If a subset of messages is failing, isolate them so they stop consuming retry capacity.

Consider shedding deliberately. If the backlog cannot be drained in acceptable time, dropping or deprioritising low-value messages is better than delaying everything, but it is a decision to make explicitly, ideally against a policy decided in advance rather than improvised at 3am.

Communicate. Asynchronous work backing up is user-visible even though nothing is erroring: signups without confirmation emails, orders without receipts. Support should know before customers report it.

Afterwards: alerting that would have caught it earlier. Message age trending rather than a depth threshold; whether the parallelism ceiling was known; and whether the overload behaviour was designed or discovered. That last one is usually the real finding, because a queue that backs up is not a surprise, it is an eventuality.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Explain what replay means and when you would use it.

Answer

Replay is re-reading messages a consumer has already processed, by moving its position backwards in a log that retains data independently of consumption. It works because retention is decoupled from acknowledgement: Kafka keeps a partition's segments for log.retention.hours=168 (7 days) by default whether or not anyone has read them. A queue that deletes on ack has nothing to replay, so this is a log property, not a general messaging one.

Four situations justify it:

  • Consumer bug. A week of OrderPlaced events were projected with a wrong currency conversion. Fix the code, rewind the offset, reprocess. Hand-repairing the derived state instead is usually infeasible.
  • New consumer. A fraud service needs history, not just events from now on. It starts at the beginning and catches up.
  • Rebuilding a derived store. A search index needs a mapping change. Rebuild from the log rather than migrating it in place.
  • Testing. Replaying production traffic into staging exercises the consumer against real input distributions.

The constraints are the hard part. Consumers must be idempotent, because replayed records were already applied once. Side effects must be suppressible: replaying a week of orders must not re-send a week of confirmation emails, so a replay mode that skips the notifier has to exist before you need it. And replaying into a shared topic hits every consumer group on it, so replay into a separate topic or an isolated group.

Rewinding one partition (Kafka clients 3.6, Java 17):

Java
Properties p = new Properties();
p.put("bootstrap.servers", "broker:9092");
p.put("group.id", "orders-indexer");
p.put("key.deserializer", StringDeserializer.class.getName());
p.put("value.deserializer", StringDeserializer.class.getName());
p.put("enable.auto.commit", "false");   // commit only after the sink write succeeds

try (KafkaConsumer<String, String> c = new KafkaConsumer<>(p)) {
    TopicPartition tp = new TopicPartition("orders", 3);
    c.assign(List.of(tp));

    long ts = Instant.parse("2024-05-01T00:00:00Z").toEpochMilli();
    OffsetAndTimestamp target = c.offsetsForTimes(Map.of(tp, ts)).get(tp);
    c.seek(tp, target.offset());   // target == null => nothing that old is retained

    while (true) {
        for (ConsumerRecord<String, String> r : c.poll(Duration.ofMillis(500))) {
            index.upsert(r.key(), r.value());   // idempotent: same key overwrites
            c.commitSync(Map.of(tp, new OffsetAndMetadata(r.offset() + 1)));
        }
    }
}

Tracing that against orders-3:

stepvalue
committed offset (next to read)5,020,001
earliest retained offset4,180,000
offsetsForTimes(2024-05-01T00:00Z)4,600,000
first record returned by the next polloffset 4,600,000
records re-delivered5,020,000 − 4,600,000 + 1 = 420,001

At the steady 200 records/s that partition sees, the replay takes 35 minutes; at 5,000 records/s it takes 84 seconds. That gap is the capacity problem. Seven days at 2,000 events/s across the topic is 1,209,600,000 events; replaying it in one hour means 336,000 events/s, 168× the steady rate. If the sink is Postgres doing 3,000 upserts/s, the replay saturates it: throttle to the sink's measured headroom, not to the consumer's.

Two preconditions that bite in an incident:

  • Committed offsets expire. offsets.retention.minutes=10080 (7 days): a group idle longer than that loses its committed offsets, and auto.offset.reset (default latest) silently starts it at the end of the log. The opposite of a replay. Pass an explicit offset or set earliest.
  • Retention is the ceiling. offsetsForTimes returns null for a timestamp older than the earliest retained segment, so the replay you planned may simply be impossible. Check the earliest offset before promising a recovery window.

Replay is per-partition, so per-key ordering survives as long as records are partitioned by key.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How do you decide what belongs in a message payload?

Answer

The main decision is between a thin message carrying an identifier and a fat one carrying the data.

Thin, { orderId: 123 }, means the consumer fetches what it needs. The message is small, cannot go stale, and the consumer gets current data. The costs are a lookup per message, coupling the consumer to the producer's data store or API, and, the subtle one, that the consumer sees the state at processing time, not at event time. If the order was cancelled between publish and processing, the consumer sees the cancellation, which may or may not be what you want.

Fat, the full order details, means the consumer needs nothing else. It is self-contained, the consumer is decoupled, and it captures the state at the moment of the event, which is usually what an event should mean. The costs are a larger message, potential staleness if the consumer assumes it is current, and a wider contract to evolve.

My default is fat enough that the common consumer needs no lookup, carrying the data as of the event, plus identifiers so a consumer needing more can fetch it. That serves both without forcing either.

Contract evolution is the part that matters more over time, because messages outlive the code that wrote them: an unprocessed message may be consumed by a newer version, and a replayed one by a much newer version.

So: add fields, never remove or repurpose them. New fields must be optional with sensible defaults. Consumers must ignore unknown fields rather than rejecting them, which is what makes producer changes safe. Version the schema explicitly so a consumer can dispatch rather than guess. And where a breaking change is unavoidable, publish both versions during a transition rather than cutting over: the same expand–migrate–contract discipline as a schema change.

What not to include: secrets and credentials, since messages are stored and logged and replayed; large binary payloads, which belong in object storage with a reference; and anything that makes the message a remote procedure call in disguise, since a message describing what happened ages far better than one describing what to do.

That last distinction is the one I would press on: an event is a fact and stays true, whereas a command encodes an intention that may not still be appropriate when it is processed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

How would you implement a job queue using a database table?

Answer

The core mechanism is claiming a row with a lock that skips rows other workers hold:

SQL
UPDATE jobs SET status = 'running', started_at = now(), worker_id = :worker
WHERE id = (
  SELECT id FROM jobs
  WHERE status = 'pending' AND run_after <= now()
  ORDER BY priority DESC, run_after
  FOR UPDATE SKIP LOCKED LIMIT 1
)
RETURNING *;

SKIP LOCKED is what makes it work with several workers. Without it every worker locks the same highest-priority row and queues behind the first, so ten workers process jobs one at a time, and this looks perfectly fine with a single worker in testing, which is why it is the common mistake.

The surrounding design matters as much as the query:

A partial index on the pending rows keeps the index small no matter how many completed jobs accumulate, which is what makes this viable long-term.

Crash recovery. A worker that dies mid-job leaves a row stuck in running forever. Recording started_at and running a sweeper that returns timed-out jobs to pending handles it, with an attempt counter and a dead-letter state after repeated failures. Without this, a crash silently loses work, and this is the piece most often missing.

Retries with backoff via run_after, so a failing job does not spin.

Idempotent handlers, since a worker can complete a job and die before marking it done. At-least-once applies here as everywhere.

Retention. A table that only grows will become the problem; delete completed jobs after a window, or partition by time and drop partitions.

Polling with a sensible interval, or a notification mechanism to avoid the latency-versus-load trade of pure polling.

The honest assessment: this is excellent up to moderate throughput and has a real advantage no broker offers. Transactional enqueue alongside the business data, which removes the dual-write problem entirely and means one less system to operate. At high throughput, polling load and row contention become the bottleneck and a purpose-built broker is right. I would start here and move when measurement says so, rather than adopting a broker pre-emptively for volume that may not arrive.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

When would you choose a database table over a dedicated message broker?

Answer

The short answer. Pick the table when the enqueue has to be atomic with a business write and the volume is moderate. That atomicity is the whole argument: INSERT INTO jobs inside the same transaction as UPDATE accounts means one commit, so the job and the state change either both exist or neither does. No broker gives you that without an outbox table plus a relay process, which is the table you were trying to avoid, plus a broker.

The mechanism.

SQL
-- PostgreSQL 16
CREATE TABLE jobs (
  id        bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  kind      text        NOT NULL,
  payload   jsonb       NOT NULL,
  run_at    timestamptz NOT NULL DEFAULT now(),
  attempts  int         NOT NULL DEFAULT 0,
  locked_by text,
  locked_at timestamptz
);
CREATE INDEX jobs_ready ON jobs (run_at) WHERE locked_by IS NULL;

Enqueue, inside the caller's transaction:

SQL
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 42;
INSERT INTO jobs (kind, payload) VALUES ('send_receipt', '{"account":42}');
COMMIT;

Claim, from a worker:

SQL
WITH claimed AS (
  SELECT id FROM jobs
  WHERE locked_by IS NULL AND run_at <= now()
  ORDER BY run_at
  FOR UPDATE SKIP LOCKED
  LIMIT 10
)
UPDATE jobs j SET locked_by = $1, locked_at = now()
FROM claimed c WHERE j.id = c.id
RETURNING j.id, j.kind, j.payload;

FOR UPDATE SKIP LOCKED is PostgreSQL 9.5+ and MySQL 8.0.1+.

Trace it with two workers. Jobs 1–20 are ready; W1 and W2 run the claim query at the same instant. W1's index scan takes rows 1–10 and locks them. W2's scan reaches rows 1–10, finds them locked, skips them without blocking, and locks 11–20. Both return ten rows and neither waits. That is what makes a table viable here: contention is skipped, not serialised.

Wake workers instead of polling. NOTIFY fires at commit, so a listener cannot miss a job that committed while it was connected. The payload must be under 8000 bytes, so send the id and let the worker fetch the row. Poll every few seconds as a backstop for missed notifications and for rows whose run_at is in the future.

Numbers. Polling every 1 s adds 500 ms mean latency; LISTEN/NOTIFY cuts that to single-digit milliseconds. A claim query hitting the partial index over a ready set of ~1,000 rows is an index scan plus ten row updates, order 1 ms, so 20 workers put the ceiling around 10–20k jobs/s on one primary. That is a labelled estimate, not a benchmark. The real ceiling is write IOPS and whether autovacuum keeps up with the update churn, not the query shape.

Move to a broker when: several independent consumer groups need the same stream (Kafka gives each group its own offset; a table needs a cursor table per consumer); replay matters (Kafka retention.ms defaults to 604800000, seven days); ordering per key across many partitions; or sustained volume past the estimate above.

Failure modes to design for. A worker that dies holding locked_by strands its rows: reclaim with UPDATE jobs SET locked_by = NULL WHERE locked_at < now() - interval '5 minutes', which makes delivery at-least-once and handlers idempotent. High update churn bloats the table; watch n_dead_tup in pg_stat_user_tables. A poison job retries forever unless attempts is capped and the row moved to a dead-letter table.

Default. Existing relational database, moderate volume: the table. You also drop a component from the on-call rotation, the backup story and the upgrade treadmill. The enqueue and claim interfaces are small, so swapping in a broker later is a contained change.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

When should work be synchronous rather than queued?

Answer

Answer in the first minute. Synchronous when the caller cannot proceed without the result, when the write must be atomic with another action, when the work is fast and reliable, or when the error has to reach the user now. Queue it when none of those hold and the work is slow, retryable, bursty, or independent of the response. The decision is arithmetic: compare the queue's added p99 against the latency you remove from the request path.

Worked example. Order submission on a 4 vCPU app node, Postgres on local NVMe, payment provider in the same region. The figures come from one such setup; the shape is the point.

stepp50p99needs the result?
validate address (in-process)2 ms6 msyes: decides the response
PSP authorize180 ms900 msyes: decides the response
insert order, commit3 ms12 msyes: must be atomic with the charge
send confirmation email400 ms1500 msno

All four synchronous: p50 = 2 + 180 + 3 + 400 = 585 ms, p99 = 6 + 900 + 12 + 1500 = 2418 ms. Move only the email to a queue: p50 = 185 ms, p99 = 918 ms. The email was 68% of p50 and 62% of p99, and nothing downstream reads its result, so it goes. The charge stays: the response body is the authorization outcome, and a decline has to reach the user inside this request.

The 3 ms commit is Postgres synchronous_commit = on (the default) waiting on a WAL fsync. Setting it off drops the commit below a millisecond, but a crash can lose recently committed transactions, bounded by wal_writer_delay (default 200 ms). A real trade, not a free win.

What synchronous looks like in code.

Python
# The caller needs the outcome, so it waits — with an idempotency key so a retry
# cannot double-charge.
intent = stripe.PaymentIntent.create(
    amount=order.total_cents,
    currency="usd",
    idempotency_key=order.id,
)
if intent.status == "requires_action":      # 3DS: the user must act now
    return {"next_action": intent.next_action}, 200
if intent.status != "succeeded":
    return {"error": intent.last_payment_error.code}, 402
Python
# Nothing downstream reads the result, so the request returns before the work.
queue.send_message(QueueUrl=EMAIL_QUEUE_URL,
                   MessageBody=json.dumps({"order_id": order.id}))
return {"order_id": order.id}, 202

When the queue is the wrong answer. Queuing a call the client then polls for buys you at-least-once delivery, a visibility timeout and a DLQ in exchange for nothing: the user still waits. A 900 ms p99 charge polled every 500 ms is two extra round trips and a worse p99 than the synchronous call it replaced.

Failure modes of the queued version, and how you see them.

  • Backlog grows when arrival exceeds drain. At 1,200 msg/s in and 1,000 msg/s out, the queue gains 200/s; after 60 s the newest message waits 12 s. Watch ApproximateAgeOfOldestMessage (SQS) or consumer lag (Kafka records-lag-max), not queue depth alone.
  • At-least-once means duplicates. A retried charge without an idempotency key double-charges, so the consumer must be idempotent on order_id.
  • A poison message retries forever unless maxReceiveCount routes it to a DLQ, where it sits unprocessed and unnoticed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How would you migrate a synchronous operation to be asynchronous?

Answer

Incrementally, because this changes user-visible behaviour and the failure mode is silent: work that quietly stops happening.

Design the user experience first, since it is the actual change. What does the response say now? How does the user see progress? How do they learn about failure? If those are unanswered, the migration will produce a worse product regardless of how clean the implementation is.

Extract the work into a function that can be called either way, taking a message-shaped input. That separates the refactoring risk from the asynchrony risk, and it is testable immediately.

Add the queue path alongside, not instead. Publish the message and keep doing the work synchronously, with the consumer processing the message but its effects discarded or written somewhere comparable. That exercises publishing, consuming, serialisation and deployment under real traffic with no user risk, and it reveals the problems while they are still cheap.

Compare. Verify the asynchronous path produces the same results as the synchronous one. This is where the genuine surprises appear: missing context that was implicit in the request, a dependency on session state, a user identity that was available synchronously and is not in the message.

Cut over gradually (a percentage, or a subset of cases) with an instant switch back. Watch consumer lag, error rates and end-to-end latency, plus whatever business metric the work affects, since that is what catches an effect the technical metrics miss.

Then remove the synchronous path, once confidence has accumulated.

The things I would ensure before starting: idempotency, since the consumer will see duplicates; the outbox, if the enqueue must be atomic with a database write; the dead-letter queue with monitoring, because failures are now silent; and the correlation identifier, because debugging now spans two systems.

And I would be explicit about what becomes possible to get wrong that was not before: the work can now happen twice, out of order, much later, or not at all with nobody noticing. Each of those needs an answer, and the migration is not finished when the code works: it is finished when those four have answers.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

How do you keep a queue-based system processing when the broker itself fails or loses quorum, and what happens to in-flight and unacknowledged messages during failover?

Answer

There are two questions inside this one, and conflating them is how people lose data quietly. Can producers still write? And what happens to a message a consumer is already holding?

Writes are a replication setting, not an availability setting. In Kafka, acks=all plus min.insync.replicas=2 on a replication factor of 3 means a write is acknowledged only once two replicas have it, so you survive one broker loss and keep accepting writes. Lose two and producers get NotEnoughReplicas, and that is the correct outcome. The failure mode to avoid is dropping min.insync.replicas to 1 to "keep processing": you can now write with a single replica alive, and if that replica dies before replicating, an unclean leader election promotes a stale replica and acknowledged messages are gone. unclean.leader.election.enable defaults to false for exactly this reason. Availability here is bought with durability, and the trade should be made deliberately, not during an incident.

In-flight messages are a different mechanism per broker.

BrokerMessage held by a consumer when the broker failsWhat the app must do
KafkaStill in the log. The only consumer state is the committed offset, so uncommitted work is redelivered after the rebalance.Idempotent consumer; commit offsets after side effects, not before.
RabbitMQ quorum queueReplicated to a majority before the publish is confirmed; on leader election, unacked messages are requeued with redelivered=true.Idempotent; treat redelivered as a hint, not a guarantee.
RabbitMQ classic queueGone with the node. Mirrored classic queues were removed in RabbitMQ 4.0.Don't put anything you can't lose on one.
SQSManaged across AZs; the message reappears when its visibility timeout expires.Idempotent; set visibility to cover worst-case processing time.

The SQS case is worth arithmetic. Visibility timeout of 30 s with a consumer whose p99 is 45 s means every slow message becomes visible again mid-processing and gets picked up by a second consumer: you have doubled the work and produced a duplicate side effect. Set it to several times p99, or extend it with a heartbeat while processing.

Failure modes and how you see them. Under-replicated partitions and a shrinking ISR are the leading indicator that you are one broker away from refusing writes; alert on them, not on producer errors. A rebalance storm, lag flat while rebalance rate spikes, usually means max.poll.interval.ms is being exceeded by slow processing, so the consumer never makes progress. A poison message gets redelivered on every failover; a DLQ with a receive count cap is what stops it cycling forever.

What quorum does not cover. Quorum is within a cluster. A region loss is a separate problem needing its own replication and an explicit RPO decision: don't let "we have three replicas" stand in for a cross-region story. And none of this removes the requirement that consumers be idempotent: every failover path above produces duplicates by design.

Curated: · Written: · Reviewed:

Difficulty: Hard