Patterncore
Message Translator
Also called Message Translator pattern, message transformer, transformer, translator, data mapping.
A message translator is a step between two systems that changes a message from the data format of one system into the format of the other, so that neither system must know the format of the other.
- Family
- integration
- Intent
- Let systems with different data formats exchange messages, by a filter between them that reads a message in one format and writes the same data in the other format.
- Also called
- message transformer, transformer
Intent
Let two systems exchange messages when each one keeps its data in its own format. The book asks: "How can systems using different data formats communicate with each other using messaging?"12 The answer: "Use a special filter, a Message Translator", which goes "between other filters or applications to translate one data format into another."1
Problem
Most systems that a company connects were not made to work together. Each one has its own data model. The book gives the example of a customer: the accounting system wants the tax number, and the customer relationship system keeps the phone numbers and the addresses. Each system expects messages in the form of its own data. Outside partners can also require a standard format of an industry body.1
A Message Channel removes the need for the sender to know where the receiver is. But if the sender must write each message in the format of the receiver, it still depends on the receiver. A change of the receiver, or a new receiver, still means a change of the sender.3
The forces are these. The systems often cannot be changed. The formats differ in names, in units, in structure and in the encoding. And a new system must not mean a change to all the systems that already talk.
Solution
Put a translator on the path of the message. It reads the message in the format of the source and writes a new message with the same data in the format of the target.1
partner ---> [ partner.orders ] ---> message ---> [ shop.orders ] ---> shop
id;name;12.50;dd/mm translator id, cents, ISO date
|
+---> [ invalid ] (a line it cannot read)
The participants are the source channel, the translator, the target channel and the two systems. Neither system knows the format of the other. The book compares the translator to the Adapter of the Gang of Four, which changes the interface of a component so that it can work in a different context.1 See Adapter pattern.
A canonical model. With direct translators, each pair of systems needs its own translator. The book gives a Canonical Data Model: "How can you minimize dependencies when integrating applications that use different data formats?" The answer: "Therefore, design a Canonical Data Model that is independent from any specific application. Require each application to produce and consume messages in this common format."4 Each system then needs one translator to the common format and one from it. The book counts the translators: 2 systems need 2 direct translators or 4 with a canonical model, 3 systems need 6 with either approach, and 6 systems need 30 direct translators or 12 with the model.4 The program below translates one customer through a canonical format and prints the same counts.
# Three systems keep a customer in three formats.
def crm_to_canonical(m):
given, family = m["FullName"].split(" ", 1)
return {"given": given, "family": family, "phone": m["Phone"]}
def canonical_to_billing(c):
# Billing wants a tax id, but the CRM has none to give.
return {"name": c["family"].upper() + ", " + c["given"], "tax_id": c.get("tax_id", "")}
def canonical_to_shop(c):
return {"display": c["given"], "phone": c["phone"].replace(" ", "")}
crm_msg = {"FullName": "Lan Pham", "Phone": "+84 236 555 0101"}
c = crm_to_canonical(crm_msg)
print("crm :", crm_msg)
print("canonical:", c)
print("billing :", canonical_to_billing(c))
print("shop :", canonical_to_shop(c))
print()
print("systems direct translators canonical translators")
for n in [2, 3, 6, 10]:
print(f"{n:7} {n * (n - 1):18} {2 * n:21}")
crm : {'FullName': 'Lan Pham', 'Phone': '+84 236 555 0101'}
canonical: {'given': 'Lan', 'family': 'Pham', 'phone': '+84 236 555 0101'}
billing : {'name': 'PHAM, Lan', 'tax_id': ''}
shop : {'display': 'Lan', 'phone': '+842365550101'}
systems direct translators canonical translators
2 2 4
3 6 6
6 30 12
10 90 20
The counts are n * (n - 1) for direct translators and 2 * n for the canonical model, when each system sends to each other system. The output also shows a limit: billing wants a tax id, but the customer system has none. A translator changes the form of data. It cannot make data that is not in the message.
Example
Each example file translates lines from a partner, in the form id;customer;amount;day/month/year, into an order of the shop with an integer id, the total in cents and an ISO 8601 date. The line with the amount 7,25 has a comma as the decimal mark, and the translator rejects it with a reason, as it does not know which value the partner means.
import re
# Lines in the format of a partner: id;customer;amount;day/month/year
partner = [
"P-17;Lan Pham;12.50;03/11/2026",
"P-18;Hoa Le;8;05/11/2026",
"P-19;Minh Tran;7,25;04/11/2026",
]
def translate(line):
"""Translate one partner line into the fields of the shop."""
pid, customer, amount, date = line.split(";")
m = re.fullmatch(r"(\d+)(?:\.(\d\d))?", amount)
if m is None:
raise ValueError("bad amount " + amount)
cents = int(m.group(1)) * 100 + int(m.group(2) or "0")
day, month, year = date.split("/")
return {"id": int(pid.removeprefix("P-")), "customer": customer,
"total_cents": cents, "date": f"{year}-{month}-{day}"}
for line in partner:
try:
o = translate(line)
except ValueError as err:
print(f"invalid: {line} ({err})")
continue
print(f"order {o['id']}: customer={o['customer']} total_cents={o['total_cents']} date={o['date']}")
order 17: customer=Lan Pham total_cents=1250 date=2026-11-03
order 18: customer=Hoa Le total_cents=800 date=2026-11-05
invalid: P-19;Minh Tran;7,25;04/11/2026 (bad amount 7,25)
- Verdict: idiom. A function from the fields of one format to a dict of the other format is the translator, and
re.fullmatchchecks the amount before the code changes it to cents. - The translator raises
ValueErrorfor a line that it cannot read, and the loop sends that line to the invalid channel with the reason. - With a broker, the translator is a consumer of the partner queue and a producer for the queue of the shop.
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
// The format of the shop.
record Order(int id, String customer, int totalCents, String date) {}
static final Pattern AMOUNT = Pattern.compile("(\\d+)(?:\\.(\\d\\d))?");
// Translate one partner line (id;customer;amount;day/month/year) into an Order.
static Order translate(String line) {
String[] f = line.split(";");
if (f.length != 4) throw new IllegalArgumentException("want 4 fields");
Matcher m = AMOUNT.matcher(f[2]);
if (!m.matches()) throw new IllegalArgumentException("bad amount " + f[2]);
int cents = Integer.parseInt(m.group(1)) * 100 + (m.group(2) == null ? 0 : Integer.parseInt(m.group(2)));
String[] d = f[3].split("/");
if (d.length != 3) throw new IllegalArgumentException("bad date " + f[3]);
int id = Integer.parseInt(f[0].replaceFirst("^P-", ""));
return new Order(id, f[1], cents, d[2] + "-" + d[1] + "-" + d[0]);
}
public static void main(String[] args) {
List<String> partner = List.of(
"P-17;Lan Pham;12.50;03/11/2026",
"P-18;Hoa Le;8;05/11/2026",
"P-19;Minh Tran;7,25;04/11/2026");
for (String line : partner) {
try {
Order o = translate(line);
System.out.printf("order %d: customer=%s total_cents=%d date=%s%n", o.id(), o.customer(), o.totalCents(), o.date());
} catch (IllegalArgumentException e) {
System.out.printf("invalid: %s (%s)%n", line, e.getMessage());
}
}
}
}
order 17: customer=Lan Pham total_cents=1250 date=2026-11-03
order 18: customer=Hoa Le total_cents=800 date=2026-11-05
invalid: P-19;Minh Tran;7,25;04/11/2026 (bad amount 7,25)
- Verdict: idiom. A record is the target format, and a static method maps a partner line to a new record.
- The method throws
IllegalArgumentExceptionwith a reason for a line that it cannot read;NumberFormatExceptionis a subclass, so a bad id also goes to the invalid channel. - Frameworks such as Apache Camel and Spring Integration call a method of this form as a translator in a route.
using System;
using System.Text.RegularExpressions;
var partner = new[]
{
"P-17;Lan Pham;12.50;03/11/2026",
"P-18;Hoa Le;8;05/11/2026",
"P-19;Minh Tran;7,25;04/11/2026",
};
foreach (var line in partner)
{
try
{
var o = Translator.Translate(line);
Console.WriteLine($"order {o.Id}: customer={o.Customer} total_cents={o.TotalCents} date={o.Date}");
}
catch (FormatException e)
{
Console.WriteLine($"invalid: {line} ({e.Message})");
}
}
// The format of the shop.
record Order(int Id, string Customer, int TotalCents, string Date);
static class Translator
{
static readonly Regex Amount = new(@"^(\d+)(?:\.(\d\d))?$");
// Translate one partner line (id;customer;amount;day/month/year) into an Order.
public static Order Translate(string line)
{
var f = line.Split(';');
if (f.Length != 4) throw new FormatException("want 4 fields");
var m = Amount.Match(f[2]);
if (!m.Success) throw new FormatException("bad amount " + f[2]);
int cents = int.Parse(m.Groups[1].Value) * 100 + (m.Groups[2].Success ? int.Parse(m.Groups[2].Value) : 0);
var d = f[3].Split('/');
if (d.Length != 3) throw new FormatException("bad date " + f[3]);
int id = int.Parse(f[0].StartsWith("P-") ? f[0][2..] : f[0]);
return new Order(id, f[1], cents, $"{d[2]}-{d[1]}-{d[0]}");
}
}
order 17: customer=Lan Pham total_cents=1250 date=2026-11-03
order 18: customer=Hoa Le total_cents=800 date=2026-11-05
invalid: P-19;Minh Tran;7,25;04/11/2026 (bad amount 7,25)
- Verdict: idiom. A positional record is the target format, and a static method maps a partner line to a new record.
- The method throws
FormatExceptionwith a reason;int.Parsethrows the same type for a bad id, so onecatchhandles all bad lines. - The range
f[0][2..]removes the prefix of the partner id.
package main
import (
"errors"
"fmt"
"regexp"
"strconv"
"strings"
)
// Order is the format of the shop.
type Order struct {
ID int
Customer string
TotalCents int
Date string
}
var amountRe = regexp.MustCompile(`^(\d+)(?:\.(\d\d))?$`)
// translate turns one partner line (id;customer;amount;day/month/year) into an Order.
func translate(line string) (Order, error) {
f := strings.Split(line, ";")
if len(f) != 4 {
return Order{}, errors.New("want 4 fields")
}
m := amountRe.FindStringSubmatch(f[2])
if m == nil {
return Order{}, errors.New("bad amount " + f[2])
}
whole, _ := strconv.Atoi(m[1])
frac := 0
if m[2] != "" {
frac, _ = strconv.Atoi(m[2])
}
id, err := strconv.Atoi(strings.TrimPrefix(f[0], "P-"))
if err != nil {
return Order{}, errors.New("bad id " + f[0])
}
d := strings.Split(f[3], "/")
if len(d) != 3 {
return Order{}, errors.New("bad date " + f[3])
}
return Order{ID: id, Customer: f[1], TotalCents: whole*100 + frac, Date: d[2] + "-" + d[1] + "-" + d[0]}, nil
}
func main() {
partner := []string{
"P-17;Lan Pham;12.50;03/11/2026",
"P-18;Hoa Le;8;05/11/2026",
"P-19;Minh Tran;7,25;04/11/2026",
}
for _, line := range partner {
o, err := translate(line)
if err != nil {
fmt.Printf("invalid: %s (%v)\n", line, err)
continue
}
fmt.Printf("order %d: customer=%s total_cents=%d date=%s\n", o.ID, o.Customer, o.TotalCents, o.Date)
}
}
order 17: customer=Lan Pham total_cents=1250 date=2026-11-03
order 18: customer=Hoa Le total_cents=800 date=2026-11-05
invalid: P-19;Minh Tran;7,25;04/11/2026 (bad amount 7,25)
- Verdict: idiom. The function
translatereturns anOrderand anerror, so each failure has a reason, and the caller decides where the bad line goes. - The amount is changed to an integer number of cents and not to a
float64, so that the value is exact. - The struct
Orderis the format of the target; a change of the partner format changes onlytranslate.
Consequences
Benefits.
- Loose coupling of the formats. The sender writes its own format, and the receiver reads its own format. Spring Integration says that transformers have "a very important role in enabling the loose-coupling of message producers and message consumers."5
- No change to the systems. The translation is in the integration, so systems that cannot change can still take part.3
- One place for the mapping. A change of a format is a change of one translator.
Liabilities.
- Many translators. With direct translation, the number grows with the square of the number of systems.4
- Loss of data. When the target format has fewer fields, or a different precision, data is lost. A translator in the other direction cannot get it back.
- Hidden rules. A translator often contains business rules, such as a default value or a change of units, that nobody documents.
- Cost on each message. Each message is parsed and written again.
When not to use it
When both sides already use one format. A shared schema or a canonical model with no difference to the format of a system needs no translator for that system.
When the target needs data that the source does not have. That is a content enricher, which gets the missing data from another place.3
When the only difference is the transport. The book uses an envelope wrapper when the message must only be put into the form that the messaging infrastructure needs.3
Variants and related patterns
Envelope Wrapper, Content Enricher, Content Filter and Claim Check. The book calls these variants of the translator. They add a wrapper, add data, remove data, or put data in a store for later.3
Normalizer. "How do you process messages that are semantically equivalent, but arrive in a different format?" The answer: "Use a Normalizer to route each message type through a custom Message Translator so that the resulting messages match a common format."6 It is a Content-Based Router with one translator for each format.
Data Mapper. In one program, a Data Mapper moves data between objects and a database. The translator does the same work between two message formats.
Known uses
- Apache Camel: the documentation of 4.14.0 lists four ways to translate, by the Transform or Set Body EIP, by a processor or a bean, by a template component, and by a data format to "marshal and unmarshal messages in different encodings".7
- Apache Kafka Connect: the Transformation interface at 4.1.0 is a "Single message transformation for Kafka Connect record types." It can "make lightweight message-at-a-time modifications." The method
applyreturns a new record, or null to drop the record.8 - Spring Integration: the transformer is an endpoint for this pattern. It can call a method of a plain Java object that takes the payload of the message and returns the new payload.5
References
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Message Translator (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 3, Messaging Systems, Message Translator; Chapter 8, Message Transformation
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Introduction to Message Transformation, introduction
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Canonical Data Model (problem and solution under CC BY), problem and solution statements; pattern text
- Spring Integration 7.1.1 reference source, Transformer, introduction
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Normalizer (problem and solution under CC BY), problem and solution statements
- Apache Camel 4.14.0 documentation source, Message Translator, introduction
- Apache Kafka 4.1.0 source, Transformation.java, interface comment and method apply, lines 26 to 55
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 V6N3XH Edit this page History Report an error Markdown