Patterncore
Claim Check
Also called Claim Check pattern, reference-based messaging, large message offload, store in library.
A claim check stores a large or sensitive payload in an external store and sends only a key to it through the messaging system; a later component uses the key to get the payload back.
- Family
- integration
- Intent
- Keep messages small, by a step that puts the payload in a persistent store and sends a reference to it in its place, so that the components that need the data can get it back by the reference.
- Also called
- reference-based messaging
Intent
Send a small reference through the messaging system in place of a large payload, and get the payload back where it is needed. The book asks: "How can we reduce the data volume of message sent across the system without sacrificing information content?"12 The answer: "Store message data in a persistent store and pass a Claim Check to subsequent components. These components can use the Claim Check to retrieve the stored information."1
Problem
Messaging systems are made for many small messages, and they often limit the size of a message.3 An Amazon SQS message can have at most 1 MiB.4 A scanned document, a video or a large report does not fit, or it fits but slows the broker.
The Azure page names four problems of large messages.3 The broker rejects a message over its limit. Large payloads use memory and disk in the broker that other messages need. Each step takes longer to serialize and transfer them. Some services charge by the size of the message. The book adds that the steps in the middle of a flow often do not need all the data, and that a large message is also harder to debug.1
The forces are these. The data must not be lost. The message must stay small. And the component at the end must still get all of the data.
Solution
Before the message goes on the channel, put the payload in a persistent store, such as a file, a database or a blob store. Put the key of the stored data in the message in place of the data. A later component uses the key to get the data back.1 The book compares this to a luggage check at an airport: you get a ticket with a number, and you use it to get your bag at the end of the trip.1
(1) put payload (5) get payload by key
sender --------------------> [ store ] <------------------- receiver
| ^
+--(2) [ key, type, size ] --> [ channel ] --> router --(4)--+
The participants are the sender, or a check luggage step, the store, the channel with the small message, and the receiver, or a content enricher step that gets the data back.1 The steps in the middle see only the key.
The order of the writes. The write to the store and the publish of the message are in two systems and are not one transaction. The Azure page says to publish the claim check only after the write of the payload succeeds; a failure between the two steps can leave a payload that no message points to.3
For all messages, or only for large ones. A sender can make a claim check for each message, or only for a message over a size. If the choice is made for each message, the format of the message must show whether the payload is inline or in the store.3 The program below sends three payloads through a broker with a limit of 256 KiB and three steps in the route, and then shows a problem of the lifecycle of the payload.
import json
LIMIT = 256 * 1024 # the largest message that the broker in this program takes
HOPS = 3 # router, translator, consumer: each hop reads and writes the message
payloads = {"invoice": 2 * 1024, "scan": 300 * 1024, "video": 5 * 1024 * 1024}
def message(kind, size, threshold):
if size <= threshold:
return size # the payload goes inline
check = {"type": kind, "claim": f"store/{kind}", "size": size}
return len(json.dumps(check))
for name, threshold in [("inline", float("inf")), ("claim check for all", 0),
("claim check over 64 KiB", 64 * 1024)]:
sizes = {k: message(k, s, threshold) for k, s in payloads.items()}
rejected = [k for k, s in sizes.items() if s > LIMIT]
moved = sum(s for k, s in sizes.items() if k not in rejected) * HOPS
print(f"{name}: rejected {', '.join(rejected) or 'none'}, {moved} bytes through the broker")
# Who deletes the payload? Here the consumer deletes it when it reads it,
# then crashes before the ack, and the broker delivers the claim check again.
store = {"store/scan": b"..."}
for delivery in (1, 2):
data = store.pop("store/scan", None)
print(f"delivery {delivery}:", "payload read" if data else "claim store/scan: payload not found")
inline: rejected scan, video, 6144 bytes through the broker
claim check for all: rejected none, 516 bytes through the broker
claim check over 64 KiB: rejected none, 6483 bytes through the broker
delivery 1: payload read
delivery 2: claim store/scan: payload not found
Inline, the broker rejects two of the three messages. With a claim check for each message, the broker moves 516 bytes in place of more than 5 MiB. With a claim check only over 64 KiB, the small invoice stays inline, and no step must go to the store for it. The last two lines show a payload that the consumer deleted when it read it: when the broker delivers the message again, the claim check points to nothing.
Example
Each example file sends a short invoice inline and a report of 276,000 bytes as a claim check. The key is the SHA-256 hash of the payload. Thus the receiver can check that the data it gets back is the data that was sent. The Azure page suggests a content hash for this.3 Then the store loses the payload, as a lifecycle rule can do, and the same message gives a claim check that cannot be resolved, which goes to the dead letter channel.
import hashlib
THRESHOLD = 1024 # payloads larger than this go to the store
store = {} # stands for a blob store or a database
channel = []
def send(kind, payload):
if len(payload) <= THRESHOLD:
message = f"{kind};inline;{payload.decode()}"
else:
key = "sha256:" + hashlib.sha256(payload).hexdigest()
store[key] = payload # store first, then publish the claim check
message = f"{kind};claim;{key};{len(payload)}"
channel.append(message)
print(f"sent {kind}: {len(message)} bytes on the channel"
+ (f" for {len(payload)} bytes in the store" if len(payload) > THRESHOLD else ""))
def receive(message):
kind, mode, rest = message.split(";", 2)
if mode == "inline":
return f"received {kind}: {rest}"
key, size = rest.split(";")
payload = store.get(key)
if payload is None:
return f"received {kind}: claim {key[:19]}... not found, to the dead letter channel"
if "sha256:" + hashlib.sha256(payload).hexdigest() != key or len(payload) != int(size):
return f"received {kind}: payload does not match the claim check"
rows = payload.count(b"\n")
return f"received {kind}: {rows} rows, hash {key[7:19]} ok"
report = b"".join(b"row %05d;widget;12.50\n" % i for i in range(12000))
send("invoice", b"INV-17 total 12.50")
send("report", report)
for m in channel:
print(receive(m))
# The lifecycle rule of the store removes the payload; then the broker delivers the claim again.
store.clear()
print(receive(channel[1]))
sent invoice: 33 bytes on the channel
sent report: 91 bytes on the channel for 276000 bytes in the store
received invoice: INV-17 total 12.50
received report: 12000 rows, hash 63b98860796d ok
received report: claim sha256:63b98860796d... not found, to the dead letter channel
- Verdict: idiom.
hashlib.sha256(payload).hexdigest()gives a key that depends only on the content, and a dict stands for the blob store. - The sender writes to the store before it puts the claim check on the channel, so a receiver never gets a key with no data behind it at that time.
- The receiver checks the hash and the size; a missing payload gives a message for the dead letter channel, not an exception.
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
public class Main {
static final int THRESHOLD = 1024; // payloads larger than this go to the store
static final Map<String, byte[]> store = new HashMap<>(); // stands for a blob store or a database
static final List<String> channel = new ArrayList<>();
static String hash(byte[] b) throws Exception {
return "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(b));
}
static void send(String kind, byte[] payload) throws Exception {
String message, extra = "";
if (payload.length <= THRESHOLD) {
message = kind + ";inline;" + new String(payload, StandardCharsets.UTF_8);
} else {
String key = hash(payload);
store.put(key, payload); // store first, then publish the claim check
message = kind + ";claim;" + key + ";" + payload.length;
extra = " for " + payload.length + " bytes in the store";
}
channel.add(message);
System.out.println("sent " + kind + ": " + message.length() + " bytes on the channel" + extra);
}
static String receive(String message) throws Exception {
String[] parts = message.split(";", 3);
String kind = parts[0], mode = parts[1], rest = parts[2];
if (mode.equals("inline")) return "received " + kind + ": " + rest;
String[] claim = rest.split(";");
String key = claim[0];
byte[] payload = store.get(key);
if (payload == null)
return "received " + kind + ": claim " + key.substring(0, 19) + "... not found, to the dead letter channel";
if (!hash(payload).equals(key) || payload.length != Integer.parseInt(claim[1]))
return "received " + kind + ": payload does not match the claim check";
long rows = new String(payload, StandardCharsets.US_ASCII).chars().filter(c -> c == '\n').count();
return "received " + kind + ": " + rows + " rows, hash " + key.substring(7, 19) + " ok";
}
public static void main(String[] args) throws Exception {
StringBuilder report = new StringBuilder();
for (int i = 0; i < 12000; i++) report.append(String.format("row %05d;widget;12.50\n", i));
send("invoice", "INV-17 total 12.50".getBytes(StandardCharsets.UTF_8));
send("report", report.toString().getBytes(StandardCharsets.US_ASCII));
for (String m : channel) System.out.println(receive(m));
// The lifecycle rule of the store removes the payload; then the broker delivers the claim again.
store.clear();
System.out.println(receive(channel.get(1)));
}
}
sent invoice: 33 bytes on the channel
sent report: 91 bytes on the channel for 276000 bytes in the store
received invoice: INV-17 total 12.50
received report: 12000 rows, hash 63b98860796d ok
received report: claim sha256:63b98860796d... not found, to the dead letter channel
- Verdict: idiom.
MessageDigest.getInstance("SHA-256")andHexFormatmake the key; aHashMap<String, byte[]>stands for the blob store. split(";", 3)with a limit keeps the rest of the message in one part.store.clear()plays the lifecycle rule that removes the payload.
using System.Security.Cryptography;
using System.Text;
const int Threshold = 1024; // payloads larger than this go to the store
var store = new Dictionary<string, byte[]>(); // stands for a blob store or a database
var channel = new List<string>();
string Hash(byte[] b) => "sha256:" + Convert.ToHexString(SHA256.HashData(b)).ToLowerInvariant();
void Send(string kind, byte[] payload)
{
string message, extra = "";
if (payload.Length <= Threshold)
{
message = $"{kind};inline;{Encoding.UTF8.GetString(payload)}";
}
else
{
var key = Hash(payload);
store[key] = payload; // store first, then publish the claim check
message = $"{kind};claim;{key};{payload.Length}";
extra = $" for {payload.Length} bytes in the store";
}
channel.Add(message);
Console.WriteLine($"sent {kind}: {message.Length} bytes on the channel{extra}");
}
string Receive(string message)
{
var parts = message.Split(';', 3);
var (kind, mode, rest) = (parts[0], parts[1], parts[2]);
if (mode == "inline") return $"received {kind}: {rest}";
var claim = rest.Split(';');
var key = claim[0];
if (!store.TryGetValue(key, out var payload))
return $"received {kind}: claim {key[..19]}... not found, to the dead letter channel";
if (Hash(payload) != key || payload.Length != int.Parse(claim[1]))
return $"received {kind}: payload does not match the claim check";
var rows = payload.Count(b => b == (byte)'\n');
return $"received {kind}: {rows} rows, hash {key[7..19]} ok";
}
var report = new StringBuilder();
for (int i = 0; i < 12000; i++) report.Append($"row {i:D5};widget;12.50\n");
Send("invoice", Encoding.UTF8.GetBytes("INV-17 total 12.50"));
Send("report", Encoding.ASCII.GetBytes(report.ToString()));
foreach (var m in channel) Console.WriteLine(Receive(m));
// The lifecycle rule of the store removes the payload; then the broker delivers the claim again.
store.Clear();
Console.WriteLine(Receive(channel[1]));
sent invoice: 33 bytes on the channel
sent report: 91 bytes on the channel for 276000 bytes in the store
received invoice: INV-17 total 12.50
received report: 12000 rows, hash 63b98860796d ok
received report: claim sha256:63b98860796d... not found, to the dead letter channel
- Verdict: idiom.
SHA256.HashDataandConvert.ToHexStringmake the key; aDictionary<string, byte[]>stands for the blob store. TryGetValuegives the missing payload as a normal case, which goes to the dead letter channel.store.Clear()plays the lifecycle rule that removes the payload.
package main
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"strconv"
"strings"
)
const threshold = 1024 // payloads larger than this go to the store
var store = map[string][]byte{} // stands for a blob store or a database
var channel []string
func hash(b []byte) string {
sum := sha256.Sum256(b)
return "sha256:" + hex.EncodeToString(sum[:])
}
func send(kind string, payload []byte) {
var message string
extra := ""
if len(payload) <= threshold {
message = kind + ";inline;" + string(payload)
} else {
key := hash(payload)
store[key] = payload // store first, then publish the claim check
message = fmt.Sprintf("%s;claim;%s;%d", kind, key, len(payload))
extra = fmt.Sprintf(" for %d bytes in the store", len(payload))
}
channel = append(channel, message)
fmt.Printf("sent %s: %d bytes on the channel%s\n", kind, len(message), extra)
}
func receive(message string) string {
parts := strings.SplitN(message, ";", 3)
kind, mode, rest := parts[0], parts[1], parts[2]
if mode == "inline" {
return "received " + kind + ": " + rest
}
key, sizeText, _ := strings.Cut(rest, ";")
size, _ := strconv.Atoi(sizeText)
payload, ok := store[key]
if !ok {
return fmt.Sprintf("received %s: claim %s... not found, to the dead letter channel", kind, key[:19])
}
if hash(payload) != key || len(payload) != size {
return "received " + kind + ": payload does not match the claim check"
}
return fmt.Sprintf("received %s: %d rows, hash %s ok", kind, bytes.Count(payload, []byte("\n")), key[7:19])
}
func main() {
var report bytes.Buffer
for i := 0; i < 12000; i++ {
fmt.Fprintf(&report, "row %05d;widget;12.50\n", i)
}
send("invoice", []byte("INV-17 total 12.50"))
send("report", report.Bytes())
for _, m := range channel {
fmt.Println(receive(m))
}
// The lifecycle rule of the store removes the payload; then the broker delivers the claim again.
clear(store)
fmt.Println(receive(channel[1]))
}
sent invoice: 33 bytes on the channel
sent report: 91 bytes on the channel for 276000 bytes in the store
received invoice: INV-17 total 12.50
received report: 12000 rows, hash 63b98860796d ok
received report: claim sha256:63b98860796d... not found, to the dead letter channel
- Verdict: idiom.
sha256.Sum256andhex.EncodeToStringmake the key, and a map of byte slices stands for the blob store. strings.SplitN(message, ";", 3)keeps any;in an inline payload, andstrings.Cutsplits the key from the size.clear(store)plays the lifecycle rule that removes the payload.
Consequences
Benefits.
- Small messages. The broker moves only the key, so a message stays under the limit and the broker stays fast.3
- Sensitive data off the path. The data stays in a store with its own access control, hidden from the steps in the middle and from tools that read the queue.3 Camel names this use: to hide the sensitive parts of a message from a party that you cannot trust.5
- Less work in the middle. Routers and translators read only a small message.3
Liabilities.
- One more system. The store must be available as long as a receiver can need the payload; if it is down, the processing stops.3
- Who deletes the payload. A component must own the delete. A payload deleted too early breaks a valid claim check, as in the program; a payload never deleted fills the store.3 The store must keep a payload at least as long as the broker can keep the message; SQS keeps a message for 4 days by default and up to 14 days.4
- More latency. The receiver makes an extra call to the store before it can start.3
- Copies. A claim check can be delivered more than once, so the receiver must be an Idempotent Receiver.3
When not to use it
When the messages fit. If the payload is under the limit of the transport and does not slow it, inline delivery is simpler and faster. Azure Service Bus Premium, for example, takes AMQP messages of up to 100 MB.3
When latency comes first. The calls to the store add network trips between the producer and the consumer.3
When the payload can be made smaller or split. Compression or a more compact format can be enough. A Splitter and an Aggregator can send a large payload as a sequence of small messages, at the cost of order, correlation and reassembly.3
Variants and related patterns
Content Filter and Content Enricher. The book places the claim check between the two: it removes data from the message for a time, and a content enricher puts it back later.1 The book puts it in the chapter on message transformation, with the Message Translator and its other variants.2
A stack of claim checks. Camel has the operations Set, Get, GetAndRemove, Push and Pop. Push and Pop use a stack and no key, and the data that comes back is merged into the current message by a filter such as body or header:foo*.5
An event from the store. In three of the Azure samples, the sender only uploads the payload to Blob Storage, and the BlobCreated event from Event Grid, with the URL of the blob, is the claim check.3
Known uses
- Apache Camel: the Claim Check EIP, which keeps the data in an internal memory store, as the Claim Check page of 4.14.0 notes.5
- Amazon SQS: the Extended Client Libraries for Java and Python put a payload in Amazon S3 and send a reference to it; the payload can have up to 2 GB.4
- Azure: samples with Blob Storage and Queue Storage, Event Hubs or Service Bus; NServiceBus has a DataBus feature for the same task.3
References
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Claim Check (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 8, Message Transformation, Claim Check
- Microsoft, Azure Architecture Center, Claim Check pattern, context and problem; solution; problems and considerations; when to use this pattern; alternatives; examples
- Amazon Simple Queue Service Developer Guide, Amazon SQS message quotas, message size; message retention
- Apache Camel 4.14.0 documentation source, Claim Check EIP, introduction; Claim Check operation; merging data using get or pop operation
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 83HZ5D Edit this page History Report an error Markdown