r/apachekafka • u/frekost • 27d ago
Tool Combining gRPC and Kafka in Java Microservices with Micronaut 4
One interesting challenge when designing Java microservices is choosing the right communication pattern.
gRPC and Apache Kafka address different requirements: synchronous RPC communication and asynchronous event-driven messaging.
With gRPC, the service contract is defined using Protocol Buffers. The .proto file describes the service methods, request messages and response messages. Maven and the Protocol Buffers compiler generate the corresponding Java classes and gRPC stubs.
For example, a Greeter service can expose a SayHello RPC method. A client sends a HelloRequest, the server processes it and returns a HelloReply through a generated gRPC stub.
With Micronaut 4 and Java 21, this provides a strongly typed communication layer without manually managing HTTP endpoints or JSON serialization.
However, synchronous RPC is not always the best choice when multiple services need to react to the same operation.
This is where Kafka comes in.
After handling a gRPC request, a service can publish a domain event, such as GreetingRequested, to a Kafka topic. Independent consumers can subscribe to that topic and process the event without being directly coupled to the original service.
This creates two distinct communication flows:
gRPC: request/response, synchronous execution, explicit service contracts.
Kafka: asynchronous message delivery, independent consumers, event-driven processing.
Combining them requires attention to several engineering details: event serialization, schema evolution, consumer groups, retry policies, idempotent processing, dead-letter topics and observability.
Another important issue is consistency between the RPC response and event publication. If an operation succeeds but publishing the event fails, the system can end up with inconsistent state. Depending on the use case, patterns such as the Transactional Outbox can help address this problem.
I'm exploring this architecture using Java 21, Micronaut 4, gRPC, Protocol Buffers, Maven and Kafka, starting from a simple Greeter service.
The gRPC implementation is available here: https://github.com/frekost/grpc-micronaut-starter-kit
I'm curious about how others approach this: do you use gRPC for synchronous communication and Kafka for domain events, or do you prefer a different architecture?