Programming Search⌘K

Patterncore

Content Enricher

Also called Content Enricher pattern, data enricher, message enrichment, enrich EIP.

A content enricher is a translator step that uses a key in a message to get missing data from another source, such as a database or a service, and adds that data to the message before it goes on.

Family
integration
Intent
Give the receiver all the data it needs, by a step that reads a key from the message, gets the missing data by computation, from the environment or from another system, and adds it to the message.
Also called
data enricher

Intent

Add the data that a receiver needs and the sender does not have. The book asks: "How do we communicate with another system if the message originator does not have all the required data items available?"12 The answer: "Use a specialized transformer, a Content Enricher", "to access an external data source in order to augment a message with missing information."1

Problem

Two systems seldom keep the same data. The book gives examples. An address message has only a ZIP code, but the receiver needs a state code too. A system sends a customer id, but the receiver needs the name and the address of the customer. An order message has an order number, but the next system needs the id of the customer of that order.1

The sender cannot always add the data. It does not have the data, or the data is not part of its domain. And the receiver must not change to look up the data itself, because then it depends on one more system.

Solution

Put a step between the sender and the receiver. The step reads a key from the message, such as a customer id, uses it to get the missing data, and adds the data to the message.1 The fields of the original message can stay in the new message or go, as the receiver needs.1

                         key            data
                      +------> [ other system ] --+
                      |                           |
  sender --> [ in ] --> content enricher <--------+ --> [ out ] --> receiver

The participants are the incoming message with its key fields, the enricher, the resource that has the data, and the enriched message.

Where the data comes from. The book names three sources.1

  • Computation. The enricher calculates the data, for example a state code from a ZIP code, or the size of the message. This form needs no outside resource and is close to a plain Message Translator.1
  • The environment. The enricher gets the data from the operating system, for example the current time for a time stamp.1
  • Another system. This is the most common source: a database, a file, an LDAP directory, an application, or even a person who types the data.1

A lookup for each message. When the data comes from another system, each message costs one call. A cache in front of that system saves calls, but a cached value can be old. The program below enriches 8 orders of 3 customers, and one customer moves after the fourth order.

# A content enricher gets the customer from another system for each order.
# The customer c1 moves after the fourth order. How many calls, and how many stale messages?
orders = [("o1", "c1"), ("o2", "c2"), ("o3", "c1"), ("o4", "c3"),
          ("o5", "c1"), ("o6", "c2"), ("o7", "c3"), ("o8", "c1")]


def run(cache_mode):
    directory = {"c1": "Leeds", "c2": "Hue", "c3": "Oslo"}
    cache, calls, stale = {}, 0, 0
    for i, (order, cid) in enumerate(orders, 1):
        if cache_mode == "none" or cid not in cache:
            calls += 1
            cache[cid] = directory[cid]
        city = cache[cid]
        if city != directory[cid]:
            stale += 1
        if i == 4:
            directory["c1"] = "York"
            if cache_mode == "event":
                cache.pop("c1", None)
    return calls, stale


for mode, label in [("none", "lookup for each message"),
                    ("keep", "cache, never cleared"),
                    ("event", "cache, cleared by a change event")]:
    calls, stale = run(mode)
    print("%-33s %d calls, %d stale" % (label + ":", calls, stale))
Output
lookup for each message:          8 calls, 0 stale
cache, never cleared:             3 calls, 2 stale
cache, cleared by a change event: 4 calls, 0 stale

Without a cache, each order makes a call, and each address is current. A cache that is never cleared needs only 3 calls, but 2 orders get the old city. When the customer system sends an event at the change and the enricher removes that entry from its cache, 4 calls are enough and no order is stale.

Example

Each example file enriches 4 orders with the three sources: the state comes from the first three digits of the ZIP code, the time comes from a clock, and the name of the customer comes from a directory. The clock has a fixed start, so that the output is the same on each run. The fourth order has a customer that the directory does not know. The enricher does not send a message with a hole in it; it reports the order as invalid, so that a router can send it to an invalid message channel or a Dead Letter Channel.

PythonGitHub
from datetime import datetime, timedelta, timezone

ZIP_PREFIX = {"981": "WA", "100": "NY", "606": "IL"}   # used to compute the state
DIRECTORY = {"c1": "Ada Park", "c2": "Lin Tran"}       # the other system


