Interview Study Guide

Guide / System design Fundamentals

6. Messaging and async processing

Created · Updated · 10 min read

Use a queue when the caller doesn’t need the result now, when you need to absorb bursts, fan out to many consumers, or decouple services so one outage doesn’t cascade.

6.1 Queue vs log#

Message queue (RabbitMQ, SQS, ActiveMQ)Event log / stream (Kafka, Kinesis, Pulsar, Redpanda)
ModelMessage deleted after ackAppend-only log; consumers track their offset
ReplayNoYes, within retention (days, or forever with compaction)
ConsumersCompeting consumers share workMany independent consumer groups each read everything
OrderingPer queue (FIFO queues), weak otherwiseStrict within a partition
Best forTask/job queues, RPC-style work, per-message routingEvent-driven architecture, CDC, analytics pipelines, event sourcing

6.2 Kafka internals you must know#

  • Topic → partitions: each partition is an ordered log on a broker, replicated (replication factor 3, min.insync.replicas=2, producer acks=all for durability).
  • Ordering is only per partition. Use a message key (order_id, user_id) so all events for one entity land in one partition, in order.
  • Consumer groups: each partition is read by exactly one consumer in a group → max parallelism = partition count. Choose partitions for future throughput; increasing them later changes key→partition mapping.
  • Offsets: consumers commit the offset after processing. Commit before processing = at-most-once; after = at-least-once.
  • Rebalancing: consumers joining/leaving pause the group; use cooperative rebalancing and static membership to reduce pauses.
  • Consumer lag (latest offset − committed offset) is the key health metric; alert on it.
  • Log compaction keeps the latest value per key (great for changelog/state topics).
  • Poison messages: a message that always fails blocks the partition → retry N times with backoff, then send to a dead-letter topic and alert.

6.3 Delivery semantics#

  • At-most-once: may lose messages, never duplicates (metrics where loss is fine).
  • At-least-once: never loses, may duplicate. The practical default. Make consumers idempotent.
  • Exactly-once: Kafka offers it inside Kafka (idempotent producer + transactions, read-process-write). End to end with external side effects (sending an email, charging a card) it is achieved as at-least-once delivery + idempotent processing (dedupe table keyed by message ID, or idempotent upserts).

6.4 Patterns#

  • Transactional outbox: the dual-write problem — you write to DB and publish to Kafka; if one fails they disagree. Fix: in the same DB transaction, insert the event into an outbox table; a relay (poller or Debezium CDC) publishes it and marks it sent. Guarantees at-least-once publish consistent with the DB.
  • Inbox / dedupe table: consumer stores processed message IDs (unique constraint) in the same transaction as its side effect.
  • Saga: a long business transaction across services as a series of local transactions, each with a compensating action (reserve inventory → charge payment → create shipment; if payment fails, release inventory). Choreography (services react to events; loose but hard to follow) vs orchestration (a coordinator like Temporal/Step Functions drives the steps; easier to reason about and monitor).
  • CDC (change data capture): stream the DB’s WAL/binlog as events (Debezium) to feed search indexes, caches, warehouses without dual writes.
  • Event sourcing: store events as the source of truth, derive current state by replay (with snapshots). Great audit trail; harder queries and schema evolution.
  • CQRS: separate write model from read models (denormalized projections optimised per query). Often paired with event sourcing; read side is eventually consistent.
  • Fan-out: pub/sub (SNS → many SQS queues, or many Kafka consumer groups).
  • Delayed / scheduled work: SQS delay queues, Redis sorted sets keyed by timestamp, or a workflow engine (Temporal) for durable timers.
  • Priority: separate queues per priority with weighted consumers rather than one priority queue.

6.5 Retries done right#

Exponential backoff with jitter (sleep = random(0, base × 2^attempt)), a max attempt count, retry only retryable errors (timeouts, 503, 429 — not 400), a retry budget so retries don’t triple load during an outage, and a DLQ for the rest. Retries are only safe if the operation is idempotent.

6.6 Kafka in depth#

Choosing the partition count. Partitions are the unit of parallelism and ordering. Estimate partitions ≥ max(target throughput ÷ per-partition throughput, max consumers wanted). A partition handles roughly 10 MB/s of writes and one consumer thread; for 100 MB/s with consumers that process 5 MB/s each you need about 20 partitions. More partitions mean more open files, longer leader elections and slower rebalances, so avoid thousands per topic without a reason. Increasing the count later changes the key → partition mapping, breaking per-key ordering for in-flight data, so plan headroom (2–3×) up front.

