Playground: producer, queue, consumersPlayground: 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.Producers burst karte hain, consumers steady rate se drain karte hain: yehi buffer queue ka poora point hai. Consumer crash karo aur backlog badhta dekho, bina ek bhi message khoye.
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.
Wo problem jo queues solve karti hain
Order place hua. Ab: card charge, inventory update, email, SMS, analytics update, warehouse notify. Ye sab synchronously karne ka matlab: user chhe kaamon ka wait kare, aur email provider down ho to order fail. Paagalpan. Queue version: order service ek "order placed" message likhti hai aur turant respond karti hai. Baaki paanch systems apni speed se consume karte hain. Isse milta hai decoupling (services ek doosre ko nahi jaanti), buffering (spikes queue mein jama hote hain, consumers crash nahi hote), aur resilience (mare hue consumer ke messages sabr se wait karte hain).
Queue vs pub-sub vs log
- Message queue (SQS, RabbitMQ): har message pool se ek consumer process karta hai. Work distribution: ye image resize karo, ye email bhejo.
- Pub-sub (SNS, Redis pub-sub): har message har subscriber ko. Notifications, cache invalidation broadcasts.
- Event log (Kafka, Kinesis): append-only, durable, replayable log, key se partitioned; har consumer group apna offset track karta hai aur history dobara padh sakta hai. Event sourcing, stream processing, analytics pipelines. Kafka ki superpower: replay; naya consumer deploy karo, day one se state rebuild karne do.
Delivery semantics: wo hissa jo sab galat karte hain
- At-most-once: fire and forget; crash matlab messages lost. Metrics sampling ke liye theek.
- At-least-once: ack tak retry; process karne ke baad, ack se pehle crash matlab duplicates. Ye realistic default hai.
- Exactly-once: arbitrary systems ke across effectively impossible; approximated by idempotent consumers (same message do baar process ho to same effect) plus dedup keys. Kafka ka transactional mode sirf Kafka ke andar exactly-once deta hai.
To universal pattern: at-least-once assume karo, har consumer ko idempotent banao. Payment consumers processed message IDs store karte hain; email consumers notification ID se dedupe karte hain.
Ordering, lag aur poison messages
- Ordering: Kafka order sirf partition ke andar guarantee karta hai. Per-user ordering chahiye? user_id se partition karo. Global ordering scale nahi karti; promise mat karo.
- Consumer lag: produced minus consumed. Badhta lag = consumers slow = data jama = retention hit hote hi data loss. Lag hi wo metric hai jis par alert lagana hai.
- Poison messages: ek malformed message har consumer ko crash kare, hamesha ke liye. Fix: N baar retry, phir dead-letter queue mein human inspection ke liye; kabhi infinite-retry mat karo.
- Backpressure: unbounded badhti queue slow-motion outage hai. Retention set karo, lag par alert, zaroorat pade to producer par load shed karo.
Worked example: flash sale order pipeline
Diwali sale: peak 50k orders/sec, DB 5k le sakta hai. Orders API validate + Kafka mein likhti hai (order_id se partition), "order received" respond. Consumers (payment, inventory, email) safe rates par process karte hain; queue spike absorb karti hai aur minutes mein drain. Payment consumer order_id par idempotent. 5 retries ke baad fail hue messages DLQ mein alert ke saath. Lag dashboard batata hai reality se kitna peeche ho.
Common interview traps
- Queue, par duplicate ka koi jawab nahi.
- Global ordering assume karna.
- Dead-letter queue nahi; lag monitoring nahi.
- Slow operation ko "async" banane ke liye queue, bina ye pooche ki user ko result abhi chahiye ya nahi.
Interview Q&A
Q: Consumer ne payment message do baar process kiya aur do baar charge ho gaya. Prevention?
A: End to end idempotency: message mein unique ID, consumer charge karne se pehle processed-IDs store (Redis/DB unique constraint) check kare, aur payment gateway ko bhi same idempotency key jaye taaki gateway retry bhi safe ho.
Q: Kafka ya RabbitMQ?
A: RabbitMQ: classic work queues, complex routing, per-message acks, kam throughput. Kafka: durable replayable log, massive throughput, consumer groups, stream processing. Task distribution -> RabbitMQ/SQS; event streams aur analytics -> Kafka.