Skip to content

Message Transformation: Translator, Enricher, Normalizer, Canonical Model ​

"Use a special filter, a Message Translator, between other filters or applications to translate one data format into another." — Hohpe and Woolf, Enterprise Integration Patterns, Message Translator

Summary: Systems almost never agree on the shape of a message, so integration needs small, single-purpose steps that change its shape (Translator, Normalizer, Mapper), its content (Enricher, Content Filter) or its wrapping (Envelope Wrapper), plus one shared contract (Canonical Data Model) so the number of steps does not explode. Focus: The seven EIP transformation patterns with their original definitions, where each one can run (producer edge, Kafka Connect or Kafka Streams, consumer edge, gateway), what RabbitMQ and Redis Streams cannot do for you, Go and Laravel code for each, the canonical-model debate, testing, performance and a complete partner-webhook pipeline. Learning goal: Decide which transformation belongs at which edge, build a chain whose failures are classified (invalid versus transient), and explain when a canonical model helps and when it becomes the thing everyone fights over.

This page owns the transformation patterns of the Enterprise Integration Patterns catalogue: Message Translator, Envelope Wrapper (in depth), Content Enricher, Content Filter, Normalizer, Canonical Data Model and Messaging Mapper. It does not re-teach its neighbours; it names them and links them. Which metadata fields an envelope should carry, versioning rules and the Claim Check live in message design and schema evolution. The Invalid Message Channel is defined in integration styles and channels, the dead-letter side in dead-letter queue. Dropping whole messages (Message Filter), splitting and routing belong to advanced routing and routing topologies. Stateful stream operators are in stream processing.

Page map ​

If you are looking forGo to
The seven patterns in a table you can memoriseEverything in one minute
Why transformation is its own concern, three beliefs to dropWhy transformation exists
The original EIP wording and what the book addsWhere the vocabulary comes from
One block per pattern with timeline, scenarios and codeThe concept catalogue
Envelope layers: header, signature, encryption, unwrapEnvelope Wrapper
Canonical model versus published language and anti-corruption layerCanonical Data Model
Where a transformation can run, and what each broker offersWhere it runs
Kafka Connect SMTs and Kafka Streams as hostsKafka hosts
Error classes, determinism, upcasters, units and time zonesMechanics
Golden files, property tests, metrics, streaming and allocationTesting, observability, performance
Three partner formats to one canonical OrderPlacedWorked pipeline
Problem-by-problem recipes in Go and LaravelSolving the classic problems
RabbitMQ, Kafka, Redis Streams side by sideBroker differences
Which pattern for which situationChoosing
Monolith to distributed scaleIn architecture
Reproduce itLab
Wrong beliefs, cheat sheet, glossaryMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The seven patterns. Each row is unpacked in the catalogue.

PatternIn plain wordsTiny exampleChanges
Message TranslatorConvert one format to anotherPartner XML with decimal commas becomes our JSON with integer centsShape
Envelope WrapperPut the data in an envelope the infrastructure accepts, take it out at the other endSign and encrypt a legacy payload that knows nothing about eitherWrapping
Content EnricherAdd data the sender did not haveOrder carries customer_id; we add tier and countryContent (more)
Content FilterRemove or flatten what the receiver should not or need not seeAnalytics gets the SKU list, not the customerContent (less)
NormalizerMany formats, one meaning: route each to its own translator, get one formatThree partners, three formats, one DraftShape (many to one)
Canonical Data ModelOne format every system translates to and fromOrderPlaced v2 for the whole companyContract
Messaging MapperKeep domain objects and messages independent through a mapper classOrder aggregate to OrderPlaced and backLayer boundary

Where each one usually runs.

HostTypical patternsStrengthWeakness
Producer edge (inside the sending service)Mapper, Envelope Wrapper, Content FilterKnows the domain, one deployEvery producer repeats it
Kafka Connect worker or Kafka Streams applicationFilter, Translator (light), routing, maskingExisting connector or stream application hosts simple casesSeparate runtime; built-in SMTs suit lightweight logic
Consumer edge (anti-corruption layer, sidecar)Translator, Normalizer, EnricherConsumer protects its own modelEvery consumer repeats it
Gateway or integration platform (API gateway, ESB, iPaaS)Normalizer, Translator, Envelope WrapperOne place for many partnersA central team and a central failure point

Three rules to remember. One stage does one job. Classify every failure as invalid (park it) or transient (retry it). Never publish half a message: if the enrichment lookup is down, retry instead of emitting an event without the data.

Why transformation exists ​

Every system has its own model of the world. The accounting system cares about tax ids, the CRM about phone numbers; a partner sends decimal commas, we store integer cents. Messaging connects them without making them identical, so somewhere a message must change shape. EIP describes this as the mismatch between application-specific models: each application expects the shape it already understands.

Without a deliberate transformation stepWith one
Parsing, unit conversion, lookups and logging sit in one consumer functionEach concern is a small testable step
A partner's field names become your public APIYour contract is yours; the partner's shape stops at the edge
A new format means editing the core handlerA new format means one new translator
Failures are one big 500Failures say which stage and whether to retry
PII travels wherever the message goesA filter decides who sees what

An everyday picture we reuse. A border crossing. The interpreter (translator) converts what the traveller says. The customs form is the envelope: officials read the form, not the luggage. The border agent who looks up your visa number is the enricher. The officer who takes only the page they need and photocopies it for the file is the content filter. A reception desk that accepts passports from 190 countries and issues one standard pass is the normalizer, and that standard pass is the canonical model.

Three beliefs to drop up front.

  1. "Transformation is just serialisation." Serialisation turns an object into bytes. Transformation changes meaning-preserving structure: units, ids, time zones, which fields exist.
  2. "The broker can do it." Kafka Connect and Kafka Streams can host it in separate application processes; they are not code inside the Kafka broker. RabbitMQ and Redis Streams normally need a consumer or sidecar for arbitrary body translation. See where it runs.
  3. "A canonical model makes everything simpler." It removes the n-squared translators, and it adds a model that every team must agree on. See the debate.

Where the vocabulary comes from ​

The patterns come from Enterprise Integration Patterns (Hohpe and Woolf, 2003), whose pattern language is built on Pipes and Filters: a message travels through independent steps connected by channels. Each transformation pattern below is one kind of filter. The following table paraphrases each primary pattern page:

PatternProblem (paraphrased)Solution (paraphrased)
Message TranslatorApplications disagree about data representationPut a conversion stage at their boundary
Envelope WrapperA legacy payload lacks the infrastructure-required wrappingAdd the wrapping at ingress and remove it at the destination
Content EnricherThe sender lacks information required downstreamCompute or retrieve the missing information before forwarding
Content FilterThe receiver needs only part of a large messageProject the required data into a smaller shape
NormalizerEquivalent facts arrive in several formatsRoute each format through its own translator into a common shape
Canonical Data ModelPairwise integrations multiply model dependenciesAgree on an application-independent exchange contract
Messaging MapperDomain and messaging code should evolve independentlyKeep the conversion in a separate component that knows both

The Translator relates to the GoF Adapter pattern; the Messaging Mapper specialises Mapper and has the identity, null and partial-update concerns familiar from Data Mapper. These relationships explain the responsibilities without making the domain depend on message encoding.

A useful transformation checklist separates layers: transport, data representation, data types and data structures. We use that split as a mental checklist: a Translator may change any of them, and most production bugs are in the middle two (a number that was a string, a time that had no zone).

The counter-movement came from Domain-Driven Design. Eric Evans's Anticorruption Layer and Published Language (see context maps) answer the same integration problem without a single company-wide model. Microsoft describes an adapter boundary that protects the downstream model from another subsystem's semantics. We compare the two in the canonical model block.

The concept catalogue ​

Message inPipes and Filters chainany order of the filters belowMessage outChange the shapeMessage Translatorone format to anotherNormalizerrouter + translatorsMessaging Mapperobject to message and backChange the contentContent Enricheradd data from outsideContent Filterremove or flatten dataClaim Checkpayload out of band (own page)Change the wrappingEnvelope Wrapperheader, signature, encryptionShare one contractCanonical Data Modelone format for n systems

Message Translator Must-know ​

In plain words: A step that takes a message in format A and returns the same meaning in format B. Nothing is added or dropped on purpose; only the form changes.

Common misunderstanding: "A translator is a JSON-to-JSON mapping function." The hard part is not field renaming, it is meaning: 19,99 with a comma is not 1999 cents until you know the currency's minor-unit digits, a local time without an offset is not UTC until you know the zone, and status: 3 is not a word until you have the partner's code table.

Definition: a filter with one input channel and one output channel that converts the data format of a message, leaving routing and business decisions to others.

1  partner XML  ->  Translator               receives <Cur>EUR</Cur> <Line unit="19,99"/>
2  look up digits for EUR (2)                ISO 4217 minor units
3  "19,99" -> 1999                           no floats; more decimals than allowed = invalid
4  "25/11/2026 10:00" Europe/Berlin -> UTC   09:00Z
5  emit canonical OrderPlaced                integer cents, UTC, namespaced id

Real scenarios: a partner sends XML and you speak JSON; a legacy ERP wants fixed-width records; an internal event must become a CloudEvents envelope for an external subscriber; v1 payloads must be lifted to v2 (an upcaster is a translator whose input and output are two versions of one type, see schema evolution).

What provides it:

ProductPrimitive for translation
RabbitMQNothing in the broker; a consumer or sidecar reads one queue and publishes to another
KafkaKafka Connect SMTs (light, per record), Kafka Streams mapValues, or a consumer-producer service
Redis StreamsNothing; a consumer group worker reads, translates, XADDs the result
LaravelA queued job, a console command, or a Pipeline of pipe classes
GoA function func(ctx, In) (Out, error); functions compose

Fix / how to use it. Make each translator a typed function so chains are checked by the compiler. Go with generics:

go
package after

import (
	"context"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"math"
	"strings"
	"time"
)

// Func is one Message Translator: a typed step that can be chained.
type Func[In, Out any] func(context.Context, In) (Out, error)

// Then composes two translators; the Pipes-and-Filters shape in one line.
func Then[A, B, C any](f Func[A, B], g Func[B, C]) Func[A, C] {
	return func(ctx context.Context, a A) (C, error) {
		b, err := f(ctx, a)
		if err != nil {
			var zero C
			return zero, err
		}
		return g(ctx, b)
	}
}

// minorDigits are ISO 4217 minor-unit digits; unknown codes are rejected
// rather than guessed (guessing 2 digits for JPY is a 100x price bug).
var minorDigits = map[string]int{"USD": 2, "EUR": 2, "GBP": 2, "JPY": 0, "KWD": 3}

// ParseMinor turns "19.99" or "5,50" into minor units without floats.
// More fractional digits than the currency allows is an error, never a rounding.
func ParseMinor(s string, digits int) (int64, error) {
	if digits < 0 || digits > 3 {
		return 0, invalid("translate", "unsupported minor-unit precision")
	}
	s = strings.TrimSpace(s)
	if strings.Count(s, ",")+strings.Count(s, ".") > 1 {
		return 0, invalid("translate", "ambiguous decimal %q", s)
	}
	s = strings.Replace(s, ",", ".", 1)
	whole, frac, decimal := strings.Cut(s, ".")
	if whole == "" || (decimal && frac == "") || len(frac) > digits {
		return 0, invalid("translate", "bad amount %q for %d digits", s, digits)
	}
	frac += strings.Repeat("0", digits-len(frac))
	var n int64
	for _, r := range whole + frac {
		if r < '0' || r > '9' {
			return 0, invalid("translate", "bad amount %q", s)
		}
		digit := int64(r - '0')
		if n > (math.MaxInt64-digit)/10 {
			return 0, invalid("translate", "amount exceeds int64")
		}
		n = n*10 + digit
	}
	return n, nil
}

// HashEmail pseudonymises the e-mail with a keyed hash (HMAC-SHA256), so the
// canonical event never carries it but a directory can still be keyed by it.
func HashEmail(key []byte, email string) string {
	m := hmac.New(sha256.New, key)
	m.Write([]byte(strings.ToLower(strings.TrimSpace(email))))
	return hex.EncodeToString(m.Sum(nil))
}

// ToCanonical maps the partner-shaped Draft onto the Canonical Data Model:
// namespaced id, UTC time, integer minor units, hashed e-mail.
func ToCanonical(hashKey []byte) Func[Draft, OrderPlaced] {
	return func(_ context.Context, d Draft) (OrderPlaced, error) {
		digits, ok := minorDigits[d.Currency]
		if !ok {
			return OrderPlaced{}, invalid("translate", "unsupported currency %q", d.Currency)
		}
		if d.PartnerOrderID == "" || len(d.Lines) == 0 || d.PlacedAt.IsZero() {
			return OrderPlaced{}, invalid("translate", "missing id, lines or time")
		}
		out := OrderPlaced{
			OrderID:  d.Partner + ":" + d.PartnerOrderID,
			Partner:  d.Partner,
			PlacedAt: d.PlacedAt.UTC().Truncate(time.Second),
			Customer: Customer{EmailHash: HashEmail(hashKey, d.CustomerEmail)},
		}
		var total int64
		for _, l := range d.Lines {
			if l.Qty <= 0 || l.SKU == "" {
				return OrderPlaced{}, invalid("translate", "qty %d for %s", l.Qty, l.SKU)
			}
			var minor int64
			var err error
			if l.PriceIsMinor {
				minor, err = ParseMinor(l.Price, 0)
			} else {
				minor, err = ParseMinor(l.Price, digits)
			}
			if err != nil {
				return OrderPlaced{}, err
			}
			out.Lines = append(out.Lines, Line{SKU: l.SKU, Qty: l.Qty, UnitPrice: Money{minor, d.Currency}})
			if minor > math.MaxInt64/int64(l.Qty) {
				return OrderPlaced{}, invalid("translate", "line amount exceeds int64")
			}
			lineTotal := minor * int64(l.Qty)
			if total > math.MaxInt64-lineTotal {
				return OrderPlaced{}, invalid("translate", "order total exceeds int64")
			}
			total += lineTotal
		}
		out.Total = Money{total, d.Currency}
		out.Enrichment = "ok"
		return out, nil
	}
}

// Upcast lifts an old payload one version at a time, on a generic map.
// An upcaster is just a Message Translator whose input and output are two
// versions of the same type (see message-design-schema-evolution).
var upcasters = map[int]func(map[string]any) map[string]any{
	1: func(m map[string]any) map[string]any { // v1 -> v2: flat hash becomes a nested customer
		if h, ok := m["customer_email_hash"].(string); ok {
			m["customer"] = map[string]any{"email_hash": h}
			delete(m, "customer_email_hash")
		}
		return m
	},
}

func Upcast(m map[string]any, from, to int) (map[string]any, error) {
	if from < 1 || to > SchemaVersionOrder || from > to {
		return nil, invalid("translate", "unsupported schema range")
	}
	for v := from; v < to; v++ {
		up, ok := upcasters[v]
		if !ok {
			return nil, invalid("translate", "missing upcaster")
		}
		m = up(m)
	}
	return m, nil
}

Laravel keeps the same idea in one class per direction; translators throw InvalidMessage for input that can never work, which the caller turns into an invalid-message record instead of a retry:

php
<?php

namespace App\Messaging\Transform;

use DateTimeZone;

/** Message Translator: partner-shaped Draft to the canonical OrderPlaced. */
final class Translator
{
    /** ISO 4217 minor-unit digits; unknown currencies are rejected, never guessed. */
    private const DIGITS = ['USD' => 2, 'EUR' => 2, 'GBP' => 2, 'JPY' => 0, 'KWD' => 3];

    public function __construct(private readonly string $hashKey) {}

    public function translate(Draft $d): OrderPlaced
    {
        $digits = self::DIGITS[$d->currency]
            ?? throw new InvalidMessage('translate', "unsupported currency {$d->currency}");
        if ($d->partnerOrderId === '' || $d->lines === []) {
            throw new InvalidMessage('translate', 'missing id or lines');
        }

        $lines = [];
        $total = 0;
        foreach ($d->lines as $l) {
            if ($l['qty'] <= 0 || $l['sku'] === '') {
                throw new InvalidMessage('translate', "qty {$l['qty']} for {$l['sku']}");
            }
            $minor = $this->parseMinor($l['price'], $l['minor'] ? 0 : $digits);
            $lines[] = ['sku' => $l['sku'], 'qty' => $l['qty'], 'unit_price' => ['amount_minor' => $minor, 'currency' => $d->currency]];
            if ($minor > intdiv(PHP_INT_MAX, $l['qty']) || $total > PHP_INT_MAX - $minor * $l['qty']) {
                throw new InvalidMessage('translate', 'amount exceeds integer range');
            }
            $total += $minor * $l['qty'];
        }

        return new OrderPlaced(
            orderId: $d->partner.':'.$d->partnerOrderId,
            partner: $d->partner,
            placedAt: $d->placedAt->setTimezone(new DateTimeZone('UTC')),
            customer: ['email_hash' => hash_hmac('sha256', strtolower(trim($d->email)), $this->hashKey)],
            lines: $lines,
            totalMinor: $total,
            currency: $d->currency,
        );
    }

    /** "19.99" or "5,50" to minor units with no floats; extra digits are an error, not a rounding. */
    public function parseMinor(string $s, int $digits): int
    {
        if ($digits < 0 || $digits > 3) { throw new InvalidMessage('translate', 'unsupported minor-unit precision'); }
        $s = str_replace(',', '.', trim($s));
        if (substr_count($s, '.') > 1 || ! preg_match('/^\d+(\.\d+)?$/', $s)) {
            throw new InvalidMessage('translate', "bad amount {$s}");
        }
        [$whole, $frac] = array_pad(explode('.', $s, 2), 2, '');
        if (strlen($frac) > $digits) {
            throw new InvalidMessage('translate', "amount {$s} has more than {$digits} decimals");
        }

        $value = ltrim($whole.str_pad($frac, $digits, '0'), '0') ?: '0';
        $max = (string) PHP_INT_MAX;
        if (strlen($value) > strlen($max) || (strlen($value) === strlen($max) && strcmp($value, $max) > 0)) {
            throw new InvalidMessage('translate', 'amount exceeds integer range');
        }
        return (int) $value;
    }
}

Envelope Wrapper Must-know ​

In plain words: Most messaging systems split a message into a header and a body. Applications that predate the messaging system only know the body. The Envelope Wrapper puts their data into an envelope the infrastructure understands on the way out, and the unwrapper takes it out again on the way in, so the application never sees the envelope.

Common misunderstanding: "The envelope is just the broker's headers, so there is nothing to design." Broker headers are one layer. A real message often has several: a business envelope (id, type, source), a signature, encryption, then the transport headers. Each is added in order and must be removed in reverse order, and the order is a security decision (sign then encrypt, or encrypt then sign, behave differently).

Definition: a wrapper that makes application data compliant with the requirements of the messaging infrastructure (header fields, routing data, authentication, encryption), paired with an unwrapper that restores the original. EIP's own examples are headers the infrastructure needs and encryption.

Transport: AMQP properties+headers, Kafka record headers, Redis entry fieldsEncryption: AES-256-GCM, nonce || ciphertextSignature: HMAC-SHA256 prefixBusiness envelope: id, type, source, versionApplication datapartner payload, opaque bytesWrap (sender)1. build business envelope2. sign3. encrypt4. publish, routing facts also in headersUnwrap (receiver)1. read transport headers2. decrypt3. verify signature4. parse envelope5. hand data to the app

Two styles of envelope.

StyleWhere the fields liveGood forBreaks when
Header styleBroker headers: AMQP properties and application headers, Kafka record headersRouting and tracing without parsing the body; small payload overheadA hop drops headers (some bridges, some HTTP gateways); Redis Streams has no header section, so fields become sibling entry fields
In-body styleA JSON or Avro envelope around the payload, payload as opaque bytesCrossing several brokers and protocols; signing the whole thingOpaque bytes in JSON are base64 (about 33% bigger); consumers must parse before they can route

