StreamObserver to Reactor Bridge: Unary, Streaming, Backpressure, and Errors
Oct 2026 · 7 min read
This article consolidates the StreamObserver to Reactor bridge into a single helper, GrpcReactiveBridge, for unary and server streaming RPCs. The streaming helper follows isReady() as backpressure and disposes the pipeline when the client cancels, then domain errors are mapped to gRPC Status via GrpcExceptionHandler and proven with tests.
Full code: https://github.com/Sch39/java-spring-boot
Problem
In previous article, each RPC wrote its own subscribe(observer::onNext, observer::onError, observer::onCompleted). For streaming RPCs that pattern is not enough: a Flux flows as fast as its source, while a slow client or one that has already left is not accounted for.
No backpressure:
onNexton aStreamObserverdoes not block when the outbound buffer is full, so a fastFluxaccumulates messages in memory.No cancellation: a client that cancels the call does not stop the server pipeline; the R2DBC query and emissions keep running.
Outcome
Readers can:
Bridge
Mono(unary) andFlux(server streaming) to aStreamObserverthrough a single helper.Apply backpressure with
ServerCallStreamObserver.isReady()andsetOnReadyHandler, and stop the pipeline viasetOnCancelHandler.Map exceptions to gRPC
Statuswith aGrpcExceptionHandlerbean and prove it from the client side.
Implementation
Folder Structure
movies-review-service/
└── src/
├── main/
│ ├── proto/review.proto # changed
│ └── java/dev/sch39/movies_review_service/
│ ├── GrpcReactiveBridge.java # new
│ ├── ReviewGrpcExceptionHandler.java # new
│ ├── ReviewGrpcService.java # changed
│ ├── Review.java
│ ├── RequestValidator.java
│ ├── ReviewHandler.java
│ └── ReviewRouter.java
└── test/java/dev/sch39/movies_review_service/
├── GrpcReactiveBridgeTest.java # new
├── ReviewGrpcServiceTest.java # changed
├── RequestValidatorTest.java
└── ReviewRouterTest.javaSetup
Continue the project:
cd movies-review-serviceThe ReviewGrpcServiceTest test uses Testcontainers, so Docker must be running.
Code Blocks
Block 1: Server streaming RPC in the contract
movies-review-service/src/main/proto/review.proto:
service ReviewService {
rpc AddReview(AddReviewRequest) returns (ReviewReply);
rpc ListReviews(ListReviewsRequest) returns (ListReviewsReply);
rpc StreamReviews(ListReviewsRequest) returns (stream ReviewReply);
}Goal: Add a StreamReviews RPC that sends one ReviewReply per review, so that ReviewServiceImplBase gets a streamReviews(request, StreamObserver<ReviewReply>) method.
Block 2: Unary bridge
movies-review-service/src/main/java/dev/sch39/movies_review_service/GrpcReactiveBridge.java:
package dev.sch39.movies_review_service;
import java.util.concurrent.atomic.AtomicBoolean;
import org.reactivestreams.Subscription;
import io.grpc.stub.ServerCallStreamObserver;
import io.grpc.stub.StreamObserver;
import reactor.core.publisher.BaseSubscriber;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public final class GrpcReactiveBridge {
private GrpcReactiveBridge() {
}
public static <T> void respond(Mono<T> source, StreamObserver<T> observer) {
source.subscribe(observer::onNext, observer::onError, observer::onCompleted);
}Goal: Consolidate the subscribe(onNext, onError, onComplete) pattern into a single respond helper used by all unary RPCs.
Block 3: Streaming bridge with backpressure and cancellation
movies-review-service/src/main/java/dev/sch39/movies_review_service/GrpcReactiveBridge.java:
public static <T> void stream(Flux<T> source, StreamObserver<T> observer) {
var call = (ServerCallStreamObserver<T>) observer;
var inFlight = new AtomicBoolean();
var subscriber = new BaseSubscriber<T>() {
@Override
protected void hookOnSubscribe(Subscription subscription) {
pump();
}
@Override
protected void hookOnNext(T value) {
call.onNext(value);
inFlight.set(false);
pump();
}
@Override
protected void hookOnComplete() {
call.onCompleted();
}
@Override
protected void hookOnError(Throwable error) {
call.onError(error);
}
void pump() {
if (call.isReady() && inFlight.compareAndSet(false, true)) {
request(1);
}
}
};
call.setOnReadyHandler(subscriber::pump);
call.setOnCancelHandler(subscriber::dispose);
source.subscribe(subscriber);
}
}Goal: Request one element only when isReady() is true, resume via setOnReadyHandler, and dispose the subscription via setOnCancelHandler.
Block 4: Service using both helpers
movies-review-service/src/main/java/dev/sch39/movies_review_service/ReviewGrpcService.java:
@Override
public void addReview(AddReviewRequest request, StreamObserver<ReviewReply> observer) {
var review = new Review(null, request.getMovieInfoId(), request.getComment(), request.getRating());
GrpcReactiveBridge.respond(template.insert(review).map(ReviewGrpcService::toReply), observer);
}
@Override
public void streamReviews(ListReviewsRequest request, StreamObserver<ReviewReply> observer) {
var reviews = template.select(Review.class)
.matching(query(where("movieInfoId").is(request.getMovieInfoId())))
.all()
.map(ReviewGrpcService::toReply)
.switchIfEmpty(Mono.error(new NoSuchElementException("no reviews for movieInfoId=" + request.getMovieInfoId())));
GrpcReactiveBridge.stream(reviews, observer);
}Goal: Replace the manual subscribe with respond for unary and use stream for the new RPC, with a movie without reviews reported as a pipeline error.
Add import java.util.NoSuchElementException; and import reactor.core.publisher.Mono;. listReviews is changed the same way as addReview: the Mono<ListReviewsReply> result is sent to GrpcReactiveBridge.respond.
Block 5: Mapping exceptions to Status
movies-review-service/src/main/java/dev/sch39/movies_review_service/ReviewGrpcExceptionHandler.java:
package dev.sch39.movies_review_service;
import java.util.NoSuchElementException;
import org.springframework.grpc.server.exception.GrpcExceptionHandler;
import org.springframework.stereotype.Component;
import io.grpc.Status;
import io.grpc.StatusException;
@Component
public class ReviewGrpcExceptionHandler implements GrpcExceptionHandler {
@Override
public StatusException handleException(Throwable exception) {
if (exception instanceof NoSuchElementException) {
return Status.NOT_FOUND.withDescription(exception.getMessage()).asException();
}
return null;
}
}Goal: Translate NoSuchElementException into Status.NOT_FOUND and return null for other exceptions so they are handled by the next handler.
Test Blocks
Test 1: Backpressure following isReady()
movies-review-service/src/test/java/dev/sch39/movies_review_service/GrpcReactiveBridgeTest.java:
package dev.sch39.movies_review_service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.Test;
import io.grpc.stub.ServerCallStreamObserver;
import reactor.core.publisher.Flux;
class GrpcReactiveBridgeTest {
static class FakeObserver extends ServerCallStreamObserver<Integer> {
final List<Integer> received = new CopyOnWriteArrayList<>();
volatile boolean ready = true;
volatile boolean completed;
int stopAfter = Integer.MAX_VALUE;
Runnable onReady = () -> {
};
Runnable onCancel = () -> {
};
@Override
public void onNext(Integer value) {
received.add(value);
if (received.size() == stopAfter) {
ready = false;
}
}
@Override
public void onError(Throwable t) {
}
@Override
public void onCompleted() {
completed = true;
}
@Override
public boolean isReady() {
return ready;
}
@Override
public void setOnReadyHandler(Runnable onReadyHandler) {
this.onReady = onReadyHandler;
}
@Override
public void setOnCancelHandler(Runnable onCancelHandler) {
this.onCancel = onCancelHandler;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public void setCompression(String compression) {
}
@Override
public void disableAutoInboundFlowControl() {
}
@Override
public void request(int count) {
}
@Override
public void setMessageCompression(boolean enable) {
}
}
@Test
void stopsRequestingWhenNotReadyAndResumesOnReady() {
var requested = new AtomicLong();
var observer = new FakeObserver();
observer.stopAfter = 3;
GrpcReactiveBridge.stream(Flux.range(1, 10).doOnRequest(requested::addAndGet), observer);
System.out.println("notReady delivered=" + observer.received.size() + " requested=" + requested.get());
assertEquals(3, observer.received.size(), "delivered while not ready");
assertEquals(3, requested.get(), "requested while not ready");
observer.ready = true;
observer.onReady.run();
System.out.println("ready delivered=" + observer.received.size() + " completed=" + observer.completed);
assertEquals(10, observer.received.size(), "delivered after ready");
assertTrue(observer.completed, "completed");
}Goal: Prove that Flux is only requested for 3 elements while the observer is not ready, and the rest flows after onReadyHandler is invoked.
Test 2: Client cancellation disposes the pipeline
movies-review-service/src/test/java/dev/sch39/movies_review_service/GrpcReactiveBridgeTest.java:
@Test
void clientCancelDisposesUpstream() throws InterruptedException {
var upstreamCancelled = new CountDownLatch(1);
var observer = new FakeObserver();
GrpcReactiveBridge.stream(
Flux.interval(Duration.ofMillis(10)).map(Long::intValue).doOnCancel(upstreamCancelled::countDown),
observer);
while (observer.received.size() < 2) {
Thread.sleep(5);
}
observer.onCancel.run();
var cancelled = upstreamCancelled.await(1, TimeUnit.SECONDS);
var sizeAtCancel = observer.received.size();
Thread.sleep(100);
System.out.println("upstreamCancelled=" + cancelled + " afterCancel=" + (observer.received.size() - sizeAtCancel));
assertTrue(cancelled, "upstream cancelled");
assertEquals(sizeAtCancel, observer.received.size(), "items after cancel");
}
}Goal: Prove that the cancellation handler cancels the Flux source and no elements are sent afterwards.
Test 3: Streaming and NOT_FOUND mapping via the stub
movies-review-service/src/test/java/dev/sch39/movies_review_service/ReviewGrpcServiceTest.java:
// additional imports: assertThrows, ArrayList, Status, StatusRuntimeException
@Test
void streamReviewsDeliversRowsAndMapsMissingMovieToNotFound() {
stub.addReview(AddReviewRequest.newBuilder().setMovieInfoId(77L).setComment("A").setRating(5.0).build());
stub.addReview(AddReviewRequest.newBuilder().setMovieInfoId(77L).setComment("B").setRating(6.0).build());
var streamed = new ArrayList<String>();
stub.streamReviews(ListReviewsRequest.newBuilder().setMovieInfoId(77L).build())
.forEachRemaining(reply -> streamed.add(reply.getComment()));
var error = assertThrows(StatusRuntimeException.class,
() -> stub.streamReviews(ListReviewsRequest.newBuilder().setMovieInfoId(999L).build()).hasNext());
System.out.println("streamed=" + streamed.size() + " missing=" + error.getStatus().getCode());
assertEquals(2, streamed.size(), "streamed reviews");
assertEquals(Status.Code.NOT_FOUND, error.getStatus().getCode(), "status code");
}Goal: Prove that the streaming RPC sends all reviews for the movie and that NoSuchElementException reaches the client as Status.Code.NOT_FOUND.
Run Test
Run from the movies-review-service/ folder:
./gradlew cleanTest test -iOutput:
...
GrpcReactiveBridgeTest > clientCancelDisposesUpstream() STANDARD_OUT
upstreamCancelled=true afterCancel=0
GrpcReactiveBridgeTest > stopsRequestingWhenNotReadyAndResumesOnReady() STANDARD_OUT
notReady delivered=3 requested=3
ready delivered=10 completed=true
...
RequestValidatorTest > invalidReviewErrorsWithSortedMessages() STANDARD_OUT
status=400 BAD_REQUEST reason=comment must be present, movieInfoId must be present, rating must not be negative
...
ReviewGrpcServiceTest > streamReviewsDeliversRowsAndMapsMissingMovieToNotFound() STANDARD_OUT
streamed=2 missing=NOT_FOUND
ReviewGrpcServiceTest > addReviewReturnsIdGeneratedByPostgres() STANDARD_OUT
reviewId=9f71534c-2f1f-4e04-86b9-5015f9c4a73d comment=Great
ReviewGrpcServiceTest > listReviewsReturnsOnlyRequestedMovie() STANDARD_OUT
movie42 count=2
...
ReviewRouterTest > streamEmitsReviewsAddedAfterSubscribe() STANDARD_OUT
sse1=first
sse2=second
ReviewRouterTest > invalidBodyIs400AndUnknownRouteIs404() STANDARD_OUT
invalid=400 unknown=404
...
BUILD SUCCESSFUL in 26sWhy It Works
Request one at a time: isReady() is true while the outbound buffer is below the threshold, and onNext never blocks (gRPC Java, flow control). GrpcReactiveBridge.stream requests one element only when isReady(), so Reactor demand follows the transport capacity, not the speed of the source.
Resume via onReadyHandler: the handler is invoked every time isReady() flips from false to true, and the documentation states that notifications can be spurious, so pump() checks isReady() again. The inFlight flag prevents two request(1) calls for one element when pump() is invoked from two paths.
Cancellation and Status: setOnCancelHandler is invoked when the call is cancelled, and dispose() on the BaseSubscriber cancels the upstream subscription. A pipeline exception is passed to onError, then the GrpcExceptionHandler bean maps it to a StatusException; a handler that does not recognize the exception returns null (Spring gRPC, Exception Handling).
Edge Cases
Tests use a fake observer: the backpressure and cancellation tests invoke FakeObserver, not a real gRPC transport, so what is proven is the bridge logic. The behavior of isReady() on a real network connection with a slow client is not tested here.
Synchronous source: Flux.range invokes hookOnNext synchronously inside request(1), so pump() is called nested. Reactor tames this recursion, but the result still depends on the nature of the source.
Exception without a handler: an exception not recognized by ReviewGrpcExceptionHandler still returns null, and the client receives an UNKNOWN status.
Trade-offs
Strategy | Pro | Con |
|---|---|---|
| One line, enough for unary | No backpressure and no cancellation for streaming |
Manual bridge | Demand follows transport capacity | More code and must be protected from races |
| Simple, bounds demand to upstream | Does not observe |
Best practice: Use respond for unary and stream for server streaming, and never write a manual subscribe in service methods.
Gotcha I Experienced
There are two types named
GrpcExceptionHandlerinspring-grpc-core 1.1.2:org.springframework.grpc.server.advice.GrpcExceptionHandlerandorg.springframework.grpc.server.exception.GrpcExceptionHandler. The one that is an interface withStatusException handleException(Throwable)is the one in theexceptionpackage.
Production Checklist
Can streaming clients be slow? Test
isReady()with a real transport, not only a fake observer.Are there new domain exceptions? Add their mapping in
GrpcExceptionHandlerso they do not fall through toUNKNOWN.Does the streaming RPC have a duration limit? Set a deadline on the client so hung calls are cancelled.
References
gRPC Java, Manual Flow Control: https://github.com/grpc/grpc-java/blob/master/examples/src/main/java/io/grpc/examples/manualflowcontrol/README.md
gRPC Java,
StreamObserver: https://github.com/grpc/grpc-java/blob/master/stub/src/main/java/io/grpc/stub/StreamObserver.javaSpring gRPC, Server (Exception Handling): https://github.com/spring-projects/spring-grpc/blob/main/spring-grpc-docs/src/main/antora/modules/ROOT/pages/server.adoc