Message queues, pub/sub & event streams
Decide between a queue and a log like Kafka and explain delivery guarantees.
By Invicly Tech, , in System Design Deep Dive. About 10 minutes to read.
In short
Message queues decouple producers from consumers so work can be buffered, retried and processed asynchronously. A queue hands each message to one worker, while a log like Kafka keeps an ordered, replayable stream many groups can read.
Think of it like this: A restaurant ticket rail: waiters pin orders, cooks take them when ready.
Explained simply
A message queue is a waiting line for work. One part of the system drops in a message such as "send this email" or "resize this photo". Another part picks it up and does the work when it can. The sender does not wait.
Think of a post box. You drop in a letter and walk away. You do not stand there until the postman comes. Letters wait safely in the box until someone collects them, even if the postman is late today.
This brings three big benefits. Spikes are absorbed: a thousand orders in one minute just make the line longer for a while. A slow or broken worker does not break the website. And you can add more workers to catch up faster.
There are two main flavours. A work queue gives each job to exactly one worker. Pub/sub and event streams give every interested service its own copy of each message. Kafka belongs to the second group and also keeps history, so you can replay old events.
Press Play on a diagram to walk through it one step at a time.
- 1Producer
API publishes a job and returns quickly
- 2Queue or topic
Durably buffers messages
- 3Consumer workers
Pull messages and process them
- 4Ack or retry
Acknowledged on success, redelivered on failure
- 5Dead-letter queue
Messages that keep failing are parked
- Message deleted after ack
- Each message to one consumer
- Easy per-message retries
- Good for task distribution
- Messages retained for days
- Ordered within a partition
- Many consumer groups replay
- Good for event streams
- Producer to Queue: Send job 421Send job 42
- Queue to Worker A: Deliver job 42, hide it for 30 s2Deliver job 42, hide it for 30 s
- Queue to Worker B: No delete after 30 s: deliver job 42 again3No delete after 30 s: deliver job 42 again
- Worker B to Queue: Done: delete job 424Done: delete job 42
- Background jobs
- Amazon SQS
- RabbitMQ
- Celery or Sidekiq on Redis
- One event, many services
- SNS topic fanning out to SQS queues
- Google Pub/Sub
- High-volume ordered stream with replay
- Apache Kafka
- Amazon Kinesis
- Redpanda
- Complex routing rules
- RabbitMQ exchanges
In depth
What happens when a worker crashes mid-job
Queues must survive workers dying. In Amazon SQS, receiving a message does not delete it. It becomes invisible for a visibility timeout, say 30 seconds. The worker deletes it only after finishing. If the worker crashes, the timeout expires and the message reappears for another worker. RabbitMQ does something similar: unacknowledged messages are requeued when a worker's connection drops.
Set the timeout longer than your slowest job, or extend it while working. If it is too short, a slow but healthy worker's job reappears and a second worker starts it too. This is exactly why delivery is "at least once".
Keys, partitions and ordering in Kafka
A Kafka topic is split into partitions. When a producer sends a message with a key, Kafka hashes the key to choose the partition, so all messages with the same key land in the same partition, in order. Choose the key to match what must stay in order: an order ID, an account ID or a user ID.
Two warnings. Adding partitions later changes which partition a key maps to, which can briefly break ordering. And a very busy key, such as one huge customer, overloads its single partition. The partition count also caps parallelism: a consumer group can use at most one consumer per partition.
When to commit: the source of delivery guarantees
A consumer tells the system it is done by acknowledging or, in Kafka, committing its offset. The timing decides the guarantee. Commit before processing and crash: the message is skipped, which is at-most-once. Commit after processing and crash: the message is processed again, which is at-least-once.
Kafka offers transactions that give exactly-once results when you read from Kafka and write back to Kafka. Once an outside system is involved, such as a database or an email provider, you get exactly-once effects by combining at-least-once delivery with idempotent work: record each message ID and skip ones you have already handled.
- Offset saved first
- Crash: message skipped
- At-most-once
- Work done first
- Crash: message processed again
- At-least-once; add idempotency
Retries and poison messages
A poison message always fails, perhaps because it has bad data. Retrying it forever wastes workers and, in Kafka, blocks every message behind it in the partition.
Retry with growing delays, then give up. In SQS, a redrive policy with maxReceiveCount of about 5 moves the message to a dead-letter queue automatically. In Kafka, the usual pattern is to publish the failing message to a retry topic, and then to a dead-letter topic, so the main partition keeps moving. Alert when a dead-letter queue is not empty, fix the bug, then replay the parked messages.
- 1Main topic
Message fails processing
- 2Retry topic
Tried again after a delay
- 3Still failing
Give up after a few tries
- 4Dead-letter topic
Main partition keeps moving
- 5Alert and fix
Then replay the parked messages
Watching lag and sizing workers
Consumer lag is how far behind workers are. In Kafka it is the newest offset minus the committed offset; in SQS it is the number of visible messages and the age of the oldest one. Rising lag means work arrives faster than it is done.
Little's Law sizes the worker pool: needed concurrency equals arrival rate times processing time. At 500 messages per second taking 0.2 seconds each, you need 100 messages in progress at once. Scale workers on lag or queue depth rather than CPU, since workers waiting on network calls can be idle on CPU yet far behind. KEDA does this for Kubernetes.
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Compare queues and pub/sub~45m
- 2Explain Kafka partitions and consumer groups~45m
- 3Explain at-least-once and exactly-once delivery~45m
- 4Choose a queue or log for a scenario~45m
Key points
- Queues absorb traffic spikes and let producers and consumers scale independently.
- Kafka orders messages per partition, not across the whole topic.
- Each partition is read by one consumer within a consumer group.
- At-least-once delivery is the norm, so consumers must be idempotent.
- Exactly-once usually means at-least-once delivery plus idempotent processing.
Key terms
Tap a card to flip it. 0/6 known
Examples
Sending a welcome email without slowing sign-up
Step 1: the sign-up API saves the user, sends a message with the user ID and a unique message ID to SQS, and returns in about 50 ms. Step 2: a worker long-polls the queue, waiting up to 20 seconds for messages. Step 3: for each message it checks whether that message ID was already handled, because SQS may deliver twice. Step 4: it sends the email, records the ID, and only then deletes the message. If the email provider is down, the message reappears and is retried; after 5 attempts a redrive policy moves it to a dead-letter queue.
import json
import boto3
sqs = boto3.client("sqs")
URL = "https://sqs.us-east-1.amazonaws.com/123456789012/welcome-emails"
while True:
resp = sqs.receive_message(QueueUrl=URL, MaxNumberOfMessages=10, WaitTimeSeconds=20)
for msg in resp.get("Messages", []):
job = json.loads(msg["Body"])
if not already_sent(job["messageId"]): # idempotency check
send_welcome_email(job["userId"])
mark_sent(job["messageId"])
sqs.delete_message(QueueUrl=URL, ReceiptHandle=msg["ReceiptHandle"])Keeping bank events in order with Kafka keys
Account 77 gets two events: deposit 100, then withdraw 80. If they go to different partitions, two consumers may process them at the same time, and the withdrawal could run first and be rejected for insufficient funds. Step 1: use the account ID as the message key. Step 2: Kafka hashes "77" to, say, partition 4, so both events go there in order. Step 3: the topic has 12 partitions, so up to 12 consumers share the work, each owning whole partitions. Different accounts are processed in parallel, but each account's events stay in order.
Quick reference
- SQS visibility timeout must be longer than your slowest job
- Kafka: same key → same partition → same order; consumers per group ≤ partitions
- Commit after processing = at-least-once; commit before = at-most-once
- Exactly-once effects = at-least-once delivery + idempotent processing
- After ~5 failed attempts, move the message to a dead-letter queue and alert
- Workers needed ≈ messages per second × seconds per message
- Scale consumers on lag or queue depth, not CPU
Common mistakes
- Assuming global ordering in Kafka across partitions.
- Non-idempotent consumers that double-charge on redelivery.
- Having more consumers in a group than partitions, leaving some idle.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Choose a work queue, pub/sub or a replayable log for each: (a) resize each uploaded photo once; (b) when an order is placed, notify inventory, email and analytics; (c) rebuild last week's click report with new logic.
- Exercise 2medium
A queue receives 800 messages per second and each takes 250 ms. Each worker process handles 10 messages at a time. How many processes do you need, with 50 percent headroom?
- Exercise 3hard
A consumer reads payment events from Kafka and updates account balances in PostgreSQL. Design it so a crash or redelivery never applies a payment twice.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Kafka or RabbitMQ?
- Use RabbitMQ or SQS for job queues with per-message retries and routing. Use Kafka for high-volume event streams that several services read and that you may want to replay.
- Can a queue lose messages?
- Managed queues like SQS and properly configured Kafka (replication factor 3, acks=all) are very durable. Messages are more often lost by consumers that acknowledge before finishing their work.
- Can I just use a database table as a queue?
- For modest volumes, yes. A PostgreSQL SELECT with FOR UPDATE SKIP LOCKED lets many workers safely claim rows. Move to a real queue when volume or fan-out grows.