Most systems combine them: routing facts (id, type, correlation id) are copied into transport headers, and the full envelope travels in the body. Which fields to carry is message design; the CloudEvents attribute list is the usual starting point.

Sender                                                     Receiver
1  raw partner payload (opaque bytes)                      9  hand raw payload to the application
2  build business envelope: id, type, source, version      8  parse envelope, check version and type
3  sign: HMAC-SHA256 over the envelope, prefix the tag     7  verify the tag; mismatch = reject, never parse
4  encrypt: AES-256-GCM, fresh random nonce per message    6  decrypt; a GCM failure also means tampering
5  publish; copy id, type, correlation id to headers  -->  5  read headers, route, trace (no body parse needed)

Real scenarios: wrapping a partner's raw webhook body in an envelope at the edge, so every later stage has an id, a source, a content type and a received-at time (the id is a hash of partner and body, so a webhook retry gets the same id); adding HMAC signatures between two services that share a broker with other teams; encrypting a payload that holds PII before it lands on a shared topic; wrapping a message in a CloudEvents-style envelope for a subscriber outside the company; passing a message through a bridge that preserves only the body.

What provides it:

ProductTransport-envelope primitiveNotes
RabbitMQ (AMQP 0-9-1)Basic properties (message_id, type, correlation_id, timestamp, content_type) plus an application headers tableBroker interceptors add only metadata (timestamp, routing node); they do not rewrite the body
KafkaRecord headers (key and bytes), key, value, timestampConfluent's serializers add a magic byte and a 4-byte schema id inside the value: an envelope layer too
Redis StreamsField-value pairs; no separate header sectionMetadata and body are sibling fields
LaravelThe job payload JSON wraps your job; ShouldBeEncrypted encrypts the whole jobLaravel's own envelope is a queue payload, not a CloudEvent

Fix / how to use it. The Go layers below are small on purpose: a Layer has Wrap and Unwrap, and a Stack applies them in order and undoes them in reverse. The Signer and Sealer are real HMAC-SHA256 and AES-256-GCM; key management (rotation, KMS) is outside this page and belongs to messaging security.

go
package after

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"strconv"
	"time"
)

// Envelope is the in-body style of Envelope Wrapper: the application data is
// opaque bytes (any partner format), the envelope carries what the messaging
// infrastructure needs. Broker headers can carry the same fields instead
// (see Headers); the in-body style survives hops that drop headers.
type Envelope struct {
	ID            string    `json:"id"`
	Type          string    `json:"type"`
	Source        string    `json:"source"`
	Version       int       `json:"version"`
	OccurredAt    time.Time `json:"occurred_at"`
	CorrelationID string    `json:"correlation_id,omitempty"`
	CausationID   string    `json:"causation_id,omitempty"`
	ContentType   string    `json:"content_type"`
	Key           string    `json:"key,omitempty"` // partition / routing key, e.g. the order id
	Data          []byte    `json:"data"`          // base64 in JSON
}

// Headers is the header-style view, for brokers with a header section
// (AMQP application headers, Kafka record headers). Redis Streams has no
// header section, so these become sibling fields of the entry.
func (e Envelope) Headers() map[string]string {
	h := map[string]string{
		"id": e.ID, "type": e.Type, "source": e.Source,
		"version":      fmt.Sprint(e.Version),
		"occurred-at":  e.OccurredAt.UTC().Format(time.RFC3339Nano),
		"content-type": e.ContentType,
	}
	if e.CorrelationID != "" {
		h["correlation-id"] = e.CorrelationID
	}
	if e.CausationID != "" {
		h["causation-id"] = e.CausationID
	}
	return h
}

// WrapRaw is the Envelope Wrapper at the edge: a partner payload we did not
// design is put, untouched, inside an envelope the infrastructure understands.
func WrapRaw(partner, contentType string, body []byte, receivedAt time.Time) Envelope {
	sum := sha256.Sum256(append([]byte(partner+"|"), body...))
	return Envelope{
		ID:          hex.EncodeToString(sum[:16]), // same webhook retry, same id
		Type:        "partner.order.received",
		Source:      "partner/" + partner,
		Version:     1,
		OccurredAt:  receivedAt.UTC(),
		ContentType: contentType,
		Data:        body,
	}
}

// Layer is one wrapping step; Unwrap must undo Wrap exactly.
type Layer interface {
	Wrap(plain []byte) ([]byte, error)
	Unwrap(wrapped []byte) ([]byte, error)
}

// Stack applies layers in order on Wrap and in reverse order on Unwrap.
type Stack []Layer

func (s Stack) Wrap(b []byte) ([]byte, error) {
	for _, l := range s {
		var err error
		if b, err = l.Wrap(b); err != nil {
			return nil, err
		}
	}
	return b, nil
}

func (s Stack) Unwrap(b []byte) ([]byte, error) {
	for i := len(s) - 1; i >= 0; i-- {
		var err error
		if b, err = s[i].Unwrap(b); err != nil {
			return nil, err
		}
	}
	return b, nil
}

// Signer prefixes an HMAC-SHA256 so a consumer can reject a tampered message.
type Signer struct{ Key []byte }

func (s Signer) Wrap(p []byte) ([]byte, error) {
	m := hmac.New(sha256.New, s.Key)
	m.Write(p)
	return append(m.Sum(nil), p...), nil
}

func (s Signer) Unwrap(w []byte) ([]byte, error) {
	if len(w) < sha256.Size {
		return nil, errors.New("signer: message too short")
	}
	m := hmac.New(sha256.New, s.Key)
	m.Write(w[sha256.Size:])
	if !hmac.Equal(m.Sum(nil), w[:sha256.Size]) {
		return nil, errors.New("signer: bad signature")
	}
	return w[sha256.Size:], nil
}

// Sealer encrypts with AES-256-GCM: nonce || ciphertext+tag.
type Sealer struct{ aead cipher.AEAD }

func NewSealer(key []byte) (Sealer, error) {
	if len(key) != 32 {
		return Sealer{}, errors.New("sealer: AES-256 requires 32 bytes")
	}
	blk, err := aes.NewCipher(key) // 32-byte key selects AES-256
	if err != nil {
		return Sealer{}, err
	}
	g, err := cipher.NewGCM(blk)
	return Sealer{aead: g}, err
}

func (s Sealer) Wrap(p []byte) ([]byte, error) {
	nonce := make([]byte, s.aead.NonceSize())
	if _, err := rand.Read(nonce); err != nil {
		return nil, err
	}
	return s.aead.Seal(nonce, nonce, p, nil), nil
}

func (s Sealer) Unwrap(w []byte) ([]byte, error) {
	n := s.aead.NonceSize()
	if len(w) < n {
		return nil, errors.New("sealer: message too short")
	}
	return s.aead.Open(nil, w[:n], w[n:], nil)
}

// Encode serialises an envelope and applies the layer stack.
func Encode(e Envelope, layers Stack) ([]byte, error) {
	b, err := json.Marshal(e)
	if err != nil {
		return nil, err
	}
	return layers.Wrap(b)
}

// Decode is the Unwrapper: undo the layers, then parse the envelope.
func Decode(b []byte, layers Stack) (Envelope, error) {
	plain, err := layers.Unwrap(b)
	if err != nil {
		return Envelope{}, err
	}
	var e Envelope
	return e, json.Unmarshal(plain, &e)
}

// FromHeaders rebuilds an envelope from header-style metadata plus a body.
func FromHeaders(h map[string]string, body []byte) Envelope {
	at, _ := time.Parse(time.RFC3339Nano, h["occurred-at"])
	v, _ := strconv.Atoi(h["version"])
	return Envelope{
		ID: h["id"], Type: h["type"], Source: h["source"], Version: v, OccurredAt: at,
		CorrelationID: h["correlation-id"], CausationID: h["causation-id"],
		ContentType: h["content-type"], Data: body,
	}
}

The Laravel envelope is an immutable value object with the same two views (headers and full JSON):

php
<?php

namespace App\Messaging\Transform;

use DateTimeImmutable;
use DateTimeInterface;

/**
 * Envelope Wrapper, in-body style: opaque application data plus the fields the
 * infrastructure needs. The same fields can travel as broker headers instead.
 */
final readonly class Envelope
{
    public function __construct(
        public string $id,
        public string $type,
        public string $source,
        public int $version,
        public DateTimeImmutable $occurredAt,
        public string $contentType,
        public string $data,
        public ?string $correlationId = null,
        public ?string $causationId = null,
        public ?string $key = null,
    ) {}

    /** The edge wrapper: a partner payload is stored untouched inside an envelope. */
    public static function wrapRaw(string $partner, string $contentType, string $body): self
    {
        return new self(
            // Same webhook retry, same id: the id is derived from the content.
            id: substr(hash('sha256', $partner.'|'.$body), 0, 32),
            type: 'partner.order.received',
            source: 'partner/'.$partner,
            version: 1,
            occurredAt: new DateTimeImmutable('now', new \DateTimeZone('UTC')),
            contentType: $contentType,
            data: $body,
        );
    }

    /** Header-style view for AMQP application headers and Kafka record headers. */
    public function headers(): array
    {
        return array_filter([
            'id' => $this->id,
            'type' => $this->type,
            'source' => $this->source,
            'version' => (string) $this->version,
            'occurred-at' => $this->occurredAt->format(DateTimeInterface::RFC3339_EXTENDED),
            'content-type' => $this->contentType,
            'correlation-id' => $this->correlationId,
            'causation-id' => $this->causationId,
        ], fn ($v) => $v !== null);
    }

    public static function fromHeaders(array $h, string $body, ?string $key = null): self
    {
        return new self(
            id: $h['id'], type: $h['type'], source: $h['source'], version: (int) $h['version'],
            occurredAt: new DateTimeImmutable($h['occurred-at']), contentType: $h['content-type'],
            data: $body, correlationId: $h['correlation-id'] ?? null,
            causationId: $h['causation-id'] ?? null, key: $key,
        );
    }

    public function toJson(): string
    {
        return json_encode([
            ...$this->headers(), 'key' => $this->key, 'data' => base64_encode($this->data),
        ], JSON_THROW_ON_ERROR);
    }
}

Pitfalls. Verify the signature before you parse anything inside it. Use a constant-time comparison (hmac.Equal, hash_equals). Never reuse a GCM nonce under the same key. With randomly generated nonces, NIST SP 800-38D says the total number of invocations with one key "shall not exceed" 2^32, so count messages per key and rotate. Put the version in the envelope so unwrap can refuse what it does not understand.

Content Enricher Must-know ​

In plain words: The message is missing something the receiver needs, so a step goes and gets it and attaches it.

Common misunderstanding: "Enrichment is a cheap lookup." It is a network call on the hot path, and if it fails you have three bad choices: drop the message, publish it half-empty, or block everything behind it. Production enrichers need a deadline, a cache, a policy for "not found", and a policy for "the service is down".

Definition: a specialised transformer that uses information in the message (usually a key) to fetch data from an external source and append it. Sources include computation (derive a state code), environment (deployment region) and another system (database, file, directory or service).

1  order{customer_email_hash: h}  ->  Enricher
2  cache lookup "customer:h"            hit and fresh        -> use it
3                                       hit but expired      -> Go: refresh inline; Laravel flexible: stale + deferred refresh
4                                       miss                 -> one call to the customer service, 2 s deadline
5  service answers 404                   -> "unknown-customer" is a valid answer; cache it as a sentinel
6  service answers 5xx or times out      -> cold cache: retry later (never publish half an event)
7                                          warm but expired cache: use the old answer, mark enrichment=degraded

Real scenarios: an order event carries customer_id, consumers need tier and country; a click event gets geo data from an IP lookup; a payment event gets the merchant's settlement account; a log line gets the deployment's region (environment); a message gets a derived field (computation) such as a state code or a total.

What provides it:

ProductHow the enrichment typically runs
RabbitMQConsumer reads the raw queue, calls the source, publishes the enriched message to a second exchange
KafkaKafka Streams joins a stream with a table (stateful, see stream processing); or a consumer with a cache; Connect InsertField only adds static values or record metadata
Redis StreamsConsumer group worker with a cache (often Redis itself)
LaravelA pipe in a job calling Http:: with timeout and Cache::flexible for stale-while-revalidate

Fix / how to use it. The Go enricher combines a TTL cache, negative caching, request coalescing (singleflight, so 20 simultaneous orders from one customer make one call), a per-lookup timeout, and a stale-on-error fallback. Unlike Laravel flexible caching, the Go example refreshes expired entries synchronously; it only serves stale data if that lookup fails. Transient failures return ErrTransient, which the pipeline turns into a retry:

go
package after

import (
	"context"
	"errors"
	"sync"
	"time"

	"golang.org/x/sync/singleflight"
)

// Directory is the external source the Content Enricher asks.
type Directory interface {
	ByEmailHash(ctx context.Context, hash string) (Customer, error)
}

// ErrNotFound is a normal answer ("new customer"), not a failure.
var ErrNotFound = errors.New("customer not found")

type cached struct {
	c       Customer
	missing bool
	expires time.Time
}

// Enricher adds customer data to the canonical event. It protects the
// directory with a TTL cache, negative caching and request coalescing, and it
// protects the pipeline with a deadline and a stale-on-error fallback.
type Enricher struct {
	Dir     Directory
	TTL     time.Duration // how long an answer is fresh
	NegTTL  time.Duration // how long "not found" is remembered
	StaleOK time.Duration // how long an expired answer may still be used if the directory fails
	Timeout time.Duration // per lookup
	Now     func() time.Time

	mu    sync.Mutex
	cache map[string]cached
	group singleflight.Group
}

func (e *Enricher) now() time.Time {
	if e.Now != nil {
		return e.Now()
	}
	return time.Now()
}

func (e *Enricher) Enrich(ctx context.Context, o OrderPlaced) (OrderPlaced, error) {
	key := o.Customer.EmailHash
	e.mu.Lock()
	hit, ok := e.cache[key]
	e.mu.Unlock()
	if ok && e.now().Before(hit.expires) {
		return apply(o, hit), nil
	}

	// One lookup per key at a time: a burst of orders from one customer is one call.
	v, err, _ := e.group.Do(key, func() (any, error) {
		lctx, cancel := context.WithTimeout(ctx, e.Timeout)
		defer cancel()
		c, err := e.Dir.ByEmailHash(lctx, key)
		if errors.Is(err, ErrNotFound) {
			return cached{missing: true, expires: e.now().Add(e.NegTTL)}, nil
		}
		if err != nil {
			return nil, err
		}
		return cached{c: c, expires: e.now().Add(e.TTL)}, nil
	})
	if err != nil {
		// Directory down or slow: an old answer beats no answer, up to StaleOK.
		if ok && e.now().Before(hit.expires.Add(e.StaleOK)) {
			o = apply(o, hit)
			o.Enrichment = "degraded"
			return o, nil
		}
		return OrderPlaced{}, transient("enrich", err) // retry later; never publish half an event
	}
	res := v.(cached)
	e.mu.Lock()
	if e.cache == nil {
		e.cache = map[string]cached{}
	}
	e.cache[key] = res
	e.mu.Unlock()
	return apply(o, res), nil
}

func apply(o OrderPlaced, c cached) OrderPlaced {
	if c.missing {
		o.Enrichment = "unknown-customer"
		return o
	}
	o.Customer.ID, o.Customer.Tier, o.Customer.Country = c.c.ID, c.c.Tier, c.c.Country
	o.Enrichment = "ok"
	return o
}

Teaching implementation limits: the in-memory cache does not evict expired keys; use a bounded cache in production. singleflight.Do shares the leader lookup context and does not independently cancel each waiting caller. The lookup deadline is not a per-waiter deadline; use a cancellation-aware design when request cancellation matters.

In Laravel, Cache::flexible gives stale-while-revalidate (the framework refreshes a stale value with a deferred, locked callback). Its source treats a cached null as a miss, so "not found" is stored as a sentinel array. The HTTP client gets a connect timeout, a request timeout and two attempts total (the retry count includes the first attempt):

php
<?php

namespace App\Messaging\Transform;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

/**
 * Content Enricher: ask the customer service, remember the answer.
 * Cache::flexible gives stale-while-revalidate: fresh for 5 minutes, served
 * as stale for up to an hour while a deferred, locked refresh recomputes it
 * (read in Illuminate\Cache\Repository). A cold cache computes inline.
 */
final class CustomerEnricher
{
    public function enrich(OrderPlaced $o): OrderPlaced
    {
        $hash = $o->customer['email_hash'];

        try {
            // flexible() treats a cached null as a miss, so "not found" is stored as a sentinel array.
            $found = Cache::flexible("customer:{$hash}", [300, 3600], fn () => $this->lookup($hash) ?? ['missing' => true]);
        } catch (ConnectionException|RequestException $e) {
            // Cold cache and the service is down: do not publish half an event.
            throw new TransientFailure('enrich', $e);
        }

        return isset($found['missing'])
            ? $o->withCustomer([], 'unknown-customer')               // new customer: a normal answer
            : $o->withCustomer($found, 'ok');
    }

    /** @return array{id:string,tier:string,country:string}|null  null = not found */
    private function lookup(string $hash): ?array
    {
        $r = Http::baseUrl(config('services.customers.url'))
            ->connectTimeout(1)->timeout(2)              // a deadline per lookup
            ->retry(2, 100, throw: false)                // two attempts total, then fall through
            ->get("/customers/by-email-hash/{$hash}");

        if ($r->status() === 404) {
            return null;
        }
        $r->throw();                                     // 5xx and 4xx other than 404 become exceptions

        return Arr::only($r->json(), ['id', 'tier', 'country']);
    }
}

Pitfalls. Enrichment makes the pipeline depend on another service's availability, which is the coupling messaging was meant to remove. Reduce it with caches, with data carried in the event (event-carried state transfer, at the price of fatter events), or with a local read model fed by events. Enriched data is a snapshot: record when it was taken, because the tier may change tomorrow.

Content Filter Important ​

In plain words: Cut the message down to what this receiver needs: drop fields, flatten nesting, mask sensitive values.

Common misunderstanding: "A filter drops messages." That is the Message Filter (a router pattern, in advanced routing): it decides whether a whole message passes. The Content Filter keeps the message and changes what is inside it. Kafka Streams filter and the Connect Filter SMT are Message Filters. ReplaceField, MaskField and mapValues are Content Filters.

Definition: a transformer that removes unimportant data items, and may flatten a deep structure into a simple list. Packaged-application messages often reflect normalized database structures; a Content Filter produces the simpler projection the receiver actually needs.

1  OrderPlaced{customer{id,email_hash,tier,country}, lines[{sku,qty,price}], placed_at:10:00:03Z}
2  analytics allowlist:  order_id, partner, total, country, tier
3  flatten lines     ->  skus:["SKU-1","SKU-2"]
4  coarsen time      ->  placed_day:"2026-11-25"
5  result: no customer id, no hash, no exact time, no prices per line

Real scenarios: an analytics topic that must not carry customer identifiers; a partner-facing feed with only the fields in the contract; logs that mask card numbers before they reach the log pipeline; a flattened view for a search indexer.

Allowlist or denylist. An allowlist (build a new, smaller type) fails safe: a new field in the source never leaks, because someone has to add it on purpose. A denylist (delete named fields) is convenient for payloads you do not own, but an allowlisted projection is also possible. A denylist fails open: a new sensitive field passes until someone notices.

ProductContent Filter primitive
Kafka ConnectReplaceField (exclude, include, renames), MaskField (fields, replacement), ExtractField, Flatten
Kafka StreamsmapValues to a smaller type (no repartition)
RabbitMQNothing in the broker; consumer code
Redis StreamsNothing; consumer code
LaravelAPI-resource-style classes or a plain allowlist method
go
package after

import (
	"strings"
)

