PrepStack › Backend › Kafka & Message Queues
Kafka & Message Queues interview cheat sheet
Queues vs logs, Kafka internals, delivery guarantees, RabbitMQ and event-driven patterns
Messaging questions show up in almost every backend and system-design round. Interviewers check that you know why you would put a broker between services, how Kafka really works (partitions, offsets, replication, consumer groups) and what delivery guarantees you actually get. Senior rounds add RabbitMQ vs Kafka vs SQS trade-offs and patterns like outbox, idempotent consumers and sagas. Client code here is illustrative; the small Python/JS/SQL simulations are runnable and verified. Read the 15-minute revision, then use Quiz mode and answer out loud.
15-minute revision
- Async messaging decouples services in time, availability and load: the producer does not wait, the consumer can be down, and the broker buffers spikes.
- Point-to-point: each message goes to one consumer (work queue). Pub/sub: each subscriber gets its own copy. Kafka does both with consumer groups.
- Queue (RabbitMQ, SQS): message is deleted once acked. Log (Kafka): records stay for the retention period and each group tracks its own offset, so you can replay.
- Kafka: topic → partitions (ordered, append-only logs) → segments on disk. Each record has an offset. Ordering is guaranteed only within a partition.
- Each partition has one leader and N−1 followers. ISR = replicas that are caught up. With
acks=all+min.insync.replicas=2+ RF 3, one broker can die with no data loss. - Kafka 4.0 (March 2025) removed ZooKeeper. Metadata now lives in KRaft: a Raft quorum of controllers storing the
__cluster_metadatalog. - Producer: same key → same partition (murmur2 hash % partitions). No key → sticky batching across partitions. Changing the partition count remaps keys.
- Producer defaults since 3.0:
acks=allandenable.idempotence=true(PID + sequence numbers stop duplicates from retries).linger.msdefaults to 5 since 4.0. - A consumer group shares the partitions of a topic: each partition goes to exactly one member. More members than partitions = idle members.
- Rebalance reassigns partitions when members join/leave/time out. Cooperative (incremental) rebalancing and the KIP-848 protocol (
group.protocol=consumer) avoid stop-the-world pauses. - Commit after processing = at-least-once (possible duplicates). Commit before = at-most-once (possible loss). So make consumers idempotent.
- Exactly-once in Kafka = idempotent producer + transactions (
sendOffsetsToTransaction) + consumers withisolation.level=read_committed. It covers Kafka-to-Kafka only. - Retention:
cleanup.policy=delete(by time/size, default 7 days) orcompact(keep the latest value per key; a null value is a tombstone). - RabbitMQ: producers publish to an exchange (direct, fanout, topic, headers); bindings route to queues; consumers ack; prefetch caps unacked messages.
- Outbox pattern: write the business row and the event in one DB transaction, then a relay/CDC publishes it. Solves the dual-write problem.
- Watch consumer lag (log-end offset − committed offset) per partition. Growing lag means consumers are too slow, stuck or rebalancing.
Messaging Fundamentals
Why asynchronous messaging
A broker lets services talk without waiting for each other, so they can fail, scale and deploy independently.
- Temporal decoupling: the consumer does not need to be up when the producer sends. The broker stores the message until someone reads it.
- Load levelling: a spike of 10k requests becomes a queue that workers drain at their own pace instead of overloading a downstream service.
- Fan-out: one event (
OrderPlaced) can feed billing, email, analytics and search without the producer knowing about any of them. - Resilience: retries, dead-letter queues and replay are built in. A slow consumer does not slow down the user-facing request.
- Costs: eventual consistency, harder debugging (tracing across hops), duplicates, ordering questions and one more piece of infrastructure to run.
- Use sync calls (REST/gRPC) when the caller needs the answer now (e.g. price check). Use messaging for side effects and work that can finish later.
Interview questions
- Why would you introduce a message queue between two services?
- What are the downsides of event-driven, async architecture?
- Command vs event message?
Point-to-point vs pub/sub, queue vs log
Point-to-point gives each message to one consumer; pub/sub gives each subscriber a copy. A queue forgets acked messages; a log keeps them for replay.
- Point-to-point (work queue): many workers compete for messages; each message is processed by one of them. Good for spreading jobs.
- Publish/subscribe: every subscription gets its own copy of each message. Good for broadcasting events.
- Queue semantics (RabbitMQ classic/quorum queues, SQS): the broker tracks each message's state and deletes it after ack. Messages are not replayable.
- Log semantics (Kafka, Pulsar, Kinesis, RabbitMQ Streams): an append-only, ordered log. Records are kept by retention, not by consumption; readers just move an offset.
- Kafka does both models with consumer groups: members of one group compete (point-to-point), and different groups each get everything (pub/sub).
- Kafka 4.2 made share groups (KIP-932, “Queues for Kafka”) production-ready: queue-like per-record acks and many consumers per partition on a normal topic.
Interview questions
- Difference between point-to-point and publish/subscribe?
- Difference between a message queue and a log-based broker like Kafka?
- Can Kafka behave like a traditional queue?
Kafka Architecture
Brokers, topics, partitions, offsets & segments
A topic is split into partitions; each partition is an ordered, append-only log stored as segment files on a broker.
- Broker: one Kafka server. A cluster is several brokers; clients connect to any broker via
bootstrap.serversand learn the rest from metadata. - Topic: a named stream of records (
orders). Partition: the unit of ordering, parallelism and storage. Partitions are spread across brokers. - Offset: a record's position in its partition (0, 1, 2…). It is unique only within that partition.
- A record has key, value, timestamp, headers. Records are written in batches, often compressed.
- On disk a partition is a folder of segments (
00000000000000000000.logplus.indexand.timeindex). Only the newest (active) segment is written; old segments are deleted or compacted as a whole. - Speed comes from sequential appends, the OS page cache, batching and zero-copy (
sendfile) from page cache to socket.
Interview questions
- What is a partition and why does Kafka use them?
- Why is Kafka so fast even though it writes to disk?
- What is a log segment?
- How do you choose the number of partitions?
Replication, leaders, followers & ISR
Each partition has one leader and several followers; only in-sync replicas can become leader, which is how acks=all avoids data loss.
- Replication factor (RF): number of copies of each partition, usually 3. One is the leader; the rest are followers that fetch from it.
- Producers write to the leader. Consumers read from the leader by default (or the nearest follower with rack-aware fetching, KIP-392).
- ISR (in-sync replicas): leader + followers that caught up within
replica.lag.time.max.ms(30 s default). Slow followers are dropped from ISR. - High watermark (HW): highest offset copied to all ISR members. Consumers only see records below the HW, so they never read data that could be lost.
acks=allwaits for the whole current ISR.min.insync.replicas(topic/broker setting) says how small the ISR may get before writes withacks=allare rejected (NotEnoughReplicas).unclean.leader.election.enable=false(default) means an out-of-sync replica may not become leader: availability is traded for no data loss.
Interview questions
- What is the ISR and why does it matter?
- What does acks=all with min.insync.replicas=2 and RF=3 give you?
- What happens when a partition leader broker dies?
- What is unclean leader election?
KRaft: Kafka without ZooKeeper
Since Kafka 4.0, cluster metadata is managed by a Raft quorum of Kafka controllers; ZooKeeper is gone.
- Before: ZooKeeper stored metadata (brokers, topics, ACLs) and one broker acted as controller. Two systems to run and secure, and slow controller failover with many partitions.
- KRaft (KIP-500): a small quorum of controller nodes uses the Raft protocol to replicate an internal metadata log,
__cluster_metadata. - One controller is the active controller (Raft leader); the others are hot standbys. Brokers replicate the metadata log and keep it in memory.
- Nodes have
process.roles:broker,controlleror both (combined mode, fine for dev). Production usually uses dedicated controllers (3 or 5). - Kafka 4.0 (March 2025) is the first release that runs only in KRaft. ZooKeeper clusters must migrate on 3.x (3.9 is the bridge release) before upgrading.
- Kafka 4.0 also requires Java 17 for brokers and Java 11 for clients.
Interview questions
- What is KRaft and why did Kafka drop ZooKeeper?
- How do you upgrade a ZooKeeper-based cluster to Kafka 4.x?
- Why do controllers come in odd numbers?
Producers & Consumers
Producers: keys, partitioning, acks, batching, idempotence
The key decides the partition (and so ordering); acks decide durability; batching decides throughput; idempotence removes retry duplicates.
- Partitioning: explicit partition if given; else if a key exists,
murmur2(key) % numPartitions; else the built-in sticky logic fills a batch for one partition before switching (KIP-794). - Choose keys for ordering (all events of one order go to one partition) but watch for hot keys that overload one partition.
send()is async: records go into per-partition batches in a buffer; a background sender thread ships them.batch.size(16 KB default) andlinger.ms(5 ms default since 4.0) control batching.- Compression (
compression.type=gzip,snappy,lz4,zstd) is applied per batch and stays compressed on the broker. - Idempotent producer (default since 3.0): the broker gives the producer an id (PID) and checks a sequence number per partition, so a retried batch is written once and in order.
- Retries are effectively unlimited, bounded by
delivery.timeout.ms(2 minutes default). Always handle the send callback or the returned future.
Interview questions
- How does Kafka decide which partition a record goes to?
- What does the idempotent producer guarantee?
- How would you tune a producer for throughput vs latency?
- What is a hot partition and how do you fix it?
Consumers, consumer groups & rebalancing
Consumers in the same group split a topic's partitions between them; a rebalance redistributes partitions when membership changes.
- A consumer polls in a loop. It must call
poll()at least everymax.poll.interval.ms(5 min default) or it is kicked out of the group. - Within one group, each partition is assigned to exactly one member. A member can own several partitions. Extra members beyond the partition count stay idle.
- Different groups are independent: each has its own offsets and gets every record (pub/sub).
- A group coordinator (a broker) manages membership. Liveness: heartbeats within
session.timeout.ms(45 s default) and the poll-interval check. - Rebalance triggers: member joins, leaves, crashes, or the topic gets new partitions. Classic eager rebalancing revokes everything first (stop-the-world); cooperative (
CooperativeStickyAssignor) moves only what must move. - KIP-848 (GA in 4.0) moves assignment to the broker and makes it incremental; opt in with
group.protocol=consumer(the default is stillclassic). Static membership (group.instance.id) avoids rebalances on quick restarts.
Interview questions
- What is a consumer group?
- What happens if you have more consumers than partitions?
- What is a rebalance and why is it a problem?
- What is static group membership?
Offset commits & where to start reading
The committed offset is the next record a group will read after a restart; when you commit relative to processing decides loss vs duplicates.
- The consumer stores the next offset to read (last processed + 1) in the internal topic
__consumer_offsets. - Auto commit (
enable.auto.commit=true, default) commits the offsets returned by previous polls everyauto.commit.interval.ms(5 s). Safe-ish only if you finish processing before the nextpoll(). - Manual commit:
commitSync()blocks and retries;commitAsync()does not block or retry (a later commit may already have passed it). Common pattern: async in the loop, sync on shutdown/revoke. auto.offset.resetapplies when the group has no committed offset (or it was deleted):latest(default) skips history,earliestreads from the start,nonethrows.- Commit offsets in
onPartitionsRevokedof aConsumerRebalanceListenerso the next owner does not redo work. - You can also store offsets in your own database in the same transaction as the results, then
seek()on assignment. That gives effectively-once processing for DB sinks.
Interview questions
- What is the difference between commitSync and commitAsync?
- Why can auto-commit lose or duplicate messages?
- A new consumer group starts and sees no messages. Why?
- How do you replay a topic for one consumer group?
Guarantees & Data Lifecycle
Ordering guarantees
Kafka keeps order only inside one partition, so related events must share a key and you must avoid reordering on retry.
- Records in one partition are stored and read in offset order. Across partitions there is no global order.
- To keep per-entity order (all events of order #7), use the entity id as the key.
- With idempotence enabled, the producer keeps order with up to 5 in-flight requests per connection. Without it,
max.in.flight.requests.per.connection > 1plus retries can reorder batches. - Consumers break order if they process records of one partition in parallel. Parallelise by key instead (e.g. Confluent Parallel Consumer, or per-key queues).
- A single-partition topic gives global order but caps throughput to one consumer.
- RabbitMQ keeps FIFO per queue, but competing consumers, prefetch and requeue mean processing order is not guaranteed. SQS FIFO orders per message group id.
Interview questions
- Does Kafka guarantee message ordering?
- How do you keep order and still scale?
- Can retries reorder messages in Kafka?
Delivery semantics & Kafka transactions
At-most-once can lose, at-least-once can duplicate, and exactly-once needs idempotence plus transactions (or idempotent side effects).
- At-most-once: commit/ack before processing. Never duplicates; may lose messages on a crash.
- At-least-once: process, then commit. Never loses; may duplicate. The default and most common choice, combined with idempotent consumers.
- Exactly-once (EOS) in Kafka: idempotent producer + transactions. A
read → process → writeloop writes output records and the input offsets atomically. - A transactional producer has a
transactional.id.initTransactions()fences older instances with the same id (zombie producers) using an epoch. - Consumers must use
isolation.level=read_committed(default isread_uncommitted) to skip aborted data; they read up to the last stable offset (LSO). - EOS covers Kafka → Kafka. Side effects outside Kafka (emails, HTTP calls, DB writes) still need idempotency or an outbox. Kafka Streams turns it on with
processing.guarantee=exactly_once_v2.
Interview questions
- Explain at-most-once, at-least-once and exactly-once.
- How does Kafka achieve exactly-once semantics?
- What is a zombie producer and how is it fenced?
- Does Kafka exactly-once cover writing to a database?
Retention & log compaction
Delete policy drops old segments by time or size; compact policy keeps only the latest record per key.
cleanup.policy=delete(default): segments older thanretention.ms(7 days default) or beyondretention.bytes(unlimited default) are deleted.- Retention applies to closed segments, so data can live a bit longer than the setting while the active segment is open.
cleanup.policy=compact: the log cleaner keeps at least the latest value for every key. Good for changelogs, current state, and__consumer_offsetsitself.- A record with a null value is a tombstone: it marks the key as deleted and is itself removed after
delete.retention.ms(1 day default). compact,deletecombines both: keep latest per key but also drop very old keys.- Offsets never change during compaction; there are just gaps. Consumers must not assume consecutive offsets.
Interview questions
- What is log compaction and when would you use it?
- What is a tombstone in Kafka?
- Can Kafka be used as permanent storage?
Retries, poison pills & dead-letter topics
Retry transient errors with backoff, send messages that keep failing to a dead-letter topic, and never let one bad record block a partition forever.
- A poison pill is a record that always fails (bad format, bug). Endless retry blocks the partition and grows lag.
- Split errors: transient (timeout, 503, lock) → retry with backoff; permanent (deserialization, validation) → straight to the DLT.
- Blocking retry: retry in place a few times. Keeps order but stalls the partition.
- Non-blocking retry: publish to
orders-retry-1,orders-retry-2topics with increasing delays, then a dead-letter topic (DLT/DLQ). The main flow continues, but per-key order is lost. - Put the error reason, stack trace, original topic/partition/offset and attempt count in headers of the DLT record. Alert on DLT growth and provide a tool to re-drive messages.
- Built-ins: Spring Kafka
DefaultErrorHandler+DeadLetterPublishingRecovereror@RetryableTopic; Kafka Connecterrors.deadletterqueue.topic.name; RabbitMQ dead-letter exchanges; SQS redrive policy (maxReceiveCount).
Interview questions
- What is a dead-letter queue/topic?
- How do you handle a poison-pill message in Kafka?
- Blocking vs non-blocking retries?
RabbitMQ & Choosing a Broker
RabbitMQ: exchanges, queues & bindings
Producers publish to an exchange; the exchange type and bindings decide which queues get a copy; consumers read from queues.
- Model (AMQP 0-9-1): producer → exchange → (bindings) → queue → consumer. Producers never write to a queue directly.
- Direct exchange: routes when the routing key equals the binding key. The nameless default exchange is direct and binds each queue by its own name.
- Fanout: copies to every bound queue, ignoring the key. Topic: pattern match on dot-separated keys (
*= one word,#= zero or more). Headers: match on header values (x-match=all|any). - Queue types: classic (single node), quorum (Raft-replicated, the choice for durable data; classic mirroring was removed in 4.0) and streams (append-only log with replay).
- Durability needs three things: durable exchange/queue, persistent messages (
delivery_mode=2) and publisher confirms. - If nothing matches, the message is dropped unless the publisher sets
mandatory(returned) or the exchange has an alternate exchange.
Interview questions
- Explain the RabbitMQ exchange types.
- What is a binding?
- Classic vs quorum queues?
RabbitMQ acks, prefetch, confirms & DLX
Consumers ack each delivery; prefetch limits unacked messages per consumer; publisher confirms make publishing safe; DLX catches rejects.
- Consumer acks:
basic.ack(done),basic.nack/basic.rejectwithrequeue=true(put back) orfalse(drop or dead-letter). Auto-ack = at-most-once. - Unacked messages are redelivered (with
redelivered=true) if the channel/connection closes. Consumers that hold a delivery too long hitconsumer_timeout(30 min default) and the channel is closed. - Prefetch (
basic.qos): max unacked messages per consumer/channel. The protocol default0means unlimited, which can flood one consumer. Typical values are 10–300. - Publisher confirms: the broker acks a publish once it is safely stored (and replicated for quorum queues). Without them a publish can be lost silently.
- Dead-letter exchange (DLX): set
x-dead-letter-exchangeon a queue; rejected (no requeue), expired (TTL) or over-limit messages are republished there. - Quorum queues count deliveries; since 4.0 the default delivery limit is 20, after which the message is dropped or dead-lettered. This stops infinite requeue loops.
Interview questions
- What is prefetch in RabbitMQ and how do you choose it?
- What are publisher confirms?
- ack vs nack vs reject?
Kafka vs RabbitMQ vs SQS
Kafka is a replayable high-throughput log; RabbitMQ is a flexible routing broker; SQS is a fully managed, simple queue.
- Pick Kafka for event streaming, many independent consumers, replay, CDC and stream processing at high throughput.
- Pick RabbitMQ for task queues, complex routing, per-message acks/TTL/priority, request-reply and lower volume with low latency.
- Pick SQS (often with SNS for fan-out) on AWS when you want zero ops and a plain work queue.
- SQS standard: at-least-once, best-effort order, near-unlimited throughput. FIFO: ordered per message group, dedup within 5 minutes, lower throughput.
- SQS mechanics: visibility timeout (30 s default) hides a received message until it is deleted; retention 4 days default, 14 max; max message 1 MiB; long polling up to 20 s.
- Managed options: Amazon MSK / Confluent Cloud for Kafka, Amazon MQ / CloudAMQP for RabbitMQ.
Interview questions
- When would you choose Kafka over RabbitMQ?
- When would you choose RabbitMQ over Kafka?
- How does SQS visibility timeout work?
- SQS standard vs FIFO?
Patterns & Operations
Transactional outbox & CDC
Write the state change and the event to the same database in one transaction, then publish the event from there.
- Dual-write problem:
db.save(order); kafka.send(event)is two systems with no shared transaction. A crash between them leaves the DB and events inconsistent. - Outbox: insert the event into an
outboxtable in the same local transaction as the business change. Either both commit or neither does. - A relay publishes outbox rows: either a poller (
SELECT … WHERE published_at IS NULL) or CDC that tails the DB log (Debezium + its outbox event router). - The relay may publish a row twice (crash after send, before marking), so it is at-least-once. Consumers must be idempotent; include a unique event id.
- Use the aggregate id as the Kafka key so events for one entity stay ordered.
- Clean the table regularly (delete published rows) or let CDC read inserts and delete immediately.
Interview questions
- What is the dual-write problem?
- How does the transactional outbox pattern work?
- Polling publisher vs CDC for the outbox?
Idempotent consumers
Since at-least-once delivery means duplicates, make handling a message twice have the same effect as handling it once.
- Duplicates come from producer retries without idempotence, consumer crashes before commit, rebalances, outbox relays and SQS visibility timeouts.
- Naturally idempotent operations:
SET status = 'PAID', upserts, deletes by id. Not idempotent:balance = balance + 50, sending an email, inserting with a generated id. - Dedup table: store each processed message id with a unique constraint, in the same DB transaction as the side effect. A duplicate insert fails, so you skip the work.
- Version checks: carry an aggregate version or sequence; ignore events with a version ≤ the one already applied.
- For external calls, pass an idempotency key to the downstream API (most payment APIs support this).
- Expire dedup rows after a window longer than the maximum redelivery delay to keep the table small.
Interview questions
- What is an idempotent consumer and why do you need one?
- How do you implement idempotency for a 'credit account' event?
- Can you rely on Kafka's idempotent producer instead?
Saga, event sourcing & CQRS
A saga replaces a distributed transaction with local steps plus compensations; event sourcing stores events as the source of truth; CQRS splits write and read models.
- Saga: a business transaction across services is a sequence of local transactions. If a step fails, run compensating actions for completed steps (refund, release stock).
- Choreography: services react to each other's events; no central brain. Simple for 2–4 steps, hard to follow as it grows.
- Orchestration: a saga orchestrator (state machine, e.g. Temporal, Camunda or a custom service) sends commands and tracks state. Easier to reason about and monitor.
- Sagas give ACD without I: other transactions can see intermediate state. Use semantic locks (status
PENDING), commutative updates or re-reads. - Event sourcing: store every state change as an immutable event; current state = fold of the events. Gives audit trail and time travel; needs snapshots and event versioning.
- CQRS: separate the command (write) model from query (read) models. Read models are projections updated from events, so they are eventually consistent.
Interview questions
- What is the saga pattern and why use it instead of 2PC?
- Choreography vs orchestration sagas?
- What is event sourcing?
- What is CQRS and does it require event sourcing?
Schemas: Schema Registry, Avro & Protobuf
Messages are a contract; a schema registry stores versioned schemas and enforces compatibility so producers can evolve without breaking consumers.
- Without schemas, a renamed JSON field silently breaks consumers. Schemas make the contract explicit and payloads compact.
- Schema Registry (Confluent, Apicurio, AWS Glue): stores schemas per subject (by default
<topic>-value), assigns ids and checks compatibility on register. - Wire format (Confluent): magic byte
0+ 4-byte schema id + binary payload. Consumers fetch and cache the schema by id. - Avro: JSON-defined schema, compact binary, reader/writer schema resolution; add fields with defaults for safe evolution.
- Protobuf: field numbers identify fields; never reuse or change a number, mark removed ones
reserved. Adding fields is safe. - Compatibility modes: BACKWARD (default; new schema reads old data, upgrade consumers first), FORWARD (old schema reads new data, upgrade producers first), FULL (both), plus
_TRANSITIVEvariants andNONE.
Interview questions
- Why use a schema registry with Kafka?
- Backward vs forward compatibility?
- Avro vs Protobuf vs JSON for events?
Backpressure & monitoring consumer lag
When consumers can't keep up, slow the intake instead of falling over, and watch lag per partition to catch it early.
- Backpressure = a slow consumer can signal or force the producer side to slow down. Brokers give natural buffering, but buffers are finite.
- Kafka is pull-based: the consumer only takes what it asks for (
max.poll.records,fetch.max.bytes). Usepause()/resume()on partitions when internal queues are full, while still callingpoll(). - RabbitMQ: prefetch bounds in-flight work; when memory/disk alarms fire, the broker blocks publishers (flow control). Queue length limits can reject or dead-letter overflow.
- Producer side:
buffer.memoryfull →send()blocks up tomax.block.ms, then throws. Broker quotas can throttle clients. - Consumer lag per partition = log-end offset − committed offset. Watch both the value and the trend; constant lag is fine, rising lag is not.
- Tools:
kafka-consumer-groups.sh --describe, consumer metricrecords-lag-max, Burrow, Prometheus exporters, Confluent Control Center / cloud consoles. Alert on lag in time (seconds behind) where possible.
Interview questions
- What is consumer lag and how do you monitor it?
- Lag keeps growing. How do you troubleshoot?
- How do you implement backpressure in a Kafka consumer?
- How does RabbitMQ apply backpressure?