Message Queues & Event Streaming
- Choose between a message queue (RabbitMQ, SQS) and a log (Kafka) for a given workload
- Explain at-most-once, at-least-once and "exactly-once", and build an idempotent consumer
- Design partitioning and ordering keys so per-account or per-order events stay in order while the system scales
- Design retries, dead-letter queues and backpressure, and configure Kafka for no data loss on a payments topic
TL;DR
- A queue hands each message to one consumer and deletes it on acknowledgement — ideal for distributing tasks. A log appends messages durably; each consumer group tracks its own offset and can replay — ideal for event streams with many independent consumers.
- In practice you get at-least-once delivery. "Exactly-once" exists only inside a closed system (for example Kafka transactions for read-process-write); end to end you need idempotent consumers.
- Ordering is per partition (or per message group). Choose the key so that events that must stay ordered — all events for one account or one order — share it.
- Parallelism in a consumer group is capped by the partition count; plan partitions up front because changing them remaps keys.
- Retries need backoff and a cap; poison messages go to a DLQ with enough context to fix and replay them, and someone must own that DLQ.
- Backpressure: consumers pull at their own pace; watch consumer lag and act on it (scale, shed, or slow producers).
- For money:
replication.factor=3,min.insync.replicas=2,acks=all, idempotent producer, no unclean leader election — and publish via a transactional outbox.
Why it matters
- E-commerce:
OrderPlacedfans out to inventory reservation, payment, notifications, loyalty, search indexing and analytics. During a sale the broker absorbs bursts that downstream services process at their own pace. Mis-keyed partitions mean "OrderCancelled" is processed before "OrderPaid". - Banking: card authorizations and transfers produce events consumed by the ledger poster, fraud features, notifications (SMS/push), AML monitoring and the data warehouse. A duplicate
TransferCompletedprocessed twice by a non-idempotent consumer sends two SMS messages (annoying) or posts two ledger entries (a reconciliation incident). - Interviews: "How do services communicate?" and "What if the consumer crashes after processing but before acknowledging?" are near-guaranteed questions.
Core concepts
Queue vs log
| Queue (RabbitMQ, SQS) | Log (Kafka, Pulsar, Kinesis) | |
|---|---|---|
| Model | Messages consumed and removed | Append-only, retained for a period or compacted |
| Consumers | Competing consumers share work | Each group reads everything independently |
| Replay | No (once acked, gone) | Yes, by resetting offsets |
| Ordering | Best effort (SQS standard), per queue with one consumer, per group (SQS FIFO) | Strict per partition |
| Per-message ack | Yes; failed messages can be redelivered individually | Offset commits per partition; one stuck message blocks the partition |
| Routing | Rich (RabbitMQ exchanges: direct, topic, fanout, headers) | Topic + key → partition |
| Delay / priority | Supported (delay queues, priorities, TTLs) | Not native; build with retry topics |
| Throughput | High | Very high, sequential I/O |
| Good for | Task distribution, jobs, RPC-style async work | Event streams, CDC, event sourcing, many consumers, stream processing |
Rule of thumb: use a queue for commands and jobs ("send this SMS", "generate this statement"), use a log for facts that many parties care about ("payment captured", "order shipped"). Many companies run both.
Delivery semantics
| Semantics | How you get it | Failure behaviour |
|---|---|---|
| At-most-once | Ack/commit before processing | Crash mid-processing loses the message |
| At-least-once | Ack/commit after processing | Crash after processing redelivers → duplicates |
| Exactly-once (effectively-once) | At-least-once + idempotent processing, or a transactional system | Duplicates are delivered but have no extra effect |
- Kafka's exactly-once semantics (EOS) cover read-from-Kafka → process → write-to-Kafka with transactions and idempotent producers (used by Kafka Streams). As soon as the side effect is an external database, SMS gateway or partner API, you are back to at-least-once plus idempotency.
- SQS FIFO deduplicates by message deduplication id within a fixed window — useful, but bounded in time and scope.
- The durable pattern is an idempotent consumer: record processed message ids in the same transaction as the side effect, or make the side effect naturally idempotent (upsert by business key, conditional update by version). See Idempotency & Exactly-Once.
Consumer groups and partitions
- A topic is split into partitions; each partition is an ordered log.
- In a consumer group, each partition is assigned to exactly one consumer at a time; one consumer may own several partitions. So max useful parallelism = number of partitions.
- When consumers join, leave or stall, the group rebalances: partitions move between consumers. Older "eager" rebalancing paused the whole group; cooperative/incremental protocols move only what is needed. A consumer that takes longer than
max.poll.interval.msbetween polls is considered dead and triggers a rebalance — slow processing can cause rebalance storms. - Consumer lag (latest offset − committed offset) is the key health metric: it tells you how far behind real time each group is.
Partitions and ordering keys
The producer chooses a partition by hashing the message key (or round-robin if there is no key). All messages with the same key go to the same partition and are therefore ordered.
| Use case | Key | Why |
|---|---|---|
| Account events (debits, credits, holds) | account_id | Balance-affecting events per account must apply in order |
| Order lifecycle | order_id | Created → Paid → Shipped → Cancelled must not be reordered |
| Customer notifications | customer_id | Avoid "delivered" arriving before "shipped" |
| Clickstream analytics | none / session_id | Order rarely matters; spread load evenly |
Things that silently break ordering:
- Changing the partition count — keys remap to new partitions (see Consistent Hashing).
- Producer retries without idempotence — a retried batch can land after a later one. Kafka's idempotent producer (on by default in recent versions) prevents this per partition.
- Parallel processing inside a consumer — fanning one partition out to a goroutine pool processes messages out of order unless you sub-partition by key in memory.
- Non-blocking retry topics — a failed message moved to a retry topic lets later messages for the same key overtake it.
- Hot keys — ordering by
merchant_idputs a mega-merchant's entire stream on one partition, which then lags.
Global ordering across all messages requires a single partition, i.e. no parallelism. Almost no business really needs it; per-entity ordering is enough.
Retries and dead-letter queues
- Classify errors. Transient (timeout, 503, lock conflict) → retry with exponential backoff and jitter. Permanent (schema violation, unknown account, business-rule rejection) → straight to DLQ; retrying will never help.
- Blocking vs non-blocking retries. Retrying in place preserves ordering but blocks the whole partition behind one bad message. Moving the message to a retry topic unblocks the partition but breaks per-key ordering. For ordered financial streams, a common compromise is to block for a short bounded time, then park the message and mark the key as "blocked" so later messages for the same key are parked too.
- Dead-letter queue content: the original payload, key, headers, source topic/partition/offset, error, attempt count and timestamps. Broker support differs: SQS has a redrive policy (
maxReceiveCount), RabbitMQ has dead-letter exchanges, Kafka leaves DLQs to the application or framework. - Someone owns the DLQ. Alert on DLQ depth, have a tool to inspect, fix and redrive messages, and track them to closure. For payment events, an unprocessed DLQ entry is an open reconciliation item (see Reconciliation & Settlement).
Backpressure
A broker decouples producer and consumer rates, but not forever:
- Pull-based consumption (Kafka, SQS) is natural backpressure: consumers fetch only what they can handle. Bound in-process buffers and worker pools; never read into an unbounded channel.
- Prefetch limits (RabbitMQ
basic.qos, Kafkamax.poll.records) cap unacknowledged work per consumer. - Lag-based autoscaling (for example KEDA on Kubernetes) adds consumers when lag grows — up to the partition count.
- Producer-side limits: broker quotas, bounded producer buffers that block or fail fast, and rate limits upstream.
- Decide what lag means for the business. Lag on analytics is fine; lag on fraud features or payment notifications is an incident. Define lag SLOs per consumer group, and shed or degrade non-critical consumers first.
Kafka internals in one page
- Partitions are stored as segment files; writes are sequential appends, reads are mostly sequential — that and the OS page cache are why Kafka is fast.
- Each partition has a leader and followers. Followers that are caught up form the ISR (in-sync replicas). A message is committed once all ISR members have it; consumers only see committed messages (up to the high watermark).
acks:0(fire and forget),1(leader wrote it; lost if the leader dies before followers copy it),all(all ISR have it).min.insync.replicas: withacks=all, the write fails if fewer than this many replicas are in sync.replication.factor=3+min.insync.replicas=2tolerates one broker down without losing acknowledged writes.unclean.leader.election.enable=false: never elect an out-of-sync replica as leader (which would silently drop committed messages). Availability gives way to durability — the right choice for payments.- Idempotent producer: the broker deduplicates retried batches using a producer id and sequence numbers. Transactions let a producer write to several partitions atomically and commit consumer offsets in the same transaction (the basis of Kafka EOS).
- Retention: delete segments older than a time or beyond a size; consumers that fall further behind than retention lose data.
- Log compaction: keep at least the latest record per key, delete older ones; a record with a null value (tombstone) deletes the key. Good for changelogs and "current state" topics (customer profile, product price), not for an audit trail.
- Consumer offsets are stored in an internal topic (
__consumer_offsets). - Metadata: Kafka historically used ZooKeeper; modern versions use the built-in Raft-based KRaft controller, and recent major versions removed ZooKeeper entirely.
Publishing reliably: the outbox
Writing to the database and publishing to the broker are two systems; if you do both in the request handler, a crash between them creates a paid order with no event, or an event for an order that rolled back. The transactional outbox writes the event into an outbox table in the same DB transaction, and a relay (or CDC) publishes it. Details in Transactional Outbox & CDC.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| RabbitMQ | Flexible routing, per-message ack, priorities, delays, quorum queues | Lower throughput than a log, no replay once acked | Task distribution, workflows, request/reply |
| Amazon SQS | Fully managed, scales automatically, DLQ built in | Limited ordering (FIFO has throughput limits), no replay, AWS-only | Cloud job queues, decoupling Lambda/ECS workers |
| Kafka | Very high throughput, replay, many consumer groups, compaction, stream processing ecosystem | Operational complexity, per-partition head-of-line blocking, no native delay/DLQ | Event streaming, CDC, analytics, event-driven architectures |
| Pulsar / Kinesis / NATS JetStream | Varying mixes of queue and log features | Smaller ecosystems or vendor lock-in | Specific fit (multi-tenancy, managed AWS, lightweight) |
| At-most-once | Simplest, no duplicates | Data loss | Metrics, logs where loss is acceptable |
| At-least-once + idempotent consumer | No loss, duplicates harmless | Dedup storage and discipline | Default for business events |
| Kafka transactions (EOS) | Exactly-once within Kafka pipelines | Only Kafka-to-Kafka, extra latency | Stream processing aggregates |
| Blocking retries | Preserves ordering | Head-of-line blocking | Strictly ordered financial streams, short outages |
| Retry topics | Partition keeps flowing | Breaks per-key ordering | Independent messages (notifications) |
In practice
- Partition count: estimate peak throughput ÷ per-partition consumer throughput, then add headroom; for example 20k msg/s ÷ 1k msg/s per consumer ≈ 20, choose 32 or 48. More partitions mean more open files, longer leader elections and more rebalance work — do not create thousands "just in case".
- Schemas: use Avro or Protobuf with a schema registry and backward-compatible evolution. An event is a public contract (see Event-Driven Architecture, CQRS & Event Sourcing).
- Message size: keep messages small (KBs). For large payloads (statement PDFs, KYC images) publish a reference to object storage — the claim-check pattern.
- Headers: include
event_id(for dedup),correlation_id,causation_id, event type and schema version. - Payments topic configuration (Kafka):
replication.factor=3
min.insync.replicas=2
unclean.leader.election.enable=false
# producer
acks=all
enable.idempotence=true
# consumer
enable.auto.commit=false # commit only after successful processing
isolation.level=read_committed
- An idempotent at-least-once consumer in Go (using
segmentio/kafka-go): the dedup insert and the side effect share one database transaction, and the offset is committed only afterwards.
package ledgerposter
import (
"context"
"database/sql"
"errors"
"fmt"
"log"
"github.com/segmentio/kafka-go"
)
var ErrPermanent = errors.New("permanent failure")
func Run(ctx context.Context, r *kafka.Reader, dlq *kafka.Writer, db *sql.DB) error {
for {
m, err := r.FetchMessage(ctx) // does not commit
if err != nil {
return err // context cancelled or reader closed
}
err = withRetry(ctx, 5, func() error { return handle(ctx, db, m) })
if err != nil {
// Exhausted retries or permanent error: park it with context.
dl := kafka.Message{Key: m.Key, Value: m.Value, Headers: append(m.Headers,
kafka.Header{Key: "error", Value: []byte(err.Error())},
kafka.Header{Key: "source", Value: []byte(fmt.Sprintf("%s/%d/%d", m.Topic, m.Partition, m.Offset))},
)}
if werr := dlq.WriteMessages(ctx, dl); werr != nil {
return werr // do not commit; message will be redelivered
}
log.Printf("parked offset %d: %v", m.Offset, err)
}
if err := r.CommitMessages(ctx, m); err != nil {
return err
}
}
}
func handle(ctx context.Context, db *sql.DB, m kafka.Message) error {
eventID := header(m, "event_id")
if eventID == "" {
return fmt.Errorf("%w: missing event_id", ErrPermanent)
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback() // no-op after Commit
res, err := tx.ExecContext(ctx,
`INSERT INTO processed_events (consumer, event_id) VALUES ('ledger-poster', $1)
ON CONFLICT DO NOTHING`, eventID)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return tx.Commit() // duplicate delivery: already applied
}
if err := postEntries(ctx, tx, m.Value); err != nil {
return err
}
return tx.Commit()
}
func header(m kafka.Message, key string) string {
for _, h := range m.Headers {
if h.Key == key {
return string(h.Value)
}
}
return ""
}
// withRetry and postEntries omitted: exponential backoff with jitter that stops
// early on ErrPermanent, and the double-entry insert for the event.
func withRetry(ctx context.Context, attempts int, fn func() error) error { return fn() }
func postEntries(ctx context.Context, tx *sql.Tx, payload []byte) error { return nil }
Common pitfalls
- Auto-commit before processing. Symptom: after a consumer crash, some orders never get confirmation emails or ledger entries; no error anywhere.
- Non-idempotent consumers. Symptom: duplicate SMS, duplicate loyalty points, double ledger postings after a rebalance or redeploy.
- Fanning out one partition to a worker pool and committing the highest offset. Symptom: a crash skips messages that were still in flight.
- Slow processing exceeding
max.poll.interval.ms. Symptom: endless rebalances, lag grows, the same messages processed repeatedly. - Hot partition from a skewed key. Symptom: one partition's lag grows while others are idle; adding consumers does not help.
- Increasing partitions on a keyed topic in production. Symptom: brief ordering violations for in-flight keys.
- Unowned DLQ. Symptom: thousands of parked payment events discovered at month-end reconciliation.
- Huge messages. Symptom: broker memory pressure, consumer timeouts, replication lag. Use claim checks.
acks=1on a money topic. Symptom: rare, unexplained missing events after a broker failover.- Dual write instead of outbox. Symptom: events for rolled-back orders, or paid orders with no event.
Interview angle
- Where it appears: any event-driven or asynchronous design — order platforms, payment systems, notification systems, fraud pipelines, CDC into search.
- Strong answer covers: queue vs log choice with reasons; delivery semantics and an idempotency strategy; ordering key and partition count; retry/DLQ policy; durability settings; lag monitoring; how events are published atomically with DB changes.
- Follow-ups: "What if the consumer crashes after writing to the DB but before committing the offset?", "How do you keep events for one account in order?", "What happens when you add partitions?", "A message keeps failing — what now?", "How do you guarantee no loss if a broker dies?", "Exactly-once — really?"
- Red flags: claiming exactly-once delivery end to end without idempotency; global ordering as a requirement; no DLQ story; publishing to Kafka inside a DB transaction and calling it atomic.
Self-check
1. When do you choose RabbitMQ or SQS over Kafka, and vice versa?
Queues fit task distribution: each job processed by one worker, per-message ack and redelivery, delays and priorities, no need for replay — for example sending notifications or generating statements. Kafka fits event streams consumed by many independent groups, needs replay or reprocessing, high throughput, CDC and stream processing — for example PaymentCaptured consumed by ledger, fraud, notifications and analytics.
2. The ledger consumer crashes after committing its DB transaction but before committing the Kafka offset. What happens and how do you make it safe?
On restart the message is redelivered, so the consumer would post the entries again. Make the consumer idempotent: insert the event id into a processed_events table in the same transaction as the ledger entries, and skip if it already exists. Then redelivery is harmless and the offset commit can safely lag.
3. Why is parallelism in a Kafka consumer group capped, and how do you pick the partition count?
Each partition is consumed by at most one member of the group, to preserve per-partition order. So more consumers than partitions sit idle. Choose partitions from target peak throughput divided by per-consumer throughput, with headroom for growth, because increasing partitions later remaps keys and disturbs ordering.
4. Scenario: events for account A arrive as Debit 100, Debit 50; the first fails transiently. You use retry topics. What goes wrong and what do you do instead?
The first debit moves to a retry topic while the second is processed, so the order is inverted — the second may be rejected for insufficient funds or the balance history becomes wrong. For balance-affecting streams, retry in place (blocking the partition briefly), or when parking a message also park all later messages for that key until it is resolved, preserving per-account order.
5. Which Kafka settings prevent losing an acknowledged payment event when a broker fails?
replication.factor=3, min.insync.replicas=2, producer acks=all and idempotence enabled, and unclean.leader.election.enable=false. A write is acknowledged only after at least two in-sync replicas have it, and an out-of-sync replica is never elected leader. Producers must also handle send errors (retry or fail the outbox relay), not ignore them.
6. What is log compaction good for, and why is it wrong for an audit trail?
Compaction keeps only the latest record per key, so a compacted topic acts like a durable key-value changelog — ideal for rebuilding current state (product prices, customer profiles, Kafka Streams state stores). An audit trail must keep every event; compaction deletes history, so audit topics use time-based retention (or are archived) instead.
7. Consumer lag on the fraud-features group is growing during a sale. Walk through your response.
Check whether lag is on all partitions (capacity) or a few (hot key or a stuck message). For capacity, scale consumers up to the partition count and look for slow downstream calls. For a hot key, consider sub-keying or isolating that entity. For a stuck message, check retries/DLQ. Meanwhile shed non-critical consumers, and if fraud scoring must stay real-time, degrade gracefully (fallback rules) rather than letting decisions use stale features.
Exercise
- Start a 3-broker Kafka cluster (Docker Compose) and create
paymentswith 6 partitions, RF 3,min.insync.replicas=2. - Write a Go producer that publishes 100k
PaymentCapturedevents keyed byaccount_idwith anevent_idheader, and the idempotent consumer above writing to PostgreSQL. - While consuming, kill the consumer with
kill -9several times and kill one broker. Verify: theprocessed_eventscount equals 100k exactly, and for every account the ledger rows are in event order. - Inject a poison message (invalid payload) and confirm it lands in
payments.dlqwith source offset and error headers while the partition keeps flowing.
Done looks like: a short report with counts before/after failures, a query proving per-account ordering, and the DLQ record.
Further reading
- Kafka: The Definitive Guide, 2nd ed. (Shapira, Palino, Sivaram, Petty), chapters on reliability, consumers and exactly-once.
- Apache Kafka documentation: design, replication, producer and consumer configuration (kafka.apache.org/documentation).
- Jay Kreps, "The Log: What every software engineer should know about real-time data's unifying abstraction" (LinkedIn Engineering, 2013).
- Designing Data-Intensive Applications (Kleppmann), Ch. 11 "Stream Processing".
- Enterprise Integration Patterns (Hohpe & Woolf) — dead letter channel, claim check, competing consumers, idempotent receiver.
- System Design Interview, Vol. 2 (Xu & Lam), Ch. 4 "Distributed Message Queue".
- RabbitMQ documentation: quorum queues, dead lettering, consumer prefetch; AWS SQS developer guide.
Related
- Transactional Outbox & CDC — publishing events atomically with DB writes.
- Idempotency & Exactly-Once — the consumer side of correctness.
- Event-Driven Architecture, CQRS & Event Sourcing — what to build on top of the broker.
- Batch & Stream Processing — processing the streams.
- Distributed Transactions: 2PC, TCC, Saga — sagas coordinated through messages.
- Notification System — queues in a classic design.
- Payment System — events in a payment flow.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).