// AnalyticsOrder is a Content Filter by allowlist: a new struct that has only
// the fields the analytics audience may see. Adding a field to OrderPlaced
// does not leak it, because this type has to be changed on purpose.
type AnalyticsOrder struct {
	OrderID   string   `json:"order_id"`
	Partner   string   `json:"partner"`
	PlacedDay string   `json:"placed_day"` // time reduced to a date
	SKUs      []string `json:"skus"`       // nested lines flattened to a list
	Total     Money    `json:"total"`
	Country   string   `json:"country,omitempty"`
	Tier      string   `json:"tier,omitempty"`
}

// ForAnalytics drops customer id and hash and the exact time, flattens lines.
func ForAnalytics(o OrderPlaced) AnalyticsOrder {
	a := AnalyticsOrder{
		OrderID: o.OrderID, Partner: o.Partner,
		PlacedDay: o.PlacedAt.UTC().Format("2006-01-02"),
		Total:     o.Total, Country: o.Customer.Country, Tier: o.Customer.Tier,
	}
	for _, l := range o.Lines {
		a.SKUs = append(a.SKUs, l.SKU)
	}
	return a
}

// StripFields is a Content Filter by denylist for payloads we do not own
// (partner JSON). Paths are dotted ("payment.card"); arrays are walked.
// Use it for logs and for what the invalid-message channel stores in clear.
func StripFields(doc map[string]any, deny ...string) {
	for _, p := range deny {
		strip(doc, strings.Split(p, "."))
	}
}

func strip(node any, path []string) {
	switch n := node.(type) {
	case map[string]any:
		if len(path) == 1 {
			delete(n, path[0])
			return
		}
		strip(n[path[0]], path[1:])
	case []any:
		for _, e := range n {
			strip(e, path)
		}
	}
}
php
<?php

namespace App\Messaging\Transform;

/** Content Filter: an allowlist for audiences, a denylist for payloads we do not own. */
final class ContentFilter
{
    /** The analytics audience gets a new, smaller shape, not a copy with holes. */
    public function forAnalytics(OrderPlaced $o): array
    {
        return [
            'order_id' => $o->orderId,
            'partner' => $o->partner,
            'placed_day' => $o->placedAt->format('Y-m-d'),
            'skus' => array_column($o->lines, 'sku'),          // nested lines flattened
            'total' => ['amount_minor' => $o->totalMinor, 'currency' => $o->currency],
            'country' => $o->customer['country'] ?? null,
            'tier' => $o->customer['tier'] ?? null,
        ];
    }

    /** Remove dotted paths ("payment.card", "items.card"); lists are walked. */
    public function strip(array $doc, string ...$deny): array
    {
        foreach ($deny as $path) {
            $doc = $this->remove($doc, explode('.', $path));
        }

        return $doc;
    }

    private function remove(array $node, array $path): array
    {
        $head = array_shift($path);
        if (array_is_list($node)) {
            return array_map(fn ($n) => is_array($n) ? $this->remove($n, [$head, ...$path]) : $n, $node);
        }
        if ($path === []) {
            unset($node[$head]);
        } elseif (isset($node[$head]) && is_array($node[$head])) {
            $node[$head] = $this->remove($node[$head], $path);
        }

        return $node;
    }
}

PII retention and erasure in immutable logs are covered in messaging security. A filter reduces what spreads; it does not remove what was already written to a log.

Normalizer Must-know ​

In plain words: Many senders describe the same thing in different formats. The Normalizer works out which format arrived and sends it through the right translator, so everything downstream sees one format.

Common misunderstanding: "A Normalizer is a big switch statement inside one parser." EIP defines it as a router plus one translator per format. The router (format detection) and the translators are separate, so adding a partner adds a translator and a registration, not a branch in shared code.

Definition: a composite of a Message Router and several Message Translators that produces messages in a common format. EIP illustrates this with a pay-per-view provider receiving reports from many affiliates. Detection options listed there: a type specifier in the header; for schema-less XML, the root element name or an XPath on sub-nodes; for CSV, field count and types; for files, the file name or folder as a surrogate Datatype Channel.

1  POST /webhooks/acme/orders      Content-Type: application/json   -> detect: json (declared)
2  POST /webhooks/berlin/orders    Content-Type: application/xml    -> detect: xml  (declared)
3  POST /webhooks/tokyo/orders     (no content type)  body: C-9;...  -> detect: csv  (sniffed: has ';')
4  each routes to its parser    -> Draft{partner, order id, email, currency, placed_at, lines}
5  one more partner             -> one more parser; the Translator and everything after stay unchanged

Real scenarios: B2B order intake from many suppliers; ingesting events from several SDK versions of one mobile app; merging logs from different vendors; a bank receiving payment files in MT103, ISO 20022 XML and CSV.

Normalizer or Translator? Use a plain Translator when there is one source format. Use a Normalizer when several formats carry the same meaning and you want one downstream path. A useful split, used in the worked pipeline: the Normalizer unifies structure (three formats become one Draft), the Translator then unifies semantics (units, time zone, ids).

go
package after

import (
	"bytes"
	"encoding/json"
	"encoding/xml"
	"mime"
	"strconv"
	"strings"
	"time"
	_ "time/tzdata" // embed the zone database: slim containers have none
)

// Draft is the Normalizer's output: one structure for three partner formats.
// Values are still the partner's (decimal strings, partner ids); making them
// canonical is the Message Translator's job.
type Draft struct {
	Partner        string
	PartnerOrderID string
	CustomerEmail  string
	Currency       string
	PlacedAt       time.Time
	Lines          []DraftLine
}

type DraftLine struct {
	SKU          string
	Qty          int
	Price        string // "19.99", "5,50" or "1999" when PriceIsMinor
	PriceIsMinor bool
}

type Format string

const (
	FormatJSON Format = "json"
	FormatXML  Format = "xml"
	FormatCSV  Format = "csv"
)

// Inbound is what the Normalizer sees after the envelope is unwrapped.
type Inbound struct {
	Partner     string
	ContentType string
	Body        []byte
}

// Detect is the router half of the EIP Normalizer. A declared content type
// wins; otherwise sniff, because "the world is far from perfect".
func Detect(in Inbound) (Format, error) {
	if mt, _, err := mime.ParseMediaType(in.ContentType); err == nil {
		switch mt {
		case "application/json":
			return FormatJSON, nil
		case "application/xml", "text/xml":
			return FormatXML, nil
		case "text/csv":
			return FormatCSV, nil
		}
	}
	switch b := bytes.TrimSpace(in.Body); {
	case len(b) == 0:
		return "", invalid("normalize", "empty body")
	case b[0] == '{':
		return FormatJSON, nil
	case b[0] == '<':
		return FormatXML, nil
	case bytes.Contains(b, []byte(";")):
		return FormatCSV, nil
	}
	return "", invalid("normalize", "unknown format (content type %q)", in.ContentType)
}

// Normalizer routes each input to the parser for its format.
type Normalizer struct {
	Parsers map[Format]func(Inbound) (Draft, error)
}

func DefaultNormalizer() Normalizer {
	return Normalizer{Parsers: map[Format]func(Inbound) (Draft, error){
		FormatJSON: parseJSON, FormatXML: parseXML, FormatCSV: parseCSV,
	}}
}

func (n Normalizer) Normalize(in Inbound) (Draft, error) {
	f, err := Detect(in)
	if err != nil {
		return Draft{}, err
	}
	p, ok := n.Parsers[f]
	if !ok {
		return Draft{}, invalid("normalize", "no parser for %s", f)
	}
	d, err := p(in)
	d.Partner = in.Partner
	return d, err
}

// Partner A: JSON, ISO 8601 with offset, decimal major units as strings.
func parseJSON(in Inbound) (Draft, error) {
	var w struct {
		OrderID  string `json:"orderId"`
		Email    string `json:"email"`
		PlacedAt string `json:"placedAt"`
		Currency string `json:"currency"`
		Items    []struct {
			SKU   string `json:"sku"`
			Qty   int    `json:"qty"`
			Price string `json:"price"`
		} `json:"items"`
	}
	if err := json.Unmarshal(in.Body, &w); err != nil {
		return Draft{}, invalid("normalize", "json: %v", err)
	}
	at, err := time.Parse(time.RFC3339, w.PlacedAt)
	if err != nil {
		return Draft{}, invalid("normalize", "json placedAt: %v", err)
	}
	d := Draft{PartnerOrderID: w.OrderID, CustomerEmail: w.Email, Currency: w.Currency, PlacedAt: at}
	for _, it := range w.Items {
		d.Lines = append(d.Lines, DraftLine{SKU: it.SKU, Qty: it.Qty, Price: it.Price})
	}
	return d, nil
}

// xmlOrder is partner B's wire shape: local time without offset
// (Europe/Berlin) and a decimal comma.
type xmlOrder struct {
	ID    string `xml:"id,attr"`
	Email string `xml:"Buyer>Email"`
	Date  string `xml:"Date"`
	Cur   string `xml:"Cur"`
	Lines []struct {
		SKU  string `xml:"sku,attr"`
		Qty  int    `xml:"qty,attr"`
		Unit string `xml:"unit,attr"`
	} `xml:"Line"`
}

func parseXML(in Inbound) (Draft, error) {
	var w xmlOrder
	if err := xml.Unmarshal(in.Body, &w); err != nil {
		return Draft{}, invalid("normalize", "xml: %v", err)
	}
	return xmlDraft(w)
}

func xmlDraft(w xmlOrder) (Draft, error) {
	loc, err := time.LoadLocation("Europe/Berlin")
	if err != nil {
		return Draft{}, err
	}
	at, err := time.ParseInLocation("02/01/2006 15:04", w.Date, loc)
	if err != nil {
		return Draft{}, invalid("normalize", "xml Date: %v", err)
	}
	d := Draft{PartnerOrderID: w.ID, CustomerEmail: w.Email, Currency: w.Cur, PlacedAt: at}
	for _, l := range w.Lines {
		d.Lines = append(d.Lines, DraftLine{SKU: l.SKU, Qty: l.Qty, Price: l.Unit})
	}
	return d, nil
}

// Partner C: one CSV line, epoch seconds, prices already in minor units:
// id;email;epoch;currency;sku:qty:minor|sku:qty:minor
func parseCSV(in Inbound) (Draft, error) {
	f := strings.Split(strings.TrimSpace(string(in.Body)), ";")
	if len(f) != 5 {
		return Draft{}, invalid("normalize", "csv: want 5 fields, got %d", len(f))
	}
	sec, err := strconv.ParseInt(f[2], 10, 64)
	if err != nil {
		return Draft{}, invalid("normalize", "csv epoch: %v", err)
	}
	d := Draft{PartnerOrderID: f[0], CustomerEmail: f[1], Currency: f[3], PlacedAt: time.Unix(sec, 0)}
	for _, part := range strings.Split(f[4], "|") {
		x := strings.Split(part, ":")
		if len(x) != 3 {
			return Draft{}, invalid("normalize", "csv line %q", part)
		}
		q, err := strconv.Atoi(x[1])
		if err != nil {
			return Draft{}, invalid("normalize", "csv qty: %v", err)
		}
		d.Lines = append(d.Lines, DraftLine{SKU: x[0], Qty: q, Price: x[2], PriceIsMinor: true})
	}
	return d, nil
}
php
<?php

namespace App\Messaging\Transform;

use DateTimeImmutable;
use DateTimeZone;
use JsonException;

/** EIP Normalizer: detect the format, route to the parser, emit one Draft shape. */
final class Normalizer
{
    public function normalize(Envelope $raw): Draft
    {
        $partner = substr($raw->source, strlen('partner/'));
        $draft = match ($this->detect($raw)) {
            'json' => $this->json($raw->data),
            'xml' => $this->xml($raw->data),
            'csv' => $this->csv($raw->data),
        };

        return new Draft($partner, ...$draft);
    }

    /** A declared content type wins; otherwise sniff the first bytes. */
    private function detect(Envelope $raw): string
    {
        $type = strtolower(trim(explode(';', $raw->contentType)[0]));
        $body = ltrim($raw->data);

        return match (true) {
            $type === 'application/json' => 'json',
            in_array($type, ['application/xml', 'text/xml'], true) => 'xml',
            $type === 'text/csv' => 'csv',
            $body === '' => throw new InvalidMessage('normalize', 'empty body'),
            $body[0] === '{' => 'json',
            $body[0] === '<' => 'xml',
            str_contains($body, ';') => 'csv',
            default => throw new InvalidMessage('normalize', "unknown format ({$raw->contentType})"),
        };
    }

    /** Partner A: JSON, ISO 8601 with offset, decimal major units as strings. */
    private function json(string $body): array
    {
        try {
            $w = json_decode($body, true, 16, JSON_THROW_ON_ERROR);
            $stamp = $w['placedAt'] ?? '';
            if (! is_string($stamp) || ! preg_match('/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/D', $stamp)) { throw new InvalidMessage('normalize', 'json: explicit RFC3339 offset required'); }
            $at = new DateTimeImmutable($stamp);
            $errors = DateTimeImmutable::getLastErrors();
            if ($errors !== false && ($errors['warning_count'] || $errors['error_count'])) { throw new InvalidMessage('normalize', 'json: invalid date'); }
        } catch (JsonException|\Exception $e) {
            throw new InvalidMessage('normalize', 'json: '.$e->getMessage());
        }

        return [
            'partnerOrderId' => (string) ($w['orderId'] ?? ''),
            'email' => (string) ($w['email'] ?? ''),
            'currency' => (string) ($w['currency'] ?? ''),
            'placedAt' => $at,
            'lines' => array_map(fn ($i) => [
                'sku' => (string) $i['sku'], 'qty' => $this->quantity($i['qty']), 'price' => (string) $i['price'], 'minor' => false,
            ], $w['items'] ?? []),
        ];
    }

    /** Partner B: XML, local time without offset (Europe/Berlin), decimal comma. */
    private function xml(string $body): array
    {
        $prev = libxml_use_internal_errors(true);
        $x = simplexml_load_string($body, options: LIBXML_NONET); // no DTD, no network: XXE-safe defaults
        libxml_use_internal_errors($prev);
        if ($x === false) {
            throw new InvalidMessage('normalize', 'xml: not well-formed');
        }
        $at = DateTimeImmutable::createFromFormat('!d/m/Y H:i', (string) $x->Date, new DateTimeZone('Europe/Berlin'));
        if ($at === false || $at->format('d/m/Y H:i') !== (string) $x->Date) {
            throw new InvalidMessage('normalize', 'xml Date: bad format');
        }
        $lines = [];
        foreach ($x->Line as $l) {
            $lines[] = ['sku' => (string) $l['sku'], 'qty' => $this->quantity((string) $l['qty']), 'price' => (string) $l['unit'], 'minor' => false];
        }

        return [
            'partnerOrderId' => (string) $x['id'], 'email' => (string) $x->Buyer->Email,
            'currency' => (string) $x->Cur, 'placedAt' => $at, 'lines' => $lines,
        ];
    }

    /** Partner C: id;email;epoch;currency;sku:qty:minor|sku:qty:minor */
    private function csv(string $body): array
    {
        $f = explode(';', trim($body));
        if (count($f) !== 5 || ! ctype_digit($f[2])) {
            throw new InvalidMessage('normalize', 'csv: want 5 fields with a numeric epoch');
        }
        $lines = [];
        foreach (explode('|', $f[4]) as $part) {
            $p = explode(':', $part);
            if (count($p) !== 3) {
                throw new InvalidMessage('normalize', "csv line {$part}");
            }
            $lines[] = ['sku' => $p[0], 'qty' => $this->quantity($p[1]), 'price' => $p[2], 'minor' => true];
        }

        return [
            'partnerOrderId' => $f[0], 'email' => $f[1], 'currency' => $f[3],
            'placedAt' => (new DateTimeImmutable('@'.$f[2])), 'lines' => $lines,
        ];
    }
    private function quantity(mixed $value): int
    {
        if ((! is_string($value) && ! is_int($value)) || ! preg_match('/^[0-9]+$/D', (string) $value)) {
            throw new InvalidMessage('normalize', 'quantity must be a positive integer');
        }
        $digits = ltrim((string) $value, '0') ?: '0';
        $max = (string) PHP_INT_MAX;
        if (strlen($digits) > strlen($max) || (strlen($digits) === strlen($max) && strcmp($digits, $max) > 0) || $digits === '0') {
            throw new InvalidMessage('normalize', 'quantity outside range');
        }
        return (int) $digits;
    }

}

