Programming Search⌘K

Patterncore

Idempotent Receiver

Also called Idempotent Receiver pattern, idempotent consumer, de-duplicating receiver, message de-duplication.

An idempotent receiver can get the same message more than once with the same result as once, because it finds duplicates by an id or because its messages have an effect that a repeat does not change.

Family
integration
Intent
Make duplicate messages safe, by a receiver that removes duplicates by their message id, or by messages whose effect is the same when they are applied once or many times.
Also called
idempotent consumer

Intent

Let a receiver get the same message twice, or more often, with the same result as once. The book asks: "How can a message receiver deal with duplicate messages?"12 The answer: "Design a receiver to be an Idempotent Receiver", "one that can safely receive the same message multiple times."1

Problem

A message can arrive more than once even when the sender sends it once.1 In the RabbitMQ tutorial, when a consumer stops before it sends its ack, RabbitMQ delivers all its unacknowledged messages again.3 So a consumer that has done the work but crashes before the ack gets the message a second time. A sender that sends again after a timeout can also make a copy.

The book notes that receivers often assume that each message comes exactly once.4 A receiver that adds money to an account, sends an e-mail or ships goods then does it twice.

The forces are these. Delivery with no loss means delivery with possible copies. The receiver must find a copy at a low cost. Its record of processed messages must not grow for ever. And after a crash, the record and the effect must agree.

Solution

The book gives two ways: remove the duplicates explicitly, or define the meaning of the messages so that a repeat has no further effect.1

  [ queue ] ---> receiver: id in the store? --yes--> ack, and ignore it
                                 |
                                 no --> apply the effect and add the id (one transaction) --> ack

De-duplication. Each message carries a unique id. The receiver keeps the ids of the messages that it has processed. For each message, it looks up the id; if the id is there, it acknowledges the message and does nothing else.

Idempotent meaning. Set the status of order 17 to paid gives the same state when it comes twice. Add 10 to the balance does not. A message with an absolute value, or an update keyed by the id of the message, needs no store of ids.

The order of the steps. Apache Camel adds the message id to its repository eagerly, before the processing ends, so that it also finds a copy of a message that is still in progress. When the processing fails, Camel removes the id again.5 The program below shows why the order matters when the process stops between the two steps. The balance and the ids are in a store that survives the crash, and the broker then delivers m1 again.

# m1 is delivered twice: the broker got no ack for the first delivery.
stream = [("m1", 10), ("m2", 5), ("m1", 10)]


def naive():
    balance = 0
    for _, amount in stream:
        balance += amount
    return balance


def dedup():
    balance, seen = 0, set()
    for mid, amount in stream:
        if mid in seen:
            continue
        balance += amount
        seen.add(mid)
    return balance


print("no check:", naive())
print("de-dup by message id:", dedup())


# Now the process crashes once, after the first step for the first delivery of m1.
# The balance and the set of seen ids are both in a store that survives the crash.
def crash_run(steps):
    db = {"balance": 0, "seen": set()}
    crashed = False
    for mid, amount in stream:
        if mid in db["seen"]:
            continue
        staged = []
        for i, step in enumerate(steps):
            if i == 1 and mid == "m1" and not crashed:
                crashed = True  # the process stops; the broker delivers m1 again
                break
            if step == "mark":
                db["seen"].add(mid)
            elif step == "apply":
                db["balance"] += amount
            elif step == "stage both":
                staged = [amount, mid]
            elif step == "commit":
                db["balance"] += staged[0]
                db["seen"].add(staged[1])
    return db["balance"]


print("mark, then apply:", crash_run(["mark", "apply"]))
print("apply, then mark:", crash_run(["apply", "mark"]))
print("one transaction for both:", crash_run(["stage both", "commit"]))
Output
no check: 25
de-dup by message id: 15
mark, then apply: 5
apply, then mark: 25
one transaction for both: 15

