Part 7 of 7 — Reactive Backend Engineering with Java & Spring

gRPC Client in WebFlux and Testing Strategy

Oct 2026 · 8 min read

This article adds a gRPC client to movies-info-service, which remains WebFlux. The gRPC stream is wrapped into a Flux, combined with movie data via zipWith, and StatusRuntimeException is mapped to HTTP status codes. Everything is tested against a fake gRPC server via in-process transport, and the tests still pass.

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

Problem

movies-info-service only knows movie data in MongoDB, while reviews live in movies-review-service, which communicates over gRPC. The async gRPC stub uses StreamObserver callbacks, not Flux, and its errors are StatusRuntimeException, which is unknown to the HTTP handler.

  1. Callback is not composable: the async stub cannot be directly zipped with the movie Mono, so it needs to be wrapped into a Flux.

  2. gRPC status leaks as 500: without mapping, a dead review service becomes an internal error in the HTTP client, even though the cause is an unavailable dependency.

Outcome

Readers will be able to:

  • Register a gRPC stub as a bean with @ImportGrpcClients and a named channel in application.yml.

  • Wrap a gRPC server stream into a Flux with Flux.create and ClientResponseObserver.

  • Test the client against a fake gRPC server via @AutoConfigureTestGrpcTransport, including mapping StatusRuntimeException to HTTP.

Implementation

Folder Structure

text
movies-info-service/
├── build.gradle                                       # changed
└── src/
    ├── main/
    │   ├── proto/review.proto                         # new
    │   ├── java/dev/sch39/movies_info_service/
    │   │   ├── ReviewClient.java                      # new
    │   │   ├── MovieInfoReviewService.java            # new
    │   │   ├── MovieInfoController.java               # changed
    │   │   ├── GlobalErrorHandler.java                # changed
    │   │   ├── MovieInfo.java
    │   │   ├── MovieInfoRepository.java
    │   │   └── MovieInfoService.java
    │   └── resources/application.yml                  # changed
    └── test/java/dev/sch39/movies_info_service/
        ├── ReviewClientTest.java                      # new
        ├── MovieInfoValidationTest.java               # changed
        ├── MovieInfoControllerTest.java
        └── MovieInfoRepositoryTest.java

Setup

Continue the project:

bash
cd movies-info-service

The review server does not need to be running: the test uses a fake gRPC server within the same process.

Code Blocks

Block 1: Client dependency and channel address

movies-info-service/build.gradle:

groovy
plugins {
	id 'java'
	id 'org.springframework.boot' version '4.1.2'
	id 'io.spring.dependency-management' version '1.1.7'
	id 'com.google.protobuf' version '0.9.6'
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-grpc-client'
	testImplementation 'org.springframework.boot:spring-boot-starter-grpc-client-test'
	testImplementation 'org.springframework.boot:spring-boot-starter-grpc-server'
}

protobuf {
	plugins {
		grpc {}
	}
}

movies-info-service/src/main/resources/application.yml:

yaml
spring:
  grpc:
    client:
      channel:
        review:
          target: static://localhost:9090
server:
  port: 8082

Purpose: Add the client starter, the protobuf plugin, and a test-only gRPC server, and define a named channel review that points to the review service.

Block 2: .proto contract as a copy

movies-info-service/src/main/proto/review.proto:

proto
syntax = "proto3";

package dev.sch39.movies_info_service.grpc;

option java_multiple_files = true;
option java_package = "dev.sch39.movies_info_service.grpc";

service ReviewService {
  rpc AddReview(AddReviewRequest) returns (ReviewReply);
  rpc ListReviews(ListReviewsRequest) returns (ListReviewsReply);
  rpc StreamReviews(ListReviewsRequest) returns (stream ReviewReply);
}

message AddReviewRequest {
  int64 movie_info_id = 1;
  string comment = 2;
  double rating = 3;
}

message ListReviewsRequest {
  int64 movie_info_id = 1;
}