Pitfalls. Prefer a declared content type, fall back to sniffing, and reject what you cannot classify instead of guessing. Pull XML parsers hand you a security surface: disable DTD loading and network access (the PHP code passes LIBXML_NONET; Go's encoding/xml knows only the standard entities plus whatever you put in Decoder.Entity, and does not fetch external ones). Load time-zone data explicitly in minimal containers, which is why the Go file imports time/tzdata: the package "provides an embedded copy of the timezone database" at a cost of "about 450 KB".

Canonical Data Model Important ​

In plain words: Instead of every system learning every other system's format, everyone learns one shared format and translates to and from it.

Common misunderstanding: "The canonical model is the company's data model, so it must be complete." A canonical message model describes what is exchanged, not what each system stores. When it tries to be the union of every system's fields, it becomes a negotiated monster that nobody can change.

Definition: a data model independent of any application, which every application produces and consumes. The point is arithmetic. EIP counts translators, assuming every application talks to every other: 2 applications need 2 translators directly and 4 with a canonical model; 3 need 6 either way; 6 applications need 30 translators without a canonical model and 12 with one (n(n-1) against 2n).

ABCDEFPoint to point: n(n-1) translators6 systems: 30CanonicalmodelABCDEFCanonical hub: 2n translators6 systems: 12

The debate. Three positions, each with a cost:

ApproachIdeaWins whenHurts when
Canonical Data Model (EIP)One company-wide message modelMany systems (say 6 or more), an integration team, an ESB, mostly stable concepts, ownership is centralTeams cannot agree, one team's concept bends to fit another's, every change needs a committee, the model leaks the biggest system's quirks
Published Language plus Open Host Service (DDD)The upstream publishes its own documented format; each consumer maps itOne clear owner per fact (Sales publishes order.placed), many consumersMany publishers of the "same" concept that disagree
Anticorruption Layer (DDD)The downstream translates everything at its own boundaryA messy or legacy upstream you cannot changeEvery consumer pays the same translation cost; an out-of-process ACL adds latency and another deployed component to maintain

A working compromise used in the example: one canonical model per business fact (OrderPlaced), owned by the context that owns the fact and versioned as in schema evolution; partners are handled by Normalizers at the edge; consumers that need a different shape add their own Content Filter or anticorruption layer. How contexts relate and who pays for translation is the subject of context maps.

1  Sales context publishes  sales.order_placed.v2   (published language, owned by Sales)
2  Fulfilment consumes it as is                     (conformist: cheap, fine)
3  Finance has its own ledger terms                 (anticorruption layer: translates v2 to ledger entries)
4  Analytics wants a smaller view                   (Content Filter: allowlist)
5  a partner sends XML                              (Normalizer at the edge: never part of the model)

When a canonical model hurts: when it is designed up front for systems that do not exist yet; when "canonical" means "the ERP's schema"; when the model has optional fields for every consumer (a "god message"); when no one owns it. When it helps: when there is a real integration hub, when many partners are normalised into one internal format, and when the model is narrow (one fact) and owned.

Messaging Mapper Important ​

In plain words: A class whose only job is to convert between your domain objects and the message, so the domain does not know about JSON and the message code does not know about domain rules.

Common misunderstanding: "Put toJson() on the entity, it is simpler." Then the message shape is welded to the entity, a database column rename breaks a public event, and the domain imports the messaging library. The mapper is a third component; neither domain objects nor messaging infrastructure need to depend on it.

Definition: a separate mapper that reads domain objects into messages and builds or updates domain objects from messages. Messages have no object references or inheritance, and a mapper deals with that. It is a specialisation of the Mapper pattern, and shares problems with Data Mapper (nulls, partial updates, identity).

Real scenarios: an Order aggregate publishing OrderPlaced; an inbound PaymentSettled event updating an aggregate through its constructor or a domain method; mapping an Eloquent model to a canonical message without exposing auto-increment keys.

Rules that matter. Rebuild objects through constructors or factories so a bad message cannot create an invalid object (the mapper is not allowed to bypass invariants). Never publish the database primary key; publish a public id. Check cross-field consistency (does the total match the lines?). Keep mapping deterministic: no clocks, no lookups, no randomness; that is what makes property tests possible.

go
// Package domain is the inside of the order service. It knows nothing about
// JSON, brokers or partners; the Messaging Mapper is the only code that does.
package domain

import (
	"errors"
	"math"
	"time"
)

// Money is a value object in minor units (cents).
type Money struct {
	minor    int64
	currency string
}

func NewMoney(minor int64, currency string) (Money, error) {
	if minor < 0 || len(currency) != 3 {
		return Money{}, errors.New("domain: invalid money")
	}
	return Money{minor: minor, currency: currency}, nil
}

func (m Money) Minor() int64     { return m.minor }
func (m Money) Currency() string { return m.currency }

// Line is one order line.
type Line struct {
	sku   string
	qty   int
	price Money
}

func NewLine(sku string, qty int, price Money) (Line, error) {
	if sku == "" || qty <= 0 || len(price.currency) != 3 || price.minor < 0 || price.minor > math.MaxInt64/int64(qty) {
		return Line{}, errors.New("domain: invalid line")
	}
	return Line{sku: sku, qty: qty, price: price}, nil
}

func (l Line) SKU() string      { return l.sku }
func (l Line) Qty() int         { return l.qty }
func (l Line) Price() Money     { return l.price }
func (l Line) Total() int64     { return l.price.minor * int64(l.qty) }
func (l Line) Currency() string { return l.price.currency }

// Order is the aggregate. Its invariants live here, not in the mapper.
type Order struct {
	id         string
	customerID string
	placedAt   time.Time
	lines      []Line
}

func NewOrder(id, customerID string, placedAt time.Time, lines []Line) (Order, error) {
	if id == "" || len(lines) == 0 {
		return Order{}, errors.New("domain: an order needs an id and at least one line")
	}
	cur := lines[0].Currency()
	var sum int64
	for _, l := range lines {
		if l.qty <= 0 || l.sku == "" || l.price.minor < 0 || l.price.minor > math.MaxInt64/int64(l.qty) || sum > math.MaxInt64-l.Total() {
			return Order{}, errors.New("domain: invalid or overflowing line")
		}
		sum += l.Total()
		if l.Currency() != cur {
			return Order{}, errors.New("domain: mixed currencies")
		}
	}
	return Order{id: id, customerID: customerID, placedAt: placedAt, lines: append([]Line(nil), lines...)}, nil
}

func (o Order) ID() string          { return o.id }
func (o Order) CustomerID() string  { return o.customerID }
func (o Order) PlacedAt() time.Time { return o.placedAt }
func (o Order) Lines() []Line       { return append([]Line(nil), o.lines...) }

// Total sums the lines in the order currency.
func (o Order) Total() Money {
	var sum int64
	for _, l := range o.lines {
		sum += l.Total()
	}
	return Money{minor: sum, currency: o.lines[0].Currency()}
}
go
package after

import (
	"errors"

	"academy/message-transformation/domain"
)

// OrderMapper is the Messaging Mapper: the only code that knows both the
// domain aggregate and the message. Neither knows the mapper exists.
type OrderMapper struct{}

func (OrderMapper) ToMessage(o domain.Order) OrderPlaced {
	m := OrderPlaced{
		OrderID:  o.ID(),
		PlacedAt: o.PlacedAt(),
		Customer: Customer{ID: o.CustomerID()},
		Total:    Money{o.Total().Minor(), o.Total().Currency()},
	}
	for _, l := range o.Lines() {
		m.Lines = append(m.Lines, Line{SKU: l.SKU(), Qty: l.Qty(), UnitPrice: Money{l.Price().Minor(), l.Price().Currency()}})
	}
	return m
}

// FromMessage rebuilds the aggregate through its constructor, so a bad message
// cannot create an invalid object, and checks that the sender's total agrees.
func (OrderMapper) FromMessage(m OrderPlaced) (domain.Order, error) {
	var lines []domain.Line
	for _, l := range m.Lines {
		p, err := domain.NewMoney(l.UnitPrice.AmountMinor, l.UnitPrice.Currency)
		if err != nil {
			return domain.Order{}, invalid("map", "%v", err)
		}
		dl, err := domain.NewLine(l.SKU, l.Qty, p)
		if err != nil {
			return domain.Order{}, invalid("map", "%v", err)
		}
		lines = append(lines, dl)
	}
	o, err := domain.NewOrder(m.OrderID, m.Customer.ID, m.PlacedAt, lines)
	if err != nil {
		return domain.Order{}, invalid("map", "%v", err)
	}
	if o.Total().Minor() != m.Total.AmountMinor || o.Total().Currency() != m.Total.Currency {
		return domain.Order{}, invalid("map", "%v", errors.New("total does not match lines"))
	}
	return o, nil
}
php
<?php

namespace App\Messaging\Transform;

use App\Models\Order;
use DateTimeImmutable;
use DateTimeZone;

/**
 * Messaging Mapper: the one class that knows both the Eloquent model and the
 * canonical message. The model has no toMessage(); the message has no model.
 */
final class OrderMapper
{
    public function toMessage(Order $order): OrderPlaced
    {
        $lines = $order->lines->map(fn ($l) => [
            'sku' => $l->sku,
            'qty' => $l->quantity,
            'unit_price' => ['amount_minor' => $l->unit_price_minor, 'currency' => $order->currency],
        ])->all();

        return new OrderPlaced(
            orderId: (string) $order->public_id,        // never the auto-increment key
            partner: 'internal',
            placedAt: DateTimeImmutable::createFromInterface($order->placed_at)->setTimezone(new DateTimeZone('UTC')),
            // An internal order has no partner e-mail; the hash stays empty by design.
            customer: ['email_hash' => '', 'id' => (string) $order->customer_public_id],
            lines: $lines,
            totalMinor: array_sum(array_map(fn ($l) => $l['qty'] * $l['unit_price']['amount_minor'], $lines)),
            currency: $order->currency,
        );
    }

    /** Build a model from a message and refuse messages whose total disagrees with their lines. */
    public function fromMessage(OrderPlaced $m): Order
    {
        if ($m->orderId === '' || $m->lines === []) { throw new InvalidMessage('map', 'id and lines required'); }
        $sum = 0;
        foreach ($m->lines as $line) {
            $qty = $line['qty'];
            $minor = $line['unit_price']['amount_minor'];
            if (! is_int($qty) || $qty <= 0 || ! is_int($minor) || $minor < 0 || $line['sku'] === '' || $line['unit_price']['currency'] !== $m->currency) {
                throw new InvalidMessage('map', 'invalid line or currency');
            }
            if ($minor > intdiv(PHP_INT_MAX, $qty) || $sum > PHP_INT_MAX - $minor * $qty) {
                throw new InvalidMessage('map', 'total exceeds integer range');
            }
            $sum += $minor * $qty;
        }
        if ($sum !== $m->totalMinor) {
            throw new InvalidMessage('map', 'total does not match lines');
        }
        $order = new Order([
            'public_id' => $m->orderId,
            'currency' => $m->currency,
            'placed_at' => $m->placedAt,
        ]);
        $order->setRelation('lines', collect($m->lines)->map(fn ($l) => new \App\Models\OrderLine([
            'sku' => $l['sku'], 'quantity' => $l['qty'], 'unit_price_minor' => $l['unit_price']['amount_minor'],
        ])));

        return $order;
    }
}
PatternOne sentenceOwner page
Claim CheckStore the big payload elsewhere and send a referencemessage design
Message FilterDrop whole messages that do not matchadvanced routing
Content-Based RouterSend each message to a channel chosen by its content (the router half of a Normalizer)routing topologies
Splitter, AggregatorBreak a message into parts, or combine partsadvanced routing
Invalid Message ChannelWhere unprocessable messages gointegration styles and channels
Dead Letter ChannelWhere messages that failed delivery godead-letter queue
Channel AdapterConnect an application to a channel (the webhook controller below is one)integration styles and channels
Message History, Wire TapRecord what a message passed throughsystem management

Where it runs: hosts and per-broker support ​

ProducerserviceProducer edgemapper, adapterin the same repoSeparate applicationKafka Connect SMTKafka Streams map, filterGateway / ESBAPI gateway policy, iPaaSRabbitMQ, Redis Streamsno broker-side transform:use a consumer or sidecarConsumer edgetranslator, enricher,anti-corruption layerConsumerserviceSame pattern, four hosts: pick by who owns the code and where the data lives

The same pattern can live in four places. The right host depends on who owns the code and where the data is.

HostWhat runs thereOwnerTypical choice for
Producer edgeA Messaging Mapper, an Envelope Wrapper, a Content Filter for the public contractThe producing team"Publish our fact in our published language"
Connect / Streams applicationKafka Connect SMTs, Kafka Streams stateless operatorsPlatform or data teamMasking, field removal, topic routing, simple reshaping
Consumer edgeTranslator, Normalizer, Enricher, anticorruption layerThe consuming team"Protect our model from theirs"
Gateway, ESB or iPaaSNormalizer for many partners, protocol bridging, envelope policyAn integration teamB2B with hundreds of partners
Sidecar or standalone transformer serviceAny of them, in its own processPlatform teamRabbitMQ and Redis Streams stacks that need broker-side-like behaviour
CapabilityRabbitMQKafkaRedis StreamsLaravel queue drivers
Built-in broker body transformationNone; custom Erlang interceptors are an extension point, built-ins stamp metadata; Streams protocol bypasses these interceptorsNone in the broker; Connect workers and Streams applications run separatelyNoneDrivers do not implement domain translation
Broker-side metadata stampingInterceptors (set_header_timestamp, set_header_routing_node); Shovel can add x-shovelled headers and overwrite properties (dest-publish-properties), but "setting headers this way is not currently supported"Record timestamp; InsertField, InsertHeader in ConnectEntry id has a time-like component, not the business event timeJob payload carries uuid, attempts
Where a translator worker runsConsumer on queue A, publishes to exchange BConsumer-producer, or Streams, or ConnectConsumer group workerA queued job, an Artisan consumer command
Atomic "result plus acknowledgement"Publisher confirms then ack (not atomic)Transactions (kgo group transact session)Publish then acknowledge; MULTI has no rollback on runtime command errorsJob completion does not make DB writes and external publishes atomic
Cost of an extra hopOne more queueOne more topic and its retentionOne more streamOne more queue name

Kafka hosts: Connect SMTs and Kafka Streams ​

Single Message Transforms (SMTs). Connect provides lightweight per-record modifications inside connector tasks, useful for reshaping data and choosing destinations. A chain is declared in the connector configuration: transforms lists aliases in order, transforms.<alias>.type names the class, and the rest of the keys are that transformation's own. Built-ins named in the guide include Cast, DropHeaders, ExtractField, Filter, Flatten, HeaderFrom, HoistField, InsertField, InsertHeader, MaskField, RegexRouter, ReplaceField, SetSchemaMetadata, TimestampConverter, TimestampRouter and ValueToKey.

SMTEIP pattern it implementsTypical use
ReplaceField$Value (exclude, include, renames)Content Filter, small TranslatorDrop phone, rename cust_id to customer_id
MaskField$Value (fields, replacement)Content FilterBlank a card number before it reaches the topic
ExtractField, HoistField, FlattenTranslator (structure)Unwrap or wrap a nested value
InsertField, InsertHeader, HeaderFromEnvelope Wrapper (metadata), light EnricherStamp data_source, copy a field into a header
Cast, TimestampConverterTranslator (types)String to int, epoch to ISO 8601
RegexRouter, TimestampRouter, ValueToKeyRouter, key choiceRename topics, set the partition key
Filter plus a predicateMessage Filter (not Content Filter)Drop test traffic; predicates: TopicNameMatches, HasHeaderKey, RecordIsTombstone, with the implicit negate
Debezium EventRouter (outbox)Translator plus routerTurn outbox rows into routed events, see change data capture
json
{
  "name": "orders-source",
  "config": {
    "connector.class": "<any source connector that emits order records>",
    "topic.prefix": "partner",
    "transforms": "dropPii,maskCard,stamp,route",
    "transforms.dropPii.type": "org.apache.kafka.connect.transforms.ReplaceField$Value",
    "transforms.dropPii.exclude": "phone,shipping_address",
    "transforms.maskCard.type": "org.apache.kafka.connect.transforms.MaskField$Value",
    "transforms.maskCard.fields": "card_number",
    "transforms.maskCard.replacement": "****",
    "transforms.stamp.type": "org.apache.kafka.connect.transforms.InsertField$Value",
    "transforms.stamp.static.field": "data_source",
    "transforms.stamp.static.value": "partner-feed",
    "transforms.route.type": "org.apache.kafka.connect.transforms.RegexRouter",
    "transforms.route.regex": "partner\\.(.*)",
    "transforms.route.replacement": "orders.raw.$1",
    "errors.tolerance": "none",
    "errors.log.enable": "true"
  }
}
properties
# Drop test traffic and tombstones before they reach the topic:
# Filter removes a record, a predicate decides which records it applies to.
transforms=dropTest
transforms.dropTest.type=org.apache.kafka.connect.transforms.Filter
transforms.dropTest.predicate=isTest
predicates=isTest
predicates.isTest.type=org.apache.kafka.connect.transforms.predicates.TopicNameMatches
predicates.isTest.pattern=.*\\.test

(Connect configurations on this page are examples, not run here.) Know the limits. Built-in SMTs process individual records and offer no arbitrary remote lookup. A custom Java SMT could call a service, but blocking I/O couples connector throughput and retry to that dependency; use a separate Enricher or stream-table join. Custom SMTs can be unit-tested with SourceRecord/SinkRecord and apply(); full connector tests need Connect. By default conversion/transformation errors fail the task, which is the right default for a bug and a bad one for one malformed record: set errors.tolerance, errors.log.enable and errors.deadletterqueue.topic.name consciously, and read dead-letter queue first. Standard Connect DLQ handling is a sink capability, not a universal source-connector guarantee; errors.tolerance=all can skip records.

Kafka Streams. The DSL offers transformations that do not need a state store: map, mapValues, flatMap, flatMapValues, filter, selectKey, peek, split (branching). The page's advice matters for transformation design: mapValues preserves keys and avoids marking the stream for repartitioning; map and selectKey can change the key, which can mark the stream for repartitioning when a later key-dependent operation needs it. Use mapValues for Translators and Content Filters, and change keys only when you mean to (see ordering and partitioning). Enrichment in Streams is a join with a KTable, which is stateful and belongs to stream processing.

java
// Illustrative Kafka Streams topology (Java, not compiled here): a Content
// Filter and a flatten as stateless operators inside the broker ecosystem.
import java.util.Map;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.KStream;

public class AnalyticsTopology {
    public static void build(StreamsBuilder b) {
        KStream<String, Map<String, Object>> placed = b.stream("orders.placed"); // value serde configured elsewhere

        placed
            .filter((orderId, order) -> order != null)                 // drop tombstones
            .filter((orderId, order) -> !"degraded".equals(order.get("enrichment")))
            .mapValues(AnalyticsTopology::forAnalytics)                // value only: key kept, no repartition
            .to("orders.analytics");
    }

    // Allowlist: build a new, smaller map instead of deleting from the old one.
    static Map<String, Object> forAnalytics(Map<String, Object> order) {
        return Map.of(
            "order_id", order.get("order_id"),
            "partner", order.get("partner"),
            "total", order.get("total"));
    }
}

(Illustrative Java, not compiled here. The two filter calls are Message Filters; the mapValues is the Content Filter.)

Gateways and integration platforms. API gateways can rewrite headers and bodies in policies; ESBs and iPaaS products (the EIP's original home) host Normalizers and Translators with graphical mappers; cloud pipes (EIP's own newer example uses Amazon EventBridge Pipes with an "Enrichment" step) host Enrichers. The trade is central ownership against a central bottleneck: API gateway and BFF covers the HTTP side, and service communication the choice between synchronous calls and messages.

Mechanics ​

Composition: Pipes and Filters in one line. A stage is a function from one type to the next, and chaining is function composition. In Go, Then(f, g) is the whole mechanism; in Laravel, the Illuminate\Pipeline\Pipeline class does the same with send($passable)->through([...])->thenReturn(), where each pipe exposes handle($passable, Closure $next) and is resolved from the container.

Partner AJSONPartner BXMLPartner CCSV lineWebhookEnvelopeWrapperraw topicpartner.orders.rawNormalizerformat routerDraftTranslatorunits, UTC, idsEnrichertier, countryCustomerdirectory + cacheInvalid message channelstage, reason, fingerprintorders.placedcanonicalContent Filterallowlistorders.analyticsno customer datainvalid: acknowledge and parktransient: retry with backoff

Classify every failure. This is the most useful rule on the page. A stage returns one of three outcomes, and the consumer loop acts on them differently.

ClassExampleRetry helps?ActionGoLaravel
InvalidUnknown currency, malformed XML, quantity 0No, same input same resultWrite an Invalid Message Channel record, acknowledgeErrInvalidInvalidMessage
TransientCustomer service timed out, broker nackYes, laterRetry with backoff, bounded attempts, then DLQErrTransientTransientFailure, release($delay)
BugNil dereference, panicNot until the code is fixedFail loudly, alert; the DLQ holds the evidencepanic; supervisor must recreate the workerexception, failed_jobs

The Invalid Message Channel record in the code stores a fingerprint (stage, a redacted stable reason, SHA-256 of the payload), not the payload, because partner payloads contain PII. Parser exceptions can contain raw input: never persist their verbatim text as the reason. The original is still in the raw topic (within its retention) and can be replayed after a fix. If you must keep the payload, keep it sealed with the envelope's Sealer.

Determinism. A redelivered message must produce the same output, including the same ids, or consumers cannot deduplicate. In the example the output event ids are sha256(raw id + type), and the raw id is sha256(partner + body): the same webhook retried twice gives the same raw id, and the same raw message transformed twice gives the same event ids. This does not guarantee byte-identical enriched snapshots: enrichment and a new webhook receipt time can change. If identical bodies can represent distinct business events, include the partner-issued occurrence id in the raw identity. See idempotent consumers. Anything non-deterministic (clocks, random ids, an enrichment that changed between attempts) belongs in a field consumers are allowed to disagree about, never in an id.

Publishing more than one output. The example publishes orders.placed and orders.analytics. Two publishes are not atomic: if the second fails, the first is already out. The pipeline returns Retry, the raw message is processed again, and the first output is re-published with the same id, which a deduplicating consumer ignores. If you cannot tolerate even that, write both outputs to an outbox table in one local transaction (outbox pattern).

Money, time and ids. Three translator bugs account for most incidents. Money: never use floating point; parse decimal strings into integer minor units using the currency's digits. The official SIX ISO 4217 list defines minor-unit digits (JPY 0, EUR 2, KWD 3). Validate integer parsing, quantity multiplication and total addition against overflow as well as decimal precision. Reject amounts with more decimals than allowed instead of rounding. Carry the currency next to every amount. Time: parse with an explicit zone, store UTC, never trust a naive local time; DST makes some local times ambiguous or missing. Ids: namespace partner ids (berlin-shop:B-77) so two partners cannot collide, and never expose database auto-increment keys.

Schema evolution. A transformation is exactly where old and new versions meet. An upcaster lifts an old payload one version at a time (v1 to v2 to v3) and the consumer only knows the latest. It is a Message Translator whose input and output are two versions of the same type; rules for compatible changes are in message design and schema evolution, and replaying old events through upcasters in event sourcing and CQRS. The Go file includes upcasters keyed by version and rejects unsupported ranges or missing steps.

Ordering. A transformation that changes the key changes the partition (Kafka) and therefore the ordering guarantee. Keep the key stable (the order id) across stages, and see ordering and partitioning before using map or selectKey.

Back-pressure. An enricher that waits on a slow service holds the message; with prefetch 20 you hold 20 in flight. Use deadlines and bounded concurrency (backpressure and flow control).

Testing, observability and performance ​

Testing transformations. Pure functions are the easy case; use three kinds of test.

TestWhat it provesHow
Golden filesThe exact canonical output for a recorded partner input did not changeStore the input and the pretty-printed expected JSON in testdata/; the test compares bytes and a -update flag rewrites them; review the diff like code
Property testsLaws hold for all inputs: parse(format(n)) == n; fromMessage(toMessage(order)) preserves total and id; unwrap(wrap(x)) == x; a flipped bit is rejectedGo testing/quick; PHP with a generator loop or a property library
Error-table testsEvery invalid class reaches the invalid channel, none reaches the output, the payload is not in clearA table of bad inputs and one assertion block
Contract testsConsumers still read what the producer emitsSee testing messaging

Add a "no PII" test for filters: run a message with a known e-mail through the pipeline and assert the string appears in none of the outputs. Pin golden files for every partner format you accept, plus the weird ones (empty lines, extra fields, BOM, non-UTF-8).

go
package after

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"sync/atomic"
	"testing"
	"testing/quick"
	"time"

	"academy/message-transformation/domain"
)

