On this page
- 1. · Concept & Definition
- 2. · Why It Matters
- 3. · How It Works
- 4. · Java / Jakarta EE Code Examples
- Deep Dive — Designing a Message Contract
- Deep Dive — Large Payloads and the Claim Check
- 5. · Configuration, Defaults & Diagnostics
- 6. · Production Usage Patterns
- 7. · Common Pitfalls & Misconceptions
- 8. · Best Practices
- 9. · Architect's Perspective & Trade-offs
- 10. · Interview Q&A
1· Concept & Definition
A JMS message has three parts: headers set by the provider or sender, properties set by the application, and a body whose type is one of five: TextMessage, BytesMessage, MapMessage, StreamMessage or ObjectMessage. The body type is a contract between producer and consumer, so it is an architectural decision, not a coding preference.

2· Why It Matters
- The payload format determines who can consume the message — one language or many.
- It determines how the contract evolves: adding a field must not break existing consumers.
ObjectMessagecarries a deserialisation risk and a class-version coupling that has caused real incidents.- Properties, not the body, are what the broker can filter on, so payload design affects routing.
- Message size affects broker memory, paging and throughput more than most teams expect.
3· How It Works
TextMessage
A TextMessage carries a String, in practice JSON or XML. It is the default choice: any language can read it, it is inspectable in broker consoles and logs, and it evolves cleanly if consumers ignore unknown fields. Its cost is size and parsing time compared with binary formats.
BytesMessage
A BytesMessage carries raw bytes, used for binary encodings such as Avro, Protobuf or compressed payloads, and for passing through opaque content. It is the fastest and most compact option, and it requires a schema agreement outside the message — usually a schema registry — to stay readable.
MapMessage
A MapMessage carries name/value pairs of primitives and strings. It is convenient for flat data and is readable by JMS clients in any language, but it has no schema, no nesting, and no standard representation outside JMS — which makes it a poor fit once non-JMS consumers appear.
StreamMessage
A StreamMessage carries an ordered sequence of primitives, read in the same order they were written. It exists mostly for historical reasons; any change to the field order breaks every consumer, so new designs should not use it.
ObjectMessage
An ObjectMessage carries a serialised Java object. It looks convenient and is the type most often regretted: producer and consumer must share the class and a compatible serialVersionUID, non-Java consumers are excluded, and deserialising untrusted input is a well-known remote-code-execution vector. Brokers now require explicit allow-lists of deserialisable classes for exactly this reason.