message ReviewReply {
  string review_id = 1;
  int64 movie_info_id = 2;
  string comment = 3;
  double rating = 4;
}

message ListReviewsReply {
  repeated ReviewReply reviews = 1;
}

Purpose: Copy the review service contract with the java_package of movies-info-service, so the client generates ReviewServiceGrpc from the same definition.

Block 3: Async stub wrapped into a Flux

movies-info-service/src/main/java/dev/sch39/movies_info_service/ReviewClient.java:

java
package dev.sch39.movies_info_service;

import org.springframework.grpc.client.ImportGrpcClients;
import org.springframework.stereotype.Component;

import dev.sch39.movies_info_service.grpc.ListReviewsRequest;
import dev.sch39.movies_info_service.grpc.ReviewReply;
import dev.sch39.movies_info_service.grpc.ReviewServiceGrpc;
import io.grpc.stub.ClientCallStreamObserver;
import io.grpc.stub.ClientResponseObserver;
import reactor.core.publisher.Flux;

@Component
@ImportGrpcClients(target = "review", types = ReviewServiceGrpc.ReviewServiceStub.class)
public class ReviewClient {

    private final ReviewServiceGrpc.ReviewServiceStub stub;

    public ReviewClient(ReviewServiceGrpc.ReviewServiceStub stub) {
        this.stub = stub;
    }

    public Flux<ReviewReply> reviews(long movieInfoId) {
        var request = ListReviewsRequest.newBuilder().setMovieInfoId(movieInfoId).build();
        return Flux.create(sink -> stub.streamReviews(request, new ClientResponseObserver<ListReviewsRequest, ReviewReply>() {
            @Override
            public void beforeStart(ClientCallStreamObserver<ListReviewsRequest> call) {
                sink.onCancel(() -> call.cancel("subscriber cancelled", null));
            }

            @Override
            public void onNext(ReviewReply reply) {
                sink.next(reply);
            }

            @Override
            public void onError(Throwable error) {
                sink.error(error);
            }

            @Override
            public void onCompleted() {
                sink.complete();
            }
        }));
    }
}

Purpose: Register the async stub for the review channel and forward onNext/onError/onCompleted to the FluxSink, with subscriber cancellation forwarded as cancel on the call.

Block 4: Combining movie and reviews

movies-info-service/src/main/java/dev/sch39/movies_info_service/MovieInfoReviewService.java:

java
package dev.sch39.movies_info_service;

import java.time.Duration;
import java.util.List;

import org.springframework.stereotype.Service;

import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Service
public class MovieInfoReviewService {

    public record MovieWithReviews(MovieInfo movie, List<String> reviews) {
    }

    private final MovieInfoService movies;
    private final ReviewClient reviews;

    public MovieInfoReviewService(MovieInfoService movies, ReviewClient reviews) {
        this.movies = movies;
        this.reviews = reviews;
    }

    public Mono<MovieWithReviews> findWithReviews(String id, long reviewMovieId) {
        var comments = reviews.reviews(reviewMovieId)
                .timeout(Duration.ofSeconds(2))
                .onErrorResume(MovieInfoReviewService::isNotFound, e -> Flux.empty())
                .map(reply -> reply.getComment())
                .collectList();
        return movies.findById(id).zipWith(comments, MovieWithReviews::new);
    }

    private static boolean isNotFound(Throwable error) {
        return error instanceof StatusRuntimeException e && e.getStatus().getCode() == Status.Code.NOT_FOUND;
    }
}

movies-info-service/src/main/java/dev/sch39/movies_info_service/MovieInfoController.java:

java
    private final MovieInfoService service;
    private final MovieInfoReviewService reviewService;

    public MovieInfoController(MovieInfoService service, MovieInfoReviewService reviewService) {
        this.service = service;
        this.reviewService = reviewService;
    }