var update = flag.Bool("update", false, "rewrite golden files")

var hashKey = []byte("test-key")

type fakeDir struct {
	calls atomic.Int32
	fn    func(string) (Customer, error)
}

func (f *fakeDir) ByEmailHash(_ context.Context, h string) (Customer, error) {
	f.calls.Add(1)
	return f.fn(h)
}

type memPub struct {
	mu   sync.Mutex
	sent map[string][]Envelope
}

func (m *memPub) Publish(_ context.Context, dest string, e Envelope) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	if m.sent == nil {
		m.sent = map[string][]Envelope{}
	}
	m.sent[dest] = append(m.sent[dest], e)
	return nil
}

func okDir() *fakeDir {
	return &fakeDir{fn: func(string) (Customer, error) { return Customer{ID: "c-1", Tier: "gold", Country: "DE"}, nil }}
}

func newPipeline(dir Directory, pub Publisher) *Pipeline {
	return &Pipeline{
		Normalizer: DefaultNormalizer(),
		Translate:  ToCanonical(hashKey),
		Enricher:   &Enricher{Dir: dir, TTL: time.Minute, NegTTL: time.Minute, StaleOK: time.Hour, Timeout: time.Second},
		Out:        pub,
	}
}

// Golden files: the exact canonical JSON for each partner input.
func TestGoldenPartners(t *testing.T) {
	cases := []struct{ partner, in, ct string }{
		{"acme", "partner_a.json", "application/json"},
		{"berlin-shop", "partner_b.xml", "application/xml; charset=utf-8"},
		{"tokyo-mart", "partner_c.csv", ""}, // no content type: sniffed
	}
	for _, c := range cases {
		t.Run(c.partner, func(t *testing.T) {
			body, err := os.ReadFile(filepath.Join("testdata", c.in))
			if err != nil {
				t.Fatal(err)
			}
			pub := &memPub{}
			out, err := newPipeline(okDir(), pub).Handle(context.Background(),
				WrapRaw(c.partner, c.ct, body, time.Date(2026, 11, 25, 7, 0, 0, 0, time.UTC)))
			if err != nil || out != Ack {
				t.Fatalf("outcome %v err %v", out, err)
			}
			var pretty bytes.Buffer
			if err := json.Indent(&pretty, pub.sent[TopicCanonical][0].Data, "", "  "); err != nil {
				t.Fatal(err)
			}
			pretty.WriteByte('\n')
			golden := filepath.Join("testdata", c.partner+".golden.json")
			if *update {
				_ = os.WriteFile(golden, pretty.Bytes(), 0o644)
			}
			want, _ := os.ReadFile(golden)
			if !bytes.Equal(pretty.Bytes(), want) {
				t.Errorf("golden mismatch for %s\n--- got\n%s--- want\n%s", c.partner, pretty.Bytes(), want)
			}
		})
	}
}

// The canonical event and the analytics event never contain the e-mail.
func TestNoPIILeaks(t *testing.T) {
	body, _ := os.ReadFile("testdata/partner_a.json")
	pub := &memPub{}
	_, _ = newPipeline(okDir(), pub).Handle(context.Background(), WrapRaw("acme", "application/json", body, time.Now()))
	for dest, evs := range pub.sent {
		for _, e := range evs {
			if strings.Contains(strings.ToLower(string(e.Data)), "alice@example.com") {
				t.Errorf("%s leaks the e-mail", dest)
			}
		}
	}
	if strings.Contains(string(pub.sent[TopicAnalytics][0].Data), "customer") {
		t.Error("analytics event must not carry customer data")
	}
}

// Invalid input goes to the invalid channel, is acknowledged, and is not stored in clear.
func TestInvalidMessageChannel(t *testing.T) {
	bad := map[string]string{
		"not json":       `{"orderId":`,
		"bad currency":   `{"orderId":"1","email":"a@b.c","placedAt":"2026-11-25T10:00:00Z","currency":"XXX","items":[{"sku":"s","qty":1,"price":"1"}]}`,
		"too many cents": `{"orderId":"1","email":"a@b.c","placedAt":"2026-11-25T10:00:00Z","currency":"JPY","items":[{"sku":"s","qty":1,"price":"1.50"}]}`,
		"zero qty":       `{"orderId":"1","email":"a@b.c","placedAt":"2026-11-25T10:00:00Z","currency":"USD","items":[{"sku":"s","qty":0,"price":"1"}]}`,
	}
	for name, in := range bad {
		t.Run(name, func(t *testing.T) {
			pub := &memPub{}
			out, err := newPipeline(okDir(), pub).Handle(context.Background(), WrapRaw("acme", "application/json", []byte(in), time.Now()))
			if out != Ack || err != nil {
				t.Fatalf("want Ack/nil, got %v/%v", out, err)
			}
			if len(pub.sent[TopicInvalid]) != 1 || len(pub.sent[TopicCanonical]) != 0 {
				t.Fatalf("routing wrong: %v", pub.sent)
			}
			if strings.Contains(string(pub.sent[TopicInvalid][0].Data), "a@b.c") {
				t.Error("invalid record stored the payload in clear")
			}
		})
	}
}

func TestEnricherCoalescesAndCaches(t *testing.T) {
	dir := &fakeDir{fn: func(string) (Customer, error) {
		time.Sleep(20 * time.Millisecond)
		return Customer{ID: "c-9", Tier: "silver"}, nil
	}}
	e := &Enricher{Dir: dir, TTL: time.Minute, NegTTL: time.Minute, Timeout: time.Second}
	var wg sync.WaitGroup
	for i := 0; i < 20; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			_, _ = e.Enrich(context.Background(), OrderPlaced{Customer: Customer{EmailHash: "h"}})
		}()
	}
	wg.Wait()
	_, _ = e.Enrich(context.Background(), OrderPlaced{Customer: Customer{EmailHash: "h"}})
	if n := dir.calls.Load(); n != 1 {
		t.Fatalf("directory called %d times, want 1", n)
	}
}

func TestEnricherStaleOnErrorAndTransient(t *testing.T) {
	now := time.Now()
	fail := false
	dir := &fakeDir{fn: func(string) (Customer, error) {
		if fail {
			return Customer{}, errors.New("directory down")
		}
		return Customer{ID: "c-1", Tier: "gold"}, nil
	}}
	e := &Enricher{Dir: dir, TTL: time.Minute, StaleOK: time.Hour, Timeout: time.Second, Now: func() time.Time { return now }}
	if _, err := e.Enrich(context.Background(), OrderPlaced{Customer: Customer{EmailHash: "h"}}); err != nil {
		t.Fatal(err)
	}
	now = now.Add(10 * time.Minute) // expired but within StaleOK
	fail = true
	o, err := e.Enrich(context.Background(), OrderPlaced{Customer: Customer{EmailHash: "h"}})
	if err != nil || o.Enrichment != "degraded" || o.Customer.Tier != "gold" {
		t.Fatalf("want degraded gold, got %+v %v", o, err)
	}
	_, err = e.Enrich(context.Background(), OrderPlaced{Customer: Customer{EmailHash: "never-seen"}})
	if !errors.Is(err, ErrTransient) {
		t.Fatalf("want ErrTransient, got %v", err)
	}
}

// Property: formatting n minor units as a decimal string and parsing it back is the identity.
func TestParseMinorRoundTrip(t *testing.T) {
	f := func(n uint32, d uint8) bool {
		digits := int(d % 4)
		pow := int64(1)
		for i := 0; i < digits; i++ {
			pow *= 10
		}
		s := fmt.Sprint(int64(n) / pow)
		if digits > 0 {
			s += fmt.Sprintf(".%0*d", digits, int64(n)%pow)
		}
		got, err := ParseMinor(s, digits)
		return err == nil && got == int64(n)
	}
	if err := quick.Check(f, nil); err != nil {
		t.Error(err)
	}
}

// Property: the Messaging Mapper round-trips every valid order.
func TestMapperRoundTrip(t *testing.T) {
	f := func(qty1, qty2 uint8, p1, p2 uint16) bool {
		cur := "EUR"
		mk := func(sku string, q uint8, p uint16) domain.Line {
			m, _ := domain.NewMoney(int64(p), cur)
			l, _ := domain.NewLine(sku, int(q%9)+1, m)
			return l
		}
		o, err := domain.NewOrder("o-1", "c-1", time.Unix(1_700_000_000, 0).UTC(), []domain.Line{mk("a", qty1, p1), mk("b", qty2, p2)})
		if err != nil {
			return false
		}
		m := OrderMapper{}
		back, err := m.FromMessage(m.ToMessage(o))
		return err == nil && back.Total() == o.Total() && back.ID() == o.ID() && len(back.Lines()) == 2
	}
	if err := quick.Check(f, nil); err != nil {
		t.Error(err)
	}
}

// Property: unwrap(wrap(x)) == x for the sign+seal stack; any flipped bit is rejected.
func TestEnvelopeStack(t *testing.T) {
	sealer, err := NewSealer(bytes.Repeat([]byte{7}, 32))
	if err != nil {
		t.Fatal(err)
	}
	st := Stack{Signer{Key: []byte("k")}, sealer}
	f := func(body []byte) bool {
		e := WrapRaw("acme", "application/json", body, time.Unix(1_700_000_000, 0))
		b, err := Encode(e, st)
		if err != nil {
			return false
		}
		got, err := Decode(b, st)
		return err == nil && got.ID == e.ID && bytes.Equal(got.Data, e.Data)
	}
	if err := quick.Check(f, nil); err != nil {
		t.Error(err)
	}
	b, _ := Encode(WrapRaw("acme", "text/plain", []byte("x"), time.Now()), st)
	b[len(b)-1] ^= 1
	if _, err := Decode(b, st); err == nil {
		t.Error("tampered message was accepted")
	}
}

func TestStripFields(t *testing.T) {
	var doc map[string]any
	_ = json.Unmarshal([]byte(`{"email":"a@b.c","items":[{"sku":"s","card":"4111"}],"payment":{"card":"4111","kind":"visa"}}`), &doc)
	StripFields(doc, "email", "items.card", "payment.card")
	b, _ := json.Marshal(doc)
	if strings.Contains(string(b), "4111") || strings.Contains(string(b), "a@b.c") {
		t.Errorf("not stripped: %s", b)
	}
}

Observability. Count by stage and outcome: transform_total{stage, outcome=ok|invalid|transient}, a latency histogram per stage (the enricher is almost always the slow one), the enrichment cache hit ratio, and the count of enrichment=degraded events. Alert on a rising invalid rate for one partner (they changed their format) rather than on the absolute count. Carry the raw envelope id as the correlation id on every output, so one partner webhook can be followed through all stages. Trace-context propagation and per-broker metrics are in messaging observability. Transformation errors go to the Invalid Message Channel and to a log line with stage and reason, never with the payload.

Performance. Allocation and payload size matter. The table is an expected, not run experiment outline, not a measured result from this authoring pass. Run the supplied benchmark on your host; no time or heap values are promised.

ApproachTime per batchBytes allocated per batchAllocationsLive heap while processing 100,000 orders
Decode the whole array, then translate eachMeasure locallyIncludes all decoded objectsMeasure locallyGrows with the decoded batch
Stream with json.Decoder (Token, More, Decode)May be slower or fasterTotal work need not shrinkMay increaseBounded by current records if reader and output remain bounded

Streaming targets peak retained memory, not guaranteed lower CPU time. Loading the complete input into memory or collecting every output defeats that bound. For small individual messages, avoid repeated marshalling, use typed structs rather than map[string]any, and add sync.Pool or reusable buffers only after profiling. Large payloads can use a claim check; base64 in an in-body envelope adds roughly one third.

go
package after

import (
	"encoding/json"
	"encoding/xml"
	"io"
)

// StreamJSONOrders turns a huge partner JSON array into one Draft at a time.
// Memory stays at one order, not the whole file; fn returning an error stops
// the stream. Use this for batch files and bulk webhooks, not for the small
// one-order messages that make up most traffic.
func StreamJSONOrders(r io.Reader, fn func(Draft) error) error {
	dec := json.NewDecoder(r)
	token, err := dec.Token()
	if err != nil || token != json.Delim('[') {
		return invalid("normalize", "json batch must be an array")
	}
	for dec.More() {
		var raw json.RawMessage
		if err := dec.Decode(&raw); err != nil {
			return invalid("normalize", "json batch element: %v", err)
		}
		d, err := parseJSON(Inbound{Body: raw})
		if err != nil {
			return err
		}
		if err := fn(d); err != nil {
			return err
		}
	}
	token, err = dec.Token()
	if err != nil || token != json.Delim(']') {
		return invalid("normalize", "json batch missing closing bracket")
	}
	if _, err := dec.Token(); err != io.EOF {
		return invalid("normalize", "json batch has trailing data")
	}
	return nil
}

// StreamXMLOrders does the same for a large XML document, one <Order> element
// at a time, using the token API instead of unmarshalling the whole tree.
func StreamXMLOrders(r io.Reader, fn func(Draft) error) error {
	dec := xml.NewDecoder(r)
	for {
		tok, err := dec.Token()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return invalid("normalize", "xml batch: %v", err)
		}
		se, ok := tok.(xml.StartElement)
		if !ok || se.Name.Local != "Order" {
			continue
		}
		var w xmlOrder
		if err := dec.DecodeElement(&w, &se); err != nil {
			return invalid("normalize", "xml order: %v", err)
		}
		d, err := xmlDraft(w)
		if err != nil {
			return err
		}
		if err := fn(d); err != nil {
			return err
		}
	}
}

PHP streams with XMLReader (a pull parser) and generators, wrapped in LazyCollection so map and chunk stay lazy:

php
<?php

namespace App\Messaging\Transform;

use Illuminate\Support\LazyCollection;
use XMLReader;

/**
 * Streaming a large partner batch: memory holds one order at a time.
 * XMLReader is a pull parser; each <Order> is expanded on its own and the
 * rest of the document is never in memory. LazyCollection wraps the generator
 * so the normal collection pipeline (map, chunk, each) stays lazy.
 */
final class StreamOrders
{
    /** @return LazyCollection<int, string> one <Order> element as an XML string */
    public static function xmlOrders(string $path): LazyCollection
    {
        return LazyCollection::make(function () use ($path) {
            $r = new XMLReader;
            if (! $r->open($path, null, LIBXML_NONET)) { throw new \RuntimeException('cannot open XML input'); }
            try {
                 $available = $r->read();
                while ($available) {
                    if ($r->nodeType === XMLReader::ELEMENT && $r->name === 'Order') {
                        yield $r->readOuterXml();
                        $available = $r->next(); // Already positioned at the next sibling.
                        continue;
                    }
                    $available = $r->read();
                }
            } finally {
                $r->close();
            }
        });
    }

    /** NDJSON (one JSON object per line) is the easiest format to stream. */
    public static function ndjsonOrders(string $path): LazyCollection
    {
        return LazyCollection::make(function () use ($path) {
            $h = fopen($path, 'rb');
            if ($h === false) { throw new \RuntimeException('cannot open NDJSON input'); }
            try {
                while (($line = fgets($h)) !== false) {
                    if (trim($line) !== '') {
                        yield $line;
                    }
                }
            } finally {
                fclose($h);
            }
        });
    }
}

// Usage inside a console command: each order is normalized and translated
// one at a time; chunk(500) bounds the size of the publish batch.
//
//   StreamOrders::xmlOrders($path)
//       ->map(fn (string $xml) => $normalizer->normalize(Envelope::wrapRaw('berlin', 'application/xml', $xml)))
//       ->map(fn (Draft $d) => $translator->translate($d))
//       ->chunk(500)
//       ->each(fn ($orders) => $publisher->publishBatch($orders));

The worked pipeline: partner webhook to canonical OrderPlaced ​

The scenario: three partners post orders to one platform. A (acme) sends JSON with ISO 8601 times and decimal strings. B (berlin-shop) sends XML with local Berlin time and decimal commas. C (tokyo-mart) sends one semicolon-separated line with epoch seconds and prices already in minor units. Downstream services want one OrderPlaced, analytics wants a version without customer data, and nobody wants to see an e-mail address on a topic.

The inputs (the Go test reads these files; the Laravel test embeds the same data):

json
{"orderId":"A-1001","email":"Alice@Example.com","placedAt":"2026-11-25T10:00:00+03:30","currency":"USD","items":[{"sku":"SKU-1","qty":2,"price":"19.99"},{"sku":"SKU-2","qty":1,"price":"5"}]}
xml
<Order id="B-77"><Buyer><Email>alice@example.com</Email></Buyer><Date>25/11/2026 10:00</Date><Cur>EUR</Cur><Line sku="SKU-1" qty="1" unit="5,50"/><Line sku="SKU-3" qty="3" unit="0,99"/></Order>
C-9;alice@example.com;1795600800;JPY;SKU-1:2:1999|SKU-2:1:500
Stage                 Input                                   Output / decision
1  webhook            raw body + Content-Type                 Envelope Wrapper: id = hash(partner+body), source=partner/acme, 202 Accepted
2  raw topic          Envelope                                partner.orders.raw (kept for replay)
3  Normalizer         Envelope.data + content type            Draft (one structure, partner values intact); unknown format => invalid
4  Message Translator Draft                                   OrderPlaced: acme:A-1001, UTC, integer cents, HMAC of lowercased e-mail
5  Content Enricher   OrderPlaced                             customer id, tier, country; 404 => unknown-customer; timeout => retry
6  publish canonical  OrderPlaced                             topic orders.placed, key = order id, deterministic event id
7  Content Filter     OrderPlaced                             AnalyticsOrder: SKUs, day, total, country, tier; no customer id
8  publish analytics  AnalyticsOrder                          topic orders.analytics
   any invalid stage  fingerprint record                      partner.orders.invalid, then acknowledge

Go: typed transformation stages ​

The Go pipeline wires the stages, classifies errors and decides the Outcome (acknowledge or retry) the consumer loop acts on:

go
package after

import (
	"context"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"errors"
)

// Publisher sends one envelope to one destination; the broker files implement it.
type Publisher interface {
	Publish(ctx context.Context, dest string, e Envelope) error
}

// Outcome tells the consumer loop what to do with the incoming message.
type Outcome int

const (
	Ack   Outcome = iota // published, or sent to the invalid channel: done
	Retry                // transient: nack/requeue or do not commit
)

// Pipeline is: Normalizer -> Translator -> Enricher, then publish twice
// (canonical for services, filtered for analytics).
type Pipeline struct {
	Normalizer Normalizer
	Translate  Func[Draft, OrderPlaced]
	Enricher   *Enricher
	Out        Publisher
}

