Event-carried state transfer and claim check

Put the whole order in the event so consumers keep a local copy and answer without the source, then keep the large part out of the event with a claim check.

40 minutesChapter 3Events between services

A customer asks the notification service about order O-1001. The service needs the customer, the item and the status. If it has to ask the order service, it fails whenever the order service is down, and every question costs a request. If the event already told it everything, it can answer alone.

Event notification carries only the order id and the consumer fetches the current state; event-carried state transfer carries the whole Order and the consumer reads its local copy
Figure 3.1: What the consumer has to do after the event

Learning objectives

  • Carry the state a consumer needs inside the event instead of a reference.
  • Guard an upsert against events that arrive out of order.
  • Keep a large or optional payload out of the event with a claim check.
  • Fetch content on demand instead of embedding it in every message.
  • Explain why Kafka’s size limits force a claim check for unbounded payloads.

Why this matters

When a notification service has to call back for every detail, it can answer nothing while the order service is down, leaving a support rep with no order to read a waiting customer. An order with a large attachment can also fail to reach the topic without warning, so a team that depends on knowing about it never finds out. Both failures stay hidden until someone notices a missing answer or a missing order, often during an outage that has already become an incident.

Pattern: Event-Carried State Transfer

The problem

An event that carries only an order id makes every consumer call back for the data. That keeps one owner of the order and always returns current state, but it couples availability: a consumer cannot answer while the source is down. Each consumer also sends order-service one request per event it reads.

The solution

Event-carried state transfer puts the state a consumer needs into the event, so the consumer keeps its own copy and never calls the source.

Fowler’s “What do you mean by ‘Event-Driven’?” names this pattern and sets it beside event notification: the source stops calling consumers, and each consumer stops calling the source. The copy is the consumer’s own table, shaped for its questions and built only from events.

How Quarkus and Camel model it

order-service publishes OrderPlaced on edp.orders.placed and OrderCancelled on edp.orders.cancelled. Each carries the whole Order from the shared domain model and its OrderStatus, keyed by order id:

{"orderId":"O-1001","order":{"id":"O-1001","customerId":"CU-77","itemSku":"SKU-42","quantity":3,"amount":59.90},"status":"PLACED"}

The event goes out after the transaction has committed. A ProducerTemplate sends it into a direct: route that owns the topic:

from(DIRECT)
        .routeId("publish-order-placed")
        .setHeader(KafkaConstants.KEY, simple("${body.orderId}"))
        .marshal().json()
        .to("kafka:" + Topics.ORDERS_PLACED);

notification-service has one consumer route per topic. Both are the same route over a different topic, so they share a base class. An event that cannot be applied is logged and skipped, and the consumer moves on:

onException(IllegalArgumentException.class, JsonProcessingException.class)
        .handled(true)
        .log(LoggingLevel.WARN, "skipped record on " + topic + ": ${exception.message}");

from("kafka:" + topic + "?groupId=notification-order-copy")
        .unmarshal().json(OrderStateEvent.class)
        .bean(OrderCopies.class, "apply");

OrderStateEvent lists only the fields this consumer reads and ignores the rest. OrderCopies.apply is a Panache upsert into notifications.order_copy, keyed by order id. It does two things beyond copying fields. An event with no order state throws IllegalArgumentException, which is how the thin event is refused. And it ignores an event that would move the status backwards, using the same OrderStatus.canMoveTo rule the lifecycle uses. A late OrderPlaced then cannot undo a cancellation that arrived first. The two topics have no order between them, and a copy that applied events in arrival order would regress.

GET /order-copies/{id} reads the table through Quarkus REST. The copy needs no HTTP client, no retry and no circuit breaker, because it makes no call.

What the copy costs

The copy is as fresh as the last event applied. A reader that needs the current status the instant an order changes cannot use it. Consumers read the event’s fields, so the producer cannot rename one without changing them. With event notification each use costs a request and returns current state; with state transfer the consumer stores the data and makes no request.

Pattern: Claim Check

The problem

An event that carries state grows with the state. An order that can hold a gift message, a delivery note or an attached document gives the event a variable, unbounded size. Every consumer of the topic receives the whole event, attachment included, whether or not it reads the attachment. Kafka bounds the size: the producer’s max.request.size defaults to 1048576 bytes and the broker’s message.max.bytes to 1048588. A payload that grows past the smaller one is rejected by the producer.

The solution

A claim check stores the large part of a message in a persistent store and passes a reference to it, so only the consumers that need the content fetch it.

Hohpe and Woolf’s Claim Check keeps the bulky data in a store and sends a key that later steps use to fetch it. Camel has a Claim Check EIP, but it stashes content to retrieve later in the same route, so it cannot carry content from one service to another. Between services the store has to be shared: here, PostgreSQL.

