Sub topic 11
Durability and persistence
This chapter assumes you know what a broker, queue, producer, and consumer are, and that you have read the chapters on acknowledgements and delivery guarantees. The examples use Python and RabbitMQ through pika. The ideas also apply to other brokers.
What durability means
A message is durable if it survives a failure of the broker. The usual failure is a process crash or a server restart. Durability is a different property from delivery guarantees. A delivery guarantee describes how many times a consumer sees a message. Durability describes whether the broker still holds the message after it has accepted it and then fails.
By default, many brokers keep messages in memory because memory is fast. If the broker restarts, anything held only in memory is gone, and the producer was already told the send worked. Durability closes that gap, at a cost in latency and throughput.
Durability has four links
A message is only as safe as the weakest of these links:
| Link | Question it answers | Typical setting |
|---|---|---|
| Queue definition | Does the queue exist after a restart? | Declare the queue as durable |
| Message | Was the message written to disk? | Mark the message persistent |
| Producer handoff | Did the broker actually take responsibility? | Publisher confirms |
| Replication | Does the message survive loss of a whole node? | Replicated queue type or replication factor |
Getting only some of these right is the most common durability bug. A durable queue holding transient messages loses the messages on restart, and the queue is left empty. A persistent message sent to a non-durable queue is lost with the queue itself.
Durable queue plus persistent message
The following code from the plan publishes a persistent message to a durable queue:
import pika
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
ch.queue_declare(queue="tasks", durable=True)
ch.basic_publish(
exchange="",
routing_key="tasks",
body=b"resize image 42",
properties=pika.BasicProperties(delivery_mode=pika.DeliveryMode.Persistent),
)
conn.close()Two settings do the work here. durable=True makes the queue definition survive a restart. delivery_mode=Persistent asks the broker to write the message to disk.
This still does not guarantee the message is safe. basic_publish returns once the client library has handed the bytes to the network. The broker may not have received them, let alone written them.
Publisher confirms
A publisher confirm is the broker's acknowledgement to the producer. It says the broker has taken responsibility for the message. For a persistent message on a durable queue, the broker sends the confirm only after the message is written to disk. On a replicated queue, it sends the confirm after the message is replicated.
This is the producer-side counterpart of the consumer acknowledgement you saw earlier. A consumer ack means the work is done. A publisher confirm means the broker now owns the message.
Here is the earlier example with confirms turned on:
import pika
from pika.exceptions import NackError, UnroutableError
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
ch.queue_declare(queue="tasks", durable=True)
ch.confirm_delivery()
try:
ch.basic_publish(
exchange="",
routing_key="tasks",
body=b"resize image 42",
properties=pika.BasicProperties(delivery_mode=pika.DeliveryMode.Persistent),
mandatory=True,
)
print("broker confirmed the message")
except (NackError, UnroutableError):
print("message was not accepted; retry or report the failure")
finally:
conn.close()After confirm_delivery(), basic_publish on a BlockingChannel waits for the broker's answer. It raises NackError if the broker refuses the message. With mandatory=True, it raises UnroutableError if no queue received the message. Without mandatory, a message sent to a non-existent routing key is silently dropped, and the confirm still arrives.
Waiting for each confirm makes publishing slow. Production code usually publishes a batch and then waits for the confirms, or uses an asynchronous confirm callback.
What persistent really costs
Writing to disk is slower than holding data in memory. Forcing the data to stable storage, called an fsync, is slower again. Brokers therefore group writes. They flush a batch of messages together, and the confirm follows the flush. This is why confirms add latency but still allow high throughput when you publish in batches.
There is a trade-off to decide deliberately:
- Persistent messages with confirms give the strongest single-node safety. They cost the most throughput and latency.
- Transient messages are fastest. They suit data you can regenerate, such as cache invalidation signals or live metrics.
- Some brokers expose a setting that delays the fsync (for example, a flush interval). A shorter interval is safer. A longer interval is faster but widens the window in which a crash loses acknowledged data.
Surviving the loss of a node
Disk persistence protects you from a process restart. It does not protect you from a failed disk, a lost virtual machine, or a node that never comes back. For that you need replication: copies of the queue on several nodes.
In RabbitMQ, quorum queues are replicated queues. They use a consensus protocol (Raft) so that a message counts as accepted once a majority of replicas have written it. You declare one with an argument:
import pika
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
ch.queue_declare(
queue="orders",
durable=True,
arguments={"x-queue-type": "quorum"},
)
conn.close()Quorum queues must be durable. They need a cluster of at least three nodes to be useful, because a majority of three tolerates one failure. They trade some throughput for safety compared with a single-node classic queue.
Log-based brokers such as Kafka take the same approach with a replication factor and a minimum in-sync replicas setting. A write is acknowledged only after enough replicas have it. You will see this model in the chapter on log-based brokers.
What happens to messages in flight
Durability interacts with consumer acknowledgements. A message stays in the queue, still persistent, until a consumer acknowledges it. If the consumer crashes after receiving the message but before acking, the broker redelivers it. The message is not lost, but a consumer may see it twice. This is the at-least-once behavior you already know. It is why durable queues need idempotent consumers.
An auto-ack consumer weakens this. The broker deletes the message as soon as it is delivered, so a crash during processing loses it, however durable the queue is. Durable storage with auto-ack gives you a safe queue and an unsafe consumer.
Common mistakes
- Persistent messages on a non-durable queue. The queue vanishes on restart, and the messages go with it.
- Durable queue, transient messages. The queue is there after restart, and it is empty.
- No publisher confirms. The producer believes a message is safe when the broker may not have it.
- Trusting a single node. Persistence on one disk does not survive the loss of that disk.
- Ignoring unroutable messages. Without
mandatoryor an alternate exchange, a message with no matching queue is dropped, even with confirms on. - Redeclaring a queue with different settings. Most brokers refuse to redeclare an existing queue with different durability arguments. Delete the queue or create a new one, and migrate the messages.
Choosing a level
Match the durability level to the cost of losing the message:
| Message type | Suggested setup |
|---|---|
| Payment or order events | Quorum or replicated queue, persistent, confirms, manual acks |
| Background jobs that can be re-triggered | Durable queue, persistent, confirms |
| Live telemetry or cache hints | Transient messages, optional confirms |
Exercise
A service declares a queue with durable=True and publishes messages with default properties. The broker restarts. What do you find afterward, and what two changes make the messages survive a restart and tell the producer when they are safe?
Show answer
The queue still exists but is empty, because the messages were transient (the default delivery mode) and were held only in memory. To fix it, publish with deliverymode set to Persistent so the broker writes them to disk. Also enable publisher confirms (confirmdelivery) and wait for the confirm, so the producer knows the broker has taken responsibility for each message.
Exercise
Your queue is durable, messages are persistent, and the producer uses confirms. A disk on the only broker node fails and cannot be recovered. Are the messages safe? What would you change?
Show answer
No. Persistence and confirms protect against a process or machine restart, not against permanent loss of the storage. Run a replicated queue type, such as a RabbitMQ quorum queue on a cluster of at least three nodes, so a majority of nodes hold each message before it is confirmed.