With no check, m1 counts twice. With the id marked first, the crash loses m1, because its second delivery looks like a copy. With the effect applied first, the crash gives a double effect. Only when the effect and the id are written in one transaction is the result 15.

Example

Each example file receives payments for orders and keeps the ids of the last three messages. The copy of pay-1 that comes at once is ignored. The copy of pay-2 comes after three other messages, when its id has left the window, so the payment counts twice. The window must be longer than the longest time in which a copy can come. Amazon SQS FIFO queues, for example, use a deduplication interval of 5 minutes.6

PythonGitHub
from collections import OrderedDict

WINDOW = 3
deliveries = [
    ("pay-1", 17, 1250), ("pay-2", 18, 800), ("pay-1", 17, 1250),
    ("pay-3", 17, 300), ("pay-4", 19, 500), ("pay-5", 20, 100),
    ("pay-2", 18, 800),
]


class PaymentReceiver:
    def __init__(self, window):
        self.window = window
        self.seen = OrderedDict()  # message id -> None, oldest first
        self.totals = {}
        self.ever = set()  # only to explain the output; a real receiver has no such set

    def receive(self, mid, order, cents):
        if mid in self.seen:
            return f"{mid}: duplicate, ignored"
        self.totals[order] = self.totals.get(order, 0) + cents
        self.seen[mid] = None
        if len(self.seen) > self.window:
            self.seen.popitem(last=False)
        note = f" (applied twice: the id left the window of {self.window} ids)" if mid in self.ever else ""
        self.ever.add(mid)
        return f"{mid}: order {order} +{cents}, total {self.totals[order]}{note}"


r = PaymentReceiver(WINDOW)
for d in deliveries:
    print(r.receive(*d))
Output
pay-1: order 17 +1250, total 1250
pay-2: order 18 +800, total 800
pay-1: duplicate, ignored
pay-3: order 17 +300, total 1550
pay-4: order 19 +500, total 500
pay-5: order 20 +100, total 100
pay-2: order 18 +800, total 1600 (applied twice: the id left the window of 3 ids)
  • Verdict: idiom. An OrderedDict keeps the ids in the order of arrival, so popitem(last=False) removes the oldest id when the window is full.
  • The id is added only after the effect, and both are in memory here; with a database, the update of the total and the insert of the id belong in one transaction.
  • The set ever exists only to explain the output; a real receiver cannot know about an id that it has forgotten.
JavaGitHub
import java.util.*;

public class Main {
    static final int WINDOW = 3;
    record Delivery(String id, int order, int cents) {}

    static class PaymentReceiver {
        // insertion order; the oldest id is removed when the window is full
        final Map<String, Boolean> seen = new LinkedHashMap<>() {
            @Override
            protected boolean removeEldestEntry(Map.Entry<String, Boolean> eldest) {
                return size() > WINDOW;
            }
        };
        final Map<Integer, Integer> totals = new HashMap<>();
        final Set<String> ever = new HashSet<>(); // only to explain the output

        String receive(Delivery d) {
            if (seen.containsKey(d.id())) return d.id() + ": duplicate, ignored";
            int total = totals.merge(d.order(), d.cents(), Integer::sum);
            seen.put(d.id(), true);
            String note = ever.add(d.id()) ? ""
                    : " (applied twice: the id left the window of " + WINDOW + " ids)";
            return d.id() + ": order " + d.order() + " +" + d.cents() + ", total " + total + note;
        }
    }

