Cheatsheet
Messaging
Queues, pub/sub and logs, delivery semantics, ordering, consumer groups, idempotent consumers, dead letter queues, backpressure, outbox and metrics.
01Queue vs pub/sub vs log
| Model | Delivery | After consumption | Replay | Typical tools | Use for |
|---|---|---|---|---|---|
| Work queue | Each message to one consumer | Deleted when acknowledged | No | RabbitMQ queues, SQS, Azure Service Bus queues | Background jobs, task distribution |
| Pub/sub (topic) | Each message to every subscription | Deleted per subscription when acknowledged | No (usually) | SNS, Service Bus topics, RabbitMQ fanout | Notifying several independent services |
| Log (event stream) | Consumers read at their own offset | Kept for a retention period | Yes, from any offset | Kafka, Kinesis, Event Hubs, Redpanda | Event sourcing, analytics, high-throughput pipelines |
- Queues decouple producers from consumers in time: the consumer can be down while the producer keeps working.
- Asynchronous messaging trades immediate answers for resilience and smoothing of load spikes.
02Delivery semantics
| Guarantee | How it arises | Risk | Typical use |
|---|---|---|---|
| At-most-once | Acknowledge before processing | Messages lost on crash | Metrics, logs where gaps are acceptable |
| At-least-once | Acknowledge after processing; redeliver on timeout | Duplicates | The default for business events |
| Effectively exactly-once | At-least-once delivery plus idempotent processing or transactional offsets | Complexity; holds only within the system boundary | Payments, inventory, anything that must not double count |
Exactly-once delivery across a network is not achievable in general. Design for at-least-once and make every consumer idempotent.
03Ordering, partitions and consumer groups
- Partition
- An ordered, append-only shard of a topic. Order is guaranteed within a partition only.
- Partition key
- Messages with the same key (e.g.
orderId) go to the same partition, so they stay in order. - Consumer group
- Consumers sharing a group id split the partitions between them; each partition is read by one member at a time.
- Rebalance
- Partitions are reassigned when consumers join or leave. Processing pauses briefly; in-flight work may be redelivered.
- Competing consumers
- Several workers read one queue; the broker hands each message to one of them. Scales throughput, loses global order.
- Parallelism in a consumer group is capped by the number of partitions; extra consumers sit idle.
- Pick partition keys with many distinct values; a hot key overloads one partition.
- Retries that requeue a message to the back of a queue break ordering for that key.
04Idempotent consumers and dead letter queues
begin transaction insert into processed_messages(message_id) values (:id) -- unique key if duplicate key: rollback; acknowledge; return apply business change commit acknowledge message
- Natural idempotency
- Operations like "set status to shipped" can be repeated safely; "add 10 to balance" cannot.
- Poison message
- A message that always fails (bad schema, missing data). Without a limit it blocks or loops forever.
- Dead letter queue (DLQ)
- Where messages go after N failed attempts. Alert on it, inspect, fix, then replay.
- Redrive
- Moving messages from the DLQ back to the main queue once the cause is fixed.
- Separate transient errors (retry with backoff) from permanent ones (send to DLQ immediately).
- Keep the original message, the error and the attempt count with each dead-lettered message.
05Outbox, retries and backpressure
- Dual-write problem
- Writing to the database and publishing to the broker are two operations; a crash between them leaves them inconsistent.
- Transactional outbox
- Insert the event into an outbox table in the same transaction as the business change. A relay publishes outbox rows and marks them sent (at-least-once).
- Retry with backoff
- Delay = base × 2^attempt, capped, with random jitter. Limit attempts, then dead-letter.
- Visibility timeout / lock duration
- How long a received message is hidden from others. Must exceed processing time, or duplicates appear.
- Backpressure
- Slow the producers when consumers fall behind: bounded queues, prefetch limits, 429 or 503 responses, or pausing reads.
- Load levelling
- A queue absorbs bursts so consumers can run at a steady, affordable rate.
06Metrics and sizing
| Metric | Meaning | Alert when |
|---|---|---|
| Queue depth / consumer lag | Messages waiting (or offsets behind the head) | Growing steadily for minutes |
| Age of oldest message | How stale the work is; closest to user impact | Exceeds the processing SLO |
| Consume rate vs publish rate | Whether consumers keep up | Consume rate below publish rate at peak |
| DLQ depth | Messages that failed permanently | Greater than zero |
| Redelivery rate | Timeouts or crashes during processing | Rising above baseline |
consumers needed = publish rate × processing time per message (Little's law) example = 2,000 msg/s × 0.05 s = 100 concurrent handlers (plus headroom) drain time = backlog / (consume rate − publish rate) example = 600,000 / (3,000 − 2,000) = 600 s to catch up retention needed ≥ longest expected consumer outage + time to drain