Part 3 of 4 — Apache Kafka Engineering Notes

Spring MVC Producers: KafkaTemplate, Keys, and JSON

Nov 2026 · 8 min read

KafkaTemplate sends OrderCreated events as JSON to a Kafka topic via a Spring MVC endpoint, using customerId as the key. The reader proves that the same key always lands in the same partition, then sees a trusted packages error on the consumer side and fixes it.

Full code: https://github.com/Sch39/java-spring-boot

Problem

The controller already accepts POST /orders, but order events need to reach Kafka in a sensible order per customer, and in a format other services can read. Without a key, one customer's messages are scattered across many partitions. Without proper JSON configuration, the consumer fails to read events that were already sent.

  1. One customer's orders are scattered: without a key, events from the same customer can land in different partitions, so their order is not guaranteed.

  2. The consumer rejects JSON: JacksonJsonDeserializer only trusts java.util and java.lang, so the OrderCreated type is rejected when read.

Outcome

The reader can:

  • Set up a Spring Boot project with KafkaTemplate<String, OrderCreated> and a JSON serializer via application.properties.

  • Prove that the same key lands in the same partition via RecordMetadata (topic, partition, offset).

  • Recognize the trusted packages error on the consumer and fix it.

Implementation

Folder Structure

text
code/order-service/
├── build.gradle
└── src/
    ├── main/
    │   ├── java/dev/sch39/orderservice/
    │   │   ├── OrderCreated.java
    │   │   ├── PublishResult.java
    │   │   ├── KafkaTopicConfig.java
    │   │   ├── OrderProducer.java
    │   │   └── OrderController.java
    │   └── resources/application.yml
    └── test/java/dev/sch39/orderservice/
        └── OrderProducerTest.java

Setup

Initialize the first project (run from the code/ folder). A local Kafka broker must be running at localhost:9092; official guide: https://kafka.apache.org/quickstart.

bash
mkdir -p order-service
cd order-service

spring init --type=gradle-project --java-version=21 --boot-version=4.1.2 --dependencies=web,kafka --group-id=dev.sch39 --artifact-id=order-service --package-name=dev.sch39.orderservice --extract . \
&& rm src/main/resources/application.properties \
  && printf 'spring:\n  application:\n    name: order-service\n' > src/main/resources/application.yml

Boot 4.1.2 brings spring-kafka 4.1.2 and kafka-clients 4.2.2.

Code Blocks

Block 1: The event as a record

code/order-service/src/main/java/dev/sch39/orderservice/OrderCreated.java:

java
package dev.sch39.orderservice;

public record OrderCreated(String orderId, String customerId, long amount) {
}

Purpose: Define the event payload that will be serialized to JSON.

Block 2: Publish result

code/order-service/src/main/java/dev/sch39/orderservice/PublishResult.java:

java
package dev.sch39.orderservice;

public record PublishResult(String topic, int partition, long offset) {
}

Purpose: Carry RecordMetadata (topic, partition, offset) into the response so the partition is visible from the outside.

Block 3: JSON serializer and acks

code/order-service/src/main/resources/application.properties:

properties
spring:
  application:
    name: order-service

  kafka:
    bootstrap-servers: localhost:9092
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.springframework.kafka.support.serializer.JacksonJsonSerializer
      acks: all
app:
  topic:
    orders: orders

Purpose: Set a String key, a JSON value, and acks=all without any extra beans.

Block 4: Topic with 3 partitions

code/order-service/src/main/java/dev/sch39/orderservice/KafkaTopicConfig.java:

java
package dev.sch39.orderservice;

import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.config.TopicBuilder;

@Configuration
class KafkaTopicConfig {

    @Bean
    NewTopic ordersTopic(@Value("${app.topic.orders}") String name) {
        return TopicBuilder.name(name).partitions(3).replicas(1).build();
    }
}

Purpose: Create a topic with 3 partitions when the application starts so key distribution can be observed.

Block 5: Publish with a key

code/order-service/src/main/java/dev/sch39/orderservice/OrderProducer.java:

java
package dev.sch39.orderservice;

import java.util.concurrent.CompletableFuture;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
public class OrderProducer {