    public static void main(String[] args) {
        List<Delivery> deliveries = List.of(
                new Delivery("pay-1", 17, 1250), new Delivery("pay-2", 18, 800), new Delivery("pay-1", 17, 1250),
                new Delivery("pay-3", 17, 300), new Delivery("pay-4", 19, 500), new Delivery("pay-5", 20, 100),
                new Delivery("pay-2", 18, 800));
        PaymentReceiver r = new PaymentReceiver();
        for (Delivery d : deliveries) System.out.println(r.receive(d));
    }
}
Output
pay-1: order 17 +1250, total 1250
pay-2: order 18 +800, total 800
pay-1: duplicate, ignored
pay-3: order 17 +300, total 1550
pay-4: order 19 +500, total 500
pay-5: order 20 +100, total 100
pay-2: order 18 +800, total 1600 (applied twice: the id left the window of 3 ids)
  • Verdict: idiom. A LinkedHashMap that overrides removeEldestEntry is a bounded store of ids in a few lines.
  • totals.merge(order, cents, Integer::sum) adds to the total of an order, or starts it.
  • The set ever exists only to explain the output; ever.add returns false for an id that came before.
const int Window = 3;
var deliveries = new (string Id, int Order, int Cents)[]
{
    ("pay-1", 17, 1250), ("pay-2", 18, 800), ("pay-1", 17, 1250),
    ("pay-3", 17, 300), ("pay-4", 19, 500), ("pay-5", 20, 100),
    ("pay-2", 18, 800),
};

var receiver = new PaymentReceiver(Window);
foreach (var (id, order, cents) in deliveries)
    Console.WriteLine(receiver.Receive(id, order, cents));

class PaymentReceiver(int window)
{
    readonly Queue<string> order = new();   // ids in the window, oldest first
    readonly HashSet<string> seen = new();
    readonly Dictionary<int, int> totals = new();
    readonly HashSet<string> ever = new();  // only to explain the output

    public string Receive(string id, int orderId, int cents)
    {
        if (seen.Contains(id)) return $"{id}: duplicate, ignored";
        totals[orderId] = totals.GetValueOrDefault(orderId) + cents;
        seen.Add(id);
        order.Enqueue(id);
        if (order.Count > window) seen.Remove(order.Dequeue());
        var note = ever.Add(id) ? "" : $" (applied twice: the id left the window of {window} ids)";
        return $"{id}: order {orderId} +{cents}, total {totals[orderId]}{note}";
    }
}
Output
pay-1: order 17 +1250, total 1250
pay-2: order 18 +800, total 800
pay-1: duplicate, ignored
pay-3: order 17 +300, total 1550
pay-4: order 19 +500, total 500
pay-5: order 20 +100, total 100
pay-2: order 18 +800, total 1600 (applied twice: the id left the window of 3 ids)
  • Verdict: idiom. A HashSet<string> gives the lookup, and a Queue<string> keeps the ids in the order of arrival for the window.
  • GetValueOrDefault reads 0 for an order with no payment yet.
  • The set ever exists only to explain the output; HashSet.Add returns false for an id that came before.
package main

import "fmt"

const window = 3

type delivery struct {
	id           string
	order, cents int
}

type receiver struct {
	order  []string // ids in the window, oldest first
	seen   map[string]bool
	totals map[int]int
	ever   map[string]bool // only to explain the output
}

func (r *receiver) receive(d delivery) string {
	if r.seen[d.id] {
		return d.id + ": duplicate, ignored"
	}
	r.totals[d.order] += d.cents
	r.seen[d.id] = true
	r.order = append(r.order, d.id)
	if len(r.order) > window {
		delete(r.seen, r.order[0])
		r.order = r.order[1:]
	}
	note := ""
	if r.ever[d.id] {
		note = fmt.Sprintf(" (applied twice: the id left the window of %d ids)", window)
	}
	r.ever[d.id] = true
	return fmt.Sprintf("%s: order %d +%d, total %d%s", d.id, d.order, d.cents, r.totals[d.order], note)
}