Producer settings that matter

SettingMeaningTypical
acks=all + min.insync.replicas=2Leader waits for in-sync replicas: no loss if one broker diesRequired for important data
enable.idempotence=trueBroker dedupes producer retries (per partition sequence numbers)On
linger.ms, batch.sizeWait a few ms to batch records: higher throughput, slightly higher latency5–20 ms
compression.typelz4/zstd cut network and diskzstd or lz4
max.in.flight.requestsWith idempotence ≤5 keeps ordering across retries5

Consumer settings and behaviour

  • enable.auto.commit=false and commit after processing (at-least-once). Committing per batch, not per message, keeps throughput.
  • max.poll.interval.ms: if processing a batch takes longer, the consumer is kicked out and the group rebalances. Reduce max.poll.records or process asynchronously.
  • Rebalances: use the cooperative-sticky assignor and static membership (group.instance.id) so a restarting pod keeps its partitions; avoid scaling consumers above partition count (extra ones sit idle).
  • Lag is measured in messages and, better, in time (age of the oldest unprocessed message).

Retry and dead-letter topology (so one bad message never blocks a partition):

orders ──► consumer ──fail──► orders.retry.1m ──► consumer ──fail──► orders.retry.10m ──► ... ──► orders.dlq
                                  (delay via a retry consumer that sleeps until message time + delay)

Keep the original message, error and attempt count in headers; build a tool to inspect and replay the DLQ; alert on DLQ depth. For strict ordering per key, retry topics break order: either block that key (park only that key) or accept reordering and make consumers order-tolerant using version numbers.

Compaction and retention. cleanup.policy=delete keeps data for a time/size; compact keeps the latest record per key (tombstone = null value deletes). Use compaction for changelogs, user-profile snapshots, configuration. retention.ms decides how far a new or lagging consumer can replay.

Schema evolution. Use a schema registry (Avro/Protobuf/JSON Schema) with compatibility rules (backward: new readers read old data). Add optional fields, never reuse field numbers, and version topics for breaking changes.

Ordering and exactly-once, precisely. Ordering holds per partition when using a key. Exactly-once within Kafka = idempotent producer + transactions (read-process-write with isolation.level=read_committed). Side effects outside Kafka still need idempotent handling.

Broker comparison#

SystemModelStrengthsChoose it whenWatch out
Kafka (also Redpanda)Distributed logThroughput, replay, many consumer groups, ecosystem (Connect, Streams, CDC)Event streaming, analytics pipelines, event-driven backbonesOperational weight, no per-message routing or delay, partition planning
RabbitMQBroker with exchanges and queues (AMQP)Flexible routing, per-message ack, priorities, TTL, low latencyTask queues and complex routing at moderate volumeNot built for huge retention or replay; throughput lower
SQS (+SNS)Managed queue (+pub/sub)Zero ops, scales automatically, DLQ built in, visibility timeoutSimple async jobs on AWS; fan-out with SNS → SQSStandard queue = at-least-once, unordered; FIFO queue has throughput caps; no replay
PulsarLog with queue semantics, tiered storageMulti-tenancy, geo-replication, shared and key-shared subscriptionsMany tenants, queue plus stream in oneSmaller ecosystem, BookKeeper complexity
Redis StreamsLight logSimple, fast, consumer groupsSmall pipelines already on RedisMemory-bound, weaker durability guarantees
Temporal / Step FunctionsWorkflow engineDurable timers, retries, saga stateLong-running business processesNot a general message bus

Visibility timeout (queues): a received message is hidden for N seconds; if not deleted (acked) in time it reappears (redelivery). Set it above processing time, extend it for long jobs.

Most asked questions#

1. Kafka vs RabbitMQ vs SQS? Kafka for high-throughput event streams with replay and many independent consumers; RabbitMQ for flexible routing and classic task queues; SQS for simple managed queues on AWS. Say what you need: replay? ordering? fan-out? ops burden?

2. How does Kafka guarantee ordering? Only within a partition, so choose a key (order_id) that groups the events that must be ordered; one partition is consumed by one consumer in a group.

3. How do you get exactly-once processing? At-least-once delivery plus idempotent consumers (dedupe table or idempotent upsert); Kafka transactions for Kafka-to-Kafka pipelines. See Idempotency.