func (p *Pipeline) stages() Func[Inbound, OrderPlaced] {
	norm := func(_ context.Context, in Inbound) (Draft, error) { return p.Normalizer.Normalize(in) }
	enrich := func(ctx context.Context, o OrderPlaced) (OrderPlaced, error) { return p.Enricher.Enrich(ctx, o) }
	return Then(Then(norm, p.Translate), enrich)
}

// Handle processes one raw envelope. Errors are classified: invalid messages
// go to TopicInvalid and are acknowledged (retrying cannot help); transient
// ones are retried; a publish failure is transient too.
func (p *Pipeline) Handle(ctx context.Context, raw Envelope) (Outcome, error) {
	order, err := p.stages()(ctx, Inbound{
		Partner:     partnerOf(raw.Source),
		ContentType: raw.ContentType,
		Body:        raw.Data,
	})
	switch {
	case errors.Is(err, ErrInvalid):
		return Ack, p.reject(ctx, raw, err)
	case err != nil:
		return Retry, err
	}

	// Deterministic ids: a redelivered raw message yields the same event ids,
	// so consumers can deduplicate (see idempotent-consumer-inbox).
	body, _ := json.Marshal(order)
	canonical := p.event(raw, TypeOrderPlaced, order.OrderID, body)
	analytics, _ := json.Marshal(ForAnalytics(order))
	if err := p.Out.Publish(ctx, TopicCanonical, canonical); err != nil {
		return Retry, err
	}
	if err := p.Out.Publish(ctx, TopicAnalytics, p.event(raw, "order.placed.analytics", order.OrderID, analytics)); err != nil {
		return Retry, err // the canonical copy is re-sent: same id, deduplicated downstream
	}
	return Ack, nil
}

func (p *Pipeline) event(raw Envelope, typ, key string, body []byte) Envelope {
	sum := sha256.Sum256([]byte(raw.ID + "|" + typ))
	return Envelope{
		ID: hex.EncodeToString(sum[:16]), Type: typ, Source: "order-intake", Key: key,
		Version: SchemaVersionOrder, OccurredAt: raw.OccurredAt,
		CorrelationID: raw.ID, CausationID: raw.ID,
		ContentType: "application/json", Data: body,
	}
}

// Reject is the Invalid Message Channel record: what failed, where, and a
// fingerprint of the input. The payload itself is NOT stored in clear.
type Reject struct {
	Stage      string `json:"stage"`
	Reason     string `json:"reason"`
	RawID      string `json:"raw_id"`
	Source     string `json:"source"`
	PayloadSHA string `json:"payload_sha256"`
}

func (p *Pipeline) reject(ctx context.Context, raw Envelope, cause error) error {
	var se *StageError
	errors.As(cause, &se)
	sum := sha256.Sum256(raw.Data)
	b, _ := json.Marshal(Reject{
		Stage: se.Stage, Reason: "invalid_" + se.Stage, RawID: raw.ID, Source: raw.Source,
		PayloadSHA: hex.EncodeToString(sum[:]),
	})
	return p.Out.Publish(ctx, TopicInvalid, Envelope{
		ID: raw.ID + ".invalid", Type: "partner.order.invalid", Source: "order-intake",
		Version: 1, OccurredAt: raw.OccurredAt, CorrelationID: raw.ID,
		ContentType: "application/json", Data: b,
	})
}

func partnerOf(source string) string {
	const prefix = "partner/"
	if len(source) > len(prefix) {
		return source[len(prefix):]
	}
	return source
}

Laravel 13: controller, job and pipes ​

The Laravel pipeline is a controller (Channel Adapter plus Envelope Wrapper), a queued job (ShouldBeEncrypted, because it carries PII), and Pipeline pipes:

php
<?php

namespace App\Http\Controllers;

use App\Messaging\Transform\Envelope;
use App\Messaging\Transform\Jobs\TransformPartnerOrder;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

/**
 * Channel Adapter + Envelope Wrapper at the edge: take whatever the partner
 * sent, wrap it untouched, queue it, answer fast. Verifying the partner's
 * signature header belongs here too (see messaging-security).
 */
final class PartnerWebhookController
{
    public function __invoke(Request $request, string $partner): Response
    {
        $raw = Envelope::wrapRaw($partner, (string) $request->header('Content-Type', ''), $request->getContent());

        TransformPartnerOrder::dispatch($raw)->onQueue('intake');

        return response('', 202);
    }
}
php
<?php

use App\Http\Controllers\PartnerWebhookController;
use Illuminate\Support\Facades\Route;

// routes/api.php: one URL per partner, any body format.
Route::post('/webhooks/{partner}/orders', PartnerWebhookController::class)
    ->where('partner', '[a-z0-9-]+');
php
<?php

namespace App\Messaging\Transform\Jobs;

use App\Messaging\Transform\Envelope;
use App\Messaging\Transform\InvalidMessage;
use App\Messaging\Transform\OrderIntake;
use App\Messaging\Transform\TransientFailure;
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;

/**
 * The consumer-edge transformation step. ShouldBeEncrypted keeps the raw
 * partner payload (e-mail, maybe a card) unreadable inside the queue backend.
 */
final class TransformPartnerOrder implements ShouldBeEncrypted, ShouldQueue
{
    use Queueable;

    public int $tries = 6;

    public function __construct(public Envelope $raw) {}

    /** Seconds before attempts 2, 3, 4...: transient failures only. */
    public function backoff(): array
    {
        return [5, 30, 120, 600];
    }

    public function handle(OrderIntake $intake): void
    {
        try {
            $intake->handle($this->raw);
        } catch (InvalidMessage $e) {
            // Invalid message channel: record why, keep a fingerprint, do not retry.
            DB::table('invalid_messages')->insert([
                'raw_id' => $this->raw->id,
                'source' => $this->raw->source,
                'stage' => $e->stage,
                'reason' => 'invalid_'.$e->stage, // Never persist parser text containing input data.
                'payload_sha256' => hash('sha256', $this->raw->data),
                'created_at' => now(),
            ]);
        } catch (TransientFailure $e) {
            $this->release($this->backoff()[min($this->attempts() - 1, 3)]);
        }
    }
}
php
<?php

namespace App\Messaging\Transform;

use App\Messaging\Transform\Pipes\Enrich;
use App\Messaging\Transform\Pipes\Normalize;
use App\Messaging\Transform\Pipes\Translate;
use Illuminate\Pipeline\Pipeline;

/**
 * Pipes and Filters with Laravel's Pipeline: send a state object through
 * classes that each expose handle($state, $next). Pipes are resolved from the
 * container, so their dependencies are injected.
 */
final class OrderIntake
{
    public function __construct(
        private readonly Pipeline $pipeline,
        private readonly ContentFilter $filter,
        private readonly Publisher $publisher,
    ) {}

    /** @throws InvalidMessage|TransientFailure */
    public function handle(Envelope $raw): void
    {
        $state = $this->pipeline
            ->send(new IntakeState($raw))
            ->through([Normalize::class, Translate::class, Enrich::class])
            ->thenReturn();

        $order = $state->order;
        // Deterministic ids: a redelivered raw message produces the same event ids.
        $this->publisher->publish('orders.placed', $this->event($raw, 'order.placed', $order->orderId, $order->toArray()));
        $this->publisher->publish('orders.analytics', $this->event($raw, 'order.placed.analytics', $order->orderId, $this->filter->forAnalytics($order)));
    }

    private function event(Envelope $raw, string $type, string $key, array $body): Envelope
    {
        return new Envelope(
            id: substr(hash('sha256', $raw->id.'|'.$type), 0, 32),
            type: $type, source: 'order-intake', version: 2, occurredAt: $raw->occurredAt,
            contentType: 'application/json', data: json_encode($body, JSON_THROW_ON_ERROR),
            correlationId: $raw->id, causationId: $raw->id, key: $key,
        );
    }
}
php
<?php

namespace App\Messaging\Transform;

/** The passable that travels through the pipes; each stage fills one field. */
final class IntakeState
{
    public ?Draft $draft = null;

    public ?OrderPlaced $order = null;

    public function __construct(public readonly Envelope $raw) {}
}
php
<?php

namespace App\Messaging\Transform\Pipes;

use App\Messaging\Transform\IntakeState;
use App\Messaging\Transform\Normalizer;
use Closure;

final class Normalize
{
    public function __construct(private readonly Normalizer $normalizer) {}

    public function handle(IntakeState $s, Closure $next): mixed
    {
        $s->draft = $this->normalizer->normalize($s->raw);

        return $next($s);
    }
}
php
<?php

namespace App\Messaging\Transform\Pipes;

use App\Messaging\Transform\IntakeState;
use App\Messaging\Transform\Translator;
use Closure;

final class Translate
{
    public function __construct(private readonly Translator $translator) {}

    public function handle(IntakeState $s, Closure $next): mixed
    {
        $s->order = $this->translator->translate($s->draft);

        return $next($s);
    }
}
php
<?php

namespace App\Messaging\Transform\Pipes;

use App\Messaging\Transform\CustomerEnricher;
use App\Messaging\Transform\IntakeState;
use Closure;

final class Enrich
{
    public function __construct(private readonly CustomerEnricher $enricher) {}

    public function handle(IntakeState $s, Closure $next): mixed
    {
        $s->order = $this->enricher->enrich($s->order);

        return $next($s);
    }
}

The supporting value objects, exceptions and publisher interface:

php
<?php

namespace App\Messaging\Transform;

use DateTimeImmutable;

/** Normalizer output: one shape for every partner format, partner values intact. */
final readonly class Draft
{
    /** @param list<array{sku:string,qty:int,price:string,minor:bool}> $lines */
    public function __construct(
        public string $partner,
        public string $partnerOrderId,
        public string $email,
        public string $currency,
        public DateTimeImmutable $placedAt,
        public array $lines,
    ) {}
}
php
<?php

namespace App\Messaging\Transform;

use DateTimeImmutable;
use DateTimeZone;

/** The Canonical Data Model for "order placed". */
final readonly class OrderPlaced
{
    /**
     * @param list<array{sku:string,qty:int,unit_price:array{amount_minor:int,currency:string}}> $lines
     * @param array{email_hash:string,id?:string,tier?:string,country?:string} $customer
     */
    public function __construct(
        public string $orderId,
        public string $partner,
        public DateTimeImmutable $placedAt,
        public array $customer,
        public array $lines,
        public int $totalMinor,
        public string $currency,
        public string $enrichment = 'ok',
    ) {}

    public function withCustomer(array $extra, string $enrichment): self
    {
        return new self(
            $this->orderId, $this->partner, $this->placedAt,
            [...$this->customer, ...$extra], $this->lines,
            $this->totalMinor, $this->currency, $enrichment,
        );
    }

    public function toArray(): array
    {
        return [
            'order_id' => $this->orderId,
            'partner' => $this->partner,
            'placed_at' => $this->placedAt->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d\TH:i:s\Z'),
            'customer' => $this->customer,
            'lines' => $this->lines,
            'total' => ['amount_minor' => $this->totalMinor, 'currency' => $this->currency],
            'enrichment' => $this->enrichment,
        ];
    }
}
php
<?php

namespace App\Messaging\Transform;

use RuntimeException;

/** Can never succeed: send to the invalid message channel, do not retry. */
final class InvalidMessage extends RuntimeException
{
    public function __construct(public readonly string $stage, string $reason)
    {
        parent::__construct("{$stage}: {$reason}");
    }
}
php
<?php

namespace App\Messaging\Transform;

use RuntimeException;
use Throwable;

/** May succeed later (lookup timed out): release the job, retry with backoff. */
final class TransientFailure extends RuntimeException
{
    public function __construct(public readonly string $stage, Throwable $previous)
    {
        parent::__construct("{$stage}: {$previous->getMessage()}", 0, $previous);
    }
}
php
<?php

namespace App\Messaging\Transform;

interface Publisher
{
    public function publish(string $destination, Envelope $envelope): void;
}

The invalid-message table, and a triage query a support engineer actually uses:

sql
CREATE TABLE invalid_messages (
    id              BIGSERIAL PRIMARY KEY,
    raw_id          VARCHAR(64)  NOT NULL,   -- envelope id of the raw message
    source          VARCHAR(255) NOT NULL,   -- partner/acme
    stage           VARCHAR(32)  NOT NULL,   -- normalize | translate | map
    reason          TEXT         NOT NULL,
    payload_sha256  CHAR(64)     NOT NULL,   -- a fingerprint, never the payload
    created_at      TIMESTAMPTZ  NOT NULL DEFAULT now()
);
CREATE INDEX invalid_messages_source_created ON invalid_messages (source, created_at DESC);

-- Which partner broke what in the last day? A spike in one reason means they changed their format.
SELECT source, stage, reason, count(*) AS n, min(created_at) AS first_seen
FROM invalid_messages
WHERE created_at > now() - interval '1 day'
GROUP BY source, stage, reason
ORDER BY n DESC
LIMIT 20;

The same table as a Laravel migration:

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('invalid_messages', function (Blueprint $table) {
            $table->id();
            $table->string('raw_id', 64)->index();     // the envelope id of the raw message
            $table->string('source');
            $table->string('stage', 32);               // normalize | translate | map
            $table->text('reason');
            $table->char('payload_sha256', 64);        // a fingerprint, never the payload
            $table->timestamp('created_at');
        });
    }
};

And the feature test (not run here): three formats to one canonical event, an invalid currency, and a customer service outage with a cold cache.

php
<?php

namespace Tests\Feature;

use App\Messaging\Transform\Envelope;
use App\Messaging\Transform\InvalidMessage;
use App\Messaging\Transform\OrderIntake;
use App\Messaging\Transform\Publisher;
use App\Messaging\Transform\TransientFailure;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

final class OrderIntakeTest extends TestCase
{
    private object $sent;

    protected function setUp(): void
    {
        parent::setUp();
        config(['services.customers.url' => 'https://customers.test']);
        $this->sent = new class implements Publisher {
            public array $byTopic = [];

            public function publish(string $destination, Envelope $envelope): void
            {
                $this->byTopic[$destination][] = $envelope;
            }
        };
        $this->app->instance(Publisher::class, $this->sent);
    }

    public function test_three_partner_formats_become_one_canonical_event(): void
    {
        Http::fake(['customers.test/*' => Http::response(['id' => 'c-1', 'tier' => 'gold', 'country' => 'DE'])]);

        $inputs = [
            ['acme', 'application/json', '{"orderId":"A-1","email":"Alice@Example.com","placedAt":"2026-11-25T10:00:00+03:30","currency":"USD","items":[{"sku":"S1","qty":2,"price":"19.99"}]}'],
            ['berlin', 'application/xml', '<Order id="B-1"><Buyer><Email>alice@example.com</Email></Buyer><Date>25/11/2026 10:00</Date><Cur>EUR</Cur><Line sku="S1" qty="2" unit="19,99"/></Order>'],
            ['tokyo', '', 'C-1;alice@example.com;1795600800;JPY;S1:2:1999'],
        ];
        foreach ($inputs as [$partner, $type, $body]) {
            app(OrderIntake::class)->handle(Envelope::wrapRaw($partner, $type, $body));
        }

        $events = array_map(fn ($e) => json_decode($e->data, true), $this->sent->byTopic['orders.placed']);
        $this->assertSame([3998, 3998, 3998], array_map(fn ($e) => $e['total']['amount_minor'], $events));
        $this->assertCount(1, array_unique(array_map(fn ($e) => $e['customer']['email_hash'], $events)));
        $this->assertStringNotContainsString('alice@example.com', json_encode($events));
    }

    public function test_bad_currency_is_invalid_not_retryable(): void
    {
        $this->expectException(InvalidMessage::class);
        app(OrderIntake::class)->handle(Envelope::wrapRaw('acme', 'application/json',
            '{"orderId":"1","email":"a@b.c","placedAt":"2026-11-25T10:00:00Z","currency":"XXX","items":[{"sku":"s","qty":1,"price":"1"}]}'));
    }

    public function test_directory_down_with_cold_cache_is_transient(): void
    {
        Cache::flush();
        Http::fake(['customers.test/*' => Http::response('boom', 503)]);
        $this->expectException(TransientFailure::class);
        app(OrderIntake::class)->handle(Envelope::wrapRaw('acme', 'application/json',
            '{"orderId":"1","email":"a@b.c","placedAt":"2026-11-25T10:00:00Z","currency":"USD","items":[{"sku":"s","qty":1,"price":"1"}]}'));
    }
}

Solving the classic problems ​

ProblemSolutionHowAdvantageCost or limit
Many partner formats, one downstream pathNormalizerDetect format, one parser per format, one DraftA new partner is one parserDetection must be reliable; a wrong guess poisons data
Units, time zones, ids differMessage TranslatorInteger minor units, UTC, namespaced ids, reject on doubtOne meaning downstreamTables of currencies and codes to maintain
Receiver needs data the sender lacksContent EnricherCache, deadline, singleflight, sentinel for "not found"Simple consumersA dependency on another service; stale data
Receiver must not see some dataContent FilterAllowlist type for audiences, denylist for foreign payloadsLess PII, smaller messagesA denylist fails open
Legacy system cannot carry headers, signatures or encryptionEnvelope WrapperWrap at the edge, unwrap at the destination, layers in orderLegacy code unchangedLayer order and key management are security decisions
Domain and message drifting togetherMessaging MapperOne class that knows both sides, constructors for invariantsSafe refactoring on both sidesMapping code to write and test
n systems, n-squared translatorsCanonical Data Model per factTranslate to and from one model, versioned2n translatorsNeeds an owner and a change process
Old and new payload versions in flightUpcaster chainLift one version at a timeConsumers know only the latestEvery old version must stay liftable
One partner file with a million ordersStreaming parsejson.Decoder tokens, XMLReader, generatorsConstant memorySlightly more CPU and code
A partner changes format silentlyGolden files, invalid-rate alert, raw replayPin recorded inputs; alert on rate per partner; reprocess the raw topic after the fixFast detection, no data lossRaw retention must cover the detection time
Enrichment service downStale-on-error, then retryUse an old answer for a bounded time, mark degraded; otherwise retryPipeline keeps movingConsumers must tolerate degraded

Problem 1: three partner formats ​

The Normalizer and Translator above. Add a partner by registering a parser and adding a golden file; nothing else changes. If the format cannot be detected, return an invalid error and let the Invalid Message Channel hold the fingerprint.

Problem 2: PII must not leave ​

Three layers, in order of strength: (1) never put it in the canonical message (the translator hashes the e-mail with HMAC and the model has no e-mail field); (2) an allowlist type per audience (AnalyticsOrder); (3) a denylist for payloads you log or park (StripFields, ContentFilter::strip). A keyed hash is pseudonymisation, not anonymisation: whoever holds the key and a candidate list can re-identify. Rotate the key deliberately and see messaging security for retention, erasure and encryption of what remains.

Problem 3: the partner changed their format ​

1  09:00  partner deploys: <Date> becomes ISO 8601
2  09:01  Normalizer XML date parser rejects the changed date contract -> invalid
3  09:01  invalid_messages gets rows, source=partner/berlin-shop, stage=normalize
4  09:05  alert: invalid rate for berlin-shop above 5 percent for 5 minutes
5  09:30  you add the second date layout, a new golden file, deploy
6  09:40  replay: reprocess partner.orders.raw from 09:00 (Kafka: new group at timestamp; Redis: XRANGE; RabbitMQ: only if raw went to a stream or was stored)
7  09:41  deterministic ids make the replay idempotent for consumers that already received some events

Problem 4: choosing what to cache in the enricher ​

DataTTLNegative cacheWhy
Customer tier, countryminutes (5)seconds to minutesChanges rarely; a stale tier is cheap
Product name, categoryhoursminutesChanges rarely
Fraud scorenever cache across messagesnoneMust be fresh
Exchange ratethe rate's validity windownoneWrong rate is money
"Not found" for a brand-new customershort (seconds)n/aThe customer may be created a moment later; see distributed data

Broker differences ​

Brokers differ in what a transformation can do inside the broker, and in how a transformation worker reads, writes and acknowledges. The pipeline code is identical; only the Publisher and the consume loop change.

