Message Queues
A queue decouples the thing that produces work from the thing that does it. That buys latency (the request returns before the work is done), resilience (the consumer can be down), and buffering (spikes are absorbed). It costs you ordering guarantees, duplication, and a new class of failure: the message that is processed twice or never.
The 60-second answer
Section titled “The 60-second answer”Queues move work off the request path and absorb bursts. Use a log (Kafka) when you need retention, replay and ordered partitions with high throughput; a broker (RabbitMQ, SQS) when you need per-message routing, acknowledgement and individual retry with delay. Delivery is at-least-once almost everywhere, so consumers must be idempotent. Order is only guaranteed within a partition or a FIFO queue, never globally. To publish reliably, write the event to the database in the same transaction and relay it out with a transactional outbox.
Why queue at all
Section titled “Why queue at all”- Latency: an image upload returns
202 Accepted; resizing happens later. - Buffering: a flash sale produces a 20× spike; the queue smooths it into a steady drain.
- Decoupling: the billing service does not need to know the email service exists.
- Retry: transient failures can be retried without the user waiting.
- Fan-out: one event, many independent consumers.
- Backpressure: queue depth is a signal to scale consumers or shed load.
The cost is that the request is no longer synchronous: the client cannot know the work succeeded. You need a status resource, a webhook, or a notification.
Kafka vs RabbitMQ vs SQS
Section titled “Kafka vs RabbitMQ vs SQS”| Kafka | RabbitMQ | SQS | |
|---|---|---|---|
| Model | Append-only partitioned log | Broker with exchanges and queues | Managed queue |
| Consumers | Pull, track their own offset | Push, per-message ack | Pull with visibility timeout |
| Retention | Time/size-based, replay possible | Until consumed | Until deleted (or retention limit) |
| Ordering | Per partition | Per queue (with one consumer) | Standard: none; FIFO: per group |
| Throughput | Very high, sequential IO | Moderate | High, managed |
| Routing | Topic + partition key | Exchanges: direct, topic, fanout, headers | None (SNS adds fan-out) |
| Delay / priority | Not native | Per-message TTL, priority queues | Delay queues, not per message |
| Ops cost | Real cluster to run (or MSK) | Moderate | None |
Kafka is a log. Messages are appended to a partition and retained regardless of consumption.
Consumers keep an offset. That is what enables replay: bring up a new consumer and it can reprocess
the last week. Ordering is per partition, so the partition key determines what is ordered — pick
it deliberately (order_id, not user_id if you need per-order ordering across events).
RabbitMQ is a broker. Producers publish to an exchange, routing rules deliver to queues, consumers acknowledge individual messages. You get per-message redelivery, dead-letter exchanges, delayed retry, priority, and flexible routing. When a message is consumed it is gone. Throughput is lower than Kafka, and a huge backlog is harder to manage.
SQS is a managed queue. You get a URL, you ReceiveMessage, you process, you delete. The
visibility timeout is the core concept: a received message is hidden for N seconds; if you do not
delete it, it reappears. That is your retry mechanism, and it is why processing can take longer
than the timeout and duplicate silently. FIFO queues add ordering and deduplication within a
message group, at lower throughput.
Delivery semantics
Section titled “Delivery semantics”| Semantics | Guarantee | How |
|---|---|---|
| At most once | May be lost, never duplicated | Ack before processing, or fire-and-forget |
| At least once | Never lost, may duplicate | Ack after processing; retry on failure |
| Exactly once | Neither | Not achievable end to end |
At-least-once is the default because the alternative loses work. Duplicates appear whenever an ack is lost, a consumer crashes after doing the work but before committing, or a producer retries after a timeout it did not see succeed.
“Exactly once” is achievable only within a single system that controls both the offset commit and the output — Kafka transactions with an idempotent producer, writing to Kafka. The moment your consumer writes to an external database and sends an email, you are back to at-least-once and must deduplicate. The honest term is effectively once: at-least-once delivery plus idempotent processing. See Idempotency.
Consumer groups and scaling
Section titled “Consumer groups and scaling”A consumer group is a set of consumers sharing the work. Each partition is assigned to exactly one consumer in the group, so parallelism is capped by partition count. 12 partitions and 20 consumers means 8 idle consumers.
- Adding a consumer triggers a rebalance; during it, processing pauses briefly.
- A slow consumer holds its partitions and causes lag on exactly those partitions.
- Lag (latest offset minus committed offset) is the metric that matters. Alert on it, not on CPU.
- Separate consumer groups for separate concerns, so a slow analytics consumer cannot delay notifications.
Ordering
Section titled “Ordering”Global ordering requires a single consumer, which caps throughput. So you order per key:
- Produce with
key = order_idso all events for an order land in one partition. - The consumer processes a partition serially.
- If a message fails, you must not skip ahead for the same key: retry it, or park it and block the partition. Head-of-line blocking is the price of ordering.
For a job queue, per-entity ordering usually means one queue per entity with a single worker, or a “ready” flag so only the next task for an entity is visible.
The transactional outbox
Section titled “The transactional outbox”The classic bug: the service writes to the database and publishes to Kafka. One succeeds, the other fails, and the system is now inconsistent — an order exists with no event, or an event for an order that was rolled back.
Publish inside the same transaction is impossible across two systems, so make the database the source of truth:
BEGIN;INSERT INTO orders (id, customer_id, total_cents, status) VALUES ($1, $2, $3, 'pending');INSERT INTO outbox (id, aggregate_id, type, payload, created_at) VALUES ($4, $1, 'order.created', $5, now());COMMIT;A relay process then reads unpublished outbox rows in order and publishes them, marking them sent:
Outbox.where(published_at: nil).order(:id).limit(500).each do |row| producer.publish(row.type, row.payload, key: row.aggregate_id) row.update!(published_at: Time.now)endProperties: atomic with the business write, ordered per aggregate, and retried on failure. It requires the consumer to tolerate duplicates (publish-then-mark can repeat), which is fine because they are idempotent.
Change Data Capture (CDC) with Debezium does the same thing without a relay process: it tails the database’s write-ahead log and emits row changes. It is less code and harder to operate, and it couples your event contract to your table shape.
Alternatives people suggest, and why they are weaker:
- Poll the table — adds load and latency, and scales badly.
- Two-phase commit — available in some stacks, but it blocks, and it is not supported by most brokers.
- Publish then write — the reverse failure, which is worse: an event for something that does not exist.
Dead letters and poisoning
Section titled “Dead letters and poisoning”A message that always fails will be retried forever and block its partition. After N attempts, move it to a dead-letter queue with the error and the original payload. Then: alert, inspect, fix the consumer, and replay from the DLQ. A DLQ nobody monitors is just a data loss mechanism with extra steps.
Follow-up questions
Section titled “Follow-up questions”- What happens to in-flight messages during a Kafka rebalance?
- How do you guarantee that an order event is published exactly when the order is committed?
- Your consumer is at-least-once. Where do you deduplicate?
- You need a retry after 15 minutes. Which queue makes that easy?
- Partition count is 6 and you need 20× throughput. What do you do, and what breaks?
- How do you reprocess a day of events after fixing a bug?
Common traps
Section titled “Common traps”- “Kafka guarantees exactly-once.” Only within Kafka’s transactional boundary. Downstream effects are at-least-once.
- “SQS is ordered.” Standard queues are not. FIFO queues order within a message group.
- “More consumers means more throughput.” Only up to the partition count.
- “The queue guarantees delivery, so we are safe.” Unbounded queues hide failure until the disk fills. Alert on lag and depth, and cap the backlog.
- “We publish in the same request, so it is atomic.” Two systems, two commits, no atomicity without an outbox or 2PC.