Interview conceptSystem Design

Message Queues And Event Streams

Asked of: Software Engineer

Last updated

Editorial architecture diagram comparing a work queue and durable event stream, showing partitions, replication, offsets, retries, backpressure, and dead-letter handling.

What's being tested

These designs test whether you can turn throughput, latency, ordering, durability, and delivery guarantees into explicit system requirements and then map them to storage, partitioning, replication, and consumer-state decisions. You should be able to reason about failures—broker loss, consumer crashes, retries, duplicates, poison messages, and backpressure—without claiming stronger guarantees than the implementation provides. General cares because reliable event-driven services support billing, notifications, workflows, and operational automation where lost or duplicated events can create user-visible or financial harm.

Core knowledge

  • Queue versus event stream: A work queue usually removes or hides a message after acknowledgement, while a stream retains an ordered log for a configured period so multiple consumer groups can replay independently. Kafka is stream-oriented; SQS is queue-oriented.
  • Partitioning converts one topic into independent ordered lanes. Hash a stable key such as account_id to preserve per-account order, but recognize that a hot key can overload one partition; global ordering sacrifices throughput and availability.
  • Offsets identify a consumer’s position, typically per partition. Commit an offset only after successful processing; committing first risks loss, while processing first risks duplicates after a crash. Store offsets durably and make handlers idempotent.
  • Delivery semantics are usually at-most-once, at-least-once, or effectively-once. True end-to-end exactly-once is difficult across external side effects; prefer an idempotency key, deduplication table, or transactional outbox over presenting “exactly once” as a broker-only feature.
  • Replication and durability require a leader plus followers or quorum writes. Acknowledging after one local disk write minimizes latency but risks loss; waiting for a majority improves durability. Define behavior when replicas lag, leaders fail, or an availability zone disappears.
  • Consumer backpressure prevents a fast producer from overwhelming slow consumers. Bound in-memory buffers, expose lag, pause or throttle fetches, and apply admission control; an unbounded queue merely converts overload into an eventual out-of-memory failure.
  • Retries and poison messages need bounded attempts, exponential backoff with jitter, and a dead-letter queue. Preserve the original payload and failure metadata, distinguish transient from permanent errors, and avoid retry storms that amplify an outage.
  • Throughput and latency should be estimated quantitatively: required partitions are roughly ⌈peak messages/sec/ sustainable messages/sec per partition⌉\lceil \text{peak messages/sec} / \text{ sustainable messages/sec per partition} \rceil, then increased for consumer parallelism and failover headroom. Track p50, p95, and p99, not averages alone.
  • Time-window aggregation maintains counters keyed by dimensions and window, such as (campaign, minute). Tumbling windows are simple; sliding windows cost more state. Late events require a lateness policy, watermark, correction, or reconciliation job rather than silently corrupting billing.
  • Scheduling delayed work commonly uses a durable min-heap, timing wheel, or bucketed time index. A timing wheel offers near-O(1)O(1) scheduling for bounded precision; shards and leases let multiple workers claim due tasks without double execution.
  • Ordering and concurrency must be stated precisely: total topic order, partition order, per-key order, or no order. Parallel consumers improve throughput but can complete messages out of order; sequence numbers or per-key serial execution are needed when order matters.
  • Observability and operations include publish latency, broker disk utilization, consumer lag, retry rate, dead-letter volume, rebalance duration, replication lag, and oldest-message age. Alert on customer-impacting symptoms, and design retention, replay, schema evolution, and capacity expansion before production traffic arrives.

Worked example: Design a distributed message queue

I would first clarify peak and sustained publish/consume rates, message size, retention, acceptable loss, ordering scope, delivery semantics, replay needs, and whether consumers belong to independent groups. I would declare an initial design of topics split into hash-partitioned logs, replicated across availability zones, with producers receiving acknowledgements after a configurable durability quorum. I would organize the answer around four pillars: broker storage and partition leadership, producer routing and acknowledgements, consumer offsets and retry handling, and observability plus operational recovery. Each consumer group would track a separate offset per partition, allowing independent replay while preserving order within a partition. I would explicitly choose at-least-once delivery and require idempotent consumers because broker-level exactly-once cannot cover arbitrary database or API side effects. I would discuss rebalancing, bounded fetch buffers, lag-based autoscaling, dead-letter handling, and retention-based replay. A key tradeoff is partition count: more partitions increase parallelism and failover flexibility but add metadata, coordination, and ordering complexity. I would close by saying that, with more time, I would load-test partition throughput, model zone-loss behavior, and specify the schema/versioning and migration strategy.

A second angle

For Design an ad click event aggregation system for real-time reporting and billing, the central issue shifts from replayable delivery to correct aggregation under duplicates, late arrivals, and financial reconciliation. I would separate the immutable click stream from materialized minute, hour, and day aggregates, using event IDs for deduplication and durable state for recovery. Dashboard freshness may tolerate approximate or eventually corrected values, while billing needs an auditable ledger and deterministic recomputation path. The design should therefore expose correction windows and reconciliation rather than treating a low-latency counter as the authoritative financial record.

Common pitfalls

Pitfall: Saying “exactly once” because the broker commits offsets transactionally is analytically incomplete; external database writes, HTTP calls, and crashes between side effects still create duplicates. State the end-to-end boundary and use idempotency or an outbox/inbox pattern.

Pitfall: Jumping straight to Kafka, partitions, and replication without clarifying throughput, retention, ordering, or loss tolerance makes the design sound memorized. Lead with requirements and name which guarantee each component provides.

Pitfall: Treating retries, rebalancing, and backpressure as implementation details misses the failure behavior interviewers probe. Explain what happens when a consumer dies mid-handler, a partition becomes hot, or downstream processing is slower than ingestion.

Connections

Expect pivots to consistent hashing, leader election, quorum replication, and idempotent API design. The interviewer may also connect this topic to the transactional outbox, change data capture, stream processing, schema evolution, and SLO-based capacity planning.

Further reading

Practice questions

Related concepts