RabbitMQ ​

RabbitMQ routes; it does not rewrite. Its message interceptors are Erlang modules (built-ins stamp a timestamp or the routing node), and Shovel and Federation move messages between brokers without changing bodies, so a transformation is a consumer: read partner.orders.raw, publish to the orders topic exchange, acknowledge. Use publisher confirms plus mandatory-return handling: a positive confirm alone does not prove any queue accepted the route. The example requires a dedicated publishing channel and one in-flight publish. Acknowledge the input only after confirmed, routable output; and a bounded prefetch (Qos) because every prefetched message is in flight through a possibly slow enricher. The Go loop acknowledges only after Handle and surfaces Ack/Nack errors; it names its own limitation (a transient failure requeues immediately, so real code routes to a delayed retry queue, see retry, backoff and delayed delivery). Invalid messages are acknowledged after the fingerprint is published, which keeps them out of the DLX path. For replaying raw input, a classic or quorum queue is consumed away; a RabbitMQ stream queue or an external store keeps it. RabbitMQ is AMQP 0-9-1's world of exchanges and bindings: RabbitMQ in depth.

go
package after

import (
	"context"
	"fmt"
	"sync"

	amqp "github.com/rabbitmq/amqp091-go"
)

// RabbitPublisher publishes with publisher confirms: Publish returns only
// after the broker has taken responsibility for the message.
type RabbitPublisher struct {
	Ch       *amqp.Channel // Confirm(false) must have been called on it
	Exchange string        // topic exchange; dest is the routing key
	mu       sync.Mutex
	returns  <-chan amqp.Return
}

// NewRabbitPublisher needs a dedicated channel with no other publishers.
func NewRabbitPublisher(ch *amqp.Channel, exchange string) (*RabbitPublisher, error) {
	if err := ch.Confirm(false); err != nil {
		return nil, err
	}
	return &RabbitPublisher{Ch: ch, Exchange: exchange, returns: ch.NotifyReturn(make(chan amqp.Return, 1))}, nil
}

func (r *RabbitPublisher) Publish(ctx context.Context, dest string, e Envelope) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	if r.returns == nil {
		return fmt.Errorf("use NewRabbitPublisher with a dedicated channel")
	}
	headers := amqp.Table{"version": int32(e.Version), "source": e.Source}
	if e.CausationID != "" {
		headers["causation-id"] = e.CausationID
	}
	dc, err := r.Ch.PublishWithDeferredConfirmWithContext(ctx, r.Exchange, dest, true, false, amqp.Publishing{
		MessageId: e.ID, Type: e.Type, Timestamp: e.OccurredAt,
		CorrelationId: e.CorrelationID, ContentType: e.ContentType,
		DeliveryMode: amqp.Persistent, Headers: headers, Body: e.Data,
	})
	if err != nil {
		return err
	}
	if dc == nil {
		return fmt.Errorf("publisher confirms required")
	}
	ok, err := dc.WaitContext(ctx)
	if err != nil {
		_ = r.Ch.Close() // Unknown confirm outcome: do not reuse this publisher.
		return err
	}
	select {
	case ret, open := <-r.returns:
		if !open {
			return fmt.Errorf("publisher return channel closed")
		}
		return fmt.Errorf("unroutable output: %d %s", ret.ReplyCode, ret.ReplyText)
	default:
	}
	if !ok {
		return fmt.Errorf("broker nacked publish to %s", dest)
	}
	return nil
}

func rabbitEnvelope(d amqp.Delivery) Envelope {
	str := func(k string) string { s, _ := d.Headers[k].(string); return s }
	v, _ := d.Headers["version"].(int32)
	return Envelope{
		ID: d.MessageId, Type: d.Type, Source: str("source"), Version: int(v),
		OccurredAt: d.Timestamp, CorrelationID: d.CorrelationId,
		CausationID: str("causation-id"), ContentType: d.ContentType, Data: d.Body,
	}
}

// RunRabbit is the consumer-edge transformation worker: RabbitMQ cannot
// transform, so a consumer reads the raw queue and publishes the result.
// Ack only after Handle succeeded. Limitation: Nack with requeue puts the
// message straight back, which is a hot loop while the directory is down; a
// real worker routes it to a delayed retry queue instead
// (see retry-backoff-delayed) and caps attempts (see dead-letter-queue).
func RunRabbit(ctx context.Context, ch *amqp.Channel, queue string, p *Pipeline) error {
	if err := ch.Qos(20, 0, false); err != nil {
		return err
	}
	msgs, err := ch.ConsumeWithContext(ctx, queue, "order-intake", false, false, false, false, nil)
	if err != nil {
		return err
	}
	for d := range msgs {
		out, err := p.Handle(ctx, rabbitEnvelope(d))
		if out == Retry || err != nil {
			if err := d.Nack(false, true); err != nil {
				return err
			}
			continue
		}
		if err := d.Ack(false); err != nil {
			return err
		}
	}
	if err := ctx.Err(); err != nil {
		return err
	}
	return fmt.Errorf("RabbitMQ delivery stream closed; reconnect")
}

In Laravel, with vladimir-yuldashev/laravel-queue-rabbitmq, the transformation is simply the queued job on the rabbitmq connection (TransformPartnerOrder::dispatch($raw)->onConnection('rabbitmq')->onQueue('intake')). The package's README documents queue connections and consumers, not per-message properties, so the publisher below is written against php-amqplib, the client library beneath it:

php
<?php

namespace App\Messaging\Transform\Brokers;

use App\Messaging\Transform\Envelope;
use App\Messaging\Transform\Publisher;
use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;

/**
 * RabbitMQ: no broker-side transformation, so the transformation worker is an
 * ordinary consumer. Written against php-amqplib, the client under
 * vladimir-yuldashev/laravel-queue-rabbitmq, whose README documents no per-message API.
 */
final class RabbitMq implements Publisher
{
    private bool $returned = false;
    private bool $nacked = false;

    /** Dedicated publisher channel: one in-flight publication, no other owner. */
    public function __construct(private readonly AMQPChannel $channel, private readonly string $exchange = 'orders')
    {
        $channel->confirm_select();
        $channel->set_return_listener(function (): void { $this->returned = true; });
        $channel->set_nack_handler(function (): void { $this->nacked = true; });
    }

    public function publish(string $destination, Envelope $e): void
    {
        $this->returned = $this->nacked = false;
        $this->channel->basic_publish(new AMQPMessage($e->data, [
            'content_type' => $e->contentType,
            'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
            'message_id' => $e->id,
            'type' => $e->type,
            'correlation_id' => $e->correlationId,
            'timestamp' => $e->occurredAt->getTimestamp(),
            'application_headers' => new AMQPTable(['source' => $e->source, 'version' => $e->version]),
        ]), $this->exchange, $destination, true);
        $this->channel->wait_for_pending_acks_returns(5.0);
        if ($this->returned || $this->nacked) {
            throw new \RuntimeException('output was unroutable or negatively confirmed');
        }
    }

    /** Consumer: ack only after the transformation published its outputs. */
    public function consume(string $queue, callable $handle): void
    {
        $this->channel->basic_qos(0, 20, false);
        $this->channel->basic_consume($queue, '', false, false, false, false, function (AMQPMessage $m) use ($handle) {
            $h = $m->get('application_headers')->getNativeData();
            try {
                $handle(new Envelope(
                    id: $m->get('message_id'), type: $m->get('type'), source: $h['source'], version: $h['version'],
                    occurredAt: (new \DateTimeImmutable)->setTimestamp($m->get('timestamp')),
                    contentType: $m->get('content_type'), data: $m->getBody(),
                ));
                $m->ack();
            } catch (\Throwable $e) {
                $m->nack(requeue: true);
                throw $e; // Supervisor recreates channels; no hot retry loop here.
            }
        });
        $this->channel->consume();
    }
}

Kafka ​

Kafka has two dedicated application runtimes for transformation; neither runs arbitrary transformation code inside the broker. Kafka Connect SMTs transform records on the way in (source connectors) or out (sink connectors); Kafka Streams runs a topology that reads topics and writes topics. For logic that does calls, caches or complex branching, a consumer-producer service is the usual host. Put routing facts in record headers, the order id in the key so one order stays on one partition, and commit offsets only after the outputs were produced. The Go loop stops a partition at the first record that needs a retry, because CommitRecords commits offsets per partition and committing a later record would skip the failed one (the franz-go docs advise committing records "in order (per partition)"). The client must use DisableAutoCommit and BlockRebalanceOnPoll; successful batches release rebalance with AllowRebalance, and processing must remain within the configured rebalance timeout. The loop owns and closes its client on exit; restart with a NEW client, because reusing the old one retains its advanced local fetch position. Every fetch error is checked. Between-topic exactly-once needs a transactional session and read-committed consumers; see delivery guarantees. The raw topic doubles as the replay source: start a new consumer group at a timestamp. See Kafka in depth.

go
package after

import (
	"context"
	"fmt"

	"github.com/twmb/franz-go/pkg/kgo"
)

// KafkaPublisher writes the envelope as record headers plus the body as value.
// The key (the order id) decides the partition, so one order stays ordered.
type KafkaPublisher struct{ Client *kgo.Client }

func (k KafkaPublisher) Publish(ctx context.Context, dest string, e Envelope) error {
	rec := &kgo.Record{Topic: dest, Key: []byte(e.Key), Value: e.Data, Timestamp: e.OccurredAt}
	for name, v := range e.Headers() {
		rec.Headers = append(rec.Headers, kgo.RecordHeader{Key: name, Value: []byte(v)})
	}
	return k.Client.ProduceSync(ctx, rec).FirstErr()
}

func kafkaEnvelope(r *kgo.Record) Envelope {
	h := make(map[string]string, len(r.Headers))
	for _, x := range r.Headers {
		h[x.Key] = string(x.Value)
	}
	e := FromHeaders(h, r.Value)
	e.Key = string(r.Key)
	return e
}

// RunKafka is consume-transform-produce with manual commits: offsets are
// committed only after the outputs were produced (at-least-once). Build the
// client with kgo.DisableAutoCommit() and kgo.BlockRebalanceOnPoll().
// Bound handler time below the configured rebalance timeout. This function
// owns and closes cl; restart with a NEW client after any failure. CommitRecords commits per partition up
// to the records it is given, so we stop at the FIRST record that needs a
// retry: committing a later record of the same partition would skip it.
// Closing lets a new client resume from committed offsets; reusing the same
// client would retain its advanced local fetch position. For exactly-once between topics use
// kgo.NewGroupTransactSession (see delivery-guarantees).
func RunKafka(ctx context.Context, cl *kgo.Client, p *Pipeline) error {
	defer cl.CloseAllowingRebalance()
	for {
		fetches := cl.PollFetches(ctx)
		if errs := fetches.Errors(); len(errs) > 0 {
			return fmt.Errorf("fetch %s/%d: %w", errs[0].Topic, errs[0].Partition, errs[0].Err)
		}
		var done []*kgo.Record
		var failed error
		fetches.EachPartition(func(part kgo.FetchTopicPartition) {
			for _, r := range part.Records {
				out, err := p.Handle(ctx, kafkaEnvelope(r))
				if out != Ack || err != nil {
					failed = err // stop this partition at the failure
					if failed == nil {
						failed = fmt.Errorf("pipeline requested retry")
					}
					return
				}
				done = append(done, r)
			}
		})
		if len(done) > 0 {
			if err := cl.CommitRecords(ctx, done...); err != nil {
				return err
			}
		}
		if failed != nil {
			return failed
		}
		cl.AllowRebalance()
	}
}

With mateusjunges/laravel-kafka the consumer handler receives a ConsumerMessage (getBody(), getHeaders(), getKey() are listed on the package's Message handlers page), and the producer takes headers, body and key on a Message. Raw codecs preserve JSON/XML/CSV bytes rather than applying JSON encoding twice; stopOnFailure prevents continuing past a failed record. Pin a package version supporting these APIs and verify compatibility in the Laravel 13 host:

php
<?php

namespace App\Messaging\Transform\Brokers;

use App\Messaging\Transform\Envelope;
use App\Messaging\Transform\Publisher;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Contracts\MessageConsumer;
use Junges\Kafka\Contracts\MessageSerializer;
use Junges\Kafka\Contracts\MessageDeserializer;
use Junges\Kafka\Contracts\ProducerMessage;
use Junges\Kafka\Facades\Kafka as KafkaFacade;
use Junges\Kafka\Message\Message;

/** Kafka: envelope as record headers, payload as value, order id as key. */
final class Kafka implements Publisher
{
    public function publish(string $destination, Envelope $e): void
    {
        $sent = KafkaFacade::publish('broker')
            ->usingSerializer(new class implements MessageSerializer {
                public function serialize(ProducerMessage $message): ProducerMessage { return $message; }
            })
            ->onTopic($destination)
            ->withMessage(new Message(headers: $e->headers(), body: $e->data, key: $e->key))
            ->send();
        if (! $sent) { throw new \RuntimeException('Kafka output was not delivered'); }
    }

    /** Consumer edge: the group id is the service name; the handler runs once per record. */
    public function consume(string $topic, callable $handle): void
    {
        KafkaFacade::consumer([$topic], 'order-intake', 'broker')
            ->usingDeserializer(new class implements MessageDeserializer {
                public function deserialize(ConsumerMessage $message): ConsumerMessage { return $message; }
            })
            ->stopOnFailure()
            ->withHandler(function (ConsumerMessage $m, MessageConsumer $consumer) use ($handle) {
                $handle(Envelope::fromHeaders($m->getHeaders(), (string) $m->getBody(), $m->getKey()));
            })
            ->build()
            ->consume();
    }
}

Redis Streams ​

Redis Streams has no transformation hook and no header section: an entry is field-value pairs, so envelope fields and body are sibling fields. A worker in a consumer group reads with XREADGROUP, transforms, XADDs the output, and XACKs the input. MULTI/EXEC prevents command interleaving but has no rollback: an XADD runtime WRONGTYPE error can still be followed by a successful XACK. The sample therefore publishes first, checks success, then acknowledges. A crash or lost reply can duplicate output; deterministic ids and consumer deduplication handle that uncertainty. A retry is simply an entry left unacknowledged in the pending entries list; the loop above reads only >, so a second loop must reclaim idle entries with XAUTOCLAIM (message acknowledgment). Streams trimmed with MAXLEN lose replay history: size the raw stream for your detection time. See Redis Streams and Pub/Sub and, for the key-value side, Redis.

go
package after

import (
	"context"

	"github.com/redis/go-redis/v9"
)

// StreamPublisher flattens the envelope into stream fields: an entry has no
// header section, so metadata and body are sibling field-value pairs.
type StreamPublisher struct{ Rdb *redis.Client }

func (s StreamPublisher) Publish(ctx context.Context, dest string, e Envelope) error {
	values := map[string]any{"body": e.Data, "key": e.Key}
	for k, v := range e.Headers() {
		values[k] = v
	}
	return s.Rdb.XAdd(ctx, &redis.XAddArgs{Stream: dest, Values: values}).Err()
}

func streamEnvelope(x redis.XMessage) Envelope {
	h := map[string]string{}
	for k, v := range x.Values {
		if s, ok := v.(string); ok && k != "body" {
			h[k] = s
		}
	}
	body, _ := x.Values["body"].(string)
	e := FromHeaders(h, []byte(body))
	e.Key, _ = x.Values["key"].(string)
	return e
}

// RunStream reads a consumer group, transforms, publishes, then XACKs.
// A crash between publish and XACK redelivers the entry: same input, same
// deterministic output ids. Limitation: an entry whose Handle returned Retry
// is left un-ACKed in the pending entries list; this loop reads only new
// entries (">"), so a second loop must reclaim idle ones with XAUTOCLAIM
// (see message-acknowledgment).
func RunStream(ctx context.Context, rdb *redis.Client, stream, group, consumer string, p *Pipeline) error {
	for {
		res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
			Group: group, Consumer: consumer, Streams: []string{stream, ">"}, Count: 20, Block: 0,
		}).Result()
		if err != nil {
			return err
		}
		for _, s := range res {
			for _, x := range s.Messages {
				if out, err := p.Handle(ctx, streamEnvelope(x)); out == Ack && err == nil {
					if err := rdb.XAck(ctx, stream, group, x.ID).Err(); err != nil {
						return err
					}
				}
			}
		}
	}
}

// PublishAndAck deliberately publishes first, then acknowledges. MULTI/EXEC
// does not roll back: a runtime XADD error could otherwise still execute XACK.
// A crash or lost reply can duplicate the output; consumers deduplicate e.ID.
func PublishAndAck(ctx context.Context, rdb *redis.Client, in, group, id, out string, e Envelope) error {
	if err := (StreamPublisher{Rdb: rdb}).Publish(ctx, out, e); err != nil {
		return err
	}
	return rdb.XAck(ctx, in, group, id).Err()
}

Laravel's own Redis queue driver stores jobs in lists and sorted sets, not streams, so a stream transformer uses the Redis facade directly (Redis::xadd, xreadgroup, xack):

php
<?php

namespace App\Messaging\Transform\Brokers;

use App\Messaging\Transform\Envelope;
use App\Messaging\Transform\Publisher;
use Illuminate\Support\Facades\Redis;

/**
 * Redis Streams: an entry has no header section, so the envelope fields and the
 * body are sibling field-value pairs. Uses the Redis facade (phpredis client):
 * Laravel's own redis queue driver uses lists, not streams.
 * The group must exist: XGROUP CREATE partner.orders.raw intake $ MKSTREAM
 */
final class RedisStreams implements Publisher
{
    public function publish(string $destination, Envelope $e): void
    {
        Redis::xadd($destination, '*', [...$e->headers(), 'key' => (string) $e->key, 'body' => $e->data]);
    }

    public function consume(string $stream, string $group, string $consumer, callable $handle): void
    {
        while (true) {
            $res = Redis::xreadgroup($group, $consumer, [$stream => '>'], 20, 5000);
            foreach ($res[$stream] ?? [] as $id => $fields) {
                $body = $fields['body'];
                $key = ($fields['key'] ?? '') ?: null;
                unset($fields['body'], $fields['key']);
                $handle(Envelope::fromHeaders($fields, $body, $key));
                if (Redis::xack($stream, $group, [$id]) !== 1) {
                    throw new \RuntimeException('stream entry was not acknowledged');
                } // after the outputs were published
            }
        }
    }
}
QuestionRabbitMQKafkaRedis Streams
Where does the transformer run?Consumer or sidecarConnect, Streams, or consumerConsumer group worker
Envelope fieldsAMQP properties plus headers tableRecord headersSibling entry fields
Ack after outputConfirm, then AckCommitRecords per partitionXACK after a successful XADD
Replay raw input after a fixStream queue or external storeNew group at an offset or timestampXRANGE or a new group from 0
Retry a transient failureDelayed retry queueRetry topic or stop the partitionLeave pending, XAUTOCLAIM
Invalid message channelDedicated queue or exchangeDedicated topicDedicated stream

Choosing ​

SituationPatternHostReason
One partner, one format, no reuseMessage TranslatorConsumer edgeDo not build a framework for one parser
Three or more formats for one meaningNormalizerEdge service or gatewayAdding a format must not touch the core
Payload must be signed or encrypted but the app cannotEnvelope WrapperProducer and consumer edgeThe application stays unchanged
Receiver needs data the event lacksContent EnricherConsumer edge with a cacheKeep producers simple; mind the dependency
Removing lookup dependency is worth a larger eventEvent-carried state transferProducerRemoves the runtime dependency
Audience must not see some fieldsContent Filter (allowlist)Producer edgeFails safe
Mask a field in a Kafka pipeline with no codeContent Filter via MaskFieldKafka ConnectNo service to run
Drop test trafficMessage Filter (Filter SMT with predicate)Kafka Connect or routerWhole messages, not content
Domain model must stay cleanMessaging MapperProducer and consumer edgeIndependent evolution
Many systems, central integration teamCanonical Data ModelHub or gatewayn-squared to 2n
Autonomous teams, one owner per factPublished language per fact plus ACL where neededProducer and consumer edgeNo committee
Legacy upstream you cannot changeAnticorruption LayerConsumer edgeProtects your model
Huge batch filesStreaming NormalizerBatch workerConstant memory
RabbitMQ or Redis Streams, "broker-side" wishA transformer service or sidecarSeparate processThe broker cannot

