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

Messaging models compared
ModelDeliveryAfter consumptionReplayTypical toolsUse for
Work queueEach message to one consumerDeleted when acknowledgedNoRabbitMQ queues, SQS, Azure Service Bus queuesBackground jobs, task distribution
Pub/sub (topic)Each message to every subscriptionDeleted per subscription when acknowledgedNo (usually)SNS, Service Bus topics, RabbitMQ fanoutNotifying several independent services
Log (event stream)Consumers read at their own offsetKept for a retention periodYes, from any offsetKafka, Kinesis, Event Hubs, RedpandaEvent 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

Delivery guarantees
GuaranteeHow it arisesRiskTypical use
At-most-onceAcknowledge before processingMessages lost on crashMetrics, logs where gaps are acceptable
At-least-onceAcknowledge after processing; redeliver on timeoutDuplicatesThe default for business events
Effectively exactly-onceAt-least-once delivery plus idempotent processing or transactional offsetsComplexity; holds only within the system boundaryPayments, 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

Idempotent consumer (inbox table)
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

What to monitor
MetricMeaningAlert when
Queue depth / consumer lagMessages waiting (or offsets behind the head)Growing steadily for minutes
Age of oldest messageHow stale the work is; closest to user impactExceeds the processing SLO
Consume rate vs publish rateWhether consumers keep upConsume rate below publish rate at peak
DLQ depthMessages that failed permanentlyGreater than zero
Redelivery rateTimeouts or crashes during processingRising above baseline
Sizing consumers
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