Queues vs streams (Kafka)
A queue hands each message to one worker and deletes it on ack; a stream (Kafka) keeps an ordered, replayable log that many consumer groups read at their own offsets.
Analogy: A queue is the ticket rail in a kitchen: a cook takes a ticket and it's gone. A stream is the restaurant's order ledger: the kitchen, the accountant and the auditor each read it at their own pace.
How it works
- In a queue, an unacked message reappears after a visibility timeout; add workers to go faster.
- A stream retains messages (7 days by default in Kafka), so any consumer group can replay by rewinding.
- Order holds only per partition: the key decides what stays ordered, and partitions cap a group's parallelism.
- At-least-once is the practical default: ack after processing, so a crash means redelivery and handlers must be idempotent.
- Add backpressure and a dead-letter queue that parks poison messages after N attempts.
Check yourself
Answer to mark it learned; your answers aren't scored.
Lag on the doc-changes topic keeps growing. You scale the embedder consumer group from 12 to 24 consumers, but throughput doesn't move. The topic has 12 partitions. Why?
Go deeper
Full explanation
Both decouple producers from consumers, but they model different things.
A message queue (SQS, RabbitMQ) is a to-do list. Each message is work for one consumer, which acks it when done; the broker then deletes it. An unacked message reappears after a visibility timeout. Add workers to go faster; ordering is weak unless you use FIFO queues.
A log/stream (Kafka, Kinesis, Redpanda) is a ledger. Messages are appended to partitions and retained (7 days by default in Kafka) whether or not anyone read them. Each consumer group tracks its own offset, so many systems read the same events and any of them can replay by rewinding. Order holds per partition, so the key (user_id, doc_id) decides what stays ordered, and a group's parallelism is capped by the partition count.
Delivery semantics:
- At-most-once: ack before processing; a crash loses the message.
- At-least-once (the practical default): ack after processing; a crash means redelivery, so handlers must be idempotent (Idempotency).
- Effectively-once: at-least-once plus dedup or idempotent writes. Kafka transactions give exactly-once only within Kafka.
Production also needs backpressure (bounded depth, autoscale on lag) and a dead-letter queue that parks poison messages after N attempts.
For AI: queue long generations to GPU workers; stream document changes into an embedding pipeline you can replay when the model changes.
Code At-least-once embedding consumer with manual commits
from confluent_kafka import Consumer
consumer = Consumer({
"bootstrap.servers": "kafka:9092",
"group.id": "embedder-v2", # new group = own offsets = full replay
"auto.offset.reset": "earliest", # a brand-new group starts at the oldest event
"enable.auto.commit": False, # commit only after the work is durable
})
consumer.subscribe(["doc-changes"]) # keyed by doc_id: per-doc ordering
while True:
msgs = consumer.consume(num_messages=64, timeout=1.0)
batch = [m for m in msgs if m.error() is None]
if not batch:
continue
docs = [parse(m.value()) for m in batch]
vectors = embed([d.text for d in docs]) # one batched GPU/API call
vector_db.upsert(ids=[d.id for d in docs], vectors=vectors) # idempotent: replays are safe
consumer.commit(asynchronous=False) # crash before this line = redelivery, not lossReal example
A document-QA product ingests ~200k document edits a day. Edits go to a compacted Kafka topic doc-changes keyed by doc_id with 12 partitions, so the latest version of every document is always retained. The embedder group runs up to 12 consumers. To move to a new embedding model, you start group embedder-v2 from offset 0 into a new index, evaluate, and flip the alias: no re-crawl. Separately, 30-page report requests (2–4 min each) go to an SQS queue: the API returns 202 with a job id, GPU workers autoscale on queue depth, and a job that fails 3 times lands in a DLQ instead of looping forever.
Trade-offs +3 · −3
+ You gain
- Decouple producers and consumers in time and rate: absorb spikes, survive consumer outages.
- Queue: the simplest way to fan work out to N workers, with retries and a DLQ built in.
- Stream: one event feed, many independent readers, and replay for backfills and new consumers.
− You pay
- At-least-once is the norm, so every consumer must be idempotent.
- Async adds latency and operational surface: lag, DLQ triage, rebalances.
- Kafka ties parallelism and ordering to partitions; adding partitions to a keyed topic remaps keys.
Use it when
Queue: background jobs that each need one worker (LLM generations, document parsing, emails). Stream: events several systems consume, needing per-entity order or replay (CDC, ingestion, audit, analytics).
Avoid it when
When the caller needs the answer within the request (just call the service), or for a few events a day, where a database table with a status column is simpler.
Numbers to know 5
- Kafka default retention: 7 days (
log.retention.hours=168); compacted topics keep the latest value per key indefinitely. - SQS visibility timeout: 30 s default, 12 h max; message retention 4 days default, 14 days max.
- Kinesis shard: 1 MB/s or 1,000 records/s in, 2 MB/s out.
- A consumer group's parallelism ≤ partition count; extra consumers sit idle.
- Little's law for sizing: jobs in flight = arrival rate × time in system (50 jobs/s × 180 s = 9,000).
Common pitfalls 4
- Visibility timeout shorter than the job: a 5-minute LLM generation with a 30 s timeout gets picked up by a second worker.
- Non-idempotent consumers: a rebalance or timeout redelivers, and you charge, email or embed twice.
- Keying by a huge tenant: one partition saturates while the others idle.
- No DLQ, or no alert on it: a poison message retries forever in a queue, or blocks its whole partition in Kafka.
Interview questions 3
Answer out loud first, then reveal.
When would you choose Kafka over SQS?Show answer
I ask whether the message is a task or a fact. A task, like 'generate this report', needs exactly one worker, retries and a DLQ: SQS or RabbitMQ, with little to operate. A fact, like 'document 812 changed', is something several systems react to, often in order per entity, and that I'll want to replay when I add a consumer or change the embedding model: that's Kafka or Kinesis. The trade-off is operational cost: partitions, retention and consumer lag become mine to own.
How do you guarantee each message is processed exactly once?Show answer
Across systems, I don't: I build effectively-once from at-least-once plus idempotent processing. The consumer commits its offset only after the effect is durable, and the effect is an upsert by natural key, or a write that records the message id in the same transaction and skips ids it has seen. Kafka transactions give exactly-once for read-process-write inside Kafka, but the moment I call a payment API or a vector DB, that boundary ends and idempotency keys take over.
How would you serve LLM jobs that take 3 minutes each?Show answer
Asynchronously. The API validates, stores the job with an idempotency key and returns 202 with a job id; the client polls, or gets an SSE stream or a webhook. Jobs go to a queue and GPU workers pull at their own pace, so a spike becomes a backlog instead of timeouts. I set the visibility timeout above p99 job time or extend it with heartbeats, send failures to a DLQ after 3 attempts, autoscale workers on queue depth, and keep separate queues per priority tier.