order-service stores the attachment in orders.claim_check and publishes a small event with the claim id and size; notification-service fetches the content from GET /claims/{id} only when asked
Figure 3.2: Store, publish the claim, fetch on demand

How Quarkus and Camel model it

A request to POST /orders may carry an attachment next to the order fields. order-service stores it in orders.claim_check (id, order_id, content, created_at) in the same transaction as the order, and the event carries a Claim in place of the content:

{"orderId":"O-1002","order":{...},"status":"PLACED","claim":{"id":"2f0c9a1e-...","size":102400}}

The event stays under 1 KB whether the attachment is one line or 100 KB. Any holder of the claim id can read the content from GET /claims/{id} on order-service. notification-service records the claim with the copy and fetches the content only for GET /order-copies/{id}/attachment, through a Quarkus REST client. The order fields never need that call.

The producer’s request limit is set to 64 KB here, far below Kafka’s default, so that a 100 KB attachment shows the limit:

camel.component.kafka.max-request-size=65536

With ORDER_EVENTS_ATTACHMENT=inline the same attachment goes inside the event instead. The producer refuses it with RecordTooLargeException, POST /orders returns 502 and nothing reaches the topic. The order itself has already committed, because the event is published after the commit. That window between the commit and the publish is a cost of publishing after commit, and it is the same for every event, large or small.

What the claim check costs

The content now lives in a second place with its own lifecycle. Someone has to decide when a claim expires, and these claims never expire. A consumer that needs the content depends on the source again: with order-service stopped, the copy answers but the attachment returns 503. The three designs compare as follows:

  Notification only Full state Claim check
Event size An id Grows with the state Small and fixed, plus a claim
Coupling Consumer calls the source for everything Consumer depends on the event’s fields Fields in the event, large part by claim
Source down Consumer cannot answer Consumer answers Consumer answers, but not the large part
Freshness Current at fetch As old as the last event Fields as old as the last event, content as stored
Producer limit Never reached Reached when state grows Not reached by the attachment
Choose it when One owner must answer with current data Consumers read most of the state and it is small Few consumers need a large, optional part

Build, run, observe

(cd examples/domain-model && mvn -B -q install)
cd examples/03-event-carried-state-transfer
mvn -B verify
./verify.sh

verify.sh places orders, one with a 100 KB attachment, and stops order-service. Watch the copy keep answering while order-service is down and the attachment return 503 until it is back. It prints 30/30 checks passed.

Try one change and rerun:

  • ORDER_EVENTS_CARRY_STATE=false ./verify.sh: the event holds only the order id and every copy answers 404.
  • ORDER_EVENTS_ATTACHMENT=inline ./verify.sh: the producer refuses the 100 KB event and the order is never placed on the topic.
  • Remove the status guard from OrderCopies.apply: a late OrderPlaced turns a cancelled copy back into PLACED.

When not to use it

Do not copy state that must be current. A balance, a stock level or a payment status that decides something right now belongs with its owner, and event notification with a fetch keeps one answer. Do not copy state into many consumers that must each keep it correct: every copy has to apply every change, and one that misses an event answers with old data. Do not carry state whose shape you cannot hold stable: consumers read the event’s fields, so renaming or removing one breaks them.

Do not use a claim check for small payloads. A reference costs a second store, a second call and a lifecycle for the stored content, and a claim kept after its order is gone still takes space, and no service is responsible for deleting it. If every consumer reads the attachment, put it in the event and raise the limits, or store it once and let them all fetch it. And a claim check does not make the publish atomic with the commit: the order can commit and the event can still fail.

Common pitfalls

  • Skipping the status guard in the upsert lets a late event move a copy backwards, undoing a more recent cancellation.
  • An event that fails validation because it carries no order state is logged and skipped rather than retried, so a malformed producer can leave a copy permanently missing with no alarm raised.
  • Inlining a large attachment instead of keeping it behind a claim trips the producer’s request-size limit after the order has already committed, so the order exists with no event to announce it.
  • Leaving claim records with no expiry policy lets stored content accumulate with nothing responsible for removing it.

🤖 Explore with your agent “In examples/03-event-carried-state-transfer, place one Order with no attachment and one with a 100 KB attachment, then read both events from edp.orders.placed. For each, say whether the OrderCopy that OrderStateEvent builds can answer GET /order-copies/{id} with order-service stopped, and whether the Claim holds the attachment size, and apply the rule: carry state the consumer reads on every use, keep a large optional part behind a claim, and fetch current data from the owner when staleness is not acceptable.” Check: both copies answer with order-service stopped, the 100 KB event is under 1 KB and holds a claim, and only the attachment request fails.

References