| Type | Payload | Interoperable | Evolvable | Verdict |
|---|---|---|---|---|
TextMessage (JSON) | String | Yes | Yes, with tolerant readers | Default choice |
BytesMessage (Avro/Protobuf) | byte[] | Yes, with a schema | Yes, with schema rules | High volume, strict contracts |
MapMessage | name → primitive | JMS clients only | Weak | Simple internal flows |
StreamMessage | ordered primitives | JMS clients only | No | Avoid in new designs |
ObjectMessage | Java object | No | No | Avoid — security and coupling |
4· Java / Jakarta EE Code Examples
// TextMessage with JSON — the default
record OrderPlaced(String eventId, long orderId, String status,
BigDecimal total, Instant occurredAt, int schemaVersion) { }
public void publish(OrderPlaced event) {
String json = jsonb.toJson(event);
context.createProducer()
.setProperty("eventType", "OrderPlaced") // for selectors
.setProperty("schemaVersion", event.schemaVersion())
.setProperty("orderId", event.orderId())
// JMSContext creates a TextMessage
.send(ordersEvents, json);
}// Consuming without casting (JMS 2.0+)
@Override
public void onMessage(Message message) {
try {
if (!(message.getStringProperty("eventType").equals("OrderPlaced"))) return;
String json = message.getBody(String.class);
OrderPlaced event = jsonb.fromJson(json, OrderPlaced.class);
handler.handle(event);
} catch (JMSException e) {
throw new EJBException(e);
}
}// BytesMessage for a binary encoding
// schema id embedded or in a property
byte[] encoded = avroEncoder.encode(event);
BytesMessage message = context.createBytesMessage();
message.writeBytes(encoded);
message.setIntProperty("schemaId", avroEncoder.schemaId());
context.createProducer().send(ordersEvents, message);
// consumer
byte[] raw = message.getBody(byte[].class);
OrderPlaced event = avroDecoder.decode(raw, message.getIntProperty("schemaId"));// MapMessage — flat, schema-less
MapMessage m = context.createMapMessage();
m.setLong("orderId", 42L);
m.setString("status", "PLACED");
m.setDouble("total", 199.90);
context.createProducer().send(ordersEvents, m);// ObjectMessage — and why brokers now restrict it
ObjectMessage om = context.createObjectMessage(new OrderPlacedDto(...)); // avoid
# Artemis / ActiveMQ client configuration required to deserialise at all:
-Dorg.apache.activemq.SERIALIZABLE_PACKAGES=com.acme.events
# an unrestricted setting has been the root cause of remote-code-execution incidentsDeep Dive — Designing a Message Contract
| Element | Guidance |
|---|---|
| Message identity | A unique event id in the payload, used for deduplication (Chapter 2) |
| Type and version | eventType and schemaVersion as properties, so consumers can filter and branch |
| Timestamp | The business time the event occurred, not just JMSTimestamp |
| Correlation | A correlation or trace id propagated across the whole flow |
| Payload | The data a consumer needs, not the producer's internal entity |
| Size | Kilobytes, not megabytes — send a reference for large content |
Two rules make contracts survivable. Producers only add: new optional fields, never removed or repurposed ones. Consumers are tolerant readers: unknown fields are ignored, missing optional fields have defaults. When a breaking change is unavoidable, publish both versions to different destinations (or with different eventType values) until every consumer has migrated.
// Tolerant reader with explicit version handling
OrderPlaced event = switch (message.getIntProperty("schemaVersion")) {
case 1 -> upgradeV1(jsonb.fromJson(json, OrderPlacedV1.class));
case 2 -> jsonb.fromJson(json, OrderPlaced.class);
// → dead-letter, alert
default -> throw new UnsupportedSchemaException(version);
};Deep Dive — Large Payloads and the Claim Check
Brokers are optimised for many small messages. A message of several megabytes consumes broker memory per delivery, triggers paging, slows failover and inflates redelivery cost. The standard remedy is the claim check: store the content in object storage or a database and send a reference.
| Payload size | Approach | Notes |
|---|---|---|
| < 100 KB | Send inline | Normal case |
| 100 KB – 1 MB | Inline with compression | Measure broker memory and paging |
| > 1 MB | Claim check | Store content, send a URL or id plus a checksum |
| Streaming content | Not a message | Use object storage plus a notification message |
// Claim check
// S3, blob store, database
String key = objectStore.put(largeDocument);
context.createProducer()
.setProperty("contentType", "application/pdf")
.setProperty("sizeBytes", largeDocument.length)
.send(documentsQueue, jsonb.toJson(new DocumentReady(eventId, key, sha256)));
// the consumer fetches by key, verifies the checksum,
and deletes or archives afterwards5· Configuration, Defaults & Diagnostics
| Concern | Setting or check |
|---|---|
| Maximum message size | Broker address setting; reject oversized payloads at the producer |
| Serialisation allow-list | SERIALIZABLE_PACKAGES (only if ObjectMessage is unavoidable) |
| Compression | Application-level; measure before enabling |
| Schema registry | For Avro/Protobuf payloads; version compatibility rules |
| Property types | Selectors compare typed values — a string "1000" is not the number 1000 |
| Encoding | UTF-8 for text payloads, stated in the contract |
| Symptom | Cause |
|---|---|
MessageFormatException on getBody | Body type differs from the expected class |
| Consumer fails after a producer release | Breaking change to the payload contract |
ClassNotFoundException on consume | ObjectMessage with a class the consumer does not have |
| Broker paging and slow delivery | Large messages or an oversized backlog |
| Selector never matches | Property set with the wrong type, or filtering on body content |
6· Production Usage Patterns
- JSON
TextMessageas the standard, witheventType,schemaVersion,eventIdand a trace id as properties. - Binary payloads with a schema registry where volume justifies them.
- A published contract per message type, versioned in the same repository as the producer.
- Claim check for anything above roughly a megabyte.
- Contract tests that verify a consumer still parses the producer's current and previous versions.
7· Common Pitfalls & Misconceptions
ObjectMessage— coupling plus a deserialisation attack surface.- Sending internal entities as the payload, exposing the producer's model.
- Breaking changes without versioning, which fail only when the consumer is redeployed.
- Routing data only in the body, so selectors cannot be used.
- Multi-megabyte messages, which degrade the broker for everyone.
- Assuming property types:
setStringProperty("amount", "1000")cannot be compared numerically in a selector.
8· Best Practices
- Use
TextMessagewith JSON unless volume or strictness demands a binary format. - Put identity, type, version and routing data in properties.
- Design producers to add only, and consumers to ignore what they do not know.
- Keep messages small; send references to large content.
9· Architect's Perspective & Trade-offs
| Criterion | JSON text | Avro / Protobuf bytes |
|---|---|---|
| Interoperability | Universal | Needs the schema and a library |
| Size and speed | Larger, slower to parse | Compact and fast |
| Schema enforcement | By convention or JSON Schema | Enforced by the registry |
| Debuggability | Readable in any console | Needs tooling to decode |
| Evolution | Tolerant readers | Formal compatibility rules |
| Best for | Most enterprise messaging | High volume, strict contracts |
10· Interview Q&A
What are the five JMS message body types?
TextMessage, BytesMessage, MapMessage, StreamMessage and ObjectMessage, alongside the plain Message, which has headers and properties but no body. TextMessage carries a string, in practice JSON or XML, and is the default choice. BytesMessage carries raw bytes for binary encodings such as Avro or Protobuf. MapMessage holds flat name/value pairs of primitives and strings, and StreamMessage an ordered sequence of primitives that must be read back in the order written. ObjectMessage carries a serialised Java object and should be avoided because of class coupling and deserialisation attacks. The body type is part of the contract between producer and consumer, so choosing it is an architectural decision.
What are message properties used for?
Properties are application-defined name/value metadata carried alongside the headers, typed as boolean, numeric or string values. Their main use is routing: the broker evaluates a message selector such as eventType = 'OrderPlaced' AND region = 'EU' against properties without parsing the body, so each consumer receives only what it needs. They also let consumers branch or reject quickly, for example on schemaVersion, and carry cross-cutting data such as an event id for deduplication or a trace id for observability. Types matter: a selector testing amount > 1000 never matches a value set with setStringProperty. Keep properties small, and never move business payload into them just to make it filterable.
Why is ObjectMessage discouraged?
It couples the producer and consumer to the same Java class and a compatible serialVersionUID, so a field change on one side can break consumption at run time with InvalidClassException or ClassNotFoundException. It excludes non-Java consumers, which matters as soon as another team or a bridge to Kafka needs the data, and the payload cannot be read in broker consoles. Worst of all, deserialising untrusted bytes is a well-known remote-code-execution vector through gadget chains, which is why ActiveMQ and Artemis refuse to deserialise unless an allow-list such as SERIALIZABLE_PACKAGES is configured. JSON in a TextMessage, or a schema-based binary format, gives the same convenience without those risks.
What does getBody(Class) provide?
getBody(Class), added in JMS 2.0, returns the payload as the requested type without casting the Message to TextMessage or BytesMessage first. A TextMessage maps to String, a BytesMessage to byte[], a MapMessage to Map, and an ObjectMessage to Serializable or the specific class. If the body cannot be assigned to that type it throws MessageFormatException, so a producer that changed body type fails clearly rather than with a ClassCastException deep in the listener. The companion isBodyAssignableTo(Class) lets a listener check first; for a StreamMessage it always returns false and getBody always throws. In practice, message.getBody(String.class) followed by JSON-B parsing is the standard consumer pattern for JSON events.
How do you evolve a message contract without breaking consumers?
Treat the payload as a published API with compatibility rules. Producers only add: new fields are optional with defaults, and existing fields are never removed, renamed or given a new meaning. Consumers are tolerant readers that ignore unknown fields, which JSON-B does by default and Jackson does once FAIL_ON_UNKNOWN_PROPERTIES is disabled. A schemaVersion property lets consumers branch explicitly, and contract tests in both pipelines prove that consumers still parse the current and previous versions. When a breaking change is unavoidable, publish both versions in parallel, on separate destinations or eventType values, until every consumer has migrated, then retire the old one on an announced date.
How do you handle very large payloads?
I use the claim-check pattern: the producer stores the content in object storage such as Amazon S3 or in a database, then sends a small message carrying the key, size, content type and a checksum. The consumer fetches the content, verifies the checksum, and archives or deletes it according to a retention policy. That keeps the broker doing what it is good at, many small messages, and avoids paging, slow failover and expensive redelivery of multi-megabyte bodies. Two details matter: the stored object must exist before the message is sent, and access to it needs the same security as the message itself, for example short-lived presigned URLs.
When would you choose a binary format over JSON?
I choose Avro or Protobuf in a BytesMessage when volume makes payload size and parsing cost significant, or when many teams need compatibility enforced rather than merely agreed. Binary encodings are typically several times smaller and faster to parse than JSON, which reduces broker memory, network and CPU at tens of thousands of messages per second, and a schema registry rejects incompatible changes before they ship. The price is debuggability, because nobody can read a message in the broker console without tooling, plus a registry to operate and libraries in every consumer language. For moderate volumes, JSON with a JSON Schema and contract tests is simpler, so binary should be justified by measurements.
How should message contracts be governed across teams?
As products owned by the producing team. Each message type has a published, versioned schema, JSON Schema, Avro or Protobuf, kept in the producer's repository and registered in a schema registry or event catalogue that lists owners, known consumers and deprecation status. Compatibility rules, usually backward-compatible additions only, are checked automatically in the producer's pipeline, and consumer-driven contract tests run in both pipelines. Common envelope fields such as event id, type, version, timestamp and trace id are defined once for the whole organisation. A breaking change needs a new version, a migration plan and a documented deprecation window, while ordinary field additions need no review meeting at all.
Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.