Message Design & Schema Evolution
"Event producers are encouraged to consider versioning from the outset" — CNCF, CloudEvents Primer, "Versioning of CloudEvents"
Summary: A message is a public API with invisible consumers that deploy on their own schedule; its envelope, its payload shape and its evolution rules decide whether you can change it without a flag day. Focus: The envelope (id, type, version, time, source, correlation/causation, tenant, key, trace), CloudEvents, thin vs fat events, versioning strategies, compatibility modes, schema registries, JSON Schema at the edge, CI checks, AsyncAPI, claim check and size limits, per broker. Learning goal: Design an OrderPlaced message that every broker can carry, evolve it from v1 to v2 while old and new consumers run side by side, and pick the compatibility mode, registry setup and upgrade order that make that safe.
This page owns the design layer of a message: what goes in the envelope and what goes in the payload, how to name and size an event, how to change its shape over years, and how tools (Schema Registry, buf breaking, JSON Schema, AsyncAPI) enforce the rules. It deliberately does not re-teach the bytes. How JSON, Protobuf, Avro and MessagePack encode a value, varints, unknown-field preservation on the wire and measured sizes live in Serialization Formats; this page links there whenever a rule depends on the encoding. Adjacent pages: event-driven architecture owns events vs commands and Fowler's three event styles in depth, event sourcing owns stored-event versioning and replay, message transformation owns the Envelope Wrapper and translators in depth, messaging observability owns trace-context propagation, messaging security owns PII and erasure, and Laravel queue internals owns the job payload machinery. Domain-level framing is in domain events vs integration events and designing for failure.
Page map
| If you are looking for | Go to |
|---|---|
| Four tables to memorise | Everything in one minute |
| Why the message is your most expensive API | Why message design matters |
| EIP, Fowler, CloudEvents, Avro, Protobuf, Confluent origins | Where it comes from |
| id, type, version, time, source, correlation, causation, tenant, key, trace | Envelope, headers and metadata |
| How to link messages of one flow | Correlation and causation ids |
| A standard envelope and its Kafka/AMQP bindings | CloudEvents |
order.placed vs OrderUpdated | Event naming |
| Notification vs event-carried state transfer | Thin vs fat events |
| Why the Eloquent row or the ORM struct must not be the payload | Never leak the internal model |
| Additive-only change and the tolerant reader | Tolerant reader and additive-only |
| Version in type vs header, upcasting, dual-publish, topic-per-major-version | Versioning strategies |
| Lifting old payloads in the consumer | Upcasting |
| BACKWARD, FORWARD, FULL, TRANSITIVE, NONE per format | Compatibility modes |
| Confluent, Apicurio, Karapace; subjects; schema id in the bytes | Schema registry |
| Validating JSON from other systems | JSON Schema at the edge |
Field numbers, reserved, defaults | Protobuf and Avro rules recap |
| Failing the build on a breaking change | Breaking-change detection in CI |
| A machine-readable contract for channels and messages | AsyncAPI |
| Payloads too big for the broker | Claim check, Size limits |
| Personal data in messages | PII |
| AMQP properties, Kafka record headers, stream fields, wire format, errors | Mechanics |
| Code | Go, Laravel, Broker differences |
| Rename, retype, split, enum, attachment, erase | Solving the classic problems |
| Which strategy for which situation | Choosing a strategy |
| Monolith to multi-region | In architecture |
Evolve OrderPlaced v1 to v2 with old and new consumers | Lab |
| Wrong beliefs, cheat sheet, every term | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The envelope. Everything a broker, a middleware or an operator needs without parsing the body.
| Field | Plain words | Example | Who needs it |
|---|---|---|---|
id | Unique name of this message | 01JD3Q8Z... (UUIDv7/ULID) | Idempotent consumer dedup |
type | Which fact this is | order.placed | Router, decoder, subscriber filters |
version | Shape of the payload for this type | 2 | Decoder, upcaster |
occurred-at | When it happened (not when it was sent) | 2026-11-25T09:30:00Z | Ordering hints, SLAs, audit |
source / producer | Who said it | orders-service | Debugging, ACLs, source+id uniqueness |
correlation-id | The whole business flow | checkout-7f3 | Tracing a saga, support tickets |
causation-id | The message that caused this one | id of payment.captured | Cause-and-effect graphs, loop detection |
tenant-id | Which customer's data | acme | Routing, quotas, isolation |
| key | Partition / ordering key | order-42 | Ordering |
traceparent | W3C trace context | 00-4bf9...-01 | Observability |
content-type | How the body is encoded | application/json | Decoder choice |
Versioning strategies.
| Strategy | Plain words | Good for | Cost |
|---|---|---|---|
| Additive-only | Only add optional fields with defaults; never rename, retype, reuse | Routine additive changes | Old fields live forever |
| Version in a header | Same type, version: 2 header, consumer branches | Small, in-house breaking changes | Every consumer must read the header |
| Version in the type name | order.placed.v2 is a new type | Real breaking change, public consumers | Two types to document and route |
| Upcasting | Consumer lifts v1 to v2 before handling | Long-lived logs, event sourcing | Upcaster chain to maintain |
| Dual-publish | Producer emits v1 and v2 for a while | Migrating many consumers | Double traffic, two schemas in sync |
| Topic-per-major-version | orders.v2 next to orders.v1 | Kafka, retention-bound history | Consumers move topics; ordering across topics lost |
Compatibility modes (Confluent Schema Registry definitions; default BACKWARD).
| Mode | Promise | Upgrade first | Typical safe change |
|---|---|---|---|
BACKWARD | New schema can read data written with the previous one | Consumers | Delete a field; add an optional field with default |
FORWARD | Previous schema can read data written with the new one | Producers | Add a field; delete an optional field |
FULL | Both | Any order | Add or delete optional fields only |
*_TRANSITIVE | Same, against all earlier versions | As above | As above |
NONE | No check | You coordinate | Anything (dangerous) |
Size limits (defaults; check your version).
| Broker | Knob | Default | What happens above it |
|---|---|---|---|
| RabbitMQ 4.x | max_message_size | 16 MiB (was 128 MiB in 3.x); max 512 MiB | Channel closed with PRECONDITION_FAILED |
| Kafka broker / topic | message.max.bytes / max.message.bytes | 1048588 bytes (record batch, after compression) | MESSAGE_TOO_LARGE (error 10) |
| Kafka producer | max.request.size | 1048576 bytes | RecordTooLargeException on the client |
| Redis Streams | proto-max-bulk-len | 512 MB per bulk string | Command rejected; memory and replication pain long before |
| CloudEvents intermediaries | spec rule | must forward ≤ 64 KiB | Larger events are "not safe" through generic hops |
Why message design matters
An HTTP API has callers you can list. A message has consumers you may never meet: a team subscribes to order.placed next quarter, a data pipeline reads the topic from offset zero next year, and a log such as Kafka keeps every version you ever produced for as long as retention allows. You cannot redeploy all of them at once, so every change must be readable by code that already exists and by code that does not exist yet. That is the whole subject.
The fundamental trade-offs:
| Simpler / looser | Richer / stricter |
|---|---|
| Schemaless JSON, no registry | Avro/Protobuf/JSON Schema with a registry or CI check |
| Thin events (id + type) | Fat events (state the consumer needs) |
| Metadata mixed into the body | Envelope in headers, pure payload in the body |
| One topic, version header | New type or new topic per major version |
| Large payloads inline | Claim check to object storage |
| Fast to start | Cheap to change later |
An everyday picture: the parcel. The label on the outside (sender, destination, tracking number, "fragile", the customs-form version) lets every depot route and track the parcel without opening it: that is the envelope. The contents are the payload. If the contents are too large for the courier's van, you hand over a collection slip and the recipient fetches the goods from a warehouse: the claim check. And when the postal service changes the customs form, depots keep accepting the old form for a while, because parcels already in transit were labelled under it: compatibility. The page returns to this parcel several times.
Three common misunderstandings, up front
- "It is just JSON, there is no schema." The schema exists the moment a consumer reads
order_id; without a registry or contract test it is implicit, and you find out it broke in production. - "Backward compatible means old consumers keep working." In Schema Registry vocabulary it is the reverse:
BACKWARDmeans a consumer on the new schema can read old data. Old consumers reading new data isFORWARD. - "Adding a field is always safe." In Avro it is backward compatible only with a default; in Protobuf it is wire-safe but a new enum value can break an exhaustive
switch; and a consumer that rejects unknown fields turns every addition into a breaking change.
Where it comes from
Hohpe and Woolf's Enterprise Integration Patterns (2003) supplies the Envelope Wrapper, Correlation Identifier and Claim Check vocabulary: infrastructure metadata around application data, a way to link requests and replies, and a reference to externally stored content. Integration styles and channels covers the Format Indicator.
Fowler's 2017 event-driven article distinguishes notification from event-carried state transfer; his Tolerant Reader discussion argues for reading the fields you need without coupling to unrelated structure. Avro specifies writer/reader schema resolution; Protobuf specifies evolution of numbered fields; Confluent exposes compatibility policies at schema registration. Apicurio and Karapace offer Confluent-compatible API surfaces, with version-specific differences that must be checked before migration.
CloudEvents standardizes event metadata and protocol bindings. AsyncAPI describes channels, operations and messages in a machine-readable contract. Neither a standardized envelope nor a valid schema proves the business meaning of a payload is correct. Greg Young's Versioning in an Event Sourced System discusses upcasting; we cite its public table of contents, not inaccessible book text.
The message, part by part
Envelope, headers and metadata Must-know
In plain words: a message has two audiences. The infrastructure (broker, inbox table, tracer, DLQ tool, operator) needs to know what and who without opening the box; the business handler needs the data. Put the first kind in headers, the second in the body.
Common misunderstanding: "Put everything in one JSON object, it is simpler." Then the router must parse every body to route, the dedup table must know every payload shape to find the id, a registry serializer cannot own the value bytes, and a claim-checked message has nowhere to put its reference.
Definition: the envelope is the set of metadata fields carried next to the payload: in AMQP 0-9-1 basic properties plus the headers table, in Kafka record headers (and the record key and timestamp), in Redis Streams sibling field-value pairs. The payload (body, value, data) is the serialized business fact, versioned on its own.
producer (orders-service) broker consumer (billing)
1 build payload {order_id, amount_minor, currency}
2 build envelope id=01JD.., type=order.placed, version=2,
occurred-at, source, correlation-id, tenant-id, key=order-42
3 publish(headers=envelope, body=payload) -> route on type/key, size check
4 read id -> inbox dedup
5 read type+version -> pick decoder
6 decode body -> handlerReal scenarios:
- An inbox table deduplicates on
(source, id)for twenty event types without knowing any payload. - A DLQ dashboard lists failures by
typeandtenant-idand shows the body only on click. - RabbitMQ headers-exchange routing or Kafka Streams filters on
typewithout deserializing Avro. - A support engineer searches logs for one
correlation-idand sees the whole checkout across five services.
Fields and why each exists:
| Field | Required? | Rule |
|---|---|---|
id | Yes | Unique per source; reused on retry of the same message so consumers can dedup; UUIDv7 or ULID sort by time (see ID generation) |
type | Yes | Past-tense fact, stable, namespaced: order.placed |
version | Yes for breaking-change strategies | Integer per type; or carry it in type/dataschema (see strategies) |
occurred-at | Yes | UTC, RFC 3339; set where the fact happened, not by the relay |
source | Yes | Producing service or bounded context |
correlation-id | Strongly recommended | Copied unchanged through the whole flow |
causation-id | Recommended | The id of the message being handled when this one was produced |
tenant-id | When multi-tenant | Never inferred from payload content |
| key | When ordering matters | Usually the aggregate id; a routing decision, not a metadata field |
traceparent | Recommended | W3C format; propagation rules are on the observability page |
content-type | Yes when formats vary | application/json, application/x-protobuf, application/vnd.apache.avro+binary |
What each broker gives you:
| Need | RabbitMQ (AMQP 0-9-1) | Kafka | Redis Streams |
|---|---|---|---|
| Standard id/type/time slots | message-id, type, timestamp, app-id, correlation-id, content-type properties | none; only key, value, timestamp, headers | none |
| Free-form metadata | headers table (typed values) | Record headers: list of string key to byte[] value | Field-value pairs in the entry |
| Key for ordering | Routing key (routing, not ordering) | Record key (partition hash) | Stream name / your own sharding |
| Body | Opaque bytes | Value bytes | One field you choose, e.g. body |
Fix / how to use it: a typed envelope in Go and a readonly DTO in Laravel; see Go and Laravel. The rule in one line: no metadata in the payload, no business data in the headers.
Correlation and causation ids Must-know
In plain words: the correlation id is the case number written on every letter about one case; the causation id is "in reply to letter #17".
Common misunderstanding: "One id is enough." With only a correlation id you know which messages belong together but not which caused which, so you cannot draw the graph or detect a loop (A causes B causes A).
Definition: correlation-id is shared by every message of one business flow and copied unchanged; causation-id equals the id of the message whose handling produced this one. The first message of a flow has causation-id empty (or the HTTP request id) and usually correlation-id = id.
message id correlation-id causation-id
1 order.placed m1 m1 (http req-9)
2 payment.requested m2 m1 m1
3 payment.captured m3 m1 m2
4 order.confirmed m4 m1 m3
5 invoice.issued m5 m1 m4
-- grep correlation m1: the whole flow; follow causation: the exact chainReal scenarios: a saga orchestrator finds its instance by correlation id; request-reply matches a reply to its request (that page owns reply queues); an event storm caused by a bad deploy is cut by finding the root causation; customer support pastes one id and gets the timeline.
| Broker | Where it goes |
|---|---|
| RabbitMQ | correlation-id is a standard property; causation-id goes in the headers table |
| Kafka | Both in record headers |
| Redis Streams | Both as fields |
Fix: never generate a new correlation id inside a consumer; derive child metadata from the parent. The Go helper Caused(parent, ...) in message.go does exactly that, and Laravel's Envelope::wrap($event, $correlationId, $causationId) takes them from the incoming message.
CloudEvents: a standard envelope Important
In plain words: instead of inventing header names per team, use the names a CNCF spec already defined, so gateways, serverless platforms and SDKs understand your events.
Common misunderstanding: "CloudEvents is a JSON format I must wrap my payload in." It defines attributes and several content modes. In binary mode your payload stays the message body untouched and the attributes become protocol headers; structured mode wraps both in one document (for example application/cloudevents+json).
Definition: CloudEvents 1.0 marks four context attributes REQUIRED: id, source, specversion (1.0) and type. Optional ones include time, subject, datacontenttype and dataschema. A distinct event needs a unique (source, id) pair. Extension names allow lowercase letters and digits, so use correlationid, not correlation-id.
Kafka binding, binary mode AMQP 1.0 binding, binary mode
1 header ce_specversion = 1.0 app-property cloudEvents_specversion = 1.0
2 header ce_id = m3 app-property cloudEvents_id = m3
3 header ce_source = orders-service app-property cloudEvents_source = orders-service
4 header ce_type = order.placed app-property cloudEvents_type = order.placed
5 header content-type = application/json content-type property = application/json
6 key = order-42 (partitionkey extension) body = {"order_id":44,...}
7 value = {"order_id":44,...}On versioning, the CloudEvents primer recommends a new type for a breaking data change and an overlap period with both representations. dataschema is a URI identifying the data contract; it does not itself validate the payload.
Real scenarios: any CloudEvents-aware router or serverless trigger filters on type/source without parsing data; a Kafka-to-HTTP bridge forwards ce_* headers as ce-* HTTP headers without touching the body; a multi-team platform agrees on one header vocabulary instead of five.
| Binding | Attribute prefix | Content modes |
|---|---|---|
| Kafka | ce_ on record headers | binary and structured (batch not supported) |
| AMQP 1.0 | cloudEvents_ or cloudEvents: on application properties | binary and structured |
| HTTP | ce- headers | binary, structured, batch |
Fix: CloudEventsHeaders(prefix, meta) in Go maps our Meta onto either binding; see Go.
Event naming Important
In plain words: name an event like a newspaper headline about something that already happened: order.placed, payment.captured, parcel.delivered.
Common misunderstanding: "OrderUpdated with the whole row is flexible." It tells the consumer nothing about why, so every consumer re-derives intent from diffs, and every column becomes contract.
Definition: an event name is <domain>.<entity>.<past-tense verb> (or entity.verb), stable for life, unique per producer, and describes a business fact, not a CRUD operation. A command (order.place, imperative) is a request that may be refused; the full distinction belongs to event-driven architecture.
| Bad | Better | Why |
|---|---|---|
OrderUpdated | order.address-changed, order.cancelled | Intent, smaller payload, separate consumers |
orders_table_insert | order.placed | Business fact, not storage event (CDC is a separate stream, see CDC) |
SendEmail on a topic | command queue notifications.send-email | It is a command, owned by the receiver |
order.placed.v2.final | order.placed + version: 2 or order.placed.v2 | One versioning scheme, documented |
Real scenarios: an analytics team subscribes only to order.cancelled instead of filtering OrderUpdated diffs; a fraud service needs payment.captured, not a payments row change; a status-change enum explodes into order.shipped, order.delivered, order.returned, each with its own fields.
Thin vs fat events and event-carried state transfer Must-know
In plain words: a thin event says "order 42 changed, ask me if you care"; a fat event says "order 42 was placed, here is everything you need about it".
Common misunderstanding: "Thin events are always more decoupled." They move coupling from the schema to runtime: every consumer now calls the producer's API, at the producer's availability, and may read a state that already moved on.
Definition: an event notification (thin) carries identifiers and type; consumers call back for details. Event-carried state transfer (fat) carries the state the consumers need so they can keep their own copy and never call back. In Fowler's framing, local state removes the callback dependency at the cost of additional transferred data and copies. A delta event carries only the changed fields; a snapshot event carries the full current state of the entity (useful on compacted Kafka topics, where the latest value per key is the state).
thin (notification) fat (event-carried state transfer)
1 orders -> order.placed {order_id:42} orders -> order.placed {order_id:42, items, total, address}
2 billing GET /orders/42 (orders must be up) billing uses payload, no call
3 shipping GET /orders/42 (N consumers = N calls) shipping uses payload, no call
4 orders changes address at T+1s orders publishes order.address-changed {..}
5 billing's GET at T+2s sees the NEW address billing's copy is updated by the next event
-- race: consumer sees a later state than the event describedReal scenarios: a search indexer needs the full product (fat or snapshot on a compacted topic); a webhook to third parties sends thin events with a signed URL so you never leak more than the URL's ACL allows; a ledger needs the exact amount at the moment of capture (fat; a callback would see refunds); a cache invalidation only needs the key (thin).
| Aspect | Thin | Fat |
|---|---|---|
| Contract size | Tiny, stable | Large; every field is a promise |
| Producer availability | Required at consume time | Not required |
| Consistency | Consumer reads latest state (may be ahead of event) | Consumer sees state as of the event |
| Payload size | Bytes | KB to MB (claim check above limits) |
| PII spread | Low | High: every copy holds the data |
Fix: the middle path most teams end up with: fact-sized events that carry what the fact is about (order_id, amount_minor, currency, line items) plus identifiers for everything else (customer_id, not the customer profile). Add fields when a real consumer needs them, not "just in case".
Never leak the internal model Must-know
In plain words: your database table is your kitchen; the event is the menu. Customers order from the menu; you are free to rearrange the kitchen.
Common misunderstanding: "Serializing the Eloquent model / ORM struct saves a mapping layer." It turns every migration into a contract change: add a column and every consumer gets it, rename one and every consumer breaks, and hidden or sensitive columns leak the day someone forgets $hidden.
Definition: the published schema is an explicit, separately versioned contract (DTO / .proto / .avsc / JSON Schema) owned by the producer and mapped from the internal model. In DDD terms this is the difference between a domain event and an integration event; see domain events vs integration events.
1 migration renames orders.total -> orders.total_amount
2 json_encode($order) now emits "total_amount"
3 billing reads $p['total'] -> null -> invoices for 0.00
4 no error anywhere; discovered at month-end closeReal scenarios: the Before snippet's json_encode($order); a Go service marshalling its GORM struct; CDC topics consumed directly by other teams (fine for replication, risky as an integration contract, which is why the outbox writes a designed payload).
Fix: a mapping function per event (OrderPlaced::fromModel() / toPayload()), contract tests that fail when the payload changes shape, and a lint rule that bans encoding ORM entities onto the wire.
Evolving the schema
Producers and consumers deploy independently, so at any moment at least two versions are in flight, and a log keeps older ones for as long as retention (or forever, with compaction or an event store). Everything below is about making that overlap safe.
Tolerant reader and additive-only changes Must-know
In plain words: the producer only ever adds optional things; the consumer reads only what it needs and ignores the rest. Together they let both sides change without talking.
Common misunderstanding: "Strict validation on the consumer is safer." A consumer that rejects unknown fields (Go Decoder.DisallowUnknownFields, JSON Schema additionalProperties: false, a Laravel validator with an exact key list) turns every additive change by the producer into an outage.
Definition: additive-only evolution allows: add an optional field with a default, add a new event type, add an enum value only if consumers have a fallback. It forbids: rename, change type or meaning, reuse a name or Protobuf field number, make an optional field required. A tolerant reader (Fowler) ignores unknown fields, tolerates absent optional ones, and assumes as little structure as possible.
producer old consumer (v1 struct) new consumer (v1.1 struct)
1 v1 {order_id, amount_minor, currency} reads 3 fields -
2 deploy v1.1: + coupon (optional) - -
3 v1.1 {order_id, amount_minor, currency, coupon}
4 ignores coupon (tolerant) OK -
5 - deploy: reads coupon or default ""
6 old v1 messages still in the log - coupon absent -> default "" OKReal scenarios: adding coupon_code to order.placed; adding channel: web|app|pos with default web; adding a new event type order.gift-wrapped that old consumers never subscribe to; adding an enum value refund_reason = chargeback, which is only safe if every consumer has a default branch.
| Format / tool | Unknown field on read | Missing field on read |
|---|---|---|
Go encoding/json | Ignored (unless DisallowUnknownFields) | Zero value |
PHP json_decode + array access | Ignored | null / undefined index; use ?? |
| Protobuf (proto3) | Kept as unknown fields, re-emitted on serialize | Default value (0, "", false) |
| Avro | Writer field absent from reader is skipped | Reader default, otherwise resolution fails |
| JSON Schema | Allowed unless additionalProperties: false | Error only if listed in required |
Fix: in Go, never call DisallowUnknownFields in consumers; use it in producer tests only. In Laravel, read with $p['coupon'] ?? null. In Avro, every new field gets a default. In Protobuf, never reuse a number (reserved).
Versioning strategies Must-know
In plain words: when a change cannot be additive, you need a way for consumers to know which shape they hold and for the old and new shapes to coexist until the last old consumer is gone.
Common misunderstanding: "We bump the version and deploy everything together." That is a flag day; with retention, replays and independent teams there is no "together".
Definition: the five strategies, from cheapest to most expensive:
- Additive-only (above): no version bump at all.
- Version in a header (
version: 2, or Protobufproto-type+version, or CloudEventsdataschema): sametype, consumers branch on the header or upcast. - Version in the type name (
order.placed.v2, or a new CloudEventstype): a new event type; consumers subscribe to it explicitly. - Dual-publish: the producer emits both v1 and v2 (two types or two topics) until consumers have moved; the CloudEvents primer recommends this.
- Topic-per-major-version:
orders.v1andorders.v2topics (Kafka) or exchanges/queues (RabbitMQ); consumers move topic when ready; old topic retires with retention.
Plus upcasting on the consumer side, which combines with any of 2 to 5 (next section).
dual-publish rollout of order.placed v2 (breaking: amount float -> amount_minor + currency)
1 week 0 producer emits order.placed (v1) only
2 week 1 producer emits order.placed (v1) AND order.placed.v2, same id-suffix, same key, in one outbox tx
3 week 1 billing, shipping still on v1 analytics switches to v2
4 week 3 billing switches to v2 (dedups on business id, ignores v1)
5 week 4 shipping switches; dashboard shows 0 consumers on v1 (consumer-group lag / queue bindings)
6 week 5 producer stops v1; v1 topic/binding removed after retentionReal scenarios: money changes from float to minor units (breaking: dual-publish or v2 type); splitting name into first_name/last_name (additive: add both, keep name until no reader needs it); a public webhook contract (version in type, never break v1); an internal two-team event (header version + upcaster is enough).
Decision table:
| Situation | Strategy | Extra technique | Reason |
|---|---|---|---|
| New optional field | Additive-only | Default value, tolerant reader | No coordination at all |
| Rename a field | Additive (add new, keep old) | Deprecate old in AsyncAPI; remove under FORWARD/FULL rules later | Readers move at their own pace |
| Change type/meaning, few in-house consumers | Version header + upcaster | BACKWARD_TRANSITIVE on the registry | One topic, one ordering |
| Change type/meaning, many or external consumers | Version in type + dual-publish | Migration dashboard of consumers per version | Nobody breaks; you control the end |
| Whole model redesign, Kafka | Topic-per-major-version | Bridge job republishing v1 into v2 (or vice versa) | Clean schema subject per topic |
| Stored events (event sourcing) | Upcasting on read | Copy-transform only as a last resort | History is immutable |
| Laravel jobs in a queue during deploy | Keep constructor compatible; add new job class | payloadVersion via createPayloadUsing | Serialized PHP names classes |
Where to put the version:
| Option | Pros | Cons | Products |
|---|---|---|---|
Header version | Body stays pure; one type name | Consumers must read it; lost if a bridge drops headers | Any broker; Kafka record headers; AMQP headers |
Inside the type (order.placed.v2) | Routable and filterable; obvious | Type list grows; subscribers must change | RabbitMQ topic exchange routing keys, CloudEvents type |
Inside the payload ("schema_version": 2) | Survives any transport | Must parse to know how to parse | Files, webhooks, legacy |
| Registry schema id in bytes | Automatic, exact | Needs the registry to read anything | Confluent/Apicurio/Karapace serializers |
dataschema URI | Standard (CloudEvents) | Informational; tooling-dependent | CloudEvents |
Upcasting on the consumer Important
In plain words: the consumer keeps only the newest model, and a chain of tiny functions converts any old message into the newest shape before the handler sees it.
Common misunderstanding: "Upcasting means rewriting the old messages." It never touches stored data; it transforms on read. Rewriting history (copy-transform into a new stream) is a separate, last-resort technique owned by event sourcing.
Definition: an upcaster is a pure function v(n) -> v(n+1) for one (type, version). The chain applies them in order until the payload reaches the consumer's latest version. Upcasters may fill defaults, rename, split or convert units; they must be deterministic (no database calls) so replays give the same result.
1 message arrives: type=order.placed, version=1, body {"order_id":42,"amount":19.99}
2 up[order.placed,1]: amount 19.99 -> amount_minor 1999, currency "USD" (v1 only ever carried dollars)
3 body is now v2 {"order_id":42,"amount_minor":1999,"currency":"USD"}
4 up[order.placed,2] not registered and latest=2 -> stop
5 unmarshal into OrderPlacedV2 -> handlerReal scenarios: a new projection replays two years of order.placed in three shapes; a consumer that rejoins after a long outage reads a backlog mixing v1 and v2; a Kafka topic with 30-day retention where v1 events still exist for 30 days after the switch.
Fix: Decode[T](upcasters, msg, latest) in Go (decode.go) and Upcasters::toLatest() in Laravel (After.php); both fail loudly when a step is missing rather than guessing.
Compatibility modes Must-know
In plain words: a compatibility mode is the rule the registry (or CI) applies before it accepts a new schema version: "can new readers read old data?", "can old readers read new data?", or both.
Common misunderstanding: "BACKWARD protects old consumers." It protects new consumers reading old data (rewind, replay, backlog). If you want old consumers to survive new data, you need FORWARD or FULL.
Definition: in Confluent terminology, BACKWARD checks a new reader against old data; FORWARD checks an old reader against new data. FULL requires both directions. Transitive variants extend the comparison to all registered versions. NONE disables this check. The default is BACKWARD; Confluent recommends BACKWARD_TRANSITIVE for Protobuf, where adding message types can affect forward compatibility.
BACKWARD: upgrade consumers first FORWARD: upgrade producers first
1 registry: v2 checked "v2 reader reads v1 data" registry: v2 checked "v1 reader reads v2 data"
2 deploy consumers with v2 (read v1 + v2) deploy producer writing v2
3 deploy producer writing v2 old consumers read v2 with v1 schema
4 old v1 data still readable on replay drain/transform retained v1 data before new-only readers
5 then upgrade consumers; old-data replay needs a separate plan
-- the order of deploys is decided by the mode, not by preferenceReal scenarios: analytics rewinds a topic to offset 0 (needs BACKWARD_TRANSITIVE, not just BACKWARD, because the oldest data may be v1 while you register v5); a mobile app you cannot force to update reads events through a gateway (needs FORWARD); a shared topic with independent teams on both sides (FULL_TRANSITIVE).
What each mode allows, per format (Confluent's summary tables; "required" means a field without a default in Avro):
| Change | Avro BW | Avro FW | Avro FULL | Protobuf BW | Protobuf FW | Protobuf FULL |
|---|---|---|---|---|---|---|
| Add optional field | yes | yes | yes | yes | yes | yes |
| Remove optional field | yes | yes | yes | yes | yes | yes |
| Add required field | no | yes | no | no | no | no |
| Remove required field | yes | no | no | no | no | no |
| Add union / oneof variant | yes | no | no | yes | no | no |
| Remove union / oneof variant | no | yes | no | no | yes | no |
| Widen an allowed scalar family | yes | no | no | conditional | conditional | conditional |
| Narrow an allowed scalar family | no | yes | no | conditional | conditional | conditional |
Protobuf scalar qualification: these are not arbitrary type conversions. Binary wire-compatible families include int32/uint32/int64/uint64/bool, sint32/sint64, and fixed32/sfixed32 or fixed64/sfixed64. Narrowing can truncate; changing boolean meaning can corrupt semantics. ProtoJSON and generated source compatibility require separate checks. Test the actual types, limits and reader versions.
JSON Schema is different: the Confluent result depends on compatibilityPolicy (LENIENT or STRICT) and whether additionalProperties permits an open or closed content model.
| Change (JSON Schema) | Lenient BW / FW / FULL | Strict, open model BW / FW / FULL | Strict, closed model BW / FW / FULL |
|---|---|---|---|
| Add optional field | yes / yes / yes | no / yes / no | yes / no / no |
| Remove optional field | yes / yes / yes | yes / no / no | no / yes / no |
| Add required field | no / yes / no | no / yes / no | no / no / no |
| Remove required field | yes / no / no | yes / no / no | no / no / no |
| Add union variant | yes / no / no | yes / no / no | yes / no / no |
| Remove union variant | no / yes / no | no / yes / no | no / yes / no |
The counter-intuitive row, "strict + open: adding an optional field is not backward compatible", follows from the open model: old data may already contain that property name with any type, so a new reader that now constrains it might reject old data.
| Mode | Upgrade order (Confluent) |
|---|---|
BACKWARD / BACKWARD_TRANSITIVE | Consumers first, then writers of the new representation |
FORWARD / FORWARD_TRANSITIVE | Producers first; before deploying new-only readers, drain or transform retained old data and plan archive/retry reads |
FULL / FULL_TRANSITIVE | Either order within the checked schema scope |
NONE | Application-controlled rollout; no registry safety net |
Schema registry Must-know
In plain words: a registry is a versioned library of schemas with a librarian at the door: every new version is checked against the rules before it is shelved, and every message carries the shelf number of the schema it was written with.
Common misunderstanding: "With a registry, consumers always get the latest schema." The deserializer fetches the writer's schema by the id inside the message and resolves it against the consumer's own reader's schema; that is how a v1 consumer reads v2 data (Avro resolution, Protobuf unknown fields).
Definition: Confluent Schema Registry stores schemas under subjects. A schema ID identifies registered content, while a version orders revisions within a subject. Registration checks the subject policy before accepting a revision. The subject name comes from a subject name strategy:
| Strategy | Subject | Effect |
|---|---|---|
TopicNameStrategy (default) | <topic>-key / <topic>-value | Compatibility is scoped to that topic's key or value contract |
RecordNameStrategy | fully qualified record name | Many event types per topic; compatibility per type across topics |
TopicRecordNameStrategy | <topic>-<fully qualified record name> | Many types per topic, checked per topic |
Wire format. The classic Confluent framing prefixes keys and values with magic byte 0 and a four-byte big-endian schema ID; Protobuf also carries message indexes before its data. Newer serializers support a separate GUID-in-header format using __value_schema_id or __key_schema_id, with data alone in the payload. The following byte table describes only the classic prefix format; do not place its magic byte in a header-mode payload.
| Bytes | Content |
|---|---|
| 0 | Magic byte 0x00 (classic prefix format) |
| 1 to 4 | Schema id, big-endian (00 00 00 11 = 17) |
| 5 to x | Protobuf only: message indexes (which message in the .proto) |
| x+1 onward | Avro binary / Protobuf / JSON bytes |
producer serializer registry consumer deserializer
1 POST /subjects/orders-value/versions -> compatibility check (BACKWARD_TRANSITIVE)
2 compatible: id=17 / incompatible: 409
3 cache id 17; value = 00 | 00 00 00 11 | avro bytes -> Kafka
4 read bytes 1..4 -> id 17
5 GET /schemas/ids/17 <- (once, then cached)
6 resolve writer v2 against reader v1
7 unknown fields dropped, defaults filledSerializer settings that matter: auto.register.schemas (controls producer-side registration; set false in production and register from CI), use.latest.version (serialize with the latest registered version instead of deriving one from the object; only when auto-register is off), and latest.compatibility.strict (default true, re-checks compatibility at serialization time).
Products:
| Registry | Formats | API | Notes |
|---|---|---|---|
| Confluent Schema Registry | Avro, Protobuf, JSON Schema | Its own REST API (the de facto standard) | Default mode BACKWARD; contexts; Confluent Cloud managed |
| Apicurio Registry (Red Hat) | Avro, Protobuf, JSON Schema, AsyncAPI, OpenAPI, and more | Own API + "Confluent Schema Registry API v7" compatibility | "rules to ensure that uploaded content is valid, or is compatible" at global, group and artifact level |
| Karapace (Aiven) | Avro, JSON Schema, Protobuf | "Drop-in replacement" for Confluent's API ("compatible with Schema Registry 6.1.1 on API level") | Open source, also Kafka REST |
| Buf Schema Registry | Protobuf modules | Buf CLI / BSR | Breaking-change policy enforced at push |
Real scenarios: a data platform where every Kafka topic is Avro and Kafka Connect sinks need the schema to create table columns; a polyglot company where Go, Java and Python services share .proto files through a registry; a migration from schemaless JSON where the GUID-in-header format avoids breaking raw consumers.
Fix: register from CI, not from producers; set the mode per subject before the first consumer; use BACKWARD_TRANSITIVE (or FULL_TRANSITIVE for shared topics); never delete a schema id that data on a topic still references (a missing referenced ID prevents deserialization).
JSON Schema validation at the edge Important
In plain words: JSON has no built-in contract, so check incoming messages against a JSON Schema at the boundary of your service, before the handler acts on half-valid data.
Common misunderstanding: "Validate with additionalProperties: false to be safe." On the consumer side that rejects every future additive field. Use closed schemas for what you produce (catching accidental leaks in tests), open schemas for what you accept.
Definition: a JSON Schema (draft 2020-12) per (type, version) describes required properties, types, formats and ranges. Edge validation runs once per message, in the consumer's middleware or the gateway, and routes invalid messages to an invalid-message channel or DLQ (see dead-letter queue) instead of retrying them.
1 message arrives: type=order.placed version=2
2 load schema https://schemas.example.com/order.placed/v2.json (cached)
3 validate body: "/amount_minor": "The data (string) must match the type: integer"
4 invalid -> no retry (it will never become valid) -> invalid-message channel with errors attached
5 valid -> upcast/decode -> handlerReal scenarios: webhooks from a payment provider; events from a partner's Kafka topic; JSON from a mobile app's offline queue; a third-party SaaS emitting CloudEvents.
| Where | Tool |
|---|---|
| Laravel | opis/json-schema (draft 2020-12, 2019-09, 07, 06), see ValidateIncomingMessage.php |
| Go | a JSON Schema library such as santhosh-tekuri/jsonschema, or typed decoding plus explicit checks |
| Registry | Confluent JSON Schema serializer validates on produce and consume |
| Gateway | AsyncAPI-driven validators, API gateways with schema plugins |
Protobuf and Avro rules recap Important
The bytes behind these rules are explained in Serialization Formats: Protobuf wire format and binary formats (Avro). Here are only the rules a message designer must obey:
| Rule | Protobuf | Avro |
|---|---|---|
| Identity of a field | Field number; changing an existing number breaks identity | Field name (resolution matches names; aliases for renames) |
| Add a field | New field numbers allow binary evolution; old code can preserve unknown fields | Needs a reader default for BACKWARD when old writers did not supply the field |
| Remove a field | Reserve the removed number and name; never reuse them | Only fields that had a default (for FORWARD) |
| Rename | Wire-safe (number unchanged) but breaks JSON mapping and generated code | Breaking unless the reader declares an alias |
| Change a type | Only between wire-compatible scalars (int32/int64/bool, etc.) | Only promotions: int to long/float/double, string to bytes, etc. |
| Enums | Unknown values preserved; first value must be the zero default (UNSPECIFIED) | Writer symbol missing in reader: reader's enum default, else error |
| Defaults | Implicit zero values (proto3); use optional for presence | Explicit reader default for absent writer fields |
| Reserved range | Field numbers 19,000 to 19,999 are reserved for the Protobuf implementation | n/a |
Fix: reserved 3; reserved "amount"; in order_placed.proto; every Avro field added after v1 has a default.
Breaking-change detection in CI Important
In plain words: let the build fail when a pull request changes a schema incompatibly, instead of letting a consumer fail in production.
Common misunderstanding: "The registry check at produce time is enough." By then the code is merged and deployed; the producer crashes on its first message (or, with auto.register.schemas=true and mode NONE, nothing stops it).
Definition: two families of checks. Schema-diff tools compare the schema in the branch with the one on main or in a registry: buf breaking --against '.git#branch=main' for Protobuf, which detects differences under source, JSON and wire compatibility policies with rule categories FILE, PACKAGE, WIRE_JSON and WIRE. Registry dry runs call the compatibility endpoint without registering: POST /compatibility/subjects/<subject>/versions/latest returns {"is_compatible": true} (Confluent, Apicurio's Confluent-compatible API, Karapace).
1 PR changes order_placed.proto: field 3 type double -> string
2 CI: buf breaking --against '.git#branch=main'
3 order_placed.proto:9:3: Field "3" with name "amount" on message "OrderPlaced" changed type from "double" to "string".
4 CI fails; author reserves 3 and adds amount_minor = 4 instead
5 CI: curl POST /compatibility/subjects/orders-value/versions/latest -> {"is_compatible":true}
6 merge; CD registers the schema (auto.register.schemas=false in apps)(The buf error text in line 3 is illustrative of the rule FIELD_SAME_TYPE; we did not run buf for this page.)
| Format | CI check | Registry check |
|---|---|---|
| Protobuf | buf breaking (WIRE, WIRE_JSON, PACKAGE, FILE) | Confluent/Apicurio/Karapace compatibility endpoint |
| Avro | Avro SchemaCompatibility (Java) or registry Maven/Gradle plugins | Same endpoint |
| JSON Schema | Registry endpoint, or a JSON Schema diff tool | Same endpoint (policy + content model matter) |
| Laravel PHP DTOs | Contract tests: snapshot of toPayload() against the published JSON Schema | n/a |
Fix: add both checks to the pipeline of the producer repository, and a consumer contract test (owned by testing messaging) to each consumer repository.
AsyncAPI as the contract Good to know
In plain words: OpenAPI describes HTTP endpoints; AsyncAPI describes channels, operations and messages for brokers, so the event catalogue is a file in Git, not a wiki page.
Common misunderstanding: "AsyncAPI replaces the registry." It references schemas (JSON Schema, Avro, Protobuf) and documents channels, bindings and headers; the registry enforces compatibility at runtime. They complement each other.
Definition: AsyncAPI models asynchronous contracts independently of a single transport. Version 3.0 separates channels, operations (send/receive) and components.messages (with headers and payload schemas), plus per-protocol bindings (AMQP exchange/queue, Kafka topic/key).
asyncapi: 3.0.0
info: { title: Orders events, version: 2.0.0 }
channels:
orders:
address: orders
messages:
orderPlacedV2: { $ref: '#/components/messages/OrderPlacedV2' }
operations:
publishOrderPlaced:
action: send
channel: { $ref: '#/channels/orders' }
components:
messages:
OrderPlacedV2:
name: order.placed
headers:
type: object
required: [id, type, version, source]
properties:
version: { type: integer, const: 2 }
payload:
type: object
required: [order_id, amount_minor, currency]
properties:
order_id: { type: integer }
amount_minor: { type: integer }
currency: { type: string, pattern: '^[A-Z]{3}$' }Real scenarios: generating docs and an event catalogue; generating Go structs or PHP DTOs; mock servers for consumer tests; marking a field deprecated before removal.
Large payloads
Claim check Must-know
In plain words: do not push the sofa through the letterbox. Put it in a warehouse and post the receipt.
Common misunderstanding: "Just raise max_message_size / message.max.bytes." Large messages hurt everything around the limit too: broker memory and page cache, replication traffic, consumer fetch sizes, prefetch buffers, DLQ storage and retries that resend the whole blob. RabbitMQ's 4.0 release notes recommend external blob storage and message references for multi-MiB content.
Definition: the claim-check pattern (EIP): the "Check Luggage" component stores the body in a persistent store (S3, MinIO, GCS, Azure Blob, a database), puts a key (the claim check) in the message, and the consumer retrieves the body by that key. Add a content hash so the consumer can verify it got the right bytes, and a lifecycle rule so orphaned objects expire.
1 producer: body 40 MiB > MaxInline (256 KiB)
2 PUT s3://claims/01JD... (sha256 = 9f86d0...)
3 publish {headers: claim-check-uri=s3://claims/01JD..., body-sha256=9f86d0...}, body empty
4 consumer: GET s3://claims/01JD... ; sha256 matches -> process
5 consumer acks; object deleted by lifecycle rule after 7 days (not by the consumer: other subscribers may need it)
-- failure: step 2 ok, publish fails -> orphan object; lifecycle rule cleans it
-- failure: object deleted before a slow consumer reads it -> poison message; keep expiry > max consumer lag + DLQ retentionReal scenarios: invoices and PDF exports; images and video for a transcoding pipeline; a nightly CSV of 2 million price changes; ML feature vectors; email bodies with attachments; any Laravel job tempted to carry a file's contents.
| Store | Notes |
|---|---|
| S3 / MinIO / GCS / Azure Blob | Pre-signed URLs for consumers without bucket credentials; lifecycle expiry; versioning off for claim buckets |
| PostgreSQL / MySQL table | Fine up to MBs; transactional with the outbox; vacuum/bloat costs |
| Redis | Fast but memory-bound; set a TTL |
| Shared filesystem | Only inside one host or cluster; avoid |
A small table makes orphan cleanup and auditing explicit when the store is not self-expiring:
-- PostgreSQL: claim-check bookkeeping next to the outbox
CREATE TABLE claim_checks (
message_id uuid PRIMARY KEY,
object_uri text NOT NULL,
sha256 char(64) NOT NULL,
size_bytes bigint NOT NULL CHECK (size_bytes > 0),
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL
);
-- inserted in the same transaction as the outbox row that references it
INSERT INTO claim_checks (message_id, object_uri, sha256, size_bytes, expires_at)
VALUES ('0193a1c2-7e4f-7b2a-9c1d-5e6f7a8b9c0d', 's3://claims/0193a1c2...', '9f86d081...', 41943040,
now() + interval '7 days');
-- nightly: objects to delete (after max consumer lag + DLQ retention)
SELECT object_uri FROM claim_checks WHERE expires_at < now() ORDER BY expires_at LIMIT 1000;Fix: CheckLuggage / Retrieve in Go (claimcheck.go) against a BlobStore interface; in Laravel, Storage::disk('s3')->put() then publish the path and hash.
Message size limits and tuning Important
In plain words: every hop has a maximum size, and the smallest one wins.
Common misunderstanding: "Kafka's limit is 1 MB per message." It is per record batch after compression on the broker (message.max.bytes = 1048588), while the Java producer's max.request.size (1048576) also constrains the uncompressed batch. Raising one without the other, and without the consumers' fetch sizes, just moves the failure.
Definition and knobs:
| Hop | Knob | Default | Note |
|---|---|---|---|
| RabbitMQ | max_message_size (rabbitmq.conf) | 16777216 (16 MiB) in 4.x; 134217728 (128 MiB) in 3.13; max 536870912 | "Messages of larger size will be rejected with a suitable channel exception." |
| Kafka broker | message.max.bytes | 1048588 | Per-topic override max.message.bytes |
| Kafka producer | max.request.size | 1048576 | Client-side RecordTooLargeException |
| Kafka producer | compression.type | none (Java client); franz-go prefers snappy | Compression helps the broker limit, not max.request.size |
| Kafka consumer | max.partition.fetch.bytes, fetch.max.bytes | 1 MiB per partition; 50 MiB per fetch | An oversized first batch is still returned "to ensure that the consumer can make progress" |
| Kafka replication | replica.fetch.max.bytes | 1 MiB | Same progress exception for the first batch |
| franz-go | ProducerBatchMaxBytes | 1,000,012 bytes, "mirrors Kafka's max.message.bytes" | FetchMaxPartitionBytes 1 MiB |
| Redis | proto-max-bulk-len | 512mb | Also client-query-buffer-limit; a big entry blocks replication and AOF rewrite |
| CloudEvents | spec | Intermediaries must pass events up to 64 KiB | A good default budget for any event |
1 producer: 1.4 MB JSON, compression lz4 -> 300 KB batch
2 max.request.size 1048576 checks the UNCOMPRESSED size -> RecordTooLargeException
3 raise max.request.size to 2 MiB -> sent, broker sees 300 KB < 1048588 -> stored
4 same payload without compression -> broker MESSAGE_TOO_LARGE
-- set an application budget (e.g. 256 KiB) below every limit; above it, claim checkReal scenarios: a product-catalogue snapshot that grew past 1 MB after a new locale; a RabbitMQ 3.x to 4.x upgrade where 20 MiB messages that used to pass are now rejected; Redis memory alarms because one stream holds base64 images.
PII in messages Good to know
Every field you put in a message is copied into every consumer, every DLQ, every log and every backup for as long as retention lasts, so keep personal data out of payloads where an id will do (or encrypt it field-by-field); retention, crypto-shredding and right-to-erasure in immutable logs are covered in messaging security.
Mechanics
Where metadata physically lives Important
| Item | RabbitMQ (AMQP 0-9-1 basic properties) | Kafka record | Redis Streams entry |
|---|---|---|---|
| Message id | message-id (shortstr) | header id (or ce_id) | field id |
| Type | type (shortstr) | header type | field type |
| Timestamp | timestamp (seconds) | record timestamp (ms; CreateTime or LogAppendTime) | entry ID's ms part is the append time; put occurred-at as a field |
| Producer | app-id | header source | field source |
| Correlation | correlation-id | header | field |
| Content type / encoding | content-type, content-encoding | header | field |
| Expiry | expiration (per-message TTL) | none per record (topic retention) | none per entry (MAXLEN/MINID trimming) |
| Persistence | delivery-mode 2 | always (replication) | AOF/RDB settings |
| Custom | headers table: typed (string, int, bool, nested table, array) | headers: string key, byte[] value; duplicates allowed, order kept | flat field-value strings |
| Key | routing key (routing only) | record key (partition hash, compaction identity) | none |
Kafka headers were added by KIP-82 (JIRA KAFKA-4208) and are part of the record format, so they are replicated, compacted and returned to consumers like the value. They are ignored by brokers for routing. Because header values are bytes, agree on UTF-8 strings for envelope fields so every client library can read them.
The registry wire format, byte by byte Good to know
value bytes of one record (Avro, schema id 17, payload {"order_id":42}):
00 magic byte (format 0 = schema id in prefix)
00 00 00 11 schema id 17, big-endian
54 Avro long 42, zigzag varint (42*2 = 84 = 0x54)
-- Protobuf adds message indexes between the id and the data; a single 0x00 means "first message"Error messages you will see Must-know
| Where | Error | Meaning | Retry? |
|---|---|---|---|
| RabbitMQ | PRECONDITION_FAILED - message size N is larger than configured max size M (channel closed) | Body above max_message_size | No: shrink or claim check |
| Kafka broker | MESSAGE_TOO_LARGE (code 10): "The request included a message larger than the max message size the server will accept." | Batch above message.max.bytes / max.message.bytes | No |
| Kafka producer (Java) | RecordTooLargeException: The message is N bytes when serialized which is larger than 1048576, which is the value of the max.request.size configuration. | Client limit | No |
| Kafka broker | RECORD_LIST_TOO_LARGE (code 18) | Batch larger than the segment size | No |
| Schema Registry | 409 Conflict, "Incompatible schema" | New version violates the subject's mode | No: fix the schema |
| Schema Registry | Error code 42201, "Invalid schema" | Schema does not parse | No |
| Schema Registry (consumer) | "schema not found" | Schema id in the bytes was deleted | No: restore the schema |
| Avro decoder | missing field with no default: "an error is signalled" | Reader added a required field | No |
| Laravel | Illuminate\Database\Eloquent\ModelNotFoundException | SerializesModels re-query found no row | No (use DeleteWhenMissingModels) |
| Laravel | RuntimeException: Failed to serialize job of type [...] | A property cannot be serialize()d (closure, resource) | No |
| PHP | unserialize(): Error at offset / incomplete class | Job class renamed or removed while jobs were queued | No |
Go
Before
A persistence struct marshalled as the wire format. No id, type, timestamp or version, and the struct's field names are now an accidental public API.
// Package before publishes whatever struct the code happens to have, with no
// envelope, no version and no metadata. It compiles; the design is the problem.
package before
import (
"context"
"encoding/json"
amqp "github.com/rabbitmq/amqp091-go"
)
// Order is the persistence struct. Every field name and type is now a public
// contract with every consumer, though nobody decided that.
type Order struct {
ID int64 `json:"id"`
CustomerID int64 `json:"customer_id"`
Email string `json:"email"`
Total float64 `json:"total"`
Status string `json:"status"`
}
func PublishOrder(ctx context.Context, ch *amqp.Channel, o Order) error {
body, err := json.Marshal(o) // rename a field and consumers break silently
if err != nil {
return err
}
// No message id, no type, no timestamp, no correlation id, no schema
// version. The consumer guesses what this is from the queue name.
return ch.PublishWithContext(ctx, "", "orders", false, false, amqp.Publishing{
Body: body,
})
}After
The typed envelope: metadata and body are separate, Fields() flattens to string pairs for brokers that only have those, and Caused() derives child metadata so correlation and causation ids are never lost.
// Package after separates metadata (headers) from the payload (body), versions
// the payload, decodes tolerantly and moves large bodies out of the broker.
package after
import (
"strconv"
"time"
)
// Meta is everything a consumer or an operator needs without parsing the body.
type Meta struct {
ID string // unique per message (per Source); the dedup key
Type string // past-tense fact, e.g. "order.placed"
Version int // schema version of the body for this Type
OccurredAt time.Time
Source string // producing service, e.g. "orders-service"
CorrelationID string // groups every message of one business flow
CausationID string // id of the message that caused this one
TenantID string // routing, quotas and data isolation per customer
Key string // partition / ordering key, usually the aggregate id
Traceparent string // W3C trace context (see messaging-observability)
ContentType string // e.g. "application/json", "application/x-protobuf"
ClaimCheckURI string // set when the body was stored outside the broker
BodySHA256 string // integrity check for the claim-checked body
}
// Message is what the broker carries: headers plus opaque bytes.
type Message struct {
Meta Meta
Body []byte
}
// Header names used on brokers that only have string key/value pairs.
const (
hID, hType, hVersion = "id", "type", "version"
hOccurredAt, hSource = "occurred-at", "source"
hCorrelation, hCausation = "correlation-id", "causation-id"
hTenant, hKey = "tenant-id", "key"
hTraceparent, hContentType = "traceparent", "content-type"
hClaimCheck, hSHA256 = "claim-check-uri", "body-sha256"
)
// Fields flattens Meta into string pairs (Kafka headers, Redis stream fields).
func (m Meta) Fields() map[string]string {
f := map[string]string{
hID: m.ID,
hType: m.Type,
hVersion: strconv.Itoa(m.Version),
hOccurredAt: m.OccurredAt.UTC().Format(time.RFC3339Nano),
hSource: m.Source,
hCorrelation: m.CorrelationID,
hContentType: m.ContentType,
}
for k, v := range map[string]string{
hCausation: m.CausationID, hTenant: m.TenantID, hKey: m.Key,
hTraceparent: m.Traceparent,
hClaimCheck: m.ClaimCheckURI, hSHA256: m.BodySHA256,
} {
if v != "" { // optional headers are simply absent
f[k] = v
}
}
return f
}
// MetaFromFields is the inverse. Unknown keys are ignored, so a newer
// producer can add headers without breaking this consumer.
func MetaFromFields(f map[string]string) Meta {
version, _ := strconv.Atoi(f[hVersion])
at, _ := time.Parse(time.RFC3339Nano, f[hOccurredAt])
return Meta{
ID: f[hID], Type: f[hType], Version: version, OccurredAt: at,
Source: f[hSource], CorrelationID: f[hCorrelation],
CausationID: f[hCausation], TenantID: f[hTenant], Key: f[hKey],
Traceparent: f[hTraceparent], ContentType: f[hContentType],
ClaimCheckURI: f[hClaimCheck], BodySHA256: f[hSHA256],
}
}
// Caused builds the metadata for a message produced while handling parent:
// same correlation id and tenant, causation id = parent's id.
func Caused(parent Meta, id, typ string, version int, now time.Time) Meta {
return Meta{
ID: id, Type: typ, Version: version, OccurredAt: now,
Source: parent.Source, CorrelationID: parent.CorrelationID,
CausationID: parent.ID, TenantID: parent.TenantID,
Traceparent: parent.Traceparent, ContentType: parent.ContentType,
}
}A tolerant decoder with an upcaster chain: unknown fields inside a known version are allowed, but unsupported future versions are rejected. This teaching v1 contract is USD-only, nonnegative, below 1,000,000 dollars and limited to two decimal places. Go converts the raw JSON decimal exactly; PHP's already-decoded numeric input uses the same bounded monetary domain with a precision guard. Exponent notation is rejected by the Go wire parser; the PHP array API has already lost that lexical distinction. Neither example is a general currency converter or arbitrary-precision money library.
package after
import (
"encoding/json"
"fmt"
"regexp"
"strconv"
"strings"
)
type step struct {
Type string
From int
}
// Upcaster rewrites a stored body from version From to From+1.
type Upcaster func(json.RawMessage) (json.RawMessage, error)
// Upcasters maps (type, version) to the function that lifts it one version.
type Upcasters map[step]Upcaster
// DefaultUpcasters shows one change that additive evolution cannot express:
// "amount" (a float) became "amount_minor" (integer cents) plus a currency.
var DefaultUpcasters = Upcasters{
{Type: "order.placed", From: 1}: func(raw json.RawMessage) (json.RawMessage, error) {
var doc map[string]json.RawMessage
if err := json.Unmarshal(raw, &doc); err != nil {
return nil, err
}
amount, err := decimalMinorUnits(doc["amount"])
if err != nil {
return nil, err
}
delete(doc, "amount")
doc["amount_minor"], _ = json.Marshal(amount)
doc["currency"] = json.RawMessage(`"USD"`) // v1 only ever carried dollars
return json.Marshal(doc)
},
}
// Decode lifts an old body to the latest version this consumer knows, then
// unmarshals it. encoding/json ignores fields it does not know, which is
// exactly the tolerance we want; never call DisallowUnknownFields here.
func Decode[T any](up Upcasters, m Message, latest int) (T, error) {
var out T
if latest < 1 || m.Meta.Version < 1 || m.Meta.Version > latest {
return out, fmt.Errorf("unsupported version %d (latest %d)", m.Meta.Version, latest)
}
body := json.RawMessage(m.Body)
for v := m.Meta.Version; v < latest; v++ {
fn, ok := up[step{m.Meta.Type, v}]
if !ok {
return out, fmt.Errorf("no upcaster for %s v%d", m.Meta.Type, v)
}
var err error
if body, err = fn(body); err != nil {
return out, fmt.Errorf("upcast %s v%d: %w", m.Meta.Type, v, err)
}
}
// Additive fields within a known version remain tolerated.
// Future versions are rejected above because they may be breaking.
if err := json.Unmarshal(body, &out); err != nil {
return out, err
}
return out, nil
}
// The teaching v1 contract permits nonnegative USD amounts below 1,000,000,
// written as plain JSON decimal numbers with at most two decimal places.
// Reject exponent notation, extra precision and overflow instead of rounding.
var decimalAmount = regexp.MustCompile(`^(0|[1-9][0-9]{0,5})(\.[0-9]{1,2})?$`)
func decimalMinorUnits(raw json.RawMessage) (int64, error) {
value := strings.TrimSpace(string(raw))
if !decimalAmount.MatchString(value) {
return 0, fmt.Errorf("amount must be a nonnegative USD decimal below 1000000 with at most two decimals")
}
parts := strings.SplitN(value, ".", 2)
whole, err := strconv.ParseInt(parts[0], 10, 64)
if err != nil {
return 0, err
}
var cents int64
if len(parts) == 2 {
fraction := parts[1]
if len(fraction) == 1 {
fraction += "0"
}
cents, err = strconv.ParseInt(fraction, 10, 64)
if err != nil {
return 0, err
}
}
return whole*100 + cents, nil
}Its test, run with go test ./...:
package after
import (
"encoding/json"
"testing"
)
type v2 struct {
OrderID int64 `json:"order_id"`
AmountMinor int64 `json:"amount_minor"`
Currency string `json:"currency"`
}
func TestUpcastV1ToV2(t *testing.T) {
m := Message{Meta: Meta{Type: "order.placed", Version: 1}, Body: []byte(`{"order_id":42,"amount":19.99,"extra":true}`)}
got, err := Decode[v2](DefaultUpcasters, m, 2)
if err != nil {
t.Fatal(err)
}
if got.AmountMinor != 1999 || got.Currency != "USD" {
t.Fatalf("got %+v", got)
}
}
func TestMissingUpcasterFails(t *testing.T) {
m := Message{Meta: Meta{Type: "order.shipped", Version: 1}, Body: []byte(`{}`)}
if _, err := Decode[v2](DefaultUpcasters, m, 2); err == nil {
t.Fatal("expected error for unknown (type, version)")
}
}
func TestExactDecimalAmounts(t *testing.T) {
for _, tc := range []struct {
raw string
want int64
}{{"0", 0}, {"0.29", 29}, {"19.99", 1999}, {"1.1", 110}, {"999999.99", 99999999}} {
got, err := decimalMinorUnits(json.RawMessage(tc.raw))
if err != nil || got != tc.want {
t.Errorf("%s: got %d, %v; want %d", tc.raw, got, err, tc.want)
}
}
for _, raw := range []string{"-0.01", "1.005", "1000000", "1e3", "null", `"1.00"`, "", "999999999999999999999999"} {
if _, err := decimalMinorUnits(json.RawMessage(raw)); err == nil {
t.Errorf("expected rejection for %q", raw)
}
}
}
func TestRejectUnsupportedVersions(t *testing.T) {
for _, version := range []int{-1, 0, 3, 99} {
m := Message{Meta: Meta{Type: "order.placed", Version: version}, Body: []byte(`{"order_id":1,"amount_minor":1999,"currency":"USD"}`)}
if _, err := Decode[v2](DefaultUpcasters, m, 2); err == nil {
t.Errorf("accepted version %d", version)
}
}
}
func TestKnownVersionToleratesAddedFields(t *testing.T) {
m := Message{Meta: Meta{Type: "order.placed", Version: 2}, Body: []byte(`{"order_id":1,"amount_minor":29,"currency":"USD","coupon":"NEW"}`)}
got, err := Decode[v2](DefaultUpcasters, m, 2)
if err != nil || got.AmountMinor != 29 {
t.Fatalf("got %+v, %v", got, err)
}
}CloudEvents attribute mapping for Kafka (ce_) and AMQP 1.0 (cloudEvents_). This helper is not an AMQP 0-9-1 transport adapter:
package after
import (
"strconv"
"time"
)
// CloudEvents binary content mode: the event data stays the message body and
// every context attribute becomes a header. The prefix depends on the protocol
// binding: "ce_" for Kafka headers, "cloudEvents_" (or "cloudEvents:") for AMQP 1.0
// application properties. This is not an AMQP 0-9-1 protocol adapter.
const (
PrefixKafka = "ce_"
PrefixAMQP = "cloudEvents_"
)
// CloudEventsHeaders maps our Meta onto CloudEvents 1.0 attributes. id, source,
// specversion and type are REQUIRED; the rest are optional or extensions.
func CloudEventsHeaders(prefix string, m Meta) map[string]string {
h := map[string]string{
prefix + "specversion": "1.0",
prefix + "id": m.ID,
prefix + "source": m.Source,
prefix + "type": m.Type,
prefix + "time": m.OccurredAt.UTC().Format(time.RFC3339Nano),
}
if m.Key != "" {
h[prefix+"subject"] = m.Key // the entity the event is about
}
// Extension attributes: lower-case alphanumerics only, per the spec.
for k, v := range map[string]string{
"dataversion": strconv.Itoa(m.Version), "correlationid": m.CorrelationID,
"causationid": m.CausationID, "tenantid": m.TenantID,
"traceparent": m.Traceparent,
} {
if v != "" && v != "0" {
h[prefix+k] = v
}
}
// In binary mode the data content type is the native content-type header.
if m.ContentType != "" {
h["content-type"] = m.ContentType
}
return h
}Protobuf with registry-less header versioning. The contract:
// The contract both versions share. Field numbers are the wire identity:
// never change or reuse them; reserve what you delete.
syntax = "proto3";
package orders.v1;
message OrderPlaced {
reserved 3; // v1 "float amount", removed in v2
reserved "amount";
int64 order_id = 1;
string customer_id = 2;
int64 amount_minor = 4; // added in v2
string currency = 5; // added in v2
}And the Go side, hand-encoded with protowire so it builds without protoc; old code reading a v2 body keeps fields 4 and 5 as unknown bytes instead of failing:
// Package protoversion shows registry-less Protobuf versioning: the schema
// version and message type travel in headers, and evolution follows the
// field-number rules. It hand-encodes with protowire so it builds without
// protoc; real code uses the generated orders.v1 package.
package protoversion
import (
"fmt"
"math"
"google.golang.org/protobuf/encoding/protowire"
)
// Headers a consumer reads before touching the body. No registry is needed:
// the message type and the version are explicit.
func Headers(version int) map[string]string {
return map[string]string{
"content-type": "application/x-protobuf",
"proto-type": "orders.v1.OrderPlaced",
"version": fmt.Sprint(version),
}
}
// EncodeV1 writes the v1 shape: field 3 is a double "amount".
func EncodeV1(orderID int64, customer string, amount float64) []byte {
var b []byte
b = protowire.AppendTag(b, 1, protowire.VarintType)
b = protowire.AppendVarint(b, uint64(orderID))
b = protowire.AppendTag(b, 2, protowire.BytesType)
b = protowire.AppendString(b, customer)
b = protowire.AppendTag(b, 3, protowire.Fixed64Type)
return protowire.AppendFixed64(b, math.Float64bits(amount))
}
// EncodeV2 writes the v2 shape: field 3 is gone (reserved), 4 and 5 are new.
func EncodeV2(orderID int64, customer string, amountMinor int64, currency string) []byte {
var b []byte
b = protowire.AppendTag(b, 1, protowire.VarintType)
b = protowire.AppendVarint(b, uint64(orderID))
b = protowire.AppendTag(b, 2, protowire.BytesType)
b = protowire.AppendString(b, customer)
b = protowire.AppendTag(b, 4, protowire.VarintType)
b = protowire.AppendVarint(b, uint64(amountMinor))
b = protowire.AppendTag(b, 5, protowire.BytesType)
return protowire.AppendString(b, currency)
}
// OrderPlacedV1 is what an old consumer was generated from.
type OrderPlacedV1 struct {
OrderID int64
CustomerID string
Amount float64
Unknown []byte // generated Go code keeps unknown fields the same way
}
// DecodeV1 behaves like old generated code: known numbers are decoded, any
// other field is skipped and preserved, never an error.
func DecodeV1(b []byte) (OrderPlacedV1, error) {
var m OrderPlacedV1
for len(b) > 0 {
num, typ, n := protowire.ConsumeTag(b)
if n < 0 {
return m, protowire.ParseError(n)
}
b = b[n:]
switch {
case num == 1 && typ == protowire.VarintType:
v, n := protowire.ConsumeVarint(b)
if n < 0 {
return m, protowire.ParseError(n)
}
m.OrderID, b = int64(v), b[n:]
case num == 2 && typ == protowire.BytesType:
v, n := protowire.ConsumeString(b)
if n < 0 {
return m, protowire.ParseError(n)
}
m.CustomerID, b = v, b[n:]
case num == 3 && typ == protowire.Fixed64Type:
v, n := protowire.ConsumeFixed64(b)
if n < 0 {
return m, protowire.ParseError(n)
}
m.Amount, b = math.Float64frombits(v), b[n:]
default:
n := protowire.ConsumeFieldValue(num, typ, b)
if n < 0 {
return m, protowire.ParseError(n)
}
m.Unknown = append(m.Unknown, protowire.AppendTag(nil, num, typ)...)
m.Unknown = append(m.Unknown, b[:n]...)
b = b[n:]
}
}
return m, nil
}The claim check, against a small BlobStore interface that an S3 or MinIO client can satisfy:
package after
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
)
// BlobStore is whatever S3-like storage you have; the policy only needs this.
type BlobStore interface {
Put(ctx context.Context, key string, data []byte) (uri string, err error)
Get(ctx context.Context, uri string) ([]byte, error)
}
// MaxInline keeps messages far below every broker limit (RabbitMQ
// max_message_size 16 MiB by default, Kafka max.message.bytes about 1 MiB).
const MaxInline = 256 * 1024
// CheckLuggage stores a large body and leaves only a reference in the message.
func CheckLuggage(ctx context.Context, s BlobStore, m Message) (Message, error) {
if len(m.Body) <= MaxInline {
return m, nil
}
sum := sha256.Sum256(m.Body)
uri, err := s.Put(ctx, "claims/"+m.Meta.ID, m.Body)
if err != nil {
return m, fmt.Errorf("claim check store: %w", err)
}
m.Meta.ClaimCheckURI = uri
m.Meta.BodySHA256 = hex.EncodeToString(sum[:])
m.Body = nil
return m, nil
}
// Retrieve is the consumer half: fetch the body and verify it.
func Retrieve(ctx context.Context, s BlobStore, m Message) (Message, error) {
if m.Meta.ClaimCheckURI == "" {
return m, nil
}
body, err := s.Get(ctx, m.Meta.ClaimCheckURI)
if err != nil {
return m, fmt.Errorf("claim check fetch: %w", err)
}
sum := sha256.Sum256(body)
if hex.EncodeToString(sum[:]) != m.Meta.BodySHA256 {
return m, fmt.Errorf("claim check %s: body hash mismatch", m.Meta.ClaimCheckURI)
}
m.Body = body
return m, nil
}The Go angle
encoding/json is tolerant by default: Unmarshal silently drops keys that match no struct field, and only Decoder.DisallowUnknownFields turns that into an error. For consumers, never turn it on; for producers of public contracts, a strict round-trip in tests catches accidental drift. Beware the other direction too: a struct round-trip (decode, then encode again) loses the fields it did not model, so a forwarding service should pass the raw bytes or json.RawMessage through.
Go has no reflection-based serializer framework like Confluent's Java KafkaAvroSerializer. In practice you generate types from .proto (protoc-gen-go, or buf generate) or Avro (hamba/avro, linkedin/goavro), talk to the registry with a client library, and add the 5-byte prefix yourself (ConfluentFrame in kafka.go). Generated Protobuf code (google.golang.org/protobuf) preserves unknown fields on proto.Unmarshal and writes them back on proto.Marshal; protojson does not have that luxury, which is why JSON round-trips lose them. Generics keep the upcaster chain small: one Decode[T] and a map keyed by (type, version).
Laravel
Before
json_encode($order) publishes the Eloquent row: all columns, any loaded relations, and every future migration as a silent contract change.
<?php
namespace App\Listeners;
use App\Models\Order;
use Illuminate\Support\Facades\Queue;
class PublishOrderUpdated
{
public function handle(Order $order): void
{
// The whole Eloquent row becomes the wire format: every column, hidden
// attributes excluded, plus whatever relations happen to be loaded.
// Add a column in a migration and every consumer sees a new field;
// rename one and every consumer breaks. No id, no type, no version.
Queue::connection('rabbitmq')->pushRaw(json_encode($order), 'orders');
}
}After
An Envelope DTO for the metadata (now with source, tenant and key), an immutable versioned event class, and an upcaster map. Headers are plain strings so they map onto any broker.
<?php
namespace App\Messaging;
use DateTimeImmutable;
use DateTimeInterface;
use InvalidArgumentException;
use Illuminate\Support\Str;
/**
* Metadata that travels in headers, never inside the payload.
*/
final readonly class Envelope
{
public function __construct(
public string $id,
public string $type, // past-tense fact: "order.placed"
public int $version, // schema version of the payload
public DateTimeImmutable $occurredAt,
public string $source, // producing service: "orders-service"
public string $correlationId,
public ?string $causationId = null,
public ?string $tenantId = null,
public ?string $key = null, // partition / ordering key
public ?string $traceparent = null,
public array $payload = [],
) {}
public static function wrap(
OrderPlaced $event,
string $correlationId,
?string $causationId = null,
?string $tenantId = null,
): self {
return new self(
id: (string) Str::uuid7(),
type: OrderPlaced::TYPE,
version: OrderPlaced::VERSION,
occurredAt: new DateTimeImmutable(),
source: (string) config('app.name'),
correlationId: $correlationId,
causationId: $causationId,
tenantId: $tenantId,
key: 'order-'.$event->orderId,
traceparent: request()?->header('traceparent'),
payload: $event->toPayload(),
);
}
/** Flat string headers; optional ones are omitted, not sent empty. */
public function headers(): array
{
return array_filter([
'id' => $this->id,
'type' => $this->type,
'version' => (string) $this->version,
'occurred-at' => $this->occurredAt->format(DateTimeInterface::RFC3339_EXTENDED),
'source' => $this->source,
'correlation-id' => $this->correlationId,
'causation-id' => $this->causationId,
'tenant-id' => $this->tenantId,
'key' => $this->key,
'traceparent' => $this->traceparent,
'content-type' => 'application/json',
], fn (?string $v) => $v !== null);
}
public function body(): string
{
return json_encode($this->payload, JSON_THROW_ON_ERROR);
}
}
/**
* The event is a fact about the past and is immutable. The payload is an
* explicit, versioned contract, not the Eloquent row.
*/
final readonly class OrderPlaced
{
public const TYPE = 'order.placed';
public const VERSION = 2;
public function __construct(
public int $orderId,
public int $amountMinor,
public string $currency,
) {}
public function toPayload(): array
{
return [
'order_id' => $this->orderId,
'amount_minor' => $this->amountMinor,
'currency' => $this->currency,
];
}
/** Reads only the fields it knows; unknown keys are ignored on purpose. */
public static function fromPayload(array $p): self
{
return new self((int) $p['order_id'], (int) $p['amount_minor'], (string) $p['currency']);
}
}
/**
* Lifts an old payload one version at a time until it matches the class above.
*/
final class Upcasters
{
public static function toLatest(string $type, int $version, array $payload, int $latest): array
{
if ($latest < 1 || $version < 1 || $version > $latest) {
throw new InvalidArgumentException("Unsupported version {$version}; latest {$latest}");
}
$steps = self::steps();
for ($v = $version; $v < $latest; $v++) {
$step = $steps[$type][$v]
?? throw new InvalidArgumentException("No upcaster for {$type} v{$v}");
$payload = $step($payload);
}
return $payload;
}
/** @return array<string, array<int, callable(array): array>> */
private static function steps(): array
{
return [
OrderPlaced::TYPE => [
// v1 carried a float "amount" in dollars; v2 uses integer minor units.
1 => static function (array $p): array {
// JSON decoding already produced a PHP number. Bound the domain
// so binary floating-point error remains far below a cent.
// Reject negatives, extra precision and non-numeric coercions.
$amount = $p['amount'] ?? null;
if ((!is_int($amount) && !is_float($amount))
|| !is_finite((float) $amount) || $amount < 0 || $amount >= 1000000) {
throw new InvalidArgumentException('Invalid v1 USD amount');
}
$scaled = $amount * 100;
if (abs($scaled - round($scaled)) > 0.000001) {
throw new InvalidArgumentException('v1 USD amount must have at most two decimals');
}
$p['amount_minor'] = (int) round($scaled);
$p['currency'] = 'USD';
unset($p['amount']);
return $p;
},
],
];
}
}The SerializesModels pitfall, and the same job designed as a message:
<?php
namespace App\Jobs;
use App\Mail\InvoiceMail;
use App\Models\Order;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\DeleteWhenMissingModels;
use Illuminate\Queue\Attributes\WithoutRelations;
use Illuminate\Support\Facades\Mail;
/**
* Pitfall: the job payload is serialize()d PHP. SerializesModels (via
* Queueable) stores only Order's class + key + loaded relation names, and
* re-queries them when the job runs. Four consequences:
* - the row is re-read later, so the invoice shows the order as it is NOW,
* not as it was when the customer paid;
* - a deleted row throws ModelNotFoundException and the job fails;
* - every loaded relation is re-loaded in full (constraints are lost);
* - the payload names App\Jobs\SendInvoice and App\Models\Order: rename or
* move either class and jobs already in the queue cannot be unserialized.
*/
class SendInvoice implements ShouldQueue
{
use Queueable;
public function __construct(public Order $order) {}
public function handle(): void
{
Mail::to($this->order->customer->email)->send(new InvoiceMail($this->order));
}
}
/**
* Same job, designed as a message: the facts needed at dispatch time are
* copied in as scalars (a snapshot), relations are not serialized, a vanished
* row discards the job quietly, and a version lets handle() branch if the
* constructor shape ever has to change while old jobs are still queued.
*/
#[WithoutRelations]
#[DeleteWhenMissingModels]
class SendInvoiceV2 implements ShouldQueue
{
use Queueable;
public const VERSION = 2;
public int $version = self::VERSION;
public function __construct(
public Order $order,
public int $amountMinorAtPayment,
public string $currency,
) {}
public function handle(): void
{
Mail::to($this->order->customer_email)->send(
new InvoiceMail($this->order, $this->amountMinorAtPayment, $this->currency),
);
}
}JSON Schema validation at the edge with opis/json-schema: an exact allowlist maps (type, version) to trusted local schema URIs before the resolver runs. Incoming metadata must never choose arbitrary filesystem paths or remote URLs.
<?php
namespace App\Messaging;
use Illuminate\Support\Facades\Log;
use Opis\JsonSchema\Errors\ErrorFormatter;
use Opis\JsonSchema\Validator;
/**
* Edge validation for messages that come from other systems. Runs before the
* handler: a body that does not match the JSON Schema for its (type, version)
* is rejected to the invalid-message channel instead of half-processed.
* Uses opis/json-schema (draft 2020-12).
*/
final class ValidateIncomingMessage
{
private Validator $validator;
public function __construct()
{
// Reuse one validator: parsed schemas are cached inside it.
$this->validator = new Validator();
$this->validator->resolver()->registerPrefix(
'https://schemas.example.com/',
resource_path('schemas/'),
);
}
/**
* @param array<string, string> $headers
* @return array{ok: bool, errors: array<string, mixed>}
*/
public function check(array $headers, string $body): array
{
$type = $headers['type'] ?? 'unknown';
$version = $headers['version'] ?? '';
// Only exact, trusted (type, version) pairs select local resources.
// Never interpolate an untrusted type or URI into a filesystem resolver.
$schemas = [
'order.placed' => [
'1' => 'https://schemas.example.com/order.placed/v1.json',
'2' => 'https://schemas.example.com/order.placed/v2.json',
],
];
$schemaId = $schemas[$type][$version] ?? null;
if ($schemaId === null) {
return ['ok' => false, 'errors' => ['contract' => ['Unsupported type/version']]];
}
$data = json_decode($body, false, 64, JSON_THROW_ON_ERROR);
$result = $this->validator->validate($data, $schemaId);
if ($result->isValid()) {
return ['ok' => true, 'errors' => []];
}
$errors = (new ErrorFormatter())->format($result->error());
Log::warning('invalid message', ['id' => $headers['id'] ?? null, 'type' => $type, 'errors' => $errors]);
return ['ok' => false, 'errors' => $errors];
}
}A version on Laravel's own job payload, and a guard for rolling deploys:
<?php
namespace App\Providers;
use Illuminate\Queue\Events\JobProcessing;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\ServiceProvider;
/**
* Laravel's own job payload is a JSON envelope (uuid, displayName, job,
* maxTries, data.commandName, data.command = serialize()d object, createdAt).
* Queue::createPayloadUsing() merges extra top-level keys into it, which is
* where an app-wide payload version and the producing release can live.
*/
class QueuePayloadVersionServiceProvider extends ServiceProvider
{
public const PAYLOAD_VERSION = 2;
public function boot(): void
{
Queue::createPayloadUsing(fn (string $connection, ?string $queue, array $payload) => [
'payloadVersion' => self::PAYLOAD_VERSION,
'producerRelease' => (string) config('app.release', 'dev'),
]);
// During a rolling deploy an old worker can pick up a job pushed by a
// new release. JobProcessing fires before the job runs; fail() deletes
// it, so the worker skips it and it waits in failed_jobs until
// `php artisan queue:retry` once every worker runs the new release.
Event::listen(function (JobProcessing $event): void {
$version = $event->job->payload()['payloadVersion'] ?? 1;
if ($version > self::PAYLOAD_VERSION) {
Log::warning('job from a newer release', ['uuid' => $event->job->uuid()]);
$event->job->fail(new \RuntimeException("payloadVersion {$version} is newer than this worker"));
}
});
}
}The Laravel angle
Laravel's queue payload is itself a message envelope. The framework source (Illuminate\Queue\Queue::createObjectPayload) builds a JSON object with uuid, displayName, job, maxTries, backoff, timeout, retryUntil, deleteWhenMissingModels, data.commandName, data.command and createdAt, where data.command is serialize(clone $job) (encrypted when the job implements ShouldBeEncrypted). Two design consequences: the payload is PHP-only (no other language can read data.command), and it names your classes, so renaming or moving a job class while jobs are queued makes them undeserializable. Queue::createPayloadUsing() lets you merge your own top-level keys, such as a payload version.
SerializesModels replaces Eloquent models with identifiers and re-queries when the job runs. It is therefore a current-state reference rather than a dispatch-time snapshot. A deleted model can produce ModelNotFoundException; use #[DeleteWhenMissingModels] only if discarding the job is correct for the domain. Loaded relations can be fetched again without their original query constraints; #[WithoutRelations] or withoutRelations() avoids carrying those relations. Copy scalar values for facts that must remain frozen, such as the amount paid.
The Laravel 13 queue docs list the built-in drivers: "database, Amazon SQS, Redis, and Beanstalkd drivers, as well as a synchronous driver", plus null. RabbitMQ and Kafka come from packages, and their envelopes are the package's, not yours: the vladimir-yuldashev/laravel-queue-rabbitmq README documents a custom RabbitMQJob class precisely for "messages published by another application" that "won't respect Laravel's job payload schema". For cross-service events, publish an explicit DTO (as in After.php and Brokers.php) and keep job classes an internal detail. Versioned event classes (OrderPlaced::VERSION = 2) plus an upcaster map give the same shape as the Go code.
Broker differences
The same envelope has a different home on each broker, and each broker leaves a different gap for you to fill.
RabbitMQ
AMQP 0-9-1 gives every message basic properties: content-type, content-encoding, delivery-mode, priority, correlation-id, reply-to, expiration, message-id, timestamp, type, user-id, app-id, plus an open-ended headers table. Use the typed properties for the standard metadata so management UI, plugins and other clients understand them, and the table for version, causation-id, tenant-id and trace context. The official CloudEvents AMQP binding targets AMQP 1.0, using application properties prefixed cloudEvents_. Our RabbitMQ snippets use AMQP 0-9-1 and a custom envelope; copying that prefix into 0-9-1 headers does not implement the official binding. Use a documented mapping or a complete structured CloudEvent body. There is no schema registry in RabbitMQ: version lives in a header or in the routing key (order.placed.v2 on a topic exchange, which makes version-in-type routable: a v1 queue binds order.placed.v1, a v2 queue binds order.placed.v2). Size is policed by max_message_size: 16 MiB by default since 4.0 (previously 128 MiB in 3.13), rejected with a PRECONDITION_FAILED channel error.
package after
import (
"context"
amqp "github.com/rabbitmq/amqp091-go"
)
// PublishAMQP uses the AMQP basic properties for the standard metadata and the
// application headers table for everything else.
func PublishAMQP(ctx context.Context, ch *amqp.Channel, exchange, key string, m Message) error {
headers := amqp.Table{"version": int32(m.Meta.Version)}
for k, v := range map[string]string{
hCausation: m.Meta.CausationID, hTenant: m.Meta.TenantID,
hTraceparent: m.Meta.Traceparent,
hClaimCheck: m.Meta.ClaimCheckURI, hSHA256: m.Meta.BodySHA256,
} {
if v != "" {
headers[k] = v
}
}
return ch.PublishWithContext(ctx, exchange, key, false, false, amqp.Publishing{
MessageId: m.Meta.ID,
Type: m.Meta.Type,
Timestamp: m.Meta.OccurredAt,
AppId: m.Meta.Source,
CorrelationId: m.Meta.CorrelationID,
ContentType: m.Meta.ContentType,
DeliveryMode: amqp.Persistent,
Headers: headers,
Body: m.Body,
})
}
// FromDelivery rebuilds a Message; absent headers simply stay empty.
func FromDelivery(d amqp.Delivery) Message {
str := func(k string) string { s, _ := d.Headers[k].(string); return s }
version, _ := d.Headers["version"].(int32)
return Message{
Meta: Meta{
ID: d.MessageId, Type: d.Type, Version: int(version),
OccurredAt: d.Timestamp, Source: d.AppId, Key: d.RoutingKey,
CorrelationID: d.CorrelationId, ContentType: d.ContentType,
CausationID: str(hCausation), TenantID: str(hTenant),
Traceparent: str(hTraceparent),
ClaimCheckURI: str(hClaimCheck), BodySHA256: str(hSHA256),
},
Body: d.Body,
}
}From PHP, the cited laravel-queue-rabbitmq documentation does not establish the per-message property calls used here, so Brokers.php (below) goes to php-amqplib directly, whose AMQPMessage accepts message_id, type, app_id, correlation_id and application_headers.
Kafka
A record has a key, a value, a timestamp and headers: a list of string key to byte-array pairs. Metadata belongs there, the value stays a pure payload (which is what lets a registry serializer own it), and the key is the partition key, a routing decision. The registry is the Kafka ecosystem's own piece: schema id in the 5-byte prefix (or a GUID in __value_schema_id since Confluent Platform 8.1.1), compatibility enforced per subject at registration, TopicNameStrategy by default. Topic-per-major-version is natural here (orders.v1, orders.v2, each its own -value subject), and retention decides how long old versions stay readable, which is why BACKWARD_TRANSITIVE matters more on Kafka than anywhere else. The CloudEvents Kafka binding uses ce_ headers. Size: message.max.bytes 1048588 on the broker (per batch, after compression), max.request.size 1048576 on the producer.
package after
import (
"context"
"encoding/binary"
"github.com/twmb/franz-go/pkg/kgo"
)
// PublishKafka puts metadata in record headers and keeps the value as the
// payload only. The key decides the partition (see ordering-partitioning).
func PublishKafka(ctx context.Context, cl *kgo.Client, topic string, m Message) error {
rec := &kgo.Record{
Topic: topic,
Key: []byte(m.Meta.Key),
Value: m.Body,
Timestamp: m.Meta.OccurredAt,
}
for k, v := range m.Meta.Fields() {
rec.Headers = append(rec.Headers, kgo.RecordHeader{Key: k, Value: []byte(v)})
}
return cl.ProduceSync(ctx, rec).FirstErr()
}
// FromRecord is the consumer half.
func FromRecord(r *kgo.Record) Message {
f := make(map[string]string, len(r.Headers))
for _, h := range r.Headers {
f[h.Key] = string(h.Value)
}
meta := MetaFromFields(f)
meta.Key = string(r.Key) // the record key is the source of truth
return Message{Meta: meta, Body: r.Value}
}
// ConfluentFrame prefixes an already Avro-encoded payload with the Schema
// Registry wire format: magic byte 0, then the 4-byte big-endian schema id.
// Real code should use the registry's serializer; this shows what is on the wire.
func ConfluentFrame(schemaID uint32, avroBody []byte) []byte {
out := make([]byte, 5, 5+len(avroBody))
binary.BigEndian.PutUint32(out[1:], schemaID)
return append(out, avroBody...)
}mateusjunges/laravel-kafka exposes this as withHeaders() or new Message(headers:, body:, key:) followed by send(); see Brokers.php.
Redis Streams
An entry is an ID plus field-value pairs; there is no separate header section, so metadata and body are sibling fields, and the producer must pick a convention (body for the payload, everything else metadata) and document it. The entry ID's millisecond part is the append time on the Redis node, not the business time, so occurred-at still needs its own field. There is no registry, no per-message TTL, and no broker-side size policy beyond proto-max-bulk-len (512 MB), so schema discipline, version headers and claim checks are entirely yours; keep entries small because streams live in memory. Versioning by stream name (orders:v2) is the equivalent of topic-per-major-version.
package after
import (
"context"
"github.com/redis/go-redis/v9"
)
// PublishStream flattens the message into stream field-value pairs. A stream
// entry has no separate header section, so metadata and body share the pairs.
func PublishStream(ctx context.Context, rdb *redis.Client, stream string, m Message) (string, error) {
values := make(map[string]any, 12)
for k, v := range m.Meta.Fields() {
values[k] = v
}
values["body"] = m.Body
return rdb.XAdd(ctx, &redis.XAddArgs{Stream: stream, Values: values}).Result()
}
// FromStream rebuilds a Message from one entry.
func FromStream(x redis.XMessage) Message {
f := make(map[string]string, len(x.Values))
for k, v := range x.Values {
if s, ok := v.(string); ok && k != "body" {
f[k] = s
}
}
body, _ := x.Values["body"].(string)
return Message{Meta: MetaFromFields(f), Body: []byte(body)}
}In Laravel the Redis facade passes dynamic calls to the client, so Redis::xadd('orders', '*', $fields) works with the default phpredis client. The Laravel side of all three brokers:
<?php
namespace App\Messaging;
use Illuminate\Support\Facades\Redis;
use Junges\Kafka\Facades\Kafka;
use Junges\Kafka\Message\Message;
use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;
final class Publishers
{
/**
* RabbitMQ: standard metadata goes into AMQP basic properties, the rest into
* the application-headers table. The laravel-queue-rabbitmq README does not
* document setting these per message, so this is written against php-amqplib,
* the client library that package is built on.
*/
public static function rabbitmq(AMQPChannel $channel, Envelope $e): void
{
$message = new AMQPMessage($e->body(), [
'content_type' => 'application/json',
'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
'message_id' => $e->id,
'type' => $e->type,
'timestamp' => $e->occurredAt->getTimestamp(),
'app_id' => $e->source,
'correlation_id' => $e->correlationId,
'application_headers' => new AMQPTable(array_filter([
'version' => $e->version,
'causation-id' => $e->causationId,
'tenant-id' => $e->tenantId,
'traceparent' => $e->traceparent,
], fn ($v) => $v !== null)),
]);
$channel->basic_publish($message, 'orders', 'order.placed');
}
/** Kafka: headers on the record, payload in the value, aggregate id as key. */
public static function kafka(Envelope $e): void
{
Kafka::publish('broker')
->onTopic('orders')
->withMessage(new Message(
headers: $e->headers(),
body: $e->payload,
key: $e->key,
))
->send();
}
/**
* Redis Streams: no header section, so metadata and body are sibling
* field-value pairs. Assumes the default phpredis client, whose xadd takes
* (key, id, fields).
*/
public static function redisStream(Envelope $e): string
{
return Redis::xadd('orders', '*', [...$e->headers(), 'body' => $e->body()]);
}
}Beyond the three:
| Broker | Metadata slot | Registry | Size limit (default) |
|---|---|---|---|
| RabbitMQ | Basic properties + headers table | None | max_message_size 16 MiB (4.x) |
| Kafka | Record headers + key | Confluent / Apicurio / Karapace | message.max.bytes 1048588 |
| Redis Streams | Fields | None | proto-max-bulk-len 512 MB |
| NATS JetStream | NATS message headers (Nats-Msg-Id drives stream deduplication) | None built in | max_payload 1MB (up to 64MB, "not recommended to use values over 8MB") |
| Apache Pulsar | Message properties (key/value map) + a per-message "Schema version" | Built-in schemas per topic | 5 MB (maxMessageSize=5242880) |
| Amazon SQS | Message attributes | None | 1,048,576 bytes (1 MiB); the Extended Client Library stores larger payloads in S3 and sends a reference (claim check), up to 2 GB |
(Details of these brokers are on other brokers.)
In production systems
- Confluent Schema Registry rejects an incompatible schema at registration with
409 Conflict, and its default mode isBACKWARD: that protects new readers of old data, not old readers of new data. Disabling auto-registration moves registration to CI/CD; it does not change the direction of compatibility; Apicurio and Karapace answer the same REST calls. - RabbitMQ 4.0 lowered the default
max_message_sizefrom 128 MiB to 16 MiB and recommends a blob store for multi-MiB messages: a documented case of the broker vendor itself recommending a claim check. - Kafka enforces
max.message.bytesper topic (default 1048588) on the compressed batch andmax.request.sizeon the uncompressed batch in the client; both surprise teams that started with small payloads. - Protobuf keeps unknown fields on binary parse and serialization, so an old service in the middle of a pipeline forwards a new field instead of dropping it, unless it serializes to JSON, which the docs list as a way to lose them.
- Laravel stores job payloads as JSON whose
data.commandisserialize()d PHP, withSerializesModelsreplacing models by identifiers; this is visible inIlluminate\Queue\Queue::createObjectPayloadand theSerializesModelstrait.
Solving the classic problems
Rename a field
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Expand and contract | Add customer_ref, write both, readers move, later remove customer_id | No version bump | Two releases; both fields for a while |
| Avro alias | Reader declares "aliases": ["customer_id"] | Writer can switch at once | Avro only |
| Protobuf rename | Keep the number, change the name | Wire-safe | Breaks JSON mapping and generated code; buf breaking WIRE passes, WIRE_JSON fails |
Change a type or meaning (float amount to minor units)
| Solution | How | Advantage | Cost |
|---|---|---|---|
| New field, deprecate old | Add amount_minor + currency; keep amount until no reader | Additive | Producers must fill both |
| Version header + upcaster | version: 2; consumers upcast v1 | One topic, order kept | All consumers need the chain first (BACKWARD) |
| New type + dual-publish | order.placed.v2 alongside v1 | Nobody breaks | Double events; dedup by business id |
Split or merge events
order.updated becomes order.address-changed and order.cancelled: publish the new types next to the old one (dual-publish), move consumers one by one, then stop the old type. For stored events, upcasters may map one old event to several new ones; that belongs to event sourcing.
Add an enum value
Wire-safe in Protobuf (unknown value kept) and needs a reader default in Avro; in code, every consumer switch/match must have a default branch first. Ship the consumers' fallback, then the producer's new value: a FORWARD-style rollout even under a BACKWARD registry.
A payload that outgrew the broker
Claim check above an application budget (for example 256 KiB), compression for the rest, and a size metric per event type so growth is seen before the limit is hit.
Remove personal data from an event
In Avro, removing a field from the new reader is generally backward compatible because the reader no longer needs it. For FORWARD, old readers need an appropriate default when new writers omit their field; roll out those readers before removing the writer field. Old copies in retained logs are still there: that is the erasure problem on messaging security.
Laravel jobs during a deploy
Add a new job class instead of changing the constructor of a queued one; keep the old class until the queue is drained; version the payload with createPayloadUsing; never rename a job class with jobs in flight.
Choosing a strategy
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| One Laravel app, queued jobs only | Explicit job constructors with scalars; SerializesModels only for "current state" jobs | #[DeleteWhenMissingModels], #[WithoutRelations] | No cross-language consumers |
| Modular monolith, in-process events + queue | Versioned event classes, envelope DTO | Contract test per module | Modules evolve separately |
| Few internal consumers, JSON | Additive-only + version header + upcaster | JSON Schema in Git, CI snapshot tests | Cheapest safe setup |
| Many teams on Kafka | Avro or Protobuf + registry, BACKWARD_TRANSITIVE | auto.register.schemas=false, CI compatibility check | Rewind and replay always work |
| Shared topic, both sides evolve independently | FULL_TRANSITIVE | Optional fields only | Any upgrade order |
| Public / partner events | CloudEvents + version in type + dual-publish | AsyncAPI, JSON Schema at their edge | You cannot coordinate partners |
| Protobuf everywhere, no registry | Header proto-type + version, buf breaking in CI | reserved for removed fields | Registry-less but checked |
| Payloads above ~256 KiB | Claim check | Lifecycle expiry > max lag + DLQ retention | Brokers are not blob stores |
In architecture: from a single process to a distributed system
Monolith: one process, one database
In a single Laravel or Go process, "messages" are in-process events and queued jobs. The schema problem still exists, in two places: queued jobs survive a deploy (the payload written by release N is read by release N+1, or by N-1 during a rolling restart), and anything stored (failed jobs, delayed jobs, the jobs table) outlives the code that wrote it. Example: SendInvoice takes Order $order; a refactor moves App\Models\Order to App\Domain\Orders\Order, and 3,000 delayed jobs fail with incomplete-class errors. The simplest correct usage: small constructors with scalars or ids, no renames of queued classes, a payloadVersion key, and Event::dispatch of explicit event objects rather than models.
Modular monolith and multiple databases
Modules talk through events, still in one deployable, but owned by different teams. Each module publishes integration events with an envelope and a versioned DTO, distinct from its internal domain events; other modules never read its tables. Example: Billing listens to Orders\OrderPlaced (v2 DTO, toPayload()), never to the orders table; a contract test in Orders snapshots the JSON so a field rename fails the Orders build, not Billing's production. This is where you write the first JSON Schema files and the envelope class that later goes on a real broker unchanged.
Microservices
Now the envelope crosses processes and languages, and every evolution rule becomes mandatory. A concrete flow, with every message carrying correlation-id = checkout-7f3:
1 orders : order.placed v2 id=m1 cause=- key=order-42 (outbox row in the same tx)
2 payments : payment.captured id=m2 cause=m1 key=order-42
3 orders : order.confirmed id=m3 cause=m2
4 shipping : still on v1 -> reads order.placed (v1) from dual-publish
5 billing : on v2 -> reads order.placed.v2; inbox dedups on (source, id)
6 analytics : replays the topic from offset 0 -> upcasts v1 history to v2What survives the service boundary: the envelope (id for idempotency, correlation for the saga), the schema contract and the compatibility mode. What does not: shared classes (a Go struct or PHP class is not a contract unless generated from one), database transactions (use the outbox), and assumptions about who consumes (use AsyncAPI and the registry to find out). Service communication covers when to use a message at all.
Distributed data: replicas, caches, multi-region
A schema registry is itself a replicated service: Karapace, for example, keeps its schemas in the _schemas Kafka topic and runs a leader/replica pair, so a registry outage stops new producers and consumers from resolving unknown ids while cached ids keep working; deserializers cache by id. Across regions, replicate schemas with the same ids (Confluent Schema Linking or a single global registry), otherwise a record mirrored from region A carries an id that region B's registry does not know. Fat events are effectively replication: each consumer keeps a copy of producer state, with the same lag and read-your-writes questions as database replication. Claim-checked objects must be readable in every region that consumes the message (bucket replication, or regional claim buckets keyed by message id).
Scaling path: 1×, 10×, 100×
| Load | Design |
|---|---|
| 1× (one app, a few queues) | Envelope DTO, JSON, additive-only, version header, upcasters in code |
| 10× (several teams, Kafka or RabbitMQ) | JSON Schema or Protobuf in a shared repo, CI checks (buf breaking, registry dry run), AsyncAPI catalogue, claim check for big payloads, size metrics per type |
| 100× (many teams, replays, multi-region) | Registry with BACKWARD_TRANSITIVE/FULL_TRANSITIVE per subject, registration only from CI, Avro/Protobuf for size and speed, schema linking across regions, topic-per-major-version for redesigns, automated "consumers per version" dashboards before retiring a version |
Lab
Goal: evolve OrderPlaced from v1 (float amount) to v2 (amount_minor + currency) while an old consumer and a new consumer run side by side. Every lab command and output below is expected, not run in this authoring pass. Part A is an in-process illustration; Parts B–D require pre-existing broker/registry services. Compilation and focused snippet tests are separate checks; no Docker labs were run.
Part A: in-process (expected, not run). From docs/snippets/messaging/message-design-schema-evolution/go:
// Command lab evolves OrderPlaced from v1 to v2 in one process and shows what
// an old consumer and a new consumer see for each message. No broker needed:
// the "topic" is a slice, which is all a log is from a reader's point of view.
package main
import (
"encoding/json"
"fmt"
"time"
"academy/message-design-schema-evolution/after"
"academy/message-design-schema-evolution/protoversion"
)
// OldConsumerView is the struct the billing service was compiled with (v1).
type OldConsumerView struct {
OrderID int64 `json:"order_id"`
Amount float64 `json:"amount"`
}
// NewConsumerView is the latest model (v2): integer minor units + currency.
type NewConsumerView struct {
OrderID int64 `json:"order_id"`
AmountMinor int64 `json:"amount_minor"`
Currency string `json:"currency"`
}
func msg(id string, version int, body string) after.Message {
return after.Message{
Meta: after.Meta{
ID: id, Type: "order.placed", Version: version,
OccurredAt: time.Date(2026, 11, 25, 9, 30, 0, 0, time.UTC),
Source: "orders-service", Key: "order-42",
ContentType: "application/json",
},
Body: []byte(body),
}
}
func main() {
topic := []after.Message{
msg("m1", 1, `{"order_id":42,"amount":19.99}`),
// Additive v1.1: a new optional field; the version stays 1.
msg("m2", 1, `{"order_id":43,"amount":5.00,"coupon":"BF26"}`),
// Breaking v2: amount removed, amount_minor + currency added.
msg("m3", 2, `{"order_id":44,"amount_minor":1250,"currency":"EUR"}`),
}
fmt.Println("== old consumer (knows v1 only, tolerant reader) ==")
for _, m := range topic {
var v OldConsumerView
_ = json.Unmarshal(m.Body, &v)
note := ""
if m.Meta.Version > 1 {
note = " <- WRONG: amount silently 0; route v2 to a new type or dual-publish"
}
fmt.Printf("%s v%d %+v%s\n", m.Meta.ID, m.Meta.Version, v, note)
}
fmt.Println("== new consumer (v2 model + upcaster chain) ==")
for _, m := range topic {
v, err := after.Decode[NewConsumerView](after.DefaultUpcasters, m, 2)
fmt.Printf("%s v%d %+v err=%v\n", m.Meta.ID, m.Meta.Version, v, err)
}
fmt.Println("== protobuf: old generated code reads a v2 body ==")
v2 := protoversion.EncodeV2(44, "c-7", 1250, "EUR")
old, err := protoversion.DecodeV1(v2)
fmt.Printf("headers=%v\n", protoversion.Headers(2))
fmt.Printf("decoded=%+v unknownBytes=%d err=%v\n",
struct {
OrderID int64
CustomerID string
Amount float64
}{old.OrderID, old.CustomerID, old.Amount}, len(old.Unknown), err)
fmt.Println("== CloudEvents binary mode, Kafka headers ==")
ce := after.CloudEventsHeaders(after.PrefixKafka, topic[2].Meta)
for _, k := range []string{"ce_specversion", "ce_id", "ce_source", "ce_type", "ce_subject", "ce_dataversion"} {
fmt.Printf("%s=%s\n", k, ce[k])
}
}$ go run ./lab
== old consumer (knows v1 only, tolerant reader) ==
m1 v1 {OrderID:42 Amount:19.99}
m2 v1 {OrderID:43 Amount:5}
m3 v2 {OrderID:44 Amount:0} <- WRONG: amount silently 0; route v2 to a new type or dual-publish
== new consumer (v2 model + upcaster chain) ==
m1 v1 {OrderID:42 AmountMinor:1999 Currency:USD} err=<nil>
m2 v1 {OrderID:43 AmountMinor:500 Currency:USD} err=<nil>
m3 v2 {OrderID:44 AmountMinor:1250 Currency:EUR} err=<nil>
== protobuf: old generated code reads a v2 body ==
headers=map[content-type:application/x-protobuf proto-type:orders.v1.OrderPlaced version:2]
decoded={OrderID:44 CustomerID:c-7 Amount:0} unknownBytes=8 err=<nil>
== CloudEvents binary mode, Kafka headers ==
ce_specversion=1.0
ce_id=m3
ce_source=orders-service
ce_type=order.placed
ce_subject=order-42
ce_dataversion=2What it shows: (1) the additive field coupon in m2 is ignored by the old consumer, no error; (2) the breaking v2 message m3 is silently misread by the old consumer, which is exactly why a breaking change needs a new type, a dual-publish or a consumers-first rollout; (3) the new consumer reads all three through the upcaster; (4) old Protobuf code keeps the 8 bytes of fields 4 and 5 as unknown fields and does not fail.
Part B: register v1 and try an incompatible v2 (expected, not run). Confluent Schema Registry (or Karapace / Apicurio's Confluent API) on localhost:8081:
$ curl -s -X PUT -H 'Content-Type: application/vnd.schemaregistry.v1+json' \
--data '{"compatibility":"BACKWARD_TRANSITIVE"}' localhost:8081/config/orders-value
{"compatibility":"BACKWARD_TRANSITIVE"}
$ curl -s -X POST -H 'Content-Type: application/vnd.schemaregistry.v1+json' \
--data '{"schema":"{\"type\":\"record\",\"name\":\"OrderPlaced\",\"fields\":[{\"name\":\"order_id\",\"type\":\"long\"},{\"name\":\"amount\",\"type\":\"double\"}]}"}' \
localhost:8081/subjects/orders-value/versions
{"id":1}
# v2 adds amount_minor and currency WITHOUT defaults and drops amount
$ curl -s -X POST ... --data '{"schema":"...amount_minor long, currency string (no defaults)..."}' \
localhost:8081/compatibility/subjects/orders-value/versions/latest
{"is_compatible":false}
# same v2 with defaults: "amount_minor" default 0, "currency" default "USD"
$ curl -s -X POST ... localhost:8081/compatibility/subjects/orders-value/versions/latest
{"is_compatible":true}Expected: a new v2 reader cannot fill amount_minor from v1 data without a default (Avro resolution fails), so BACKWARD_TRANSITIVE rejects it; with defaults it passes. Note the semantic trap: compatible is not correct. amount_minor = 0 for old orders is valid Avro and wrong money, which is why the upcaster (Part A) or dual-publish is still needed for meaning changes.
Part C: old and new consumers on Kafka with dual-publish (expected, not run).
1 producer v2 writes to orders (type order.placed, version 1) AND orders.v2 (version 2) in one outbox tx
2 $ kcat -C -b localhost:9092 -t orders -f '%h %s\n' -c 1
id=m3,type=order.placed,version=1 {"order_id":44,"amount":12.50}
3 $ kcat -C -b localhost:9092 -t orders.v2 -f '%h %s\n' -c 1
id=m3,type=order.placed,version=2 {"order_id":44,"amount_minor":1250,"currency":"USD"}
4 old billing group on "orders" keeps working; new billing group on "orders.v2" starts
5 kafka-consumer-groups --describe shows lag 0 on both; old group is stopped, then the v1 topic retiresThis dual-publish example keeps USD in both versions. A v1 contract that was USD-only cannot faithfully represent a new EUR fact by dropping its currency; hold that new capability until legacy readers migrate, or explicitly exclude unrepresentable facts from the legacy contract.
Part D: size limits (expected, not run).
$ head -c 20000000 /dev/urandom > big.bin # 20,000,000 bytes
# RabbitMQ 4.x, default max_message_size 16 MiB: publish big.bin from any client (e.g. the Go PublishAMQP)
-> channel closed: PRECONDITION_FAILED - message size 20000000 is larger than configured max size 16777216
# Kafka, default max.request.size / message.max.bytes
$ kcat -P -b localhost:9092 -t orders big.bin
-> Message production error: MSG_SIZE_TOO_LARGE (Broker: Message size too large)Then rerun with the claim check (CheckLuggage in Go): the broker receives a ~1 KiB message with claim-check-uri and body-sha256, and the consumer fetches and verifies the object.
Common misconceptions
| Belief | Reality |
|---|---|
| JSON needs no schema | The schema exists as soon as a consumer reads a field; without a registry or contract test it is implicit and breaks in production |
BACKWARD protects old consumers | It protects new consumers reading old data; old consumers reading new data is FORWARD |
BACKWARD lets me replay the whole topic | Only against the previous version; replaying from offset 0 needs BACKWARD_TRANSITIVE |
| Adding a field is always safe | Avro needs a default; strict consumers reject unknown fields; new enum values break exhaustive switches |
| Compatible means correct | A default of 0 for amount_minor is compatible and wrong; meaning changes need upcasters or a new type |
| Protobuf renames are free | Wire-safe, but they break JSON mapping and generated code |
| Removing a Protobuf field lets me reuse its number | Never; reserved the number and the name |
| Put the version in the payload, it is simplest | The consumer must parse to know how to parse; headers or type names route without decoding |
| Thin events are always more decoupled | They move coupling to runtime calls and race with later state |
| Fat events are free | Every field is a promise, and every copy spreads PII |
| Just raise the broker's size limit | Memory, replication, fetch sizes and retries all suffer; use a claim check |
| Kafka's limit is per message | message.max.bytes is per record batch after compression; the producer checks uncompressed size |
SerializesModels sends the model | It sends class + key and re-queries at run time: current state, possible ModelNotFoundException |
| A registry means consumers use the latest schema | They resolve the writer's schema by id against their own reader's schema |
| CloudEvents forces a JSON wrapper | Binary mode keeps your body untouched and moves attributes to headers |
Cheat sheet
| Topic | What to remember |
|---|---|
| Envelope | id, type, version, occurred-at, source, correlation-id, causation-id, tenant-id, key, traceparent, content-type; no metadata in the body |
| Ids | source + id unique; reuse id on retry; correlation copied, causation = parent id |
| CloudEvents | Required: id, source, specversion, type; Kafka ce_, AMQP cloudEvents_; binary mode keeps body |
| Naming | Past tense, business fact, order.placed; commands are imperative and owned by the receiver |
| Thin vs fat | Thin = notification + callback; fat = event-carried state transfer; default to fact-sized |
| Internal model | Never serialize ORM rows; explicit DTO / .proto / .avsc |
| Evolution default | Additive-only + tolerant reader |
| Breaking change | Version header + upcaster (few consumers) or new type + dual-publish (many) or topic-per-major-version (redesign) |
| Modes | BACKWARD default (consumers first), FORWARD (producers first), FULL (any order), _TRANSITIVE (all versions) |
| Kafka + replay | BACKWARD_TRANSITIVE; Protobuf best practice too |
| Registry | Subject <topic>-value; magic byte 0 + 4-byte id; auto.register.schemas=false in prod |
| Protobuf | Numbers are identity; reserved deleted numbers and names; binary keeps unknown fields |
| Avro | Names are identity; every new field has a default; aliases for renames |
| CI | buf breaking --against '.git#branch=main'; registry /compatibility/... dry run |
| Size | RabbitMQ 16 MiB (4.x) / 128 MiB (3.x); Kafka 1048588 batch; budget ~64 to 256 KiB; claim check above |
| Laravel | Job payload = JSON + serialize(); SerializesModels re-queries; #[WithoutRelations], #[DeleteWhenMissingModels]; createPayloadUsing |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Which fields belong in the envelope rather than the payload, and why? Must-know
Answer
Answer: id, type, version, occurred-at, source, correlation-id, causation-id, tenant-id, key, traceparent, content-type. Brokers, inbox tables, tracers, DLQ tools and decoders need them without knowing the payload schema; a registry serializer can then own the body bytes.
2 — A consumer handling payment.captured (id m2, correlation m1) publishes order.confirmed. What are its correlation and causation ids? Important
Answer
Answer: Correlation m1 (copied unchanged), causation m2 (the id of the message being handled).
3 — Your registry is in BACKWARD mode. Which do you deploy first, producers or consumers? Must-know
Answer
Answer: Consumers. BACKWARD guarantees new readers can read old data, not that old readers can read new data, so Consumers first, then writers of the new representation.
4 — Why does Confluent recommend BACKWARD_TRANSITIVE for Protobuf, and why does it matter for Kafka replays? Good to know
Answer
Answer: Adding Protobuf message types can break forward compatibility; and plain BACKWARD checks only the previous version, while a replay from offset 0 reads every version still retained, so the new schema must read all of them.
5 — In Avro, you add currency without a default. Which mode rejects it and why? Important
Answer
Answer: BACKWARD (and FULL): a new reader reading old data finds no currency and no default, and resolution fails. FORWARD accepts it (old readers ignore the new field).
6 — You removed Protobuf field 3. What must you do with its number and name? Important
Answer
Answer: Mark both reserved (reserved 3; reserved "amount";) so nobody reuses them; reusing a number makes old data decode into the wrong field.
7 — When is a thin event the better choice than event-carried state transfer? Must-know
Answer
Answer: When consumers need only to know that something changed (cache invalidation), when the data is sensitive or large (send a reference), or when consumers must read the latest state anyway. Fat events win when consumers need the state as of the event and must work while the producer is down.
8 — What exactly is in the first five bytes of a Confluent-serialized Kafka value? Good to know
Answer
Answer: Magic byte 0, then the 4-byte big-endian schema id; Protobuf adds message indexes before the data.
9 — A 1.4 MB JSON event compresses to 300 KB with lz4. Which Kafka limit stops it with default settings? Important
Answer
Answer: The producer's max.request.size (1048576), which also constrains the uncompressed batch size: RecordTooLargeException. The broker's message.max.bytes would accept the compressed 300 KB batch.
10 — Name three pitfalls of passing an Eloquent model to a queued Laravel job. Must-know
Answer
Answer: The job sees the current row, not the state at dispatch; a deleted row throws ModelNotFoundException (use #[DeleteWhenMissingModels]); relations are re-loaded in full without their constraints (use #[WithoutRelations]). Also: the serialized payload names the classes, so renames break queued jobs.
11 — In a claim check, who deletes the stored object, and when? Important
Answer
Answer: Not the consumer (other subscribers or retries may need it): a lifecycle rule or a cleanup job, after a period longer than the maximum consumer lag plus DLQ retention.
12 — Why should a consumer's JSON Schema not use additionalProperties: false? Important
Answer
Answer: It rejects every additive change by the producer, which turns safe evolution into an outage. Closed schemas are for checking what you produce.
Glossary
| Term | Meaning |
|---|---|
| Envelope | Metadata carried next to the payload (headers/properties); EIP Envelope Wrapper |
| Payload / body | The serialized business fact |
| Header | A metadata key-value pair on a message (Kafka record header, AMQP property or headers entry, stream field) |
| Message id | Unique id per source; the dedup key |
| Correlation id | Id shared by every message of one business flow |
| Causation id | Id of the message whose handling produced this one |
| Tenant id | Customer/tenant the data belongs to |
| Partition key | Key that decides partition and ordering (Kafka record key) |
| traceparent | W3C trace-context header |
| CloudEvents | CNCF spec for event metadata; required id, source, specversion, type |
| Binary content mode | CloudEvents mode: data is the body, attributes are headers (ce_, cloudEvents_) |
| Structured content mode | CloudEvents mode: attributes and data in one document |
dataschema | CloudEvents URI of the schema data adheres to |
| Event notification | Thin event: id + type, consumers call back |
| Event-carried state transfer | Fat event carrying the state consumers need |
| Delta / snapshot event | Changed fields only / full current state of the entity |
| Integration event | Event published for other services, distinct from internal domain events |
| Tolerant reader | Consumer that ignores unknown and tolerates missing optional fields (Postel's law) |
| Additive-only | Evolution that only adds optional fields or new types |
| Upcaster | Pure function lifting a payload from version n to n+1 on read |
| Dual-publish | Producer emits old and new versions in parallel during migration |
| Topic-per-major-version | A new topic/stream/exchange per breaking version |
| Expand and contract | Add new field, migrate readers, then remove old field |
| Schema registry | Service storing versioned schemas and enforcing compatibility (Confluent, Apicurio, Karapace) |
| Subject | Registry namespace under which schema versions are kept (<topic>-value) |
| Subject name strategy | TopicNameStrategy, RecordNameStrategy, TopicRecordNameStrategy |
| Schema id | Registry-wide id of a schema, embedded in the message bytes |
| Magic byte | First byte of the Confluent wire format (0 = schema id in prefix) |
| Writer's schema / reader's schema | Avro: schema used to write the data / schema the reader expects; resolved at read time |
| BACKWARD / FORWARD / FULL | New reads old / old reads new / both |
| TRANSITIVE | Compatibility checked against all earlier versions |
| NONE | Compatibility checks disabled |
compatibilityPolicy | Confluent JSON Schema LENIENT or STRICT policy |
| Open / closed content model | JSON Schema additionalProperties true / false |
auto.register.schemas | Serializer setting that registers schemas from the client |
use.latest.version | Serializer setting that uses the latest registered schema |
| Field number | Protobuf field identity on the wire |
reserved | Protobuf declaration that forbids reuse of numbers/names |
| Unknown fields | Protobuf fields not in the reader's schema, preserved in binary |
| Avro alias | Alternative name that lets a reader match a renamed field |
| JSON Schema | Vocabulary for validating JSON (draft 2020-12) |
opis/json-schema | PHP JSON Schema validator |
buf breaking | Buf CLI command detecting breaking Protobuf changes (FILE, PACKAGE, WIRE_JSON, WIRE) |
| AsyncAPI | Machine-readable spec for message-driven APIs |
| Claim check | Store large payload externally, send a reference (EIP) |
| Object storage | S3, MinIO, GCS, Azure Blob |
max_message_size | RabbitMQ body limit (16 MiB default in 4.x, 128 MiB in 3.x) |
message.max.bytes / max.message.bytes | Kafka broker / topic max record batch size (1048588) |
max.request.size | Kafka producer request cap (1048576) |
proto-max-bulk-len | Redis max bulk string length (512mb) |
PRECONDITION_FAILED | AMQP error used for an oversized message |
RecordTooLargeException | Kafka client error for an oversized record |
SerializesModels | Laravel trait storing model identifiers instead of models in job payloads |
WithoutRelations / DeleteWhenMissingModels | Laravel job attributes: skip relations / drop job if model is gone |
createPayloadUsing | Laravel hook adding keys to every job payload |
| PII | Personally identifiable information |
References
- CNCF, CloudEvents specification, Primer: Versioning of CloudEvents, Kafka protocol binding, AMQP protocol binding
- Confluent, Schema evolution and compatibility, Formats, serializers and deserializers (wire format, subject name strategies), Schema Registry API reference
- Apicurio, Introduction to Apicurio Registry
- Aiven, Karapace README
- Apache Avro 1.11.1, Specification
- Protobuf, Language guide (proto 3): Updating a message type, unknown fields
- Buf, buf README (breaking-change detection)
- AsyncAPI, Specification 3.0.0
- Opis, JSON Schema validator, loader/resolver, README
- Hohpe & Woolf, Envelope Wrapper and Claim Check
- Martin Fowler, What do you mean by "Event-Driven"? (2017), Tolerant Reader
- Greg Young, Versioning in an Event Sourced System (table of contents only)
- RabbitMQ, configure.md (4.x), configure.md (3.13), 4.0.1 release notes,
rabbit_channel.erl(size check) - Kafka 4.1, Broker configs, Topic configs, Producer configs, Consumer configs, KIP-82 Add Record Headers,
Errors.java,KafkaProducer.java - Redis, Streams, XADD, redis.conf (
proto-max-bulk-len) - NATS, server configuration (
max_payload); Apache Pulsar, Messaging concepts; AWS, Amazon SQS message quotas - Go packages: amqp091-go, franz-go kgo, go-redis, protowire
- Laravel 13: Queues, Events, Redis; framework source
Queue.php,SerializesModels.php,Jobs/Job.php - Packages: laravel-queue-rabbitmq, php-amqplib
AMQPMessage, Laravel Kafka: message payload