func main() {
	deliveries := []delivery{
		{"pay-1", 17, 1250}, {"pay-2", 18, 800}, {"pay-1", 17, 1250},
		{"pay-3", 17, 300}, {"pay-4", 19, 500}, {"pay-5", 20, 100},
		{"pay-2", 18, 800},
	}
	r := &receiver{seen: map[string]bool{}, totals: map[int]int{}, ever: map[string]bool{}}
	for _, d := range deliveries {
		fmt.Println(r.receive(d))
	}
}
Output
pay-1: order 17 +1250, total 1250
pay-2: order 18 +800, total 800
pay-1: duplicate, ignored
pay-3: order 17 +300, total 1550
pay-4: order 19 +500, total 500
pay-5: order 20 +100, total 100
pay-2: order 18 +800, total 1600 (applied twice: the id left the window of 3 ids)
  • Verdict: idiom. A map gives the lookup of an id, and a slice keeps the ids in the order of arrival, so the oldest one can be removed.
  • r.totals[d.order] += d.cents works for a new order too, because a missing key reads as 0.
  • The map ever exists only to explain the output; a real receiver has no such map.

Consequences

Benefits.

  • Safe redelivery. The broker and the senders can retry, and each message still has its effect once.
  • Simple recovery. After a crash, the messages can be delivered again with no manual repair.
  • One place for the rule. The check is in the receiver, not in each sender.

Liabilities.

  • A store of ids. It must survive a restart, and the competing consumers of one queue must share it. Camel has many repositories, from one in memory to Cassandra, JDBC, Kafka, MongoDB and Redis.5
  • A limit on the store. A store with no limit grows for ever. A store with a limit lets a late copy through, as the example shows.
  • A stable id. The sender must keep the id when it sends again. SQS can make the id from the content: it uses a SHA-256 hash of the body of the message, but not its attributes.6
  • More work for each message. Each message needs a lookup and a write.
  • Application logic. Spring Integration calls it "a functional pattern" and says that "the whole idempotency logic should be implemented in the application."7

When not to use it

When the effect is already idempotent. A message that sets a value or deletes a record by its key can come twice with no harm, and a store of ids only adds cost.1

When a copy does no harm. A message that only refreshes a cache or a display can be processed again.

When the broker removes the copies that matter. SQS FIFO queues do not add a copy when a sender sends again within the 5-minute deduplication interval.6 Check which copies the feature covers before you remove the check from the receiver.

Message filter. Camel describes its Idempotent Consumer as a message filter that removes duplicates.5 Spring Integration can instead mark a copy with the header duplicateMessage set to true, so that the handler decides, or send it to a discard channel.7

A high-water mark. In place of a set of ids, Spring Integration can keep one value for each key, such as the last line number of a file, and accept a message only when its value is newer.7

Guaranteed delivery and retries. Guaranteed Delivery and a sender with Retry with backoff make copies, and an idempotent receiver makes them safe. The Azure page on Competing Consumers asks for idempotent processing for the same reason.8

Known uses

  • Apache Camel: the Idempotent Consumer EIP with a pluggable IdempotentRepository, as the Idempotent Consumer page of 4.14.0 lists.5
  • Spring Integration: the IdempotentReceiverInterceptor with a MetadataStoreSelector, applied to an existing endpoint.7
  • Amazon SQS FIFO queues: a message deduplication ID from the sender, or content-based deduplication.6

References

  1. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Idempotent Receiver (problem and solution under CC BY), problem and solution statements; pattern text
  2. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Designing, Building, and Deploying Messaging Solutions, Addison-Wesley, 2003, Chapter 10, Messaging Endpoints, Idempotent Receiver
  3. RabbitMQ tutorials, Work Queues (Python), message acknowledgment
  4. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Introduction to Messaging Endpoints, message consumer patterns
  5. Apache Camel 4.14.0 documentation source, Idempotent Consumer EIP, introduction; Idempotent Consumer implementations
  6. Amazon Simple Queue Service Developer Guide, Exactly-once processing in Amazon SQS, whole page
  7. Spring Integration 7.1.1 reference source, Idempotent Receiver Enterprise Integration Pattern, introduction; MetadataStoreSelector
  8. Microsoft, Azure Architecture Center, Competing Consumers pattern, problems and considerations

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/B9TJ6Z/text.yaml