How to Use Protobuf and gRPC Between Java Services
Use Protobuf and gRPC between Java services: define a proto file, generate code, write a server and client, set deadlines and evolve messages.

gRPC is a remote procedure call framework from Google that sends Protobuf messages over HTTP/2. It fits calls between services, where payload size, speed and a typed contract matter more than being able to try the endpoint in a browser. This post builds a small order service on Java 25 with grpc-java 1.7x and Protobuf 4: the contract, code generation, a server, a client with a deadline, streaming, and the rules for changing a message after it is in use.
The contract comes first
syntax = "proto3";
package com.example.orders;
option java_multiple_files = true;
option java_package = "com.example.orders.grpc";
service OrderService {
rpc GetOrder (GetOrderRequest) returns (Order);
rpc WatchOrders (WatchRequest) returns (stream Order);
}
message GetOrderRequest { string order_id = 1; }
message WatchRequest { string customer_id = 1; }
message Order {
string order_id = 1;
string customer_id = 2;
int64 total_cents = 3;
Status status = 4;
reserved 5;
}
enum Status {
STATUS_UNSPECIFIED = 0;
PLACED = 1;
SHIPPED = 2;
}Every field has a number, and the number, not the name, identifies the field on the wire. That is why the numbers are permanent. The enum needs a zero value that means "unset", because proto3 sends nothing for a field at its default, and a receiver cannot tell zero from absent. Money is an integer count of cents, not a double, for the usual reasons.
Generate the Java code
<plugin>
<groupId>io.github.ascopes</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>3.4.0</version>
<configuration>
<protocVersion>4.30.2</protocVersion>
<binaryMavenPlugins>
<binaryMavenPlugin>
<groupId>io.grpc</groupId>
<artifactId>protoc-gen-grpc-java</artifactId>
<version>1.73.0</version>
</binaryMavenPlugin>
</binaryMavenPlugins>
</configuration>
<executions>
<execution>
<goals><goal>generate</goal></goals>
</execution>
</executions>
</plugin>Plugin coordinates and versions move often, so check the gRPC Java documentation for the current ones before copying. Run mvn generate-sources and you get immutable message classes with builders, plus OrderServiceGrpc with the server base class and the client stubs. Keep the .proto files in one module that both sides depend on, so there is a single copy of the contract. Two copies drift, and the drift shows up as fields that silently stay at their defaults.
The server
class OrderServiceImpl extends OrderServiceGrpc.OrderServiceImplBase {
@Override
public void getOrder(GetOrderRequest req, StreamObserver<Order> out) {
var order = repository.find(req.getOrderId());
if (order == null) {
out.onError(Status.NOT_FOUND
.withDescription("no such order")
.asRuntimeException());
return;
}
out.onNext(toProto(order));
out.onCompleted();
}
}
Server server = ServerBuilder.forPort(9090)
.addService(new OrderServiceImpl())
.build()
.start();A unary call completes with one onNext and one onCompleted, or with onError. Calling neither leaves the client waiting until its deadline. Errors use gRPC status codes such as NOT_FOUND, INVALID_ARGUMENT and DEADLINE_EXCEEDED. They map loosely to HTTP codes, and the comparison is in HTTP status codes. Do not throw ordinary exceptions and expect a clean error: an uncaught exception reaches the client as UNKNOWN, which tells the caller nothing.
The client, with a deadline
ManagedChannel channel = ManagedChannelBuilder.forAddress("orders", 9090)
.usePlaintext()
.build();
OrderServiceGrpc.OrderServiceBlockingStub stub =
OrderServiceGrpc.newBlockingStub(channel)
.withDeadlineAfter(500, TimeUnit.MILLISECONDS);
Order order = stub.getOrder(
GetOrderRequest.newBuilder().setOrderId("o-42").build());The deadline is mandatory in practice. gRPC has no default, so a call to a stuck server waits forever and ties up the caller's thread. Pick a value from what the callee really takes and propagate the remaining time to downstream calls, so a chain of services shares one budget.
usePlaintext() is for local development. In production use TLS, or let a service mesh provide mutual TLS. A ManagedChannel is expensive to create and safe to share between threads: build one per target and reuse it, and shut it down on exit. Creating a channel per request is the classic mistake, and it shows up as connection churn and slow first calls. With Spring Boot the grpc starters wire channels and services as beans, as in gRPC with Spring Boot.
Streaming replaces polling
WatchOrders returns a stream. The server calls onNext as orders change and onCompleted when it is done, and the client reads from the blocking stub's iterator or supplies an observer. HTTP/2 flow control means a slow client slows the server instead of exhausting its memory, which polling cannot offer. Streams are long-lived, so give them a deadline too, or handle cancellation, and check Context.current().isCancelled() in a server loop so a departed client does not keep it working.
Changing messages without breaking callers
- Add new fields with new numbers. An old reader skips fields it does not know.
- Never change a field's number or type. If a field is removed, mark its number
reserved, as theOrdermessage does, so nobody reuses it for something else. - Use
optionalor a wrapper type when a missing value must be told apart from zero. - Rename fields freely on the wire, since names do not travel, but remember that the JSON mapping uses names.
The same discipline applies to events on a broker, where versioning event schemas covers the equivalent rules.
Observability and testing
Add a server interceptor to log each call's method, status and duration, because gRPC hides this from a normal access log. The client can use an interceptor to attach a trace id as metadata, which travels like an HTTP header. Metrics by method and status code, with latency histograms, give you the first view of a misbehaving dependency.
For tests, grpc-java ships an in-process transport. InProcessServerBuilder and InProcessChannelBuilder connect a client to a server in the same JVM with no ports and no network, so a service test starts in milliseconds and cannot collide with another build. Use it for logic and error codes, then keep one test over a real socket to catch serialization and TLS mistakes.
Retries and load balancing
A channel can retry failed calls according to a service config, but retries are safe only for idempotent methods, as with any RPC. Do not enable them for a call that charges a card. Client-side load balancing is another point that surprises people: a plain DNS name that resolves to a single virtual IP sends every call on one long-lived HTTP/2 connection to one instance, so adding replicas changes nothing. Either use a load balancer that understands HTTP/2 streams, configure the channel with a round-robin policy over several addresses, or let a mesh do it.
What you give up compared with REST
gRPC gives you a typed contract, streaming, deadlines and compact payloads. The price is tooling: browsers cannot speak it without a proxy, curl needs a tool such as grpcurl, and some corporate proxies mishandle HTTP/2. The decision between the styles is laid out in REST versus GraphQL versus gRPC.
Test a service without a network
A gRPC service can be tested in one JVM with the in-process transport, which skips sockets and ports and still runs the real serialization and the real stubs:
class OrderServiceTest {
private Server server;
private ManagedChannel channel;
private OrderServiceGrpc.OrderServiceBlockingStub stub;
@BeforeEach
void start() throws IOException {
String name = InProcessServerBuilder.generateName();
server = InProcessServerBuilder.forName(name).directExecutor()
.addService(new OrderServiceImpl(new InMemoryOrders())).build().start();
channel = InProcessChannelBuilder.forName(name).directExecutor().build();
stub = OrderServiceGrpc.newBlockingStub(channel);
}
@AfterEach
void stop() throws InterruptedException {
channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
}
@Test
void returnsTheOrder() {
Order order = stub.getOrder(GetOrderRequest.newBuilder().setId("42").build());
assertEquals("42", order.getId());
}
@Test
void unknownIdIsNotFound() {
StatusRuntimeException error = assertThrows(StatusRuntimeException.class,
() -> stub.getOrder(GetOrderRequest.newBuilder().setId("missing").build()));
assertEquals(Status.Code.NOT_FOUND, error.getStatus().getCode());
}
}The second test checks the failure that clients depend on. The server side returns it with responseObserver.onError(Status.NOT_FOUND.withDescription("no order " + id).asRuntimeException()). A caller that branches on the status code is relying on that contract, so write a test for every code the service documents. Add a case with a deadline of a few milliseconds against a handler that sleeps, and assert DEADLINE_EXCEEDED, which proves that your server code does not ignore cancellation.
When not to use it
A public API for browsers or third parties is better as REST, where anyone can call it with what they have. Inside a system of services that you control, gRPC earns its keep when calls are frequent and payloads matter. The references are the gRPC Java documentation and the Protocol Buffers language guide.