4. What is consumer lag and what do you do about it? Distance between latest and committed offset (or age of the oldest message). Scale consumers up to partition count, speed processing (batching, async I/O), fix hot partitions, or fix a slow downstream; alert on lag growth.

5. Explain the outbox pattern. Write the business row and an outbox row in one transaction; a relay publishes outbox rows to Kafka and marks them sent. It removes the dual-write inconsistency and gives at-least-once publishing.

6. Choreography vs orchestration for sagas? Choreography: services react to events (simple, decoupled, hard to see the whole flow). Orchestration: a coordinator drives steps and compensations (clear, observable, central dependency). Prefer orchestration for flows with many steps and compensations.

7. What do you do with a poison message? Bounded retries with backoff, then a DLQ with context, alert, and a replay tool, so the partition keeps moving.

8. When would you not use a queue? When the caller needs the result immediately, when latency is critical and failure must be visible synchronously, or when the added eventual consistency is unacceptable.

Senior-level questions#

1. “Consumers keep rebalancing and throughput collapses. Why?” Processing exceeds max.poll.interval.ms, GC pauses, pods restarting from autoscaling or health probes, or eager rebalancing stopping the world. Fix: smaller batches, cooperative assignor, static membership, longer session timeouts, readiness that does not flap, and separate slow work from the poll loop.

2. “How do you reprocess 30 days of events after a bug?” Deploy fixed code under a new consumer group, reset offsets to the timestamp, run at a throttled rate, ensure idempotent sinks (upserts keyed by event ID), separate the replay from live traffic (different cluster or quota), and verify with counts/checksums. Retention must cover 30 days.

3. “A hot key makes one partition 10× busier. What now?” Add a salt for keys that tolerate loss of strict ordering across salts, split heavy entities into sub-entities, use a custom partitioner that spreads known hot keys while keeping a sequence number for reassembly, or pre-aggregate before the topic.

4. “How do you guarantee no event loss between the DB and Kafka?” Outbox with CDC (Debezium) or a polling relay; idempotent producer; acks=all; consumers commit after processing; monitoring of outbox age; reconciliation job comparing DB state and downstream state.

5. “How do you evolve an event schema without breaking consumers?” Registry with compatibility checks in CI, additive changes only, tolerant readers, versioned event types for breaking changes with a dual-publish period, and consumer-driven contract tests.

6. “Design delayed retries (1 min, 10 min, 1 hour) without blocking.” Tiered retry topics with a consumer that holds messages until due_time (pausing the partition), or a scheduler/ workflow engine; for SQS use delay queues; keep attempt counters in headers; final DLQ.

7. “Message ordering across multiple topics or entities?” Not provided; design events to be order-independent (version numbers, state machines that reject or buffer invalid transitions), or put related events in one topic keyed by the aggregate.

Quiz#

1. 40 MB/s of writes, a consumer processes 4 MB/s. Minimum partitions?

At least 10 for consumer parallelism (40 ÷ 4), plus headroom: 20 or so, and check broker throughput per partition (about 10 MB/s).

2. What happens if you add partitions to a keyed topic?

hash(key) % partitions changes, so new events for a key may go to a different partition than old events, breaking per-key ordering during the transition.

3. At-least-once with auto-commit before processing: what is the actual semantic?

At-most-once: if the consumer crashes after the commit but before finishing, the message is lost. Commit after processing for at-least-once.

4. Which setting combination avoids data loss on a single broker failure?

Replication factor 3, min.insync.replicas=2, producer acks=all (plus idempotence and unclean leader election disabled).

5. What is log compaction good for?

Keeping the latest value per key (changelogs, current state topics, config), allowing a new consumer to rebuild state without the full history.

6. A consumer exceeds max.poll.interval.ms. What happens?

The coordinator treats it as dead, removes it from the group and rebalances; its uncommitted messages are reprocessed by another consumer.

7. SQS standard queue guarantees?

At-least-once delivery, best-effort ordering. Use FIFO queues (with deduplication ID and message groups) for ordering, at lower throughput.

8. Why should consumers be idempotent even with Kafka transactions?

Transactions only cover Kafka reads and writes; external effects (emails, payments, DB writes) can be repeated after a crash or rebalance.

Finished this page?Mark it done to track your progress across the guide.
Pritam Ghosh · System design & AI engineering study notes