// rest of the code is still the same

    @GetMapping("/{id}/with-reviews")
    public Mono<ResponseEntity<MovieInfoReviewService.MovieWithReviews>> findWithReviews(@PathVariable String id,
            @RequestParam long reviewMovieId) {
        return reviewService.findWithReviews(id, reviewMovieId)
                .map(ResponseEntity::ok)
                .switchIfEmpty(Mono.just(ResponseEntity.notFound().build()));
    }

Purpose: Combine the movie Mono with the list of comments via zipWith, apply a 2-second timeout, and treat NOT_FOUND from the review service as an empty list.

The controller receives MovieInfoReviewService reviewService via the constructor and imports org.springframework.web.bind.annotation.RequestParam.

Because the controller constructor changed, the old tests that use @WebFluxTest must mock that new dependency. Add the following field below @MockitoBean private MovieInfoService service;:

projects-article/movies-info-service/src/test/java/dev/sch39/movies_info_service/MovieInfoValidationTest.java:

java
    @MockitoBean
    private MovieInfoReviewService reviewService;

Block 5: Mapping StatusRuntimeException to HTTP

movies-info-service/src/main/java/dev/sch39/movies_info_service/GlobalErrorHandler.java:

java
    @ExceptionHandler(StatusRuntimeException.class)
    public ResponseEntity<String> handleGrpcStatus(StatusRuntimeException ex) {
        var status = switch (ex.getStatus().getCode()) {
            case UNAVAILABLE -> HttpStatus.SERVICE_UNAVAILABLE;
            case DEADLINE_EXCEEDED -> HttpStatus.GATEWAY_TIMEOUT;
            default -> HttpStatus.BAD_GATEWAY;
        };
        return ResponseEntity.status(status).body("review service: " + ex.getStatus().getCode());
    }

    @ExceptionHandler(TimeoutException.class)
    public ResponseEntity<String> handleTimeout(TimeoutException ex) {
        return ResponseEntity.status(HttpStatus.GATEWAY_TIMEOUT).body("review service: timeout");
    }

Purpose: Map gRPC statuses and Flux timeouts to 503/504/502 so that review service failures do not appear as an internal error.

Add import java.util.concurrent.TimeoutException; and import io.grpc.StatusRuntimeException;.

Test Blocks

Test 1: Server stream becomes a Flux, status becomes an error

movies-info-service/src/test/java/dev/sch39/movies_info_service/ReviewClientTest.java:

java
package dev.sch39.movies_info_service;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.List;

import org.junit.jupiter.api.BeforeEach;
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.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.webtestclient.autoconfigure.AutoConfigureWebTestClient;
import org.springframework.context.annotation.Bean;
import org.springframework.test.web.reactive.server.WebTestClient;

import dev.sch39.movies_info_service.grpc.ListReviewsRequest;
import dev.sch39.movies_info_service.grpc.ReviewReply;
import dev.sch39.movies_info_service.grpc.ReviewServiceGrpc;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
import reactor.test.StepVerifier;

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.mongodb.database=movies_info_grpc_test")
@AutoConfigureWebTestClient
@AutoConfigureTestGrpcTransport
class ReviewClientTest {

    @TestConfiguration
    static class FakeReviewServer {
        @Bean
        ReviewServiceGrpc.ReviewServiceImplBase fakeReviewService() {
            return new ReviewServiceGrpc.ReviewServiceImplBase() {
                @Override
                public void streamReviews(ListReviewsRequest request, StreamObserver<ReviewReply> observer) {
                    switch ((int) request.getMovieInfoId()) {
                        case 1 -> {
                            observer.onNext(ReviewReply.newBuilder().setComment("Great").build());
                            observer.onNext(ReviewReply.newBuilder().setComment("Dark").build());
                            observer.onCompleted();
                        }
                        case 2 -> observer.onError(Status.UNAVAILABLE.asRuntimeException());
                        default -> observer.onError(Status.NOT_FOUND.asRuntimeException());
                    }
                }
            };
        }
    }

    private static final String URL = "/v1/movie-info";

    @Autowired
    private ReviewClient client;