class Clock:  # the environment; a fixed start keeps the output the same each run
    def __init__(self):
        self.t = datetime(2026, 1, 5, 9, 0, 0, tzinfo=timezone.utc)

    def now(self):
        self.t += timedelta(seconds=1)
        return self.t


class Enricher:
    def __init__(self, clock):
        self.clock = clock
        self.lookups = 0

    def enrich(self, msg):
        self.lookups += 1
        name = DIRECTORY.get(msg["customer"])
        if name is None:
            return None, "customer %s not found" % msg["customer"]
        out = dict(msg)  # keep the fields of the original message
        out["name"] = name
        out["state"] = ZIP_PREFIX.get(msg["zip"][:3], "??")
        out["received"] = self.clock.now().strftime("%H:%M:%S")
        return out, None


incoming = [
    {"order": "o1", "customer": "c1", "zip": "98101"},
    {"order": "o2", "customer": "c2", "zip": "10001"},
    {"order": "o3", "customer": "c1", "zip": "60601"},
    {"order": "o4", "customer": "c9", "zip": "98101"},
]
enricher = Enricher(Clock())
enriched = invalid = 0
for msg in incoming:
    out, err = enricher.enrich(msg)
    if err:
        invalid += 1
        print("invalid: %s %s" % (msg["order"], err))
        continue
    enriched += 1
    print("%s %s %s, %s %s, received %s" % (out["order"], out["customer"], out["name"],
                                           out["zip"], out["state"], out["received"]))
print("lookups: %d, enriched: %d, invalid: %d" % (enricher.lookups, enriched, invalid))
Output
o1 c1 Ada Park, 98101 WA, received 09:00:01
o2 c2 Lin Tran, 10001 NY, received 09:00:02
o3 c1 Ada Park, 60601 IL, received 09:00:03
invalid: o4 customer c9 not found
lookups: 4, enriched: 3, invalid: 1
  • Verdict: idiom. A dict stands for the customer directory, dict(msg) keeps the original fields, and the enricher adds three new ones.
  • The clock is an object that the enricher gets in its constructor, so a test can give it a fixed time.
  • A miss returns an error in place of a half-filled message, so the caller can route it.
JavaGitHub
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class Main {
    record Order(String id, String customer, String zip) {}
    record Enriched(Order order, String name, String state, Instant received) {}

    static final Map<String, String> ZIP_PREFIX = Map.of("981", "WA", "100", "NY", "606", "IL");
    static final Map<String, String> DIRECTORY = Map.of("c1", "Ada Park", "c2", "Lin Tran");

    static class Enricher {
        Clock clock = Clock.fixed(Instant.parse("2026-01-05T09:00:00Z"), ZoneOffset.UTC);
        int lookups = 0;

        Optional<Enriched> enrich(Order o) {
            lookups++;
            String name = DIRECTORY.get(o.customer());
            if (name == null) {
                return Optional.empty();
            }
            clock = Clock.offset(clock, Duration.ofSeconds(1));
            String state = ZIP_PREFIX.getOrDefault(o.zip().substring(0, 3), "??");
            return Optional.of(new Enriched(o, name, state, clock.instant()));
        }
    }

    public static void main(String[] args) {
        var fmt = DateTimeFormatter.ofPattern("HH:mm:ss").withZone(ZoneOffset.UTC);
        var incoming = List.of(new Order("o1", "c1", "98101"), new Order("o2", "c2", "10001"),
                new Order("o3", "c1", "60601"), new Order("o4", "c9", "98101"));
        var e = new Enricher();
        int enriched = 0, invalid = 0;
        for (Order o : incoming) {
            var m = e.enrich(o);
            if (m.isEmpty()) {
                invalid++;
                System.out.println("invalid: " + o.id() + " customer " + o.customer() + " not found");
                continue;
            }
            enriched++;
            var r = m.get();
            System.out.printf("%s %s %s, %s %s, received %s%n", o.id(), o.customer(), r.name(),
                    o.zip(), r.state(), fmt.format(r.received()));
        }
        System.out.printf("lookups: %d, enriched: %d, invalid: %d%n", e.lookups, enriched, invalid);
    }
}
Output
o1 c1 Ada Park, 98101 WA, received 09:00:01
o2 c2 Lin Tran, 10001 NY, received 09:00:02
o3 c1 Ada Park, 60601 IL, received 09:00:03
invalid: o4 customer c9 not found
lookups: 4, enriched: 3, invalid: 1
  • Verdict: idiom. Records hold the order and the enriched message, and Map.of stands for the directory and the ZIP table.
  • java.time.Clock.fixed and Clock.offset give a clock that the program controls, so the output is the same on each run.
  • Optional.empty() marks a miss, and the caller reports the order as invalid.