In architecture: from a single process to a distributed system ​

Monolith (one process, one database) ​

A Laravel application receives the partner webhook. The controller wraps the raw body in an Envelope and dispatches TransformPartnerOrder on the database or redis queue driver (both are among the drivers Laravel's queue docs list). The job runs the Pipeline in-process: Normalize, Translate, Enrich from a local customers table (no HTTP call, so no timeout problem), then the OrderMapper builds an Eloquent Order inside one database transaction (ACID and transactions). A queued job normally runs in a separate worker process even within one monolith; only synchronous execution stays in the request process. A local DB transaction still does not include an external broker publish. Within each worker, but keeping the stages separate pays off already: three partner formats, tests with golden files, an invalid_messages table. In Go the same is a function chain called from an HTTP handler. Avoid the before shape: one handler that parses, looks up, logs the card number and publishes.

go
// Package before is the shape most teams start with: one consumer function
// that parses, converts, looks up, logs and publishes in the same place.
// It works on the happy path and fails in every way described on the page.
package before

import (
	"encoding/json"
	"log"
	"net/http"
)

// partnerOrder is the partner's wire format used directly as our model.
type partnerOrder struct {
	OrderID string  `json:"orderId"`
	Email   string  `json:"email"`
	Total   float64 `json:"total"` // 19.99 as a float: rounding bugs waiting
	Card    string  `json:"card"`  // PII we never needed
}

type customerService interface {
	Get(email string) (tier string, err error)
}

type publisher interface {
	Publish(topic string, body []byte) error
}

// Handle is a webhook handler doing six jobs.
func Handle(cs customerService, pub publisher) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var in partnerOrder
		if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
			http.Error(w, "bad json", 400) // the partner's only format; the XML partner is "not supported"
			return
		}
		log.Printf("order received: %+v", in) // logs the e-mail and the card number

		tier, err := cs.Get(in.Email) // one network call per message, no cache, no timeout
		if err != nil {
			http.Error(w, "customer lookup failed", 500) // partner retries, we call again
			return
		}

		out, _ := json.Marshal(map[string]any{
			"id": in.OrderID, "email": in.Email, "total": in.Total, "tier": tier, "card": in.Card,
		})
		_ = pub.Publish("orders", out) // error ignored; every consumer now depends on the partner's field names
		w.WriteHeader(202)
	}
}

Modular monolith (modules, several schemas) ​

Modules (Orders, Billing, Fulfilment) share a process but not models. Each module exposes a small Contracts namespace with the events it publishes: that is its published language, and nothing else may be imported across the boundary. Inside a module a Messaging Mapper turns aggregates into those events; a consuming module maps them to its own types at its edge (an anticorruption layer in code, no network). The enricher calls the other module's public interface instead of reading its tables, so a later extraction to a service changes the implementation of the interface, not the stages. Keep one canonical type per fact and put the version in the type name. See context maps and domain events and integration events.

Microservices ​

partner POST ──> intake service (Channel Adapter + Envelope Wrapper)
                      │  partner.orders.raw        (raw envelopes, retained for replay)
                      ▼
              transformer service (Normalizer -> Translator -> Enricher)
                      │  ──> partner.orders.invalid        (fingerprints)
                      ├──> orders.placed       (canonical OrderPlaced v2, key = order id)
                      └──> orders.analytics    (Content Filter output)
orders.placed ──> billing service      (own anticorruption layer: OrderPlaced -> ledger entry)
orders.placed ──> fulfilment service   (conformist: reads OrderPlaced as is)
orders.analytics ──> warehouse loader  (no customer data by construction)

Ownership: the intake team owns the edge and the partner formats; the order domain team owns OrderPlaced and its schema registry entry; each consumer owns its filter or anticorruption layer. Failure handling crosses services: the transformer acknowledges invalid input (parked, alerted), retries transient failures with backoff, and relies on deterministic ids so consumers deduplicate redeliveries (idempotent consumers). If the transformer must emit the canonical event and a database row, use an outbox. Workflows that span services are sagas; the transformation stages are not part of them, they are the edge in front.

Distributed data (caches, replicas, multi-region) ​

The enricher's cache and the customer directory's replicas make enrichment a snapshot, and sometimes a wrong one.

FailureWhat happensMitigation
New customer, directory replica lags (replication lag)Lookup returns 404, the event says unknown-customer for someone who existsShort negative-cache TTL; if the order is within seconds of customer creation, retry with delay; reconcile later with a corrective event
Cached tier is stale after an upgradeGold customer processed as silver for up to the TTLShort TTL for tier, or invalidate the key on a customer.updated event
Cache node lost (Redis)A burst of lookups hits the directoryRequest coalescing (singleflight, Cache::flexible lock), a concurrency limit
Two regions, one canonical modelA v2 producer in region A, v1 consumers in region BCompatible changes only, upcasters at the consumer (schema evolution)
Partner posts to the nearest regionSame order posted twice to two regionsContent-derived raw id; deduplicate on it (inbox)
Time zones across regionsA local time interpreted in the wrong regionParse with the partner's declared zone, never the server's

For consensus and consistency models behind these (what "read your writes" costs), see distributed SQL and consensus.

Scaling path ​

LoadShapeWhat changes
1x (tens of orders per minute)One queued job in the monolith, in-process pipelineGolden files, an invalid table, a stage-level metric
10xA worker pool, enrichment cache, ShouldBeEncrypted jobs, a dedicated queueCache hit ratio and directory latency become the key metrics; add retries with backoff
100xA standalone transformer service, raw topic partitioned by partner, Connect SMTs for masking, a read model of customers fed by events instead of callsStreaming parsers for batch partners; per-partner rate limits; consumer groups scale the transformer (competing consumers); the enricher stops calling out
Many teams and partnersOne published language per fact, a registry, anticorruption layers at consumers, a platform team for the NormalizerGovernance of the model, contract tests (testing messaging)

In production systems ​

  • Kafka Connect's user guide documents SMTs as "lightweight message-at-a-time modifications" with transforms chains, predicates (TopicNameMatches, HasHeaderKey, RecordIsTombstone) and error handling that fails fast by default (errors.tolerance=none).
  • Debezium's outbox pattern ships an event-routing SMT ("Outbox Event Router") for turning outbox rows into routed events: a Translator plus a router in one Connect transform (change data capture).
  • RabbitMQ documents message interceptors (incoming: timestamp, routing node; outgoing: timestamp) as a generic broker mechanism, and states that Streams protocol messages are not intercepted: broker-side transformation of bodies is not built in.
  • The EIP site shows a Content Enricher built with Amazon EventBridge Pipes: an SQS queue of ids, an "Enrichment" step (Lambda reading DynamoDB) and an output queue.
  • Laravel's Illuminate\Pipeline\Pipeline implements Pipes and Filters (send, through, then, thenReturn) and Cache::flexible implements stale-while-revalidate with a deferred, locked refresh.

Lab ​

Every scenario below is expected, not run. No Docker is used. Broker commands require an already provisioned reader environment; local source QA is recorded separately in HANDOFF and is not evidence that these integration experiments ran.

1 cd docs/snippets/messaging/message-transformation/go
  gofmt -l .
  go vet ./...
  go test -count=1 ./...
  # expected, not run: no format/vet errors; unit tests pass
2 go test ./after -run TestGolden -v
  # expected, not run: acme, berlin-shop and tokyo-mart match golden outputs
3 go test ./after -run '^$' -bench Batch -benchmem
  # expected, not run: compare time and allocation on your host
4 go test ./after -run LiveHeap -v
  # expected, not run: bounded streaming retains fewer decoded objects
5 Kafka Connect SMT trial, pre-existing installation only
  # Replace the illustrative connector.class placeholder with an installed connector.
  # The source must emit structured order records. POST the whole name/config object:
  curl -X POST -H 'Content-Type: application/json' --data @connect/orders-source-connector.json \
    http://localhost:8083/connectors
  # expected, not run: phone/shipping_address removed, card_number masked, data_source added
6 RabbitMQ, declared topology and envelope-aware publisher/worker already configured
  # Publish a raw Envelope, not a bare CSV payload: metadata is required.
  # expected, not run: two confirmed outputs precede the input ack
  # Remove the output binding: a mandatory return must prevent input ack.
7 Redis Streams, group/worker already configured
  redis-cli XGROUP CREATE partner.orders.raw intake '$' MKSTREAM
  redis-cli XADD partner.orders.raw '*' id x type partner.order.received source partner/tokyo-mart version 1 occurred-at 2026-11-25T07:00:00Z content-type text/plain body 'C-9;a@b.c;1795600800;JPY;S:1:100'
  redis-cli XRANGE orders.placed - +
  # expected, not run: canonical output, then input acknowledged
8 Laravel 13 host with bindings, models, migrations, cache and HTTP fakes
  php artisan test --filter OrderIntakeTest
  # expected, not run: valid formats pass, invalid/cold-directory failures follow policy

Fault experiments: set currency to XXX (invalid record, no successful output); stop a cold directory (retry); flip an encrypted-envelope bit (authentication failure); make the Redis output key the wrong type (publication fails and the input must remain pending). These are proposed experiments, not broker execution claims.

Common misconceptions ​

BeliefReality
Transformation is serialisationSerialisation is bytes; transformation changes structure, units, time zones and ids
The Content Filter drops messagesThat is the Message Filter. A Content Filter keeps the message and removes content
Kafka Streams filter is a Content FilterIt drops whole records (a Message Filter). mapValues to a smaller type is the Content Filter
RabbitMQ can transform messages for youIts interceptors stamp metadata; there is no declarative body transformation. A consumer does it
A canonical model removes couplingIt replaces n-squared pairwise coupling with coupling to one model that must be owned and versioned
One canonical model for the whole company is the goalNarrow models per fact, owned by the context that owns the fact, usually work better
Floats are fine for pricesUse integer minor units and the currency's digits; reject extra decimals
An enrichment lookup failure can be ignoredPublishing half an event moves the failure downstream; retry, or mark degraded knowingly
A hashed e-mail is anonymousA keyed hash is pseudonymous; with the key and a candidate list it can be reversed by matching
Signing and encrypting are the same layerThey are two layers whose order matters; verify before you parse
Upcasters are a special mechanismThey are Message Translators between two versions of the same type
The Invalid Message Channel should store the payloadStore a fingerprint and keep the original in the raw log within retention, or sealed

Cheat sheet ​

TopicWhat to remember
TranslatorTyped function In to Out; units, time zones and ids are the real work
Envelope WrapperLayers in order on send, reverse on receive; verify the signature before parsing
EnricherCache, deadline, coalescing, sentinel for not found, stale-on-error, retry when cold
Content FilterKeeps the message, changes the content; allowlist fails safe
Message FilterDrops whole messages; Kafka Filter SMT and Streams filter are this
NormalizerRouter plus one translator per format; structure first, semantics after
Canonical Data Modeln(n-1) to 2n translators; own it narrowly, per fact
Messaging MapperNeither side knows the mapper; rebuild via constructors; never publish db keys
Where it runsProducer edge, Kafka Connect/Streams, consumer edge, gateway; RabbitMQ and Redis Streams: consumer
FailuresInvalid: park and ack; transient: retry with backoff; bug: fail loudly
DeterminismSame input, same output ids; ids from content hashes
TestingGolden files per partner, property tests for laws, a no-PII assertion
PerformanceStreaming bounds peak memory, not total work; typed structs over maps
KafkamapValues over map (no repartition); commit per partition in order
Redis StreamsNo headers; publish then XACK, check errors; reclaim pending with XAUTOCLAIM

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What is the difference between a Content Filter and a Message Filter, and which one is the Kafka Connect Filter SMT? Important ​

Answer

Answer: A Message Filter decides whether a whole message passes (router family); the Content Filter keeps the message and removes or flattens fields. The Filter SMT with a predicate drops records, so it is a Message Filter. ReplaceField and MaskField are Content Filters.

2 — A partner sends 19,99 EUR with a decimal comma and another sends 1999 JPY in minor units. What must the translator know to produce one canonical amount? Must-know ​

Answer

Answer: The currency's minor-unit digits (EUR 2, JPY 0) and whether the partner's value is already in minor units. It should parse without floats and reject more decimals than the currency allows.

3 — Why does the Normalizer have a router and separate translators instead of one parser? Important ​

Answer

Answer: EIP defines it as a Message Router plus a Message Translator per format, so a new format adds a translator and a registration without touching shared code, and each translator is testable alone.

4 — An enrichment lookup times out and the cache is cold. What should the pipeline do, and why? Must-know ​

Answer

Answer: Return a transient error and retry later with backoff. Publishing the event without the data would push an incomplete fact to every consumer. If a stale cached answer exists, use it within a bounded time and mark the event degraded.

5 — Name the layers of a signed, encrypted, enveloped message and the unwrap order. Good to know ​

Answer

Answer: Application data, business envelope, signature, encryption, transport headers. Unwrap in reverse: read headers, decrypt, verify the signature, parse the envelope, hand the data over.

6 — When does a Canonical Data Model hurt? Important ​

Answer

Answer: When it is designed up front for hypothetical systems, equals one system's schema, has optional fields for every consumer, or has no owner. It helps with many systems, a real integration hub, a narrow per-fact model and clear ownership.

7 — Which Kafka Streams operator should a Translator use, and why not map? Important ​

Answer

Answer: mapValues: it keeps the key and does not cause data repartitioning. map (and selectKey) can change the key, which marks the stream for repartitioning and affects ordering.

8 — Can RabbitMQ transform a message body on the broker? Must-know ​

Answer

Answer: Not declaratively. Message interceptors are Erlang modules and the built-ins only stamp metadata; Shovel can overwrite some properties but not rewrite bodies. A consumer or sidecar does the work.

9 — Why must output event ids be deterministic, and how does the example achieve it? Important ​

Answer

Answer: A redelivered input must produce the same ids so consumers can deduplicate. The raw id is a hash of partner and body, and each output id is a hash of the raw id and event type.

10 — If streaming parsing is not faster on your host, why use it? Good to know ​

Answer

Answer: It bounds retained decoded data when the reader and output are also bounded. That matters for large batches; measure CPU and allocations locally instead of assuming a speed improvement.

11 — What belongs in an Invalid Message Channel record, and what does not? Important ​

Answer

Answer: Stage, reason, source, raw id and a payload fingerprint. Not the payload in clear, because partner payloads contain PII; the original stays in the raw log or is kept sealed.

Glossary ​

TermDefinition
Message TranslatorA filter that converts one data format into another (EIP)
Envelope WrapperWraps application data in an envelope the messaging infrastructure accepts; the unwrapper restores it
UnwrapperThe step that removes the envelope at the destination
Content EnricherAdds data from computation, the environment or another system to a message
Content FilterRemoves or flattens data inside a message, keeping the message
Message FilterDrops whole messages that do not match a condition (routing family)
NormalizerA router plus per-format translators that outputs one common format
Canonical Data ModelOne application-independent model that every system produces and consumes
Messaging MapperA class that maps between domain objects and messages; neither knows it exists
Pipes and FiltersIndependent processing steps connected by channels
Anticorruption LayerA downstream translation layer protecting its model from another context's model (DDD)
Published LanguageA documented exchange format published by the upstream context (DDD)
Open Host ServiceAn upstream protocol offered to many consumers (DDD)
SMT (Single Message Transform)A Kafka Connect per-record transformation configured with transforms
Predicate (Connect)A condition that decides whether an SMT applies; with negate to invert
Kafka Streams DSLLibrary operators such as map, mapValues, filter, selectKey
RepartitioningRe-keying a stream through a topic so records with the same key meet
UpcasterA translator that lifts an old payload version to the next
DraftIn this page's code, the Normalizer output: one structure, partner values intact
Minor unitsThe smallest currency unit as an integer (cents); digits per ISO 4217
HMACKeyed hash used to sign a message or pseudonymise an identifier
AES-GCMAuthenticated encryption; a nonce must never repeat under one key
NonceA number used once per encryption under a key
singleflightDuplicate call suppression: concurrent identical lookups share one call
Negative cachingCaching "not found" so it is not looked up repeatedly
Stale-while-revalidateServing an old value while a refresh runs; Cache::flexible in Laravel
Golden fileA stored expected output compared byte for byte in a test
Property testA test of a law over generated inputs, such as unwrap(wrap(x)) == x
Invalid Message ChannelWhere messages that can never be processed are sent
Channel AdapterConnects an application or protocol to a message channel
SidecarA helper process deployed next to a service to do a cross-cutting job
ESB / iPaaSCentral integration platforms hosting translators and routers

| Allowlist / Denylist | Explicitly allowed output fields versus named fields removed; new fields are excluded only by the allowlist. | | PII / Pseudonymisation / Anonymisation | Personal data; a keyed replacement remains linkable with extra information, unlike an anonymity claim. | | Determinism / Snapshot | Stable input-to-output choices; enrichment is a time-specific view and may change across retries. | | TTL / Stale-on-error / degraded | Freshness window; bounded old data may be used on lookup failure with an explicit degraded marker. | | Publisher confirm / mandatory / basic.return | Broker confirmation plus return handling distinguishes accepted publications from unroutable ones. | | Ack / Nack / Prefetch | Consumer settlement or rejection; prefetch bounds unacknowledged deliveries. | | CommitRecords / DisableAutoCommit | Explicit ordered offset commits after output; auto-commit must be disabled for this loop. | | BlockRebalanceOnPoll / AllowRebalance | franz-go gates group ownership changes while a polled batch is processed, then releases them. | | XADD / XREADGROUP / XACK | Append a stream entry, deliver to a group, and remove an entry from its pending list. | | PEL / XAUTOCLAIM | Pending Entries List and idle-entry ownership recovery; reading > alone is not recovery. | | MULTI/EXEC / WRONGTYPE | Redis isolated command execution has no rollback on runtime errors such as the wrong key type. | | transforms / errors.tolerance / DLQ | Ordered Connect aliases; none fails tasks, all may skip bad records; standard DLQ is sink-specific. | | ReplaceField / MaskField / ExtractField / HoistField / Flatten | Connect field selection/renaming, masking, extraction, wrapping and flattening transforms. | | InsertField / InsertHeader / HeaderFrom / DropHeaders | Connect insertion or copying of metadata and removal of headers. | | Cast / TimestampConverter / SetSchemaMetadata | Connect type/time conversion and schema metadata adjustment. | | RegexRouter / TimestampRouter / ValueToKey | Connect topic naming and record-key construction. | | TopicNameMatches / HasHeaderKey / RecordIsTombstone / negate | Connect predicates for topic, header presence or null-value records, with optional inversion. | | map / mapValues / selectKey / KTable | Streams transformations of key/value or just value; a table provides keyed state for enrichment joins. | | Pipeline / Cache::flexible / ShouldBeEncrypted | Laravel stage composition, deferred cache refresh and encrypted queued-job payloads. | | XMLReader / LazyCollection / json.Decoder | Pull parsing and lazy iteration; memory bounds require bounded input and output too. | | Serialization / Transport / Representation / Data type / Structure | Bytes encoding, delivery mechanism, representation conventions, value types and field organisation are different transformation axes. | | UTC / DST / ISO 4217 / Overflow | Time standard, daylight-saving ambiguity, currency minor-unit metadata and integer range overflow. | | Raw log / Replay / Retention / MAXLEN | Stored original messages, reprocessing, storage lifetime and Redis stream trimming. | | Outbox / Inbox / Idempotency | Durably stage output with local state, record consumed identities and make retries safe for effects. |

References ​

Built by Morteza Negahi