{}DSA Atlas

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.

Intermediate → Advanced7 interview questions

Why asynchronous messaging?

Synchronous: user waits for everything API payment email invoice PDF analytics 2.5 s Asynchronous: respond after the essential step API payment OrderPlaced event email worker invoice worker analytics consumer 300 ms
Do the essential work synchronously; publish an event for everything else.

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

ModelSemanticsExamples
Point-to-point queueeach message processed by one consumer (competing consumers)SQS, RabbitMQ queues, Celery/Sidekiq
Pub/subeach message delivered to every subscriptionSNS, Google Pub/Sub, RabbitMQ fanout, Redis pub/sub (no durability)
Log / streamdurable ordered log; consumers track their own position; replayableKafka, Kinesis, Pulsar, Redpanda, Redis Streams

Kafka in depth

producer producer topic: orders (3 partitions) P0 P1 P2 offset 0 → 4 (append-only) group: billing consumer A ← P0, P1 consumer B ← P2 group: analytics consumer X ← P0,P1,P2 same key → same partition → ordered · each group reads independently at its own offset
Partitions give parallelism and per-key ordering; consumer groups give both load sharing and pub/sub.
ConceptDetail
Topicnamed stream of records
Partitionordered log; unit of parallelism and ordering
Offsetposition of a record in a partition
Keydetermines the partition (hash(key) % partitions)
Brokerserver storing partitions; leader per partition handles reads/writes
Replicationreplication.factor=3; followers in the ISR; acks=all + min.insync.replicas=2 for durability
Consumer grouppartitions split among members; scale up to #partitions
Retentionby time/size; log compaction keeps the latest record per key
KRaftRaft-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.

Python
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

RabbitMQSQS (standard / FIFO)Kafka
Modelbroker with exchanges → queuesmanaged queuedistributed log
Deliverypush to consumers, ack per messagepull, visibility timeoutpull by offset
Retention after consumedeleteddeletedkept (replayable)
Orderingper queue (single consumer)none / per message groupper partition
Routingrich (topic, headers, fanout)via SNS filtersby topic/partition
Throughput10k–100k msg/seffectively unlimited (standard); FIFO limited (~3k–30k/s with batching/high-throughput mode)millions msg/s
Opsself-hosted or managedzeroself-hosted or managed (MSK, Confluent)

Delivery semantics

At most onceack → processcrash = message lost At least onceprocess → ackcrash = duplicate Effectively onceat-least-once+ idempotent processing design every consumer as if it will see each message more than once
Default to at-least-once delivery with idempotent consumers.

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

main topic consumer retry-1m retry-10m retry-1h DLQ → alert, inspect, redrive non-retryable errors go straight to the DLQ
Back off with delayed retry queues; park poison messages instead of blocking the partition.

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

ChoreographyOrchestration
Controlservices react to eventsa coordinator tells services what to do
Couplingloosecoordinator knows the flow
Visibilityflow is implicit, spread outexplicit, one place (Temporal, Step Functions)
Best forsimple fan-out reactionsmulti-step business processes with compensations (sagas)

Event sourcing

Text
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

commands write model write DB / events projector → SQL views projector → search index projector → cache queries read API read models are eventually consistent and rebuildable from events
Commands and queries use different models, each optimised for its job.

Stream processing

Process events continuously: windowed aggregations (clicks per minute), joins between streams, enrichment, anomaly detection.

EngineNotes
Kafka Streamslibrary inside your service; exactly-once with Kafka transactions
Apache Flinkstateful stream processing, event-time windows, watermarks, savepoints
Spark Structured Streamingmicro-batches, unified with batch
ksqlDB / RisingWave / Materializestreaming 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

0 / 7 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.