    @Autowired
    private MovieInfoRepository repository;

    @Autowired
    private WebTestClient web;

    private String movieId;

    @BeforeEach
    void saveMovie() {
        repository.deleteAll().block();
        movieId = repository.save(new MovieInfo(null, "Batman Begins", 2005, List.of("Christian Bale")))
                .block().movieInfoId();
    }

    @Test
    void clientTurnsServerStreamIntoFluxAndStatusIntoError() {
        var comments = client.reviews(1).map(ReviewReply::getComment).collectList().block();
        System.out.println("comments=" + comments);
        assertEquals(List.of("Great", "Dark"), comments, "streamed comments");

        StepVerifier.create(client.reviews(99))
                .expectErrorSatisfies(error -> {
                    var code = ((StatusRuntimeException) error).getStatus().getCode();
                    System.out.println("errorCode=" + code);
                    assertEquals(Status.Code.NOT_FOUND, code, "status code");
                })
                .verify();
    }

Purpose: Prove that the async stub via in-process transport produces a Flux containing two comments, and that NOT_FOUND from the server arrives as a StatusRuntimeException error.

Test 2: Movie and reviews combined, NOT_FOUND becomes empty

movies-info-service/src/test/java/dev/sch39/movies_info_service/ReviewClientTest.java:

java
    @Test
    void withReviewsMergesMovieAndReviewsAndTreatsNotFoundAsEmpty() {
        var merged = web.get().uri(URL + "/{id}/with-reviews?reviewMovieId=1", movieId)
                .exchange().expectStatus().isOk()
                .expectBody(MovieInfoReviewService.MovieWithReviews.class).returnResult().getResponseBody();
        var none = web.get().uri(URL + "/{id}/with-reviews?reviewMovieId=99", movieId)
                .exchange().expectStatus().isOk()
                .expectBody(MovieInfoReviewService.MovieWithReviews.class).returnResult().getResponseBody();

        System.out.println("merged=" + merged.movie().name() + " " + merged.reviews() + " none=" + none.reviews());
        assertEquals(List.of("Great", "Dark"), merged.reviews(), "merged reviews");
        assertEquals(List.of(), none.reviews(), "reviews for NOT_FOUND");
    }

Purpose: Prove that the HTTP endpoint returns the movie along with its comments, and that a movie without reviews still returns 200 with an empty list.

Test 3: UNAVAILABLE becomes 503

movies-info-service/src/test/java/dev/sch39/movies_info_service/ReviewClientTest.java:

java
    @Test
    void unavailableReviewServiceBecomes503() {
        var body = web.get().uri(URL + "/{id}/with-reviews?reviewMovieId=2", movieId)
                .exchange().expectStatus().isEqualTo(503)
                .expectBody(String.class).returnResult().getResponseBody();

        System.out.println("status=503 body=" + body);
        assertEquals("review service: UNAVAILABLE", body, "error body");
    }
}

Purpose: Prove that a StatusRuntimeException with UNAVAILABLE status is mapped by GlobalErrorHandler to HTTP 503 with a message that does not leak internal details.

Run Test

Run from the movies-info-service/ folder:

bash
./gradlew cleanTest test -i

Output:

text
...
MovieInfoControllerTest > updateReplacesFieldsAndKeepsId() STANDARD_OUT
...
    updated=MovieInfo[movieInfoId=6ae44b8236d9f2d448fae4e9, name=The Dark Knight, year=2008, cast=[Heath Ledger]]
    count=1

MovieInfoControllerTest > deletedIdReturnsNotFound() STANDARD_OUT
    count after delete=0

MovieInfoControllerTest > createThenFindById() STANDARD_OUT
    saved=MovieInfo[movieInfoId=6ae44b8236d9f2d448fae4eb, name=Batman Begins, year=2005, cast=[Christian Bale]]
    found=MovieInfo[movieInfoId=6ae44b8236d9f2d448fae4eb, name=Batman Begins, year=2005, cast=[Christian Bale]]
