Queues, Streams & Event-Driven Architecture
Why asynchrony, message queues vs pub/sub vs logs, Kafka internals (topics, partitions, offsets, consumer groups, replication), RabbitMQ and SQS, delivery semantics and exactly-once, ordering, retries and dead-letter queues, backpressure, the outbox pattern, event sourcing, CQRS, and stream processing.
Why asynchronous messaging?
Benefits: lower latency, decoupling, load levelling, fan-out, failure isolation (the email service being down doesn't fail checkout), independent scaling of consumers.
Messaging models
| Model | Semantics | Examples |
|---|---|---|
| Point-to-point queue | each message processed by one consumer (competing consumers) | SQS, RabbitMQ queues, Celery/Sidekiq |
| Pub/sub | each message delivered to every subscription | SNS, Google Pub/Sub, RabbitMQ fanout, Redis pub/sub (no durability) |
| Log / stream | durable ordered log; consumers track their own position; replayable | Kafka, Kinesis, Pulsar, Redpanda, Redis Streams |
Kafka in depth
| Concept | Detail |
|---|---|
| Topic | named stream of records |
| Partition | ordered log; unit of parallelism and ordering |
| Offset | position of a record in a partition |
| Key | determines the partition (hash(key) % partitions) |
| Broker | server storing partitions; leader per partition handles reads/writes |
| Replication | replication.factor=3; followers in the ISR; acks=all + min.insync.replicas=2 for durability |
| Consumer group | partitions split among members; scale up to #partitions |
| Retention | by time/size; log compaction keeps the latest record per key |
| KRaft | Raft-based metadata quorum (ZooKeeper removed in Kafka 4.0) |
Why it's fast: sequential disk I/O, page cache, zero-copy sendfile, batching and compression, partition parallelism.
from confluent_kafka import Producer, Consumer
p = Producer({"bootstrap.servers": "kafka:9092", "enable.idempotence": True, "acks": "all"})
p.produce("orders", key="ord_981", value=b'{"event":"OrderPlaced","total":99800}')
p.flush()
c = Consumer({"bootstrap.servers": "kafka:9092", "group.id": "billing",
"enable.auto.commit": False, "auto.offset.reset": "earliest"})
c.subscribe(["orders"])
while True:
msg = c.poll(1.0)
if msg is None or msg.error():
continue
handle_idempotently(msg.key(), msg.value()) # dedupe by event id
c.commit(message=msg) # commit AFTER processing → at-least-once
RabbitMQ and SQS in brief
| RabbitMQ | SQS (standard / FIFO) | Kafka | |
|---|---|---|---|
| Model | broker with exchanges → queues | managed queue | distributed log |
| Delivery | push to consumers, ack per message | pull, visibility timeout | pull by offset |
| Retention after consume | deleted | deleted | kept (replayable) |
| Ordering | per queue (single consumer) | none / per message group | per partition |
| Routing | rich (topic, headers, fanout) | via SNS filters | by topic/partition |
| Throughput | 10k–100k msg/s | effectively unlimited (standard); FIFO limited (~3k–30k/s with batching/high-throughput mode) | millions msg/s |
| Ops | self-hosted or managed | zero | self-hosted or managed (MSK, Confluent) |
Delivery semantics
Ordering
- Global ordering kills parallelism — avoid needing it.
- Per-key ordering: partition by entity key (Kafka key, SQS FIFO message group ID).
- Retries can reorder (a failed message retried later while newer ones succeed) → use per-key retry queues, or version numbers in events so consumers ignore stale updates.
Retries, DLQs and poison messages
Patterns
Transactional outbox
Write the event to an outbox table in the same transaction as the state change; a relay/CDC publishes it. See Backend concurrency.
Event-driven choreography vs orchestration
| Choreography | Orchestration | |
|---|---|---|
| Control | services react to events | a coordinator tells services what to do |
| Coupling | loose | coordinator knows the flow |
| Visibility | flow is implicit, spread out | explicit, one place (Temporal, Step Functions) |
| Best for | simple fan-out reactions | multi-step business processes with compensations (sagas) |
Event sourcing
Account 42 event stream
1 AccountOpened {owner: "asha"}
2 MoneyDeposited {amount: 10000}
3 MoneyWithdrawn {amount: 2500}
4 MoneyDeposited {amount: 4000}
state = fold(events) → balance 11500 (snapshot every N events)
CQRS
Stream processing
Process events continuously: windowed aggregations (clicks per minute), joins between streams, enrichment, anomaly detection.
| Engine | Notes |
|---|---|
| Kafka Streams | library inside your service; exactly-once with Kafka transactions |
| Apache Flink | stateful stream processing, event-time windows, watermarks, savepoints |
| Spark Structured Streaming | micro-batches, unified with batch |
| ksqlDB / RisingWave / Materialize | streaming SQL |
Key concepts: event time vs processing time, windows (tumbling, sliding, session), watermarks for late data, state stores with checkpoints, exactly-once via transactional sinks.
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.