Sub topic 2
Keys, Values, and JSON Serialization
Assume you know Java, Spring Boot beans, dependency injection, and basic publish/subscribe messaging. You also need a local Kafka broker running at localhost:9092.
Keys, values, and JSON serialization
A Kafka record has a key and a value. The key helps Kafka choose a partition. Records with the same key go to the same partition, so Kafka preserves their order within that key. The value contains the business data.
Serialization converts an object into bytes before sending it. Deserialization converts bytes back into an object. Spring Kafka can use JSON for this conversion.
spring:
kafka:
bootstrap-servers: localhost:9092
producer:
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
consumer:
group-id: order-service
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
properties:
spring.json.trusted.packages: com.example.orders
spring.json.value.default.type: com.example.orders.OrderEventThe trusted-package setting limits which Java classes the JSON deserializer may create. Avoid trusting every package in an exposed application.
public record OrderEvent(String orderId, long amountCents) {}Publishing with `KafkaTemplate`
KafkaTemplate sends records asynchronously. Use a stable business identifier as the key when events for that identifier must remain ordered.
@Service
public class OrderPublisher {
private final KafkaTemplate<String, OrderEvent> kafkaTemplate;
public OrderPublisher(KafkaTemplate<String, OrderEvent> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
public void publish(OrderEvent event) {
kafkaTemplate.send("orders", event.orderId(), event)
.whenComplete((result, error) -> {
if (error != null) {
// Record the failure and take corrective action.
return;
}
System.out.println(result.getRecordMetadata().offset());
});
}
}The callback tells you whether Kafka accepted the send. It does not mean that a downstream service finished processing the event.
Consuming with `@KafkaListener`
@KafkaListener(topics = "orders", groupId = "order-service")
public void onOrder(OrderEvent event) {
System.out.println(event.orderId());
}A listener receives the deserialized value. Consumers in one group share partitions. Consumers in different groups each receive the records independently.
Concurrency and offset commits
Set concurrency to run multiple listener consumers in one application instance:
@KafkaListener(
topics = "orders",
groupId = "order-service",
concurrency = "3"
)
public void onOrder(OrderEvent event) {
process(event);
}Concurrency cannot exceed the number of partitions that the group can use. More consumers do not create more parallelism when there are too few partitions.
Spring commonly commits offsets after the listener returns successfully. With manual acknowledgment, add an Acknowledgment parameter and call ack.acknowledge() only after processing succeeds. Manual acknowledgment gives control, but failing to acknowledge can cause records to be delivered again.
Exercise
What key should you use when all events for one order must stay ordered?
Show answer
Use the order ID as the Kafka record key.