Patterncore
Guaranteed Delivery
Also called Guaranteed Delivery pattern, guaranteed messaging, persistent messaging, durable messaging, reliable messaging, store and forward.
Guaranteed delivery makes a message persistent: the messaging system writes it to disk before it accepts it, and keeps it there until the receiver acknowledges it, so a crash does not lose it.
- Family
- integration
- Intent
- Make each message persistent, so that a message that the messaging system accepted is not lost when a process or a computer of the messaging system crashes.
- Also called
- persistent delivery, durable messaging, store and forward
Intent
Make a message survive a crash of the messaging system. The book asks: "How can the sender make sure that a message will be delivered, even if the messaging system fails?"12 The answer is to write the message to a store that outlives the process, before the messaging system tells the sender that it has the message.
Problem
A shop sends an order to a warehouse on a queue. The broker keeps its queues in memory. The broker process stops after it accepts the order and before the warehouse reads it. When the broker starts again, its queues are empty. The shop thinks that the order was sent, and the warehouse never sees it.
The forces are these. Memory is fast, and a disk is slow: each write that must reach the disk adds a delay to each send. The sender must know when it can forget a message, so the messaging system must tell it when the message is safe. And a message can be lost at each step: in the sender, on the network, in the broker, and in the receiver before it has done the work.
Solution
"Use Guaranteed Delivery to make messages persistent so that they are not lost even if the messaging system crashes."1 The messaging system has a data store on each computer where it runs. A send is complete only when the message is in the store of the sender. The message stays in a store until the next store has it, and it leaves the last store only when the receiver acknowledges it.1
sender messaging system receiver
| send m1 ---------> write m1 to disk, fsync
| <--------- confirm (m1 is safe)
| deliver m1 ----------------------> do the work
| delete m1 from disk <------------- ack m1
The participants are the sender, the persistent store of the messaging system, and the receiver. Two signals make the chain: a confirm from the store to the sender, and an acknowledgement from the receiver to the store.
Jakarta Messaging. Jakarta Messaging gives the choice as a delivery mode. "The NON_PERSISTENT mode is the lowest overhead delivery mode because it does not require that the message be logged to stable storage."3 Thus "A Jakarta Messaging provider failure can cause a NON_PERSISTENT message to be lost."3 For the PERSISTENT mode, a provider "must deliver a PERSISTENT message once-and-only-once", and the specification adds: "This means a Jakarta Messaging provider failure must not cause it to be lost, and it must not deliver it twice."3 On a topic, the mode is not sufficient: a subscriber that is not durable misses the messages that are sent when it is not active, also when they are PERSISTENT.3
RabbitMQ. A RabbitMQ publisher puts its channel in confirm mode, and the broker confirms each message. "For persistent messages routed to durable queues, this means persisting to disk".4 The queue must be durable and the message must be persistent; the reliability guide calls this critically important for important data.5 The disk write is not at once: the message store writes to disk "in batches after an interval (a few hundred milliseconds) to minimise the number of fsync(2) calls", and "A RabbitMQ node can lose persistent messages if it fails before said messages are written to disk."4 So the publisher must keep a message until the confirm comes.
Kafka. Kafka puts the guarantee in copies on many brokers, not in a disk write on one. "All data is immediately written to a persistent log on the filesystem without necessarily flushing to disk."6 "A message is considered committed only when all replicas in the in-sync replicas (ISR) for that partition have applied it to their log."6 A committed message is not lost while one broker that has a copy of its partition stays alive.6 The producer setting acks=all waits for the full set of in-sync replicas, and the source code says of it: "This is the strongest available guarantee."7 In Kafka 4.1, all is the default.7
At least once, not exactly once. The store keeps a message until the ack, so a receiver that does the work and stops before the ack gets the message again. The program below shows this. A durable queue keeps a log on disk with one line for each send and each ack, and it calls fsync after each line. The receiver ships parcel m2 and stops before it can ack it. When the receiver starts again, it reads the log, and m2 is still pending.
import os
import tempfile
class DurableQueue:
"""A queue whose state is a log on disk: one line for each send and each ack."""
def __init__(self, path):
self.path = path
self.pending = {}
if os.path.exists(path):
with open(path) as f:
for line in f:
op, mid, *body = line.rstrip("\n").split(" ", 2)
if op == "send":
self.pending[mid] = body[0]
else:
self.pending.pop(mid, None)
def _log(self, line):
with open(self.path, "a") as f:
f.write(line + "\n")
f.flush()
os.fsync(f.fileno())
def send(self, mid, body):
self._log(f"send {mid} {body}") # returns only when the line is on disk
self.pending[mid] = body
def ack(self, mid):
self._log(f"ack {mid}")
del self.pending[mid]
shipped = []
def ship(mid, body):
shipped.append(mid)
print(f"ship {mid}: {body}")
path = os.path.join(tempfile.mkdtemp(), "parcels.log")
q = DurableQueue(path)
q.send("m1", "parcel to Hanoi")
q.send("m2", "parcel to Hue")
q.send("m3", "parcel to Da Nang")
mid, body = next(iter(q.pending.items()))
ship(mid, body)
q.ack(mid)
mid, body = next(iter(q.pending.items()))
ship(mid, body)
print("crash after the work, before the ack")
del q
q = DurableQueue(path) # the receiver starts again and reads the log
print("pending after restart:", " ".join(q.pending))
for mid, body in list(q.pending.items()):
ship(mid, body)
q.ack(mid)
print("pending:", len(q.pending))
print("m2 shipped", shipped.count("m2"), "times")
os.remove(path)
ship m1: parcel to Hanoi
ship m2: parcel to Hue
crash after the work, before the ack
pending after restart: m2 m3
ship m2: parcel to Hue
ship m3: parcel to Da Nang
pending: 0
m2 shipped 2 times
No message was lost, but m2 was shipped twice. The same can happen on the side of the sender. RabbitMQ says that a producer that recovers from a failure "should retransmit any messages for which an acknowledgement has not been received from the broker", and that this can make duplicates, "because the broker might have sent a confirmation that never reached the producer".5 A receiver of a guaranteed channel must be idempotent, or it must find the duplicates. Kafka gives one answer for the producer side: with idempotence on, "the producer will ensure that exactly one copy of each message is written in the stream", and "Idempotence is enabled by default if no conflicting configurations are set."7
Example
Each example file keeps two queues: one in memory and one with a log on disk. It sends three orders to each, then simulates a crash: it makes new objects, and the durable queue reads its log again. The queue in memory has lost the three orders, and the durable queue still has them. The receiver then takes one order and acks it, and after a second crash the durable queue has the other two.
Each example forces the data to the disk after each line: os.fsync in Python, File.Sync in Go, FileDescriptor.sync in Java and FileStream.Flush(true) in C#. A write without it can stay in the cache of the operating system, and a crash of the computer can lose it. A crash of the process alone does not lose such a write.
import os
import tempfile
class DurableQueue:
def __init__(self, path):
self.path = path
self.pending = {}
if os.path.exists(path):
with open(path) as f:
for line in f:
op, mid, *body = line.rstrip("\n").split(" ", 2)
if op == "send":
self.pending[mid] = body[0]
else:
self.pending.pop(mid, None)
def _log(self, line):
with open(self.path, "a") as f:
f.write(line + "\n")
f.flush()
os.fsync(f.fileno())
def send(self, mid, body):
self._log(f"send {mid} {body}")
self.pending[mid] = body
def ack(self, mid):
self._log(f"ack {mid}")
del self.pending[mid]
path = os.path.join(tempfile.mkdtemp(), "orders.log")
memory = {}
durable = DurableQueue(path)
for i in (1, 2, 3):
memory[f"m{i}"] = f"order-{i}"
durable.send(f"m{i}", f"order-{i}")
print(f"before crash: memory {len(memory)}, durable {len(durable.pending)}")
memory = {} # a crash loses what was only in memory
durable = DurableQueue(path)
print(f"after crash: memory {len(memory)}, durable {len(durable.pending)}")
mid = next(iter(durable.pending))
print(f"receive {mid} {durable.pending[mid]}, ack")
durable.ack(mid)
durable = DurableQueue(path)
print("after second crash: durable", len(durable.pending), " ".join(durable.pending))
os.remove(path)
before crash: memory 3, durable 3
after crash: memory 0, durable 3
receive m1 order-1, ack
after second crash: durable 2 m2 m3
- Verdict: idiom. Python has no persistent queue. A file that the program appends to, with
os.fsyncafter each line, is the store; the queue reads it again when it starts. sendreturns only afterfsync, so a caller that seessendreturn knows that the line is on disk. This is the confirm of the pattern.- The log grows for ever. A real store removes the acked records from time to time, for example by writing the pending ones to a new file and renaming it over the old one.
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
// A queue whose state is a log on disk: one line for each send and each ack.
static final class DurableQueue {
final Path path;
final Map<String, String> pending = new LinkedHashMap<>();
DurableQueue(Path path) throws IOException {
this.path = path;
if (Files.exists(path)) {
for (String line : Files.readAllLines(path, StandardCharsets.UTF_8)) {
String[] p = line.split(" ", 3);
if (p[0].equals("send")) {
pending.put(p[1], p[2]);
} else {
pending.remove(p[1]);
}
}
}
}
void log(String line) throws IOException {
try (FileOutputStream out = new FileOutputStream(path.toFile(), true)) {
out.write((line + "\n").getBytes(StandardCharsets.UTF_8));
out.getFD().sync();
}
}
void send(String id, String body) throws IOException {
log("send " + id + " " + body);
pending.put(id, body);
}
void ack(String id) throws IOException {
log("ack " + id);
pending.remove(id);
}
}
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("gd");
Path path = dir.resolve("orders.log");
Map<String, String> memory = new HashMap<>();
DurableQueue durable = new DurableQueue(path);
for (int i = 1; i <= 3; i++) {
memory.put("m" + i, "order-" + i);
durable.send("m" + i, "order-" + i);
}
System.out.println("before crash: memory " + memory.size() + ", durable " + durable.pending.size());
memory = new HashMap<>(); // a crash loses what was only in memory
durable = new DurableQueue(path);
System.out.println("after crash: memory " + memory.size() + ", durable " + durable.pending.size());
String id = durable.pending.keySet().iterator().next();
System.out.println("receive " + id + " " + durable.pending.get(id) + ", ack");
durable.ack(id);
durable = new DurableQueue(path);
System.out.println("after second crash: durable " + durable.pending.size() + " "
+ String.join(" ", durable.pending.keySet()));
Files.delete(path);
Files.delete(dir);
}
}
before crash: memory 3, durable 3
after crash: memory 0, durable 3
receive m1 order-1, ack
after second crash: durable 2 m2 m3
- Verdict: idiom. The Java standard library has no persistent queue. A log file with
FileDescriptor.syncafter each line is the store. - A
LinkedHashMapkeeps the pending messages in the order of the log, so the receiver takes the oldest one first. - In Jakarta Messaging, the same choice is the delivery mode of the producer,
DeliveryMode.PERSISTENT, and the provider does the writes.
using System.Text;
var dir = Directory.CreateTempSubdirectory("gd").FullName;
var path = Path.Combine(dir, "orders.log");
var memory = new Dictionary<string, string>();
var durable = new DurableQueue(path);
for (int i = 1; i <= 3; i++)
{
memory[$"m{i}"] = $"order-{i}";
durable.Send($"m{i}", $"order-{i}");
}
Console.WriteLine($"before crash: memory {memory.Count}, durable {durable.Pending.Count}");
memory = new Dictionary<string, string>(); // a crash loses what was only in memory
durable = new DurableQueue(path);
Console.WriteLine($"after crash: memory {memory.Count}, durable {durable.Pending.Count}");
var id = durable.Ids()[0];
Console.WriteLine($"receive {id} {durable.Pending[id]}, ack");
durable.Ack(id);
durable = new DurableQueue(path);
Console.WriteLine($"after second crash: durable {durable.Pending.Count} {string.Join(" ", durable.Ids())}");
Directory.Delete(dir, true);
// A queue whose state is a log on disk: one line for each send and each ack.
sealed class DurableQueue
{
private readonly string path;
private readonly List<string> order = new();
public Dictionary<string, string> Pending { get; } = new();
public DurableQueue(string path)
{
this.path = path;
if (!File.Exists(path))
{
return;
}
foreach (var line in File.ReadLines(path))
{
var p = line.Split(' ', 3);
if (p[0] == "send")
{
Pending[p[1]] = p[2];
order.Add(p[1]);
}
else
{
Pending.Remove(p[1]);
}
}
}
private void Log(string line)
{
using var f = new FileStream(path, FileMode.Append, FileAccess.Write);
var bytes = Encoding.UTF8.GetBytes(line + "\n");
f.Write(bytes);
f.Flush(flushToDisk: true);
}
public void Send(string id, string body)
{
Log($"send {id} {body}");
Pending[id] = body;
order.Add(id);
}
public void Ack(string id)
{
Log($"ack {id}");
Pending.Remove(id);
}
// The pending ids in the order they were sent.
public List<string> Ids() => order.Where(Pending.ContainsKey).ToList();
}
before crash: memory 3, durable 3
after crash: memory 0, durable 3
receive m1 order-1, ack
after second crash: durable 2 m2 m3
- Verdict: idiom. .NET has no persistent queue. A log file with
FileStream.Flush(flushToDisk: true)after each line is the store. Flush()with no argument only empties the buffer of the stream into the operating system. The argumenttruealso asks the operating system to write the data to the disk.Directory.CreateTempSubdirectorygives the log a new directory for each run, and the program deletes it at the end.
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
)
// durableQueue keeps its state in a log on disk: one line for each send and each ack.
type durableQueue struct {
path string
order []string
pending map[string]string
}
func open(path string) (*durableQueue, error) {
q := &durableQueue{path: path, pending: map[string]string{}}
f, err := os.Open(path)
if os.IsNotExist(err) {
return q, nil
} else if err != nil {
return nil, err
}
defer f.Close()
s := bufio.NewScanner(f)
for s.Scan() {
p := strings.SplitN(s.Text(), " ", 3)
if p[0] == "send" {
q.pending[p[1]] = p[2]
q.order = append(q.order, p[1])
} else {
delete(q.pending, p[1])
}
}
return q, s.Err()
}
func (q *durableQueue) log(line string) error {
f, err := os.OpenFile(q.path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
return err
}
if _, err = f.WriteString(line + "\n"); err == nil {
err = f.Sync()
}
if cerr := f.Close(); err == nil {
err = cerr
}
return err
}
func (q *durableQueue) send(id, body string) error {
if err := q.log("send " + id + " " + body); err != nil {
return err
}
q.pending[id] = body
q.order = append(q.order, id)
return nil
}
func (q *durableQueue) ack(id string) error {
if err := q.log("ack " + id); err != nil {
return err
}
delete(q.pending, id)
return nil
}
// ids gives the pending ids in the order they were sent.
func (q *durableQueue) ids() []string {
var out []string
for _, id := range q.order {
if _, ok := q.pending[id]; ok {
out = append(out, id)
}
}
return out
}
func main() {
dir, err := os.MkdirTemp("", "gd")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "orders.log")
memory := map[string]string{}
durable, err := open(path)
if err != nil {
panic(err)
}
for i := 1; i <= 3; i++ {
id, body := fmt.Sprintf("m%d", i), fmt.Sprintf("order-%d", i)
memory[id] = body
if err := durable.send(id, body); err != nil {
panic(err)
}
}
fmt.Printf("before crash: memory %d, durable %d\n", len(memory), len(durable.pending))
memory = map[string]string{} // a crash loses what was only in memory
if durable, err = open(path); err != nil {
panic(err)
}
fmt.Printf("after crash: memory %d, durable %d\n", len(memory), len(durable.pending))
id := durable.ids()[0]
fmt.Printf("receive %s %s, ack\n", id, durable.pending[id])
if err := durable.ack(id); err != nil {
panic(err)
}
if durable, err = open(path); err != nil {
panic(err)
}
fmt.Println("after second crash: durable", len(durable.pending), strings.Join(durable.ids(), " "))
}
before crash: memory 3, durable 3
after crash: memory 0, durable 3
receive m1 order-1, ack
after second crash: durable 2 m2 m3
- Verdict: idiom. Go has no persistent queue. A log file with
File.Syncafter each line is the store, andopenreads it again after a crash. logreturns the error ofSyncand ofClose. A program that ignores them can tell the sender that a message is safe when the write failed.- A Go map has no order, so the queue keeps a separate slice of the ids in the order they were sent.
Consequences
Benefits.
- A crash does not lose accepted messages. The sender can forget a message when the confirm comes.
- The sender and the receiver need not run at the same time. A message waits on disk until the receiver is there.
- A clear contract. The confirm and the ack tell each side when its part is done.
Liabilities.
- Speed. Each persistent message costs a disk write, or a write on many brokers. Brokers write in batches to reduce the number of
fsynccalls, and this adds a delay to each confirm.4 - Disk space. Messages for a receiver that is down stay on disk until it comes back. A durable subscription for a program that never comes back holds its messages until somebody deletes the subscription.
- Duplicates. A crash between the work and the ack, or between the confirm and its arrival at the sender, gives the same message twice, as the program shows.
- The guarantee has limits. A persistent message in a queue that is not durable, a broker that fails before its batch write, or a store on a disk that fails can still lose messages.45 Replication across computers covers the last case.6
When not to use it
For data that is soon out of date. A position of a vehicle or a price that comes each second is replaced by the next message. Jakarta Messaging calls the NON_PERSISTENT mode the lowest overhead mode;3 use it, or a channel in memory, for such data.
When the sender can produce the message again. If the data is in a database of the sender, a lost message can be sent again from it, and a fast channel in memory can be sufficient.
As the only protection. Guaranteed delivery keeps the message in the messaging system. It does not make the receiver do the work. Add a Dead Letter Channel for the messages that always fail, and idempotent receivers for the duplicates.
Variants and related patterns
Durable subscriber. On a Publish-Subscribe Channel, a persistent message reaches a subscriber that was not active only if the subscription is durable.3
Store and forward. The chain of stores in the solution is store and forward: each computer keeps the message until the next one has it.1
Transactions. In standard AMQP 0-9-1, the only way to make sure that a message is not lost is a transactional channel. RabbitMQ says that transactions "are unnecessarily heavyweight and decrease throughput by a factor of 250", and it gives publisher confirms for the same need.4
Dead Letter Channel. A Dead Letter Channel keeps the persistent messages that cannot be delivered.
Retries. A sender that has no confirm sends again, with a delay; see Retry with backoff.
Known uses
- Apache Kafka: ProducerConfig.java at 4.1.0 gives the meaning of
acks=0,acks=1andacks=all; the same file setsallas the default.7 - Jakarta Messaging: the delivery modes PERSISTENT and NON_PERSISTENT.3
- RabbitMQ: durable queues, persistent messages and publisher confirms.45
References
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Guaranteed Delivery (problem and solution under CC BY), problem and solution statements; pattern text
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Designing, Building, and Deploying Messaging Solutions, Addison-Wesley, 2003, Chapter 4, Messaging Channels, Guaranteed Delivery
- Jakarta Messaging 3.1 specification, 7.7 Message delivery mode; Table 4-1 Pub/sub reliability
- RabbitMQ documentation, Consumer Acknowledgements and Publisher Confirms, When Will Published Messages Be Confirmed by the Broker; Publisher Confirms and Guaranteed Delivery
- RabbitMQ documentation, Reliability Guide, Data Safety on the RabbitMQ Side; Data Safety on the Publisher Side
- Apache Kafka 4.1.0 documentation source, design.html, Message Delivery Semantics; Replication
- Apache Kafka 4.1.0 source, ProducerConfig.java, ACKS_DOC, lines 124 to 138; ACKS_CONFIG default, lines 383 to 386; ENABLE_IDEMPOTENCE_DOC, lines 336 to 342
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag DBNWZH Edit this page History Report an error Markdown