gRPC in Spring Boot 4.1: The New Auto-Configuration, End to End

Estimated reading time: ~35 minutes. All the code, the benchmark scripts and the raw outputs are in the companion repository.
In this tutorial we build a complete gRPC server and client using the gRPC support that now ships inside Spring Boot itself, and the languages and frameworks used are Spring Boot 4.1, Java 25, gRPC (grpc-java 1.80.0) and Protocol Buffers 4.34.2, built with Gradle and Lombok as in our previous tutorials. We’ll wire up a server and a client, then add health checks, centralised error handling, TLS, tests and OpenTelemetry tracing, and finish by benchmarking REST against gRPC on the very service we’ve just built.
Why now? Spring Boot 4.1 was released on 10 June 2026, and its headline change for anyone doing service-to-service work is that the gRPC starters, auto-configuration, properties and test support moved out of the separate spring-grpc project and into Spring Boot proper. That single fact makes almost every existing gRPC tutorial for Spring out of date: the ones you’ll find near the top of a search still teach either the abandoned third-party net.devh starter or the pre-4.1 org.springframework.grpc coordinates. Everything in this guide was built and run on Boot 4.1.0 GA, the outputs you’ll see are real, and the benchmark numbers at the end are our own.
You should be comfortable with Spring Boot and Gradle. You don’t need any previous gRPC experience; we’ll cover the Protocol Buffers contract from scratch. To follow along you’ll want a JDK (Boot 4.1 keeps the Java 17 baseline, and we build on Java 25) and, optionally, grpcurl for poking at the server from a terminal.
If you’re still on Spring Boot 3.x, our migration guide to Spring Boot 4 covers that jump, and the Spring Boot 4 release post covers what changed in 4.0 itself. This tutorial assumes you’re already on the 4.x line.
Tutorial contents
Due to the number of sections, here are the individual parts so you can jump straight to a specific one if required.
- What actually changed in Spring Boot 4.1
- Setting up the projects
- Defining the service contract
- The data layer and some depot stock
- Building the gRPC server
- Health checks
- Building the client
- Error handling with @GrpcAdvice
- TLS with SSL bundles
- Testing
- Observability: metrics and traces
- REST vs gRPC: the benchmark
- Summing Up
What actually changed in Spring Boot 4.1
A quick bit of history, because the coordinate shuffle only makes sense with it. Spring’s gRPC support grew up in a standalone project, spring-grpc, which reached 1.0 against Spring Boot 4.0 under the org.springframework.grpc group. On 10 June 2026, the same day Boot 4.1 went GA, spring-grpc 1.1.0 was released, and its release notes state it plainly: “The main change in 1.1.0 is the migration of autoconfiguration to Spring Boot 4.1.0.”
In practice that means the starters you add to your build are now Boot’s own:
org.springframework.boot:spring-boot-starter-grpc-serverorg.springframework.boot:spring-boot-starter-grpc-clientorg.springframework.boot:spring-boot-starter-grpc-server-testorg.springframework.boot:spring-boot-starter-grpc-client-test
The spring-grpc project itself lives on as the core programming model. Its library, spring-grpc-core:1.1.0, is what provides @GrpcService, @ImportGrpcClients and GrpcChannelFactory, and it arrives transitively through the starters. You never declare spring-grpc in your build at all. The old org.springframework.grpc starters are deprecated; the 1.0.x artifacts remain on Maven Central for projects pinned to Boot 4.0.
Back in November 2025, when Dave Syer announced the plan to fold the auto-configuration into Boot, he wrote of the migration: “We will publish explicit guidance on that when the time comes.” As of writing, that explicit guidance consists of a draft wiki page, so here is the mapping we relied on while building this project. The property tree was restructured as well as re-homed, and these are the renames most likely to bite:

| spring-grpc 1.0 (Boot 4.0) | Spring Boot 4.1 |
|---|---|
spring.grpc.client.channels.<name>.address | spring.grpc.client.channel.<name>.target (singular channel, and address becomes target) |
spring.grpc.client.channels.<name>.default-deadline | spring.grpc.client.channel.<name>.default.deadline |
spring.grpc.server.keep-alive.* | spring.grpc.server.keepalive.* |
spring.grpc.server.max-inbound-message-size | spring.grpc.server.inbound.message.max-size |
spring.grpc.server.address (combined host:port) | spring.grpc.server.address (address only) plus a separate spring.grpc.server.port |
spring.grpc.server.health.actuator.* | Removed; health is now configured under spring.grpc.server.health.* |
One behavioural change deserves its own sentence: spring-grpc 1.0 automatically scanned for generated stub classes on the classpath, and Boot 4.1 no longer does. Client stubs are registered explicitly with @ImportGrpcClients, which we’ll use when we build the client module.
Beyond the migration, Boot 4.1 also took over the protobuf build tooling on both Gradle and Maven, which turns out to be one of the nicest surprises in the whole release. We’ll see it first-hand in the next section.
Setting up the projects
We’ll build two separate Spring Boot applications: grpc-server, which owns the data and exposes the gRPC service, and grpc-client, which calls it over gRPC and fronts it with a small REST facade. Two processes keep the roles honest, and it means the benchmark later on hits one process per protocol style.
As usual, I’ll use IntelliJ IDEA as my preferred IDE, and its new-project wizard is backed by Spring Initializr, so the same selections on the website give you an identical project if that’s your route. For the server, create a Gradle project named grpc-server with group com.tucanoo, Java 25, and select the following dependencies: Spring gRPC Server, Spring Web, Spring Data JPA, H2 Database, Spring Boot Actuator, OpenTelemetry, Lombok and Spring Boot DevTools. The Spring gRPC Server entry is the one doing the heavy lifting here; the rest give us a repository to serve, health indicators to bridge, and tracing for later.


Repeat for the client with the new-module wizard, adding it alongside the server: a module named grpc-client, this time with just Spring gRPC Client, Spring Web, OpenTelemetry, Lombok and DevTools. We’ll look at both build files in a moment.