...
MovieInfoRepositoryTest > saveGeneratesIdOnEmbeddedMongo() STANDARD_OUT
...
    saved=MovieInfo[movieInfoId=6ae44b8336d9f2d448fae4ed, name=Inception, year=2010, cast=[Leonardo DiCaprio]]
...
MovieInfoValidationTest > invalidBodyReturns400WithFieldMessages() STANDARD_OUT
    400 body=cast: cast must not be empty, name: name must be present, year: year must be a positive number

MovieInfoValidationTest > unexpectedExceptionReturns500WithoutLeakingDetails() STANDARD_OUT
    500 body=internal error
...
ReviewClientTest > withReviewsMergesMovieAndReviewsAndTreatsNotFoundAsEmpty() STANDARD_OUT
...
    merged=Batman Begins [Great, Dark] none=[]

ReviewClientTest > unavailableReviewServiceBecomes503() STANDARD_OUT
    status=503 body=review service: UNAVAILABLE

ReviewClientTest > clientTurnsServerStreamIntoFluxAndStatusIntoError() STANDARD_OUT
    comments=[Great, Dark]
    errorCode=NOT_FOUND
...
BUILD SUCCESSFUL in 28s

Why It Works

Named channel: @ImportGrpcClients(target = "review", ...) registers the stub as a bean that uses the review channel, whose address is read from spring.grpc.client.channel.review.target (Spring gRPC, Client). This annotation is required to register the stub as a bean; it is no longer automatic.

Flux.create and ClientResponseObserver: the async stub calls onNext/onError/onCompleted from gRPC threads, and FluxSink is safe to call from other threads. beforeStart provides access to ClientCallStreamObserver, where cancel can be invoked when the subscriber cancels.

In-process transport: @AutoConfigureTestGrpcTransport connects the stub to a server in the same process without a network port, and the fake server is registered as an ordinary BindableService bean (Spring gRPC, Server). Error mapping still goes through @ControllerAdvice because StatusRuntimeException flows as a Mono error to the HTTP handler.

Edge Cases

Cancellation and timeout are not tested: sink.onCancel(... call.cancel(...)) and .timeout(Duration.ofSeconds(2)) are in the code, but no test proves that the call is actually cancelled or that TimeoutException becomes 504.

Flux.create without backpressure to gRPC: the default Flux.create strategy is an unbounded buffer, so a large stream from the server is held in memory if the subscriber is slow. This client does not manage flow control like the server-side bridge in StreamObserver to Reactor Bridge: Unary, Streaming, Backpressure, and Errors.

The fake server is not the real server: the tested contract is a copy of the .proto, so changes in the review service are not automatically detected. Integration tests against the real movies-review-service with Testcontainers are not demonstrated in this article.

Trade-offs

Strategy

Pro

Con

In-process fake gRPC server

Fast, no Docker or ports

Does not catch mismatches with the real implementation

Mock ReviewClient (@MockitoBean)

Simplest for controller tests

The Flux.create wrapper and Status mapping are not tested

Real review service in Testcontainers

Closest to production

Slow, requires Docker and a built image

Best practice: Test the client wrapper and error mapping against an in-process fake server, and keep a small number of integration tests against the real service for the contract.

Gotchas I Experienced

  • @WebFluxTest(MovieInfoController.class) in MovieInfoValidationTest failed to load the context after the controller received MovieInfoReviewService: NoSuchBeanDefinitionException: No qualifying bean of type 'dev.sch39.movies_info_service.MovieInfoReviewService' available. That old test needs @MockitoBean private MovieInfoReviewService reviewService;.

Production Checklist

  • Is the .proto copied to the client? Share it via a common module or contract version so it does not diverge from the server.

  • Is the channel target hardcoded to localhost:9090? Move it to an environment variable per environment.

  • Do the gRPC calls have a deadline? Set a deadline or timeout so a hanging review service does not hold up the HTTP request.

References