    private final KafkaTemplate<String, OrderCreated> template;
    private final String topic;

    OrderProducer(KafkaTemplate<String, OrderCreated> template,
                  @Value("${app.topic.orders}") String topic) {
        this.template = template;
        this.topic = topic;
    }

    public CompletableFuture<PublishResult> publish(OrderCreated event) {
        return template.send(topic, event.customerId(), event)
                .thenApply(r -> new PublishResult(
                        r.getRecordMetadata().topic(),
                        r.getRecordMetadata().partition(),
                        r.getRecordMetadata().offset()));
    }
}

Purpose: Send the event with customerId as the key and convert SendResult into PublishResult.

Block 6: POST /orders endpoint

code/order-service/src/main/java/dev/sch39/orderservice/OrderController.java:

java
package dev.sch39.orderservice;

import java.util.List;
import java.util.UUID;
import java.util.stream.IntStream;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/orders")
class OrderController {

    record CreateOrderRequest(String customerId, long amount) {
    }

    private final OrderProducer producer;

    OrderController(OrderProducer producer) {
        this.producer = producer;
    }

    @PostMapping
    PublishResult create(@RequestBody CreateOrderRequest request) {
        return producer.publish(newEvent(request.customerId(), request.amount())).join();
    }

    private static OrderCreated newEvent(String customerId, long amount) {
        return new OrderCreated(UUID.randomUUID().toString(), customerId, amount);
    }
}

Purpose: Accept a single order and return the topic, partition, and offset from the publish result.

Block 7: POST /orders/bulk endpoint

code/order-service/src/main/java/dev/sch39/orderservice/OrderController.java:

java
    @PostMapping("/bulk")
    List<PublishResult> bulk(@RequestParam String customerId, @RequestParam int count) {
        return IntStream.range(0, count)
                .mapToObj(i -> producer.publish(newEvent(customerId, 100 + i)))
                .toList().stream()
                .map(f -> f.join())
                .toList();
    }

Purpose: Send several orders for one customer at once so their partitions can be compared.

Test Blocks

Test 1: Same key, same partition

code/order-service/src/test/java/dev/sch39/orderservice/OrderProducerTest.java:

java
package dev.sch39.orderservice;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.errors.RecordDeserializationException;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.kafka.support.serializer.JacksonJsonDeserializer;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.test.web.servlet.MockMvc;

@SpringBootTest
@AutoConfigureMockMvc
class OrderProducerTest {

    static final String TOPIC = "orders-test-" + UUID.randomUUID();

    @DynamicPropertySource
    static void topic(DynamicPropertyRegistry registry) {
        registry.add("app.topic.orders", () -> TOPIC);
    }

    @AfterAll
    static void deleteTopic() throws Exception {
        try (AdminClient admin = AdminClient.create(Map.<String, Object>of("bootstrap.servers", "localhost:9092"))) {
            admin.deleteTopics(List.of(TOPIC)).all().get();
        }
    }

    @Autowired
    OrderProducer producer;

    @Autowired
    MockMvc mvc;

    private static KafkaConsumer<String, OrderCreated> consumer(String trustedPackages) {
        Properties props = new Properties();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-" + UUID.randomUUID());
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonJsonDeserializer.class);
        if (trustedPackages != null) {
            props.put(JacksonJsonDeserializer.TRUSTED_PACKAGES, trustedPackages);
        }
        KafkaConsumer<String, OrderCreated> consumer = new KafkaConsumer<>(props);
        consumer.subscribe(List.of(TOPIC));
        return consumer;
    }

    @Test
    void sameKeyGoesToSamePartition() {
        Set<Integer> partitions = java.util.stream.IntStream.range(0, 5)
                .mapToObj(i -> producer.publish(new OrderCreated(UUID.randomUUID().toString(), "c-same", i)).join())
                .map(PublishResult::partition)
                .collect(Collectors.toSet());
        System.out.println("key=c-same partitions=" + partitions);
        assertEquals(1, partitions.size(), "partitions for one key: got " + partitions + ", want 1");
    }
}

Purpose: Prove that five events with the key c-same land in only one partition.

Test 2: The endpoint returns metadata

code/order-service/src/test/java/dev/sch39/orderservice/OrderProducerTest.java:

java
    @Test
    void postOrderReturnsRecordMetadata() throws Exception {
        mvc.perform(post("/orders").contentType("application/json")
                        .content("{\"customerId\":\"c-http\",\"amount\":250}"))
                .andDo(r -> System.out.println("POST /orders -> " + r.getResponse().getContentAsString()))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.topic").value(TOPIC))
                .andExpect(jsonPath("$.partition").isNumber())
                .andExpect(jsonPath("$.offset").isNumber());
    }

Purpose: Prove that POST /orders publishes the event to the correct topic and returns the partition and offset.

Test 3: Bulk for one customer

code/order-service/src/test/java/dev/sch39/orderservice/OrderProducerTest.java:

java
    @Test
    void bulkWithSameCustomerStaysOnOnePartition() throws Exception {
        String body = mvc.perform(post("/orders/bulk").param("customerId", "c-bulk").param("count", "5"))
                .andExpect(status().isOk())
                .andReturn().getResponse().getContentAsString();
        List<Integer> partitions = com.jayway.jsonpath.JsonPath.read(body, "$[*].partition");
        System.out.println("POST /orders/bulk partitions=" + partitions);
        assertEquals(5, partitions.size(), "records: got " + partitions.size() + ", want 5");
        assertEquals(1, Set.copyOf(partitions).size(), "partitions: got " + partitions + ", want one distinct value");
    }

Purpose: Prove that /orders/bulk for a single customerId produces five records in one partition.

Test 4: The consumer rejects the type (broken)

code/order-service/src/test/java/dev/sch39/orderservice/OrderProducerTest.java:

java
    @Test
    void consumerWithDefaultTrustedPackagesFails() {
        producer.publish(new OrderCreated(UUID.randomUUID().toString(), "c-broken", 1)).join();
        try (KafkaConsumer<String, OrderCreated> c = consumer(null)) {
            RecordDeserializationException ex = assertThrows(RecordDeserializationException.class, () -> {
                long end = System.currentTimeMillis() + 15_000;
                while (System.currentTimeMillis() < end) {
                    c.poll(Duration.ofMillis(500));
                }
            });
            System.out.println("error=" + ex.getCause().getMessage());
        }
    }

Purpose: Show that a consumer with the default trusted packages fails to read OrderCreated with a RecordDeserializationException.

Test 5: Trusted packages fixed

code/order-service/src/test/java/dev/sch39/orderservice/OrderProducerTest.java:

java
    @Test
    void consumerWithTrustedPackagesReadsEvent() {
        OrderCreated sent = new OrderCreated(UUID.randomUUID().toString(), "c-fixed", 42);
        producer.publish(sent).join();
        try (KafkaConsumer<String, OrderCreated> c = consumer("dev.sch39.orderservice")) {
            long end = System.currentTimeMillis() + 15_000;
            OrderCreated got = null;
            while (got == null && System.currentTimeMillis() < end) {
                for (ConsumerRecord<String, OrderCreated> r : c.poll(Duration.ofMillis(500))) {
                    if (r.value().orderId().equals(sent.orderId())) {
                        got = r.value();
                        System.out.println("key=" + r.key() + " value=" + got);
                    }
                }
            }
            assertNotNull(got, "event not consumed: got null, want " + sent);
            assertEquals(sent, got, "event: got " + got + ", want " + sent);
        }
    }

Purpose: Prove that once the dev.sch39.orderservice package is trusted, the same event is read intact along with its key.

Run Test

Run from the code/order-service/ folder:

bash
./gradlew test --rerun-tasks -i

Output:

text
...
OrderProducerTest > bulkWithSameCustomerStaysOnOnePartition() STANDARD_OUT
    POST /orders/bulk partitions=[1,1,1,1,1]

OrderProducerTest > consumerWithDefaultTrustedPackagesFails() STANDARD_OUT
    error=The class 'dev.sch39.orderservice.OrderCreated' is not in the trusted packages: [java.util, java.lang]. If you believe this class is safe to deserialize, add its package via the 'spring.json.trusted.packages' property or the 'addTrustedPackages()' method. Trusting all packages with '*' allows any type on the classpath to be deserialized, so list the specific packages you need instead.