The wizard leaves the two modules side by side under one parent folder. You can delete the unnecessary HELP.md files. Here is the server’s complete build.gradle:
plugins {
id 'java'
id 'org.springframework.boot' version '4.1.0'
id 'io.spring.dependency-management' version '1.1.7'
id 'com.google.protobuf' version '0.9.6'
}
group = 'com.tucanoo'
version = '0.0.1-SNAPSHOT'
description = 'grpc-server'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(25)
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-h2console'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-grpc-server'
implementation 'org.springframework.boot:spring-boot-starter-opentelemetry'
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'com.h2database:h2'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-actuator-test'
testImplementation 'org.springframework.boot:spring-boot-starter-data-jpa-test'
testImplementation 'org.springframework.boot:spring-boot-starter-grpc-server-test'
testImplementation 'org.springframework.boot:spring-boot-starter-opentelemetry-test'
testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test'
testCompileOnly 'org.projectlombok:lombok'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
testAnnotationProcessor 'org.projectlombok:lombok'
}
tasks.named('test') {
useJUnitPlatform()
}Two things to notice. First, the web starter is called spring-boot-starter-webmvc now, part of Boot 4’s modular renaming (the migration guide linked above covers those renames in full). Second, and this is the part I didn’t expect: the file applies the com.google.protobuf plugin and then configures nothing. If you’ve done gRPC on the JVM before, you’ll be expecting a twenty-line protobuf { } block naming the protoc artifact, the codegen plugin, version numbers and source-set wiring. There isn’t one, and you don’t need one.
The reason lives in Boot’s own Gradle plugin. Spring Boot 4.1 ships a ProtobufPluginAction that reacts to the protobuf plugin being applied and configures everything itself: the protoc artifact (resolved at 4.34.2, version-aligned with Boot’s managed protobuf-java), the io.grpc:protoc-gen-grpc-java codegen plugin (resolved at 1.80.0, aligned with the managed gRPC libraries), and a resolution strategy that keeps the code generator matching whatever gRPC version is on your runtime classpath. Drop .proto files into src/main/proto/, run the build, and the generated message classes and service stubs appear under build/generated/sources/proto/main/ and get compiled with no further wiring. Across this entire project, both build.gradle files are exactly as Initializr generated them: the total build-file delta for all the protobuf and gRPC codegen you’ll see below is zero lines.
A small bonus hiding in there: Boot passes @generated=omit to the code generator, so the generated stubs carry no @javax.annotation.Generated annotation. Older gRPC guides always made you add a javax.annotation-api dependency to keep those stubs compiling. That habit can be retired too.
Maven users get the same treatment: spring-boot-starter-parent 4.1 pre-configures io.github.ascopes:protobuf-maven-plugin (not the old org.xolstice plugin most tutorials still show), so your POM declares the plugin with a bare generate execution and no version or configuration.
The client’s build.gradle is the same shape: it swaps the server starter for spring-boot-starter-grpc-client, drops the JPA, H2 and actuator entries, and uses spring-boot-starter-grpc-client-test in the test scope. The full file is in the repository.
Defining the service contract
Our demo domain is a galactic parts depot: an inventory service for starship components that other systems can query for part details, search by name and category, and watch for stock movements. Under grpc-server/src/main/proto/, create parts_depot.proto:
syntax = "proto3";
package tucanoo.depot.v1;
option java_multiple_files = true;
option java_package = "com.tucanoo.depot.v1";
service PartsDepot {
rpc GetPart(GetPartRequest) returns (PartResponse);
rpc SearchParts(SearchRequest) returns (SearchResponse);
rpc WatchStock(WatchStockRequest) returns (stream StockUpdate);
rpc StreamParts(StreamPartsRequest) returns (stream PartResponse);
}
message GetPartRequest {
int64 id = 1;
}
message PartResponse {
int64 id = 1;
string part_number = 2;
string name = 3;
string category = 4;
double unit_price_credits = 5;
int32 stock_level = 6;
string warehouse_planet = 7;
}
message SearchRequest {
string query = 1;
string category = 2;
}
message SearchResponse {
repeated PartResponse results = 1;
}
message WatchStockRequest {
int64 part_id = 1;
}
message StockUpdate {
int64 part_id = 1;
int32 stock_level = 2;
string warehouse_planet = 3;
int64 timestamp_millis = 4;
}
message StreamPartsRequest {
int32 repeat_count = 1;
}
The contract has two unary calls (GetPart and SearchParts, one request in, one response out) and two server-streaming calls, where the server pushes a stream of messages for a single request. WatchStock simulates a live stock feed; StreamParts is a bulk-transfer call we’ll use in the benchmark section. The java_multiple_files and java_package options just control where the generated Java lands, in our case com.tucanoo.depot.v1.
Run ./gradlew build and the plugin generates both the message classes and a PartsDepotGrpc class containing the server base class and the client stubs. That one file is the contract’s whole surface area on the Java side.
The same proto file is copied into the client module’s src/main/proto/. I went back and forth on this one: the textbook answer is a shared module (or a published proto/stub artifact) so the contract exists in exactly one place, and that’s what I’d do on a real estate with more than a couple of services. For a two-module tutorial the shared module adds build ceremony that teaches nothing about gRPC, so I kept a duplicated copy in each module and accepted the burden of keeping them identical. It’s a real trade-off, and one worth making deliberately.
The data layer and some depot stock
The server needs something to serve. Under com.tucanoo.grpcserver.part, create the Part entity:
package com.tucanoo.grpcserver.part;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.math.BigDecimal;
@Entity
@Getter
@Setter
@NoArgsConstructor
public class Part {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String partNumber;
private String name;
private String category;
private BigDecimal unitPriceCredits;
private int stockLevel;
private String warehousePlanet;
}
And its repository, with two derived queries for the search call:
package com.tucanoo.grpcserver.part;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface PartRepository extends JpaRepository<Part, Long> {
List<Part> findByNameContainingIgnoreCase(String name);
List<Part> findByNameContainingIgnoreCaseAndCategoryIgnoreCase(String name, String category);
}
For seed data we use the same trick as our previous tutorials: an import.sql on the classpath, which Hibernate runs automatically against the embedded H2 database at startup. Ours loads a 40-row catalogue of depot stock. The first few rows, so you can see the shape:
insert into part (id, part_number, name, category, unit_price_credits, stock_level, warehouse_planet) values (1, 'PD-001', 'Hyperdrive Motivator Mk III', 'Propulsion', 12500.00, 14, 'Tatooine');
insert into part (id, part_number, name, category, unit_price_credits, stock_level, warehouse_planet) values (2, 'PD-002', 'Class 0.5 Hyperdrive Core', 'Propulsion', 89000.00, 2, 'Coruscant');
insert into part (id, part_number, name, category, unit_price_credits, stock_level, warehouse_planet) values (8, 'PD-008', 'Power Converter, 12V Universal', 'Power', 145.00, 210, 'Tatooine');
insert into part (id, part_number, name, category, unit_price_credits, stock_level, warehouse_planet) values (22, 'PD-022', 'Moisture Vaporator Condenser Coil', 'Environmental', 480.00, 130, 'Tatooine');
The full file, hyperdrive cores to escape-pod ejection charges, is in the repository. H2 with Hibernate’s create-drop default is fine for a tutorial; in production you’d be pointing at a real database with versioned migrations rather than a classpath script.
The server’s application.yaml is short. The datasource line names the in-memory database, open-in-view is switched off as it should be on any service that isn’t rendering views, and the management block we’ll come back to in the observability section:
spring:
application:
name: grpc-server
datasource:
url: jdbc:h2:mem:depot
jpa:
open-in-view: false
management:
endpoints:
web:
exposure:
include: health, metrics
# No collector running by default -- switch these back on via the 'otel' profile
otlp:
metrics:
export:
enabled: false
tracing:
export:
otlp:
enabled: false
logging:
export:
otlp:
enabled: false
Building the gRPC server
Now the part the tutorial is named after, and it’s almost anticlimactic. Under com.tucanoo.grpcserver.grpc, create a PartsDepotGrpcService class extending the generated base class:
package com.tucanoo.grpcserver.grpc;
import com.tucanoo.depot.v1.GetPartRequest;
import com.tucanoo.depot.v1.PartResponse;
import com.tucanoo.depot.v1.PartsDepotGrpc;
import com.tucanoo.depot.v1.SearchRequest;
import com.tucanoo.depot.v1.SearchResponse;
import com.tucanoo.depot.v1.StockUpdate;
import com.tucanoo.depot.v1.StreamPartsRequest;
import com.tucanoo.depot.v1.WatchStockRequest;
import com.tucanoo.grpcserver.part.Part;
import com.tucanoo.grpcserver.part.PartNotFoundException;
import com.tucanoo.grpcserver.part.PartRepository;
import io.grpc.Status;
import io.grpc.stub.StreamObserver;
import lombok.RequiredArgsConstructor;
import org.springframework.grpc.server.service.GrpcService;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
@GrpcService
@RequiredArgsConstructor
public class PartsDepotGrpcService extends PartsDepotGrpc.PartsDepotImplBase {
private final PartRepository partRepository;
@Override
public void getPart(GetPartRequest request, StreamObserver<PartResponse> responseObserver) {
if (request.getId() <= 0) {
throw new IllegalArgumentException("part id must be positive, got " + request.getId());
}
Part part = partRepository.findById(request.getId())
.orElseThrow(() -> new PartNotFoundException(request.getId()));
responseObserver.onNext(toResponse(part));
responseObserver.onCompleted();
}
@Override
public void searchParts(SearchRequest request, StreamObserver<SearchResponse> responseObserver) {
List<Part> parts = request.getCategory().isBlank()
? partRepository.findByNameContainingIgnoreCase(request.getQuery())
: partRepository.findByNameContainingIgnoreCaseAndCategoryIgnoreCase(
request.getQuery(), request.getCategory());
SearchResponse.Builder response = SearchResponse.newBuilder();
parts.forEach(part -> response.addResults(toResponse(part)));
responseObserver.onNext(response.build());
responseObserver.onCompleted();
}
@Override
public void watchStock(WatchStockRequest request, StreamObserver<StockUpdate> responseObserver) {
Part part = partRepository.findById(request.getPartId())
.orElseThrow(() -> new PartNotFoundException(request.getPartId()));
// Simulated feed: five updates then done. Blocking the handler thread is fine
// here because gRPC dispatches each call on its executor, not the event loop.
int stock = part.getStockLevel();
try {
for (int i = 0; i < 5; i++) {
stock = Math.max(0, stock + ThreadLocalRandom.current().nextInt(-4, 5));
responseObserver.onNext(StockUpdate.newBuilder()
.setPartId(part.getId())
.setStockLevel(stock)
.setWarehousePlanet(part.getWarehousePlanet())
.setTimestampMillis(System.currentTimeMillis())
.build());
Thread.sleep(500);
}
responseObserver.onCompleted();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
responseObserver.onError(Status.CANCELLED.withCause(e).asRuntimeException());
}
}
@Override
public void streamParts(StreamPartsRequest request, StreamObserver<PartResponse> responseObserver) {
// Streams the whole catalogue repeat_count times -- a firehose for the benchmark
// section. Production streaming code should add flow control with
// ServerCallStreamObserver#setOnReadyHandler rather than pushing unconditionally.
int repeatCount = Math.clamp(request.getRepeatCount(), 1, 1000);
List<PartResponse> catalogue = partRepository.findAll().stream()
.map(this::toResponse)
.toList();
for (int i = 0; i < repeatCount; i++) {
catalogue.forEach(responseObserver::onNext);
}
responseObserver.onCompleted();
}
private PartResponse toResponse(Part part) {
return PartResponse.newBuilder()
.setId(part.getId())
.setPartNumber(part.getPartNumber())
.setName(part.getName())
.setCategory(part.getCategory())
.setUnitPriceCredits(part.getUnitPriceCredits().doubleValue())
.setStockLevel(part.getStockLevel())
.setWarehousePlanet(part.getWarehousePlanet())
.build();
}
}
That single @GrpcService annotation (from org.springframework.grpc.server.service) is the entire server-side wiring. There’s no registration code, no server builder, no port binding. The unary methods follow the same pattern: build a response, hand it to responseObserver.onNext(), call onCompleted(). The streaming methods call onNext() as many times as they like first. You’ll notice getPart throws plain domain exceptions and never touches the gRPC Status API; the error-handling section explains where those exceptions go.
Start the application and watch the log:
o.s.boot.tomcat.TomcatWebServer : Tomcat initialized with port 8080 (http) o.s.boot.tomcat.TomcatWebServer : Tomcat started on port 8080 (http) with context path '/' o.s.grpc.server.NettyGrpcServerFactory : Registered gRPC service: tucanoo.depot.v1.PartsDepot o.s.grpc.server.NettyGrpcServerFactory : Registered gRPC service: grpc.reflection.v1.ServerReflection o.s.grpc.server.NettyGrpcServerFactory : Registered gRPC service: grpc.health.v1.Health o.s.g.s.lifecycle.GrpcServerLifecycle : gRPC Server started, listening on address: [/[0:0:0:0:0:0:0:0]:9090], port: 9090
One process, two transports: Tomcat on 8080 for HTTP, a Netty gRPC server on 9090 (the default, changeable via spring.grpc.server.port). And look at the other two services registered alongside ours. Reflection and health arrived without us asking. Reflection matters immediately, because it’s what lets grpcurl discover the API without being handed the proto file.
On Java 25 you’ll also see this at startup:
WARNING: sun.misc.Unsafe::arrayBaseOffset has been called by com.google.protobuf.UnsafeUtil (protobuf-java-4.34.2)
That’s protobuf-java touching sun.misc.Unsafe, which the JDK now warns about ahead of eventual removal. It’s cosmetic today and appears on every boot; nothing to fix on your side, just don’t let it startle you.
Now let’s talk to it. With the server running, grpcurl can list what’s there:

$ grpcurl -plaintext localhost:9090 list
grpc.health.v1.Health
grpc.reflection.v1.ServerReflection
tucanoo.depot.v1.PartsDepot
$ grpcurl -plaintext localhost:9090 describe tucanoo.depot.v1.PartsDepot
tucanoo.depot.v1.PartsDepot is a service:
service PartsDepot {
rpc GetPart ( .tucanoo.depot.v1.GetPartRequest ) returns ( .tucanoo.depot.v1.PartResponse );
rpc SearchParts ( .tucanoo.depot.v1.SearchRequest ) returns ( .tucanoo.depot.v1.SearchResponse );
rpc WatchStock ( .tucanoo.depot.v1.WatchStockRequest ) returns ( stream .tucanoo.depot.v1.StockUpdate );
}(We captured that describe before StreamParts was added for the benchmark section, so it lists three RPCs; run it against the finished project and you’ll see a fourth.)
A unary call returns our seed data:
$ grpcurl -plaintext -d '{"id": 1}' localhost:9090 tucanoo.depot.v1.PartsDepot/GetPart
{
"id": "1",
"part_number": "PD-001",
"name": "Hyperdrive Motivator Mk III",
"category": "Propulsion",
"unit_price_credits": 12500,
"stock_level": 14,
"warehouse_planet": "Tatooine"
}And the streaming call shows five messages arriving roughly half a second apart (note the timestamps):
$ grpcurl -plaintext -d '{"part_id": 8}' localhost:9090 tucanoo.depot.v1.PartsDepot/WatchStock
{
"part_id": "8",
"stock_level": 213,
"warehouse_planet": "Tatooine",
"timestamp_millis": "1784477328944"
}
{
"part_id": "8",
"stock_level": 215,
"warehouse_planet": "Tatooine",
"timestamp_millis": "1784477329445"
}
{
"part_id": "8",
"stock_level": 216,
"warehouse_planet": "Tatooine",
"timestamp_millis": "1784477329945"
}
(two more updates follow)If you’ve built SSE streams over HTTP for this kind of live feed (we did exactly that in our LLM response streaming tutorial), server-streaming gRPC is the strongly-typed sibling: the contract declares the stream, and the generated stubs handle it natively on both sides.
Since Tomcat is already running in this process, we’ll also expose the same catalogue over plain REST. This gives the benchmark section a like-for-like JSON endpoint on the same repository and the same data. Under com.tucanoo.grpcserver.api, create PartController:
package com.tucanoo.grpcserver.api;
import com.tucanoo.grpcserver.part.Part;
import com.tucanoo.grpcserver.part.PartRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
import java.util.List;
@RestController
@RequestMapping("/api/parts")
@RequiredArgsConstructor
public class PartController {
private final PartRepository partRepository;
@GetMapping("/{id}")
public ResponseEntity<PartDto> getPart(@PathVariable Long id) {
return partRepository.findById(id)
.map(part -> ResponseEntity.ok(PartDto.from(part)))
.orElse(ResponseEntity.notFound().build());
}
@GetMapping
public List<PartDto> searchParts(@RequestParam(defaultValue = "") String query,
@RequestParam(defaultValue = "") String category) {
List<Part> parts = category.isBlank()
? partRepository.findByNameContainingIgnoreCase(query)
: partRepository.findByNameContainingIgnoreCaseAndCategoryIgnoreCase(query, category);
return parts.stream().map(PartDto::from).toList();
}
public record PartDto(Long id, String partNumber, String name, String category,
BigDecimal unitPriceCredits, int stockLevel, String warehousePlanet) {
static PartDto from(Part part) {
return new PartDto(part.getId(), part.getPartNumber(), part.getName(), part.getCategory(),
part.getUnitPriceCredits(), part.getStockLevel(), part.getWarehousePlanet());
}
}
}
A quick curl -s localhost:8080/api/parts/1 confirms the same hyperdrive motivator comes back as JSON.
Before moving on, one option we describe but didn’t build: Boot 4.1 can also run gRPC through the servlet container itself, on Tomcat over HTTP/2. Per the docs, the switch is a dependency swap: exclude io.grpc:grpc-netty, add io.grpc:grpc-servlet-jakarta, and set server.http2.enabled=true. Instead of a separate Netty server on 9090, gRPC calls arrive on the same port as your REST endpoints (spring.grpc.server.port is ignored in this mode) and pass through the same servlet filters and Spring Security chain, which is attractive when you’re already fronting everything with a gateway (we’ve written about that setup in our API gateway tutorial) or when opening a second port is an operational headache. The trade-off is that you take Tomcat’s HTTP/2 configuration on as your problem. We stayed with the default standalone Netty server throughout this tutorial, and the Boot 4.1 gRPC reference covers the servlet route if you need it.
That’s it for the server itself. You may continue reading or return to the contents above.
Health checks
We saw grpc.health.v1.Health in the startup log, so let’s establish what it does before we improve it:
$ grpcurl -plaintext localhost:9090 grpc.health.v1.Health/Check
{
"status": "SERVING"
}That works with nothing beyond the server starter, because the starter includes io.grpc:grpc-services, which supplies the standard health (and reflection) implementations. This is the protocol-level health check that load balancers and service meshes speak natively.
The more useful behaviour is the bridge to Spring Boot’s own health system, and this one has a dependency subtlety we confirmed against the published POMs: the bridge classes compile against spring-boot-health as an optional dependency, so it is on you to bring it, which in practice means having spring-boot-starter-actuator on the classpath as we do. With actuator present, a scheduler copies Boot’s aggregated health into the gRPC health service, mapping UP to SERVING. Without it, you still get the endpoint above; the docs indicate it simply keeps answering SERVING, though we ran with actuator present throughout, so we haven’t observed that mode ourselves.
To watch the bridge do something, we’ll give the depot a maintenance switch. Under com.tucanoo.grpcserver.maintenance, create a MaintenanceHealthIndicator:
package com.tucanoo.grpcserver.maintenance;
import org.springframework.boot.health.contributor.Health;
import org.springframework.boot.health.contributor.HealthIndicator;
import org.springframework.stereotype.Component;
import java.util.concurrent.atomic.AtomicBoolean;
// Reports DOWN while the depot is in maintenance mode. The gRPC health bridge
// picks this up and flips grpc.health.v1 to NOT_SERVING on its next sweep.
@Component("maintenance")
public class MaintenanceHealthIndicator implements HealthIndicator {
private final AtomicBoolean underMaintenance = new AtomicBoolean(false);
public void setUnderMaintenance(boolean value) {
underMaintenance.set(value);
}
@Override
public Health health() {
return underMaintenance.get()
? Health.down().withDetail("reason", "depot is under maintenance").build()
: Health.up().build();
}
}
Note the import: HealthIndicator now lives in org.springframework.boot.health.contributor, part of Boot 4’s module split, so muscle memory from the old actuate package will send you to the wrong import. Alongside it, a small controller to flip the switch at runtime:
package com.tucanoo.grpcserver.maintenance;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/api/maintenance")
@RequiredArgsConstructor
public class MaintenanceController {
private final MaintenanceHealthIndicator maintenance;
@PutMapping("/{state}")
public Map<String, Boolean> setMaintenance(@PathVariable boolean state) {
maintenance.setUnderMaintenance(state);
return Map.of("underMaintenance", state);
}
}
Now the experiment, which we ran live. Call PUT /api/maintenance/true and hit both health surfaces. Actuator’s /actuator/health flips to 503 immediately. The gRPC Check, though, keeps answering SERVING for a few more seconds, then flips to NOT_SERVING. The bridge is polled, not event-driven: a scheduler sweeps Boot’s aggregated health into the gRPC health service every 5 seconds by default (spring.grpc.server.health.schedule.period, with a matching 5 second initial delay). Flip maintenance back off and SERVING returns on the next sweep. If your orchestrator’s failure detection assumes instant health transitions, that lag is worth knowing about, and the period is tunable if 5 seconds is too lazy for you.
By default only the overall health (the check with an empty service name) is populated. Ask about a named service, tucanoo.depot.v1.PartsDepot say, and the check fails with a NotFound status and an “unknown service” message. You can map named services to specific health indicators through configuration. The service name contains dots, so the map key needs brackets:
spring.grpc.server.health.service.[tucanoo.depot.v1.PartsDepot].include=maintenance
After that, a Check for the named service reflects the listed indicators. One subtlety we noticed while testing this: the named service only becomes known to the health service after the scheduler’s first sweep, so for the first few seconds after boot it still answers NotFound. Poll accordingly. The related switches are spring.grpc.server.health.enabled, which has no declared default and is effectively on whenever a gRPC service is present, plus spring.grpc.server.health.include-overall-health and spring.grpc.server.reflection.enabled, both defaulting to true, the latter covering the reflection service we used earlier.
Building the client
Over to the second application. The client’s whole gRPC configuration is one annotation and one property. Here’s GrpcClientApplication:
package com.tucanoo.grpcclient;
import com.tucanoo.depot.v1.PartsDepotGrpc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.grpc.client.ImportGrpcClients;
@SpringBootApplication
@ImportGrpcClients(target = "depot", types = PartsDepotGrpc.PartsDepotBlockingStub.class)
public class GrpcClientApplication {
public static void main(String[] args) {
SpringApplication.run(GrpcClientApplication.class, args);
}
}
Remember that Boot 4.1 dropped the classpath scanning spring-grpc 1.0 did, so this is the replacement: @ImportGrpcClients names the stub types you want as beans (or a basePackages to scan) and the channel they should use, and the auto-configuration registers each one in the context. Our single line registers a PartsDepotBlockingStub bean bound to a channel named depot, injectable by type anywhere in the application.
The channel itself is pure configuration, in application.properties:
spring.application.name=grpc-client
server.port=8081
spring.grpc.client.channel.depot.target=localhost:9090
# No collector running by default -- switch these back on via the 'otel' profile
management.otlp.metrics.export.enabled=false
management.tracing.export.otlp.enabled=false
management.logging.export.otlp.enabled=false
Note the property shape from the migration table earlier: singular channel, and target for the address. Each named channel also accepts keepalive, deadline, TLS and load-balancing settings under the same prefix; we’ll use the TLS one shortly.
To exercise the stub we’ll front it with a REST facade, which doubles as the second half of our benchmark rig. Under com.tucanoo.grpcclient.api, create DepotController:
package com.tucanoo.grpcclient.api;
import com.tucanoo.depot.v1.GetPartRequest;
import com.tucanoo.depot.v1.PartResponse;
import com.tucanoo.depot.v1.PartsDepotGrpc;
import com.tucanoo.depot.v1.SearchRequest;
import com.tucanoo.depot.v1.StockUpdate;
import com.tucanoo.depot.v1.WatchStockRequest;
import io.grpc.Status.Code;
import io.grpc.StatusRuntimeException;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/depot/parts")
@RequiredArgsConstructor
public class DepotController {
private final PartsDepotGrpc.PartsDepotBlockingStub partsDepot;
@GetMapping("/{id}")
public PartView getPart(@PathVariable long id) {
try {
return PartView.from(partsDepot.getPart(GetPartRequest.newBuilder().setId(id).build()));
} catch (StatusRuntimeException e) {
if (e.getStatus().getCode() == Code.NOT_FOUND) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getStatus().getDescription());
}
throw e;
}
}
@GetMapping
public List<PartView> searchParts(@RequestParam(defaultValue = "") String query,
@RequestParam(defaultValue = "") String category) {
return partsDepot.searchParts(SearchRequest.newBuilder()
.setQuery(query)
.setCategory(category)
.build())
.getResultsList().stream()
.map(PartView::from)
.toList();
}
@GetMapping("/{id}/stock")
public List<StockView> watchStock(@PathVariable long id) {
List<StockView> updates = new ArrayList<>();
partsDepot.watchStock(WatchStockRequest.newBuilder().setPartId(id).build())
.forEachRemaining(update -> updates.add(StockView.from(update)));
return updates;
}
public record PartView(long id, String partNumber, String name, String category,
double unitPriceCredits, int stockLevel, String warehousePlanet) {
static PartView from(PartResponse p) {
return new PartView(p.getId(), p.getPartNumber(), p.getName(), p.getCategory(),
p.getUnitPriceCredits(), p.getStockLevel(), p.getWarehousePlanet());
}
}
public record StockView(long partId, int stockLevel, String warehousePlanet, long timestampMillis) {
static StockView from(StockUpdate u) {
return new StockView(u.getPartId(), u.getStockLevel(), u.getWarehousePlanet(), u.getTimestampMillis());
}
}
}
The stub is injected by constructor like any other bean. The blocking stub’s server-streaming call returns a plain Iterator, which the stock endpoint drains into a list; each next() blocks until the server pushes the next message, so this method takes about two and a half seconds by design. With both applications running:
$ curl -s localhost:8081/depot/parts/1
{"id":1,"partNumber":"PD-001","name":"Hyperdrive Motivator Mk III","category":"Propulsion","unitPriceCredits":12500.0,"stockLevel":14,"warehousePlanet":"Tatooine"}
$ curl -s -o /dev/null -w '%{http_code}' localhost:8081/depot/parts/999
404
$ curl -s localhost:8081/depot/parts/8/stock
[{"partId":8,"stockLevel":208,"warehousePlanet":"Tatooine","timestampMillis":1784477621196},{"partId":8,"stockLevel":211,...REST in the front, gRPC behind it, end to end. That’s essentially all a gRPC client needs in Boot 4.1: an annotation, a property, and constructor injection. You may continue reading or return to the contents.
Error handling with @GrpcAdvice
Back on the server, we left getPart throwing a plain PartNotFoundException. First the exception itself, under com.tucanoo.grpcserver.part:
package com.tucanoo.grpcserver.part;
public class PartNotFoundException extends RuntimeException {
public PartNotFoundException(long partId) {
super("No part with id " + partId);
}
}
Without any handling, an uncaught exception in a gRPC handler surfaces to callers as a bare UNKNOWN status, which helps nobody. The traditional fix was to hand-build Status.NOT_FOUND...asRuntimeException() at every throw site and pass it to responseObserver.onError(). Boot 4.1 gives us the same centralised model we’ve had in MVC for years with @ControllerAdvice: a @GrpcAdvice class translating domain exceptions to statuses in one place. Under com.tucanoo.grpcserver.grpc:
package com.tucanoo.grpcserver.grpc;
import com.tucanoo.grpcserver.part.PartNotFoundException;
import io.grpc.Status;
import org.springframework.grpc.server.advice.GrpcAdvice;
import org.springframework.grpc.server.advice.GrpcExceptionHandler;
// Careful with the imports here: @GrpcExceptionHandler (the annotation, advice package)
// shares its name with the GrpcExceptionHandler functional interface in
// org.springframework.grpc.server.exception. The IDE will happily offer both.
@GrpcAdvice
public class DepotGrpcExceptionAdvice {
@GrpcExceptionHandler
public Status handlePartNotFound(PartNotFoundException e) {
return Status.NOT_FOUND.withDescription(e.getMessage());
}
@GrpcExceptionHandler
public Status handleIllegalArgument(IllegalArgumentException e) {
return Status.INVALID_ARGUMENT.withDescription(e.getMessage());
}
}
The exception type each method handles is inferred from its parameter, and the return type can be Status, StatusException or StatusRuntimeException. There is no enable property and nothing to register: a global exception-handling interceptor is always active on the server, and the presence of a @GrpcAdvice bean plugs your methods into it. (If you prefer, any bean implementing the functional GrpcExceptionHandler interface joins the same chain; that’s the second import in the comment above.)
That comment is there because the collision is easy to hit and miserable to diagnose. The annotation org.springframework.grpc.server.advice.GrpcExceptionHandler and the functional interface org.springframework.grpc.server.exception.GrpcExceptionHandler share a simple name, both are on the classpath, and the IDE’s auto-import will cheerfully pick either. Inside a @GrpcAdvice class you want the advice package; import the other one and your handler methods are silently ignored. The import statement is the only visible difference.
The advice covers streaming handlers as well as unary ones, which we verified directly:
$ grpcurl -plaintext -d '{"id": 999}' localhost:9090 tucanoo.depot.v1.PartsDepot/GetPart
ERROR: Code: NotFound Message: No part with id 999
$ grpcurl -plaintext -d '{"id": -1}' localhost:9090 tucanoo.depot.v1.PartsDepot/GetPart
ERROR: Code: InvalidArgument Message: part id must be positive, got -1
$ grpcurl -plaintext -d '{"part_id": 999}' localhost:9090 tucanoo.depot.v1.PartsDepot/WatchStock
ERROR: Code: NotFound Message: No part with id 999On the client side, a status arrives as a catchable StatusRuntimeException, which is exactly what the DepotController facade caught earlier to produce its HTTP 404.
TLS with SSL bundles
Everything so far has been plaintext, which is fine on a developer laptop and nowhere else. Boot 4.1 configures gRPC TLS through the same SSL bundles mechanism the rest of Boot uses, so if you’ve configured a bundle for Tomcat or a mail client, this will look familiar.
A decision first: we put TLS in a separate tls Spring profile in both modules and kept the default profile plaintext. That way the tutorial teaches both modes, the grpcurl examples above stay simple, and the benchmark runs on the default profile. Generate a self-signed certificate into the server’s src/main/resources/certs/:
openssl req -x509 -noenc -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 \
-keyout server.key -out server.crt -days 825 -subj "/CN=localhost" \
-addext "subjectAltName=DNS:localhost,IP:127.0.0.1"
Needless to say, a self-signed certificate baked into the repository is a tutorial device: in production these come from your CA or ACME pipeline and live outside the artifact, and Boot’s PEM bundles will happily read them from filesystem paths instead of the classpath. The server’s application-tls.yaml declares a bundle named depot and points the gRPC server at it:
# TLS profile: run with --spring.profiles.active=tls
# Self-signed cert generated with:
# openssl req -x509 -noenc -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 \
# -keyout server.key -out server.crt -days 825 -subj "/CN=localhost" \
# -addext "subjectAltName=DNS:localhost,IP:127.0.0.1"
spring:
ssl:
bundle:
pem:
depot:
keystore:
certificate: classpath:certs/server.crt
private-key: classpath:certs/server.key
grpc:
server:
ssl:
bundle: depot
The client gets a copy of the public certificate (just server.crt, never the key) in its own resources as a trust anchor, and its application-tls.properties is two lines:
# TLS profile: trust the server's self-signed cert and switch the channel to TLS
spring.ssl.bundle.pem.depot.truststore.certificate=classpath:certs/server.crt
spring.grpc.client.channel.depot.ssl.bundle=depot
Setting the channel’s ssl.bundle is sufficient; ssl.enabled switches itself on when a bundle is present. Start both applications with --spring.profiles.active=tls and the facade works exactly as before, now over an encrypted channel. For mutual TLS you’d add a truststore to the server’s bundle and set spring.grpc.server.ssl.client-auth=require.
grpcurl needs its flags adjusted to match. TLS is actually grpcurl’s default, so you drop -plaintext, point it at the certificate, and you should get the same SERVING answer as before:
$ grpcurl -cacert src/main/resources/certs/server.crt localhost:9090 grpc.health.v1.Health/Check
The failure modes are worth triggering once on purpose, because they look completely different. Keep -plaintext against the TLS server and the call hangs until its deadline expires (context deadline exceeded): the server is waiting for a TLS handshake that never comes. Use TLS but forget -cacert and it fails fast with certificate signed by unknown authority. If you see the first symptom between two of your own services, check both ends agree about TLS before debugging anything else; Baeldung’s long-standing gRPC guide calls this mismatch out as a common pitfall, and now you’ve seen exactly what it looks like from both sides.
Testing
First, a categorical statement we checked by unzipping the test jar: there is no @GrpcTest slice in Boot 4.1. The complete annotation surface of spring-boot-grpc-test is @AutoConfigureTestGrpcTransport and @LocalGrpcServerPort, and the intended model is a full @SpringBootTest context with a test transport, not a slice. Save yourself the search.
@AutoConfigureTestGrpcTransport starts an in-process gRPC server (no network, no ports) and routes every channel the test creates to it. Conveniently, spring-boot-starter-grpc-server-test also pulls in the client-side channel machinery, so a server project can write stub-based tests without touching its main dependency list. In grpc-server/src/test/java:
package com.tucanoo.grpcserver;
import com.tucanoo.depot.v1.GetPartRequest;
import com.tucanoo.depot.v1.PartResponse;
import com.tucanoo.depot.v1.PartsDepotGrpc;
import com.tucanoo.depot.v1.StreamPartsRequest;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.grpc.test.autoconfigure.AutoConfigureTestGrpcTransport;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.grpc.client.GrpcChannelFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
@SpringBootTest
@AutoConfigureTestGrpcTransport
class PartsDepotGrpcServiceTests {
@Autowired
private GrpcChannelFactory channels;
@Test
void getPartReturnsSeedData() {
var stub = PartsDepotGrpc.newBlockingStub(channels.createChannel("in-process"));
PartResponse part = stub.getPart(GetPartRequest.newBuilder().setId(1).build());
assertThat(part.getPartNumber()).isEqualTo("PD-001");
assertThat(part.getName()).isEqualTo("Hyperdrive Motivator Mk III");
assertThat(part.getWarehousePlanet()).isEqualTo("Tatooine");
}
@Test
void missingPartMapsToNotFoundViaAdvice() {
var stub = PartsDepotGrpc.newBlockingStub(channels.createChannel("in-process"));
var thrown = catchThrowableOfType(StatusRuntimeException.class,
() -> stub.getPart(GetPartRequest.newBuilder().setId(999).build()));
assertThat(thrown.getStatus().getCode()).isEqualTo(Status.Code.NOT_FOUND);
assertThat(thrown.getStatus().getDescription()).isEqualTo("No part with id 999");
}
@Test
void nonPositiveIdMapsToInvalidArgumentViaAdvice() {
var stub = PartsDepotGrpc.newBlockingStub(channels.createChannel("in-process"));
var thrown = catchThrowableOfType(StatusRuntimeException.class,
() -> stub.getPart(GetPartRequest.newBuilder().setId(-1).build()));
assertThat(thrown.getStatus().getCode()).isEqualTo(Status.Code.INVALID_ARGUMENT);
}
@Test
void streamPartsRepeatsTheCatalogue() {
var stub = PartsDepotGrpc.newBlockingStub(channels.createChannel("in-process"));
var messages = stub.streamParts(StreamPartsRequest.newBuilder().setRepeatCount(3).build());
int count = 0;
while (messages.hasNext()) {
messages.next();
count++;
}
assertThat(count).isEqualTo(120); // 40-part catalogue x 3
}
}
These run the real service, real advice and real seed data through the full gRPC call path, minus the network. A detail that had me curious: the string passed to createChannel is effectively a label under the test transport, because the test channel factory accepts any target and routes everything to the in-process server. Passing “in-process” is a convention that makes the test’s intent obvious to the next reader.
Sometimes you do want the real Netty transport in the loop, HTTP/2 framing and all. Ask for a random port and inject it:
package com.tucanoo.grpcserver;
import com.tucanoo.depot.v1.PartsDepotGrpc;
import com.tucanoo.depot.v1.SearchRequest;
import com.tucanoo.depot.v1.SearchResponse;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.boot.grpc.test.autoconfigure.LocalGrpcServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(properties = "spring.grpc.server.port=0")
class PartsDepotServerTransportTests {
@LocalGrpcServerPort
private int grpcPort;
@Test
void searchPartsOverRealNettyTransport() {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", grpcPort)
.usePlaintext()
.build();
try {
var stub = PartsDepotGrpc.newBlockingStub(channel);
SearchResponse response = stub.searchParts(
SearchRequest.newBuilder().setQuery("vaporator").build());
assertThat(response.getResultsCount()).isEqualTo(2);
} finally {
channel.shutdownNow();
}
}
}
Port 0 means a dynamic port, and @LocalGrpcServerPort is the gRPC twin of @LocalServerPort (under the covers it’s literally a meta-annotated @Value("${local.grpc.server.port}")). Finally, the TLS profile deserves a test too, so the handshake configuration can’t rot unnoticed. I chose to keep this one in the suite: the random port and the in-repo trust anchor make it deterministic, and it never flaked across our runs.
package com.tucanoo.grpcserver;
import com.tucanoo.depot.v1.GetPartRequest;
import com.tucanoo.depot.v1.PartsDepotGrpc;
import io.grpc.Grpc;
import io.grpc.ManagedChannel;
import io.grpc.TlsChannelCredentials;
import org.junit.jupiter.api.Test;
import org.springframework.boot.grpc.test.autoconfigure.LocalGrpcServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.test.context.ActiveProfiles;
import java.io.IOException;
import java.io.InputStream;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(properties = "spring.grpc.server.port=0")
@ActiveProfiles("tls")
class PartsDepotTlsTransportTests {
@LocalGrpcServerPort
private int grpcPort;
@Test
void handshakesWithTrustedSelfSignedCert() throws IOException {
var credentials = TlsChannelCredentials.newBuilder()
.trustManager(certificate())
.build();
ManagedChannel channel = Grpc.newChannelBuilderForAddress("localhost", grpcPort, credentials).build();
try {
var part = PartsDepotGrpc.newBlockingStub(channel)
.getPart(GetPartRequest.newBuilder().setId(1).build());
assertThat(part.getPartNumber()).isEqualTo("PD-001");
} finally {
channel.shutdownNow();
}
}
private InputStream certificate() throws IOException {
return new ClassPathResource("certs/server.crt").getInputStream();
}
}
./gradlew test runs green in both modules: seven tests across four classes on the server (including the default context-loads test Initializr generated), one on the client. That’s it for testing; you may continue reading or return to the contents.
Observability: metrics and traces
We added the OpenTelemetry starter on Initializr back at the start, and it’s time to explain the export switches we’ve been carrying in the default configuration since then. With spring-boot-starter-opentelemetry on the classpath, the OTLP metrics exporter assumes a collector at http://localhost:4318 and tries to publish to it every minute. Run without a collector and your log fills with a fresh export failure each time. Harmless, but noisy, which is why both applications disable OTLP export in their default profile and switch it back on in a dedicated otel profile for when a collector is actually running.

The server’s application-otel.yaml:
# Run with --spring.profiles.active=otel alongside an OTLP collector on localhost:4318
management:
otlp:
metrics:
export:
enabled: true
opentelemetry:
tracing:
export:
otlp:
# metrics default to localhost:4318, but trace export stays off until
# an endpoint is given explicitly
endpoint: http://localhost:4318/v1/traces
tracing:
export:
otlp:
enabled: true
sampling:
probability: 1.0
The client’s application-otel.properties mirrors it. That endpoint line earned its comment the hard way. Metrics default to localhost:4318, so we assumed traces would too; instead the collector received metrics and precisely zero traces until we set management.opentelemetry.tracing.export.otlp.endpoint explicitly. The OTLP span exporter simply isn’t created without it in this setup. If you’re staring at a collector wondering where your traces went, check that property before anything else. Sampling defaults to 0.1, so we also raise it to 1.0 for the demo, and spans ship in batches on a 5 second schedule, so give it a moment before concluding it’s broken.
With an OpenTelemetry collector running and both apps on the otel profile, a single curl localhost:8081/depot/parts/1 produced exactly one trace with three spans in a clean parent-child chain:
| Service | Span | Kind | Parent |
|---|---|---|---|
| grpc-client | http get /depot/parts/{id} | Server (Tomcat) | root |
| grpc-client | tucanoo.depot.v1.PartsDepot/GetPart | Client | the Tomcat span |
| grpc-server | tucanoo.depot.v1.PartsDepot/GetPart | Server | the gRPC client span |

The part that deserves attention is what we didn’t do to get this. Trace context propagated across the gRPC hop with no configuration at all, because Boot 4.1 auto-registers Micrometer’s observation interceptors on both sides: ObservationGrpcServerInterceptor on the server (governed by spring.grpc.server.observation.enabled, default true) and its client twin (spring.grpc.client.observation.enabled, also default true). The docs are quiet about the server side, so we confirmed it in the Boot 4.1 sources and then watched it work: the server interceptor picks up the context from the incoming gRPC metadata and continues the trace.
Metrics come along for free as well. With the management endpoints exposed, /actuator/metrics on the server gains a grpc.server timer plus grpc.server.active, grpc.server.received and grpc.server.sent, tagged with rpc.service, rpc.method, rpc.type and grpc.status_code, and the client publishes the mirror set under grpc.client. Between the trace table and those tags you have per-method latency and error rates without writing a line of instrumentation.
Observation being on by default is a choice with a price, though, and we measured the price. Hold that thought for the next section.
REST vs gRPC: the benchmark
We benchmarked the depot service the same way we benchmarked virtual threads in Spring Boot 4: k6 driving a closed model, warm-up discarded, load generator and server kept apart, per-run CPU verified, and honest caveats stated up front. k6 speaks HTTP, so the gRPC side uses ghz (v0.120.0) with the same concurrency and duration; the REST side is k6 v2.1.0 as before.
The comparison is deliberately narrow and fair: the same Spring Boot process serves the same 40-row H2 catalogue over REST JSON (GET /api/parts/{id}, Tomcat, port 8080) and gRPC (PartsDepot/GetPart, Netty, port 9090). Same repository, same data row (id=7), 16 concurrent callers, default profile exactly as this tutorial leaves it. So this measures transport and serialisation, with everything else held constant.
First, the honesty section, because the environment shaped the method. These runs were made on a shared, virtualised 2-vCPU sandbox whose two vCPUs are hyperthread siblings of a single physical core (an i9-9900K host under Hyper-V), and whose real CPU allocation drifts minute to minute in ways the guest can’t see. So we built the harness around paired bursts: each pair boots a fresh JVM, warms both protocols at full load, then measures REST and gRPC back to back within seconds of each other, with the order alternated between pairs and a fixed-work CPU probe run before and after each pair so throttled phases could be detected and discarded. The server was pinned to one vCPU (saturated at 99 to 100% in every measured run, by design), the load generators to the other (never above 30% busy, so never the limiter). A JDK 25 AOT cache sped up startup identically for both protocols; no other JVM tuning. The absolute numbers below belong to that odd little box and shouldn’t travel. The ratios are the point, and the bench/ folder in the repository has the scripts so you can reproduce them on hardware you trust.
Four clean order-balanced pairs of 12-second runs at concurrency 16:
| Pair | Order | REST req/s | REST p50/p95/p99 (ms) | gRPC req/s | gRPC p50/p95/p99 (ms) |
|---|---|---|---|---|---|
| 1 | REST first | 1,509 | 7.2 / 29.0 / 41.3 | 1,999 | 7.7 / 13.0 / 16.5 |
| 2 | gRPC first | 1,752 | 6.5 / 25.3 / 33.3 | 1,647 | 8.7 / 18.1 / 27.1 |
| 3 | REST first | 1,528 | 7.2 / 28.8 / 41.1 | 2,047 | 7.4 / 13.0 / 17.7 |
| 4 | gRPC first | 1,698 | 6.7 / 26.0 / 34.9 | 1,853 | 8.0 / 15.0 / 21.7 |
| Median | 1,613 | 7.0 / 27.4 / 38.0 | 1,926 | 7.9 / 14.0 / 19.7 |

How to read that. On throughput, gRPC came out about 19% ahead at the median, but note the spread: whichever protocol ran second in a pair scored higher, a residual warm-up effect, which is exactly why we alternated the order. Comparing like position with like, gRPC leads in all four position-matched comparisons. On latency, the medians are near identical at 7 to 9ms, because the actual work per request (an H2 lookup and some serialisation) is the same. The difference is in the percentiles: gRPC’s p95 and p99 are roughly half of REST’s at the same concurrency. The medians are basically level; the gap between the two only shows up in the tail latencies. During the throttled host phases we discarded from the table, the gap widened further in gRPC’s favour, consistent with protobuf-over-HTTP/2 costing less per request when CPU is scarce.
One fairness note on connection models, since it’s the first objection anyone raises: ghz used its default single HTTP/2 connection with 16 multiplexed in-flight calls, and k6 used 16 keep-alive HTTP/1.1 connections. We left both alone, because that is how each protocol is idiomatically deployed; forcing them to match would have made one of them unidiomatic. Smaller payloads are also simply part of what protobuf is: the same part encodes to 68 bytes against 156 bytes of JSON.
What the default observation costs
Remember that the default profile keeps Micrometer observation instrumentation active for both protocols even when nothing consumes it. We ran an A/B with observation disabled on both sides (spring.grpc.server.observation.enabled=false and management.observations.enable.http.server.requests=false), and this was the result that genuinely surprised me. REST barely noticed: around 0 to 5%, within noise. gRPC jumped from roughly 2,000 req/s to 2,554, with p50 dropping from about 7.5ms to 5.9ms. On this box, the auto-registered server observation interceptor was costing gRPC roughly 20 to 25% of its throughput while no collector was even attached. That figure comes from one clean fast-phase pair (the host’s throttling windows cost us the repeats, though the direction held in the slow ones), so treat the exact percentage as indicative. The practical takeaway holds either way: if you aren’t exporting metrics or traces from a gRPC server, spring.grpc.server.observation.enabled=false is a meaningful free win, and if you are, at least you now know the instrumentation isn’t free.
What streaming is for
Finally, the streaming demonstration, which is not a like-for-like comparison and isn’t presented as one. StreamParts pushes the whole 40-part catalogue repeat_count times down one RPC; the REST equivalent refetches the catalogue as a 6,407-byte JSON response, repeatedly, over 16 connections. Same server lifetime, same probe-checked window:
| Leg | Messages/s | Payload MB/s | Parts records/s |
|---|---|---|---|
| gRPC StreamParts, 1 stream | ~86,000 | ~5.9 | ~86,000 |
| gRPC StreamParts, 16 streams | ~234,000 | ~15.9 | ~234,000 |
| REST catalogue fetch, 16 connections | n/a | ~2.2 | ~13,600 |
A single gRPC stream moved about six times the parts-records per second of 16 concurrent REST connections; 16 streams moved about seventeen times, at which point the server core is saturated with pure serialisation and transport work. Two footnotes. Each REST response re-serialises the full JSON and pays per-request overhead every time, which is precisely the difference being demonstrated. And protobuf’s 68 bytes per part against roughly 160 bytes of JSON means the records-per-second ratio flatters gRPC more than the raw MB/s ratio does (about 2.7 to 7 times). If you’re shipping a lot of small structured messages to another service, this is the use case where the protocol choice has a measurable effect on throughput.
Raw tool outputs, probe logs and per-run CPU accounting are alongside the scripts in the repository. We’d like to see the pair ratios from a machine that isn’t sharing one physical core with its own load generator, so if you run bench/ on real hardware, tell us what you get.
Summing up
SO by now we now have a working, albeit somewhat simplified, gRPC estate: a server with health checks, centralised error handling, TLS and tracing, a client wired up with one annotation, tests against both in-process and real transports, and numbers describing how it performs against REST on the same data. To be clear about what we simplified: the database is in-memory and reseeded on every boot, the certificate is self-signed and lives in the repository, there’s no authentication on the gRPC surface, and no deadlines or retry policies are configured on the channel. Every one of those has a production answer that didn’t fit here.
Which makes them good exercises. If you want to take this further:
- Bidirectional streaming. We covered server streaming only. Add a client-streaming or bidi RPC to the proto (a live restock negotiation, say) and see how the generated stub API changes shape.
- Security. Boot 4.1 auto-configures Spring Security for gRPC servers, including an OAuth2 resource-server mode. Put a token check in front of the depot.
- Deadlines and retries. Set
spring.grpc.client.channel.depot.default.deadline, watch what a slowWatchStockdoes to the caller, then explore per-method retry policy via the channel’s service config. - Share the proto properly. Replace the duplicated proto file with a shared module or a published stub artifact, and feel where the build complexity lands.
Don’t forget all the code is available on GitHub, including the benchmark harness and raw results. If you’re planning the wider move to the Spring Boot 4 line, our migration guide and the virtual threads benchmark are the companion reads. I hope this has shown how much of the ceremony that used to surround gRPC on the JVM has simply gone: in Boot 4.1 a gRPC service is an annotated class and a proto file, and the platform does the rest.