using System;
using System.Collections.Generic;

var zipPrefix = new Dictionary<string, string> { ["981"] = "WA", ["100"] = "NY", ["606"] = "IL" };
var directory = new Dictionary<string, string> { ["c1"] = "Ada Park", ["c2"] = "Lin Tran" };
var time = new DateTimeOffset(2026, 1, 5, 9, 0, 0, TimeSpan.Zero);
Func<DateTimeOffset> clock = () => time = time.AddSeconds(1);

int lookups = 0;
(Enriched? Msg, string? Error) Enrich(Order o)
{
    lookups++;
    if (!directory.TryGetValue(o.Customer, out var name))
    {
        return (null, $"customer {o.Customer} not found");
    }
    var state = zipPrefix.GetValueOrDefault(o.Zip[..3], "??");
    return (new Enriched(o, name, state, clock()), null);
}

var incoming = new[] { new Order("o1", "c1", "98101"), new Order("o2", "c2", "10001"),
                       new Order("o3", "c1", "60601"), new Order("o4", "c9", "98101") };
int enriched = 0, invalid = 0;
foreach (var o in incoming)
{
    var (m, err) = Enrich(o);
    if (m is null)
    {
        invalid++;
        Console.WriteLine($"invalid: {o.Id} {err}");
        continue;
    }
    enriched++;
    Console.WriteLine($"{o.Id} {o.Customer} {m.Name}, {o.Zip} {m.State}, received {m.Received:HH:mm:ss}");
}
Console.WriteLine($"lookups: {lookups}, enriched: {enriched}, invalid: {invalid}");

record Order(string Id, string Customer, string Zip);
record Enriched(Order Order, string Name, string State, DateTimeOffset Received);
Output
o1 c1 Ada Park, 98101 WA, received 09:00:01
o2 c2 Lin Tran, 10001 NY, received 09:00:02
o3 c1 Ada Park, 60601 IL, received 09:00:03
invalid: o4 customer c9 not found
lookups: 4, enriched: 3, invalid: 1
  • Verdict: idiom. Records hold the order and the enriched message, and TryGetValue tells a miss from a hit.
  • The enricher returns a tuple of a message and an error, so a miss does not throw.
  • GetValueOrDefault gives ?? for a ZIP prefix that is not in the table.
package main

import (
	"fmt"
	"time"
)

type Order struct {
	ID, Customer, Zip string
}

type Enriched struct {
	Order
	Name, State string
	Received    time.Time
}

var zipPrefix = map[string]string{"981": "WA", "100": "NY", "606": "IL"}
var directory = map[string]string{"c1": "Ada Park", "c2": "Lin Tran"}

type Enricher struct {
	now     func() time.Time
	lookups int
}

func (e *Enricher) Enrich(o Order) (Enriched, error) {
	e.lookups++
	name, ok := directory[o.Customer]
	if !ok {
		return Enriched{}, fmt.Errorf("customer %s not found", o.Customer)
	}
	state, ok := zipPrefix[o.Zip[:3]]
	if !ok {
		state = "??"
	}
	return Enriched{Order: o, Name: name, State: state, Received: e.now()}, nil
}

func main() {
	t := time.Date(2026, 1, 5, 9, 0, 0, 0, time.UTC)
	clock := func() time.Time { t = t.Add(time.Second); return t }
	e := &Enricher{now: clock}
	incoming := []Order{{"o1", "c1", "98101"}, {"o2", "c2", "10001"}, {"o3", "c1", "60601"}, {"o4", "c9", "98101"}}
	enriched, invalid := 0, 0
	for _, o := range incoming {
		m, err := e.Enrich(o)
		if err != nil {
			invalid++
			fmt.Printf("invalid: %s %v\n", o.ID, err)
			continue
		}
		enriched++
		fmt.Printf("%s %s %s, %s %s, received %s\n", m.ID, m.Customer, m.Name, m.Zip, m.State, m.Received.Format("15:04:05"))
	}
	fmt.Printf("lookups: %d, enriched: %d, invalid: %d\n", e.lookups, enriched, invalid)
}
Output
o1 c1 Ada Park, 98101 WA, received 09:00:01
o2 c2 Lin Tran, 10001 NY, received 09:00:02
o3 c1 Ada Park, 60601 IL, received 09:00:03
invalid: o4 customer c9 not found
lookups: 4, enriched: 3, invalid: 1
  • Verdict: idiom. The Enriched struct embeds Order, so the original fields stay, and the new fields are next to them.
  • The enricher gets the clock as a func() time.Time, so the program can give it a fixed start.
  • A missing customer gives an error, and the comma-ok form of the map lookup tells a miss from an empty value.

Consequences

Benefits.

  • The sender and the receiver stay as they are. Neither one must know the other system that has the data.
  • One place for a lookup. Many flows can use the same enricher in front of the same resource.
  • The receiver gets a complete message. It can work with no extra calls of its own.

Liabilities.

  • One more dependency in the path. If the resource is slow or down, the flow waits or stops. EventBridge Pipes calls an enrichment synchronously and waits for its response before it calls the target.3
  • Old data. A cache saves calls but can give a value that has changed, as the program shows.
  • Larger messages. Each enricher makes the message bigger. EventBridge Pipes limits the response of an enrichment to 6 MB.3
  • Lost fields. In Camel, the enrich step needs an AggregationStrategy to merge the original message and the reply. With no strategy, the reply becomes the result, and it replaces the original message.4

When not to use it

When the receiver needs less, not more. If the message has too much data for the receiver, use a Content Filter. The book asks: "How do you simplify dealing with a large message, when you are interested only in a few data items?" The answer: "Use a Content Filter to remove unimportant data items from a message leaving only important items."5

When the data can be computed. If no outside resource is needed, a Message Translator does the same work.1

When the call costs too much for each message. A synchronous call for each message adds its latency to the whole flow.3 A receiver that needs the data only for a few messages can get it itself.

Request-reply or polling. Camel has two enrichers. enrich uses a producer and is usually a Request-Reply call, for example to a web service. pollEnrich uses a Polling Consumer and usually reads one message from a resource, such as a file or an FTP server.4 The Camel page for pollEnrich says: "It is good practice to use timeout value."6 By default, the poll waits until a message comes, and it can block for ever; with a timeout of 0, it returns at once.6

Headers or the payload. Spring Integration has a header enricher, which adds headers with fixed or computed values, and a payload enricher. The payload enricher sends the message to a request channel, waits for the reply like a gateway, and copies values from the reply into the payload with SpEL expressions.7 Its documentation says: "Enrichers are a variant of transformers."7

A dynamic resource. Camel can compute the address of the resource from the message, for example an HTTP path with the order id in it.4

Claim Check. A Claim Check takes data out of a message for a time. Later, another component uses a content enricher to get the data back with the claim check.8

Enrich and filter. An EventBridge Pipes enrichment that returns an empty response stops the event, so the step can also act as a filter.3

Known uses

  • Apache Camel: the Enrich EIP of 4.14.0 and the Poll Enrich EIP of 4.14.0, with an AggregationStrategy to merge the data.46
  • Spring Integration: the <header-enricher> and <enricher> elements, as the Content Enricher page of 7.1.1 describes.7
  • Amazon EventBridge Pipes: the enrichment step, which can call a Lambda function, an API Gateway API, an API destination or an Express workflow of Step Functions.3 The EIP site shows a pipe in which a Lambda function gets the data from a DynamoDB table by a key in the message.1

References

  1. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Content Enricher (problem and solution under CC BY), problem and solution statements; pattern text; example with Amazon EventBridge Pipes
  2. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Designing, Building, and Deploying Messaging Solutions, Addison-Wesley, 2003, Chapter 8, Message Transformation, Content Enricher
  3. Amazon EventBridge User Guide, Event enrichment in Amazon EventBridge Pipes, enrichment step; filtering events using enrichment; invoking enrichments
  4. Apache Camel 4.14.0 documentation source, Enrich EIP, introduction; content enrichment using Enrich EIP; aggregation strategy is optional; using dynamic uris
  5. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Content Filter (problem and solution under CC BY), problem and solution statements; pattern text
  6. Apache Camel 4.14.0 documentation source, Poll Enrich EIP, poll enrich with timeout
  7. Spring Integration 7.1.1 reference documentation source, Content Enricher, header enricher; payload enricher
  8. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Claim Check (problem and solution under CC BY), pattern text

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/CRGF9V/text.yaml