OrderProducerTest > postOrderReturnsRecordMetadata() STANDARD_OUT
    POST /orders -> {"topic":"orders-test-e3a7f997-fe24-4c01-aa62-32f323000ff4","partition":1,"offset":5}

OrderProducerTest > sameKeyGoesToSamePartition() STANDARD_OUT
    key=c-same partitions=[1]

OrderProducerTest > consumerWithTrustedPackagesReadsEvent() STANDARD_OUT
    key=c-fixed value=OrderCreated[orderId=a16ace43-da7f-46b0-ad17-98ca8d460954, customerId=c-fixed, amount=42]

...
BUILD SUCCESSFUL in 22s

Manual E2E

Run the service from the code/order-service/ folder, then test from another terminal with curl (the local broker at localhost:9092 must be running):

bash
./gradlew bootRun
bash
curl -s -X POST localhost:8080/orders -H 'Content-Type: application/json' -d '{"customerId":"c1","amount":250}'
curl -s -X POST 'localhost:8080/orders/bulk?customerId=c1&count=5'
curl -s -X POST 'localhost:8080/orders/bulk?customerId=c2&count=5'

Output:

text
{"topic":"orders","partition":2,"offset":0}
[{"topic":"orders","partition":2,"offset":1},{"topic":"orders","partition":2,"offset":2},{"topic":"orders","partition":2,"offset":3},{"topic":"orders","partition":2,"offset":4},{"topic":"orders","partition":2,"offset":5}]
[{"topic":"orders","partition":1,"offset":0},{"topic":"orders","partition":1,"offset":1},{"topic":"orders","partition":1,"offset":2},{"topic":"orders","partition":1,"offset":3},{"topic":"orders","partition":1,"offset":4}]

Purpose: Prove that orders for c1 always land in partition 2 while c2 lands in partition 1 on the running service.

Why It Works

Keys and partitions: When a record has a key, the producer picks the partition from the key's hash (murmur2) modulo the number of partitions, so the same key produces the same partition as long as the partition count stays fixed. Order is only guaranteed within a single partition, so using customerId as the key preserves event order per customer.

KafkaTemplate.send: The send method returns a CompletableFuture<SendResult>. SendResult carries RecordMetadata with the topic, partition, and offset, which are mapped to PublishResult in thenApply.

JSON serializer: JacksonJsonSerializer writes the payload as JSON and adds a type header. On the consumer side, JacksonJsonDeserializer uses that header to pick the class, but only for packages in TRUSTED_PACKAGES (default java.util, java.lang). That is why OrderCreated is rejected until its package is registered.

Edge Cases

Changing the partition count: Adding partitions changes the result of the hash modulo, so existing keys can move to different partitions and ordering across time is no longer guaranteed.

Null key: Records without a key are spread across partitions with no ordering guarantee per entity.

Asynchronous send: send does not block. Calling join() in the controller makes the request wait for the result, so broker errors surface as exceptions in the request instead of disappearing silently.

Trade-offs

Strategy

Pro

Con

customerId key

Order preserved per customer

High-traffic customers make partitions unbalanced

No key

Even distribution

No ordering guarantee per entity

Specific trusted package

Only known types are deserialized

Each new event package must be registered

Best practice: Choose a key from the entity whose order matters (here customerId), fix the partition count from the start, and register trusted packages specifically rather than *.

Gotchas I Ran Into

  • Spring Boot 4.1.2 brings spring-kafka 4.1.2 with Jackson 3 (tools.jackson.core:jackson-databind:3.1.7), so the classes are JacksonJsonSerializer and JacksonJsonDeserializer, not the old JsonSerializer.

  • The error The class 'dev.sch39.orderservice.OrderCreated' is not in the trusted packages: [java.util, java.lang] appears on the consumer as a RecordDeserializationException from poll(), not when the producer sends. The send still succeeds.

Production Checklist

  • Events whose order matters? Use a key from that entity.

  • Can the partition count change? Set it from the start, since adding partitions moves keys.

  • Consumer reading JSON? Register specific trusted packages, not *.

  • Event loss not allowed? Use acks=all and handle exceptions from send.

References