Message Queues & Kafka

Decoupling services and absorbing spiky traffic: queues, pub-sub, delivery guarantees, idempotency.

Intermediate8 min read
Language
Theme
Order serviceresponds instantly"order placed"Queue / topicEmailInventoryAnalyticsIdempotencydedupe by message IDQueue = decoupling + spike buffer. Ordering is per-partition (Kafka)
Key idea at a glance
INTERACTIVE

Playground: producer, queue, consumers

Producers burst, consumers drain at a steady rate: that buffer is the whole point of a queue. Crash a consumer and watch the backlog grow, without losing a single message.

Producer
→
queue
→

The problem queues solve

An order is placed. Now: charge the card, update inventory, send email, send SMS, update analytics, notify the warehouse. Doing this synchronously means the user waits for all six, and if the email provider is down, the order fails. Madness. The queue version: the order service writes one "order placed" message and responds instantly. The other five systems consume the message at their own pace. This buys decoupling (services do not know about each other), buffering (spikes pile up in the queue instead of crashing consumers), and resilience (a dead consumer's messages wait patiently).

Queue vs pub-sub vs log

  • Message queue (SQS, RabbitMQ): each message is processed by one consumer from a pool. Work distribution: resize this image, send this email.
  • Pub-sub (SNS, Redis pub-sub): each message goes to every subscriber. Notifications, cache invalidation broadcasts.
  • Event log (Kafka, Kinesis): an append-only, durable, replayable log partitioned by key; each consumer group tracks its own offset and can re-read history. Event sourcing, stream processing, analytics pipelines. Kafka's superpower: replay; deploy a new consumer, let it rebuild state from day one.

Delivery semantics: the part everyone gets wrong

  • At-most-once: fire and forget; a crash means lost messages. Fine for metrics sampling.
  • At-least-once: retry until acknowledged; a crash after processing but before ack means duplicates. This is the realistic default.
  • Exactly-once: effectively impossible across arbitrary systems; approximated by idempotent consumers (process the same message twice with the same effect) plus dedup keys. Kafka's transactional mode gives exactly-once within Kafka only.

So the universal pattern: assume at-least-once, make every consumer idempotent. Payment consumers store processed message IDs; email consumers dedupe by notification ID.

Ordering, lag and poison messages

  • Ordering: Kafka guarantees order only within a partition. Need per-user ordering? Partition by user_id. Global ordering does not scale; do not promise it.
  • Consumer lag: messages produced minus consumed. Growing lag = consumers too slow = data piling up = eventual data loss when retention hits. Lag is the metric to alert on.
  • Poison messages: one malformed message crashes every consumer that tries it, forever. Fix: retry N times, then move to a dead-letter queue for human inspection; never infinite-retry in place.
  • Backpressure: a queue that grows unboundedly is a slow-motion outage. Set retention, alert on lag, and shed load at the producer when needed.

Worked example: flash sale order pipeline

Diwali sale: 50k orders/sec peak, DB can take 5k. Orders API validates + writes to Kafka (partitioned by order_id), responds "order received". Consumers (payment, inventory, email) process at safe rates; the queue absorbs the spike and drains in minutes. Payment consumer is idempotent on order_id. Failed-after-5-retries messages land in a DLQ with an alert. Lag dashboard tells you exactly how far behind reality is.

Common interview traps

  • A queue with no duplicate story.
  • Assuming global ordering.
  • No dead-letter queue; no lag monitoring.
  • Using the queue to make a slow operation "async" without asking if the user actually needs the result now.

Interview Q&A

Q: A consumer processed a payment message twice and charged twice. Prevention?
A: Idempotency end to end: the message carries a unique ID, the consumer checks a processed-IDs store (Redis/DB unique constraint) before charging, and the payment gateway itself gets the same idempotency key so even a gateway retry is safe.

Q: Kafka or RabbitMQ?
A: RabbitMQ: classic work queues, complex routing, per-message acks, lower throughput. Kafka: durable replayable log, massive throughput, consumer groups, stream processing. Task distribution -> RabbitMQ/SQS; event streams and analytics -> Kafka.

Key takeaways

Interview pointer

Add a queue and the interviewer asks: 'what about duplicates?' Answer: I will assume at-least-once and make consumers idempotent, checking message IDs in a dedupe table or Redis. Bonus: mention lag monitoring and a dead-letter queue for failed messages.