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

gRPC Server with R2DBC Postgres

Oct 2026 · 7 min read

This article adds a gRPC server to movies-review-service from a .proto contract, stores reviews in PostgreSQL via R2DBC, then proves it with tests that call gRPC stubs against Postgres in Testcontainers. Review ids are generated by Postgres, the review list is filtered per movie, and previous tests still pass because WebFlux is kept alongside the gRPC server.

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

Problem

The REST service from the previous article had a contract that only lived in handler code and documentation, and its data was in MongoDB. Moving the transport to gRPC and storage to Postgres means three new things at once: a .proto contract with generated code, an R2DBC driver that does not create the schema itself, and tests that need a real database.

  1. Schema is not created automatically: unlike MongoDB, the Postgres table must exist before the first insert, and Spring Boot only runs schema.sql automatically for embedded databases.

  2. Database errors appear vaguely on the client: a failure inside the pipeline reaches the gRPC client as StatusRuntimeException: UNKNOWN, not as an SQL message.

Outcome

Readers can:

  • Write a .proto contract, run the com.google.protobuf Gradle plugin on Boot 4.1, and implement ReviewServiceImplBase as a @Service.

  • Map a record to a table with @Table and use R2dbcEntityTemplate for reactive insert and select.

  • Test the gRPC server via in-process transport and Postgres in Testcontainers with @ServiceConnection.

Implementation

Folder Structure

text
|compose-reactive.yml
|.spring-boot-reactive-env.example
|movies-review-service/
├── build.gradle                                       # changed
└── src/
    ├── main/
    │   ├── proto/review.proto                         # new
    │   ├── java/dev/sch39/movies_review_service/
    │   │   ├── Review.java                            # changed
    │   │   ├── ReviewGrpcService.java                 # new
    │   │   ├── RequestValidator.java
    │   │   ├── ReviewHandler.java
    │   │   └── ReviewRouter.java
    │   └── resources/schema.sql                       # new
    └── test/java/dev/sch39/movies_review_service/
        ├── ReviewGrpcServiceTest.java                 # new
        ├── RequestValidatorTest.java
        └── ReviewRouterTest.java

Setup

Continue from the project:

bash
cd movies-review-service

The new tests use Testcontainers, so Docker must be running. Postgres does not need to be run manually for tests. The following three files are only needed to run the real service (./gradlew bootRun).

Add the postgres service to compose-reactive.yml (below mongodb):

yaml
  postgres:
    image: postgres:17
    container_name: spring-boot-reactive-postgres
    environment:
      POSTGRES_DB: ${POSTGRES_DB}
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
    ports:
      # host 5433: 5432 is often used by another local Postgres
      - "127.0.0.1:5433:5432"
    volumes:
      - postgres-data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 10s

Register the volume in the volumes: section at the bottom (postgres-data:).

projects-article/.spring-boot-reactive-env.example (copy to .spring-boot-reactive-env, which is already git-ignored, then change the password):

plaintext
POSTGRES_DB=reviews
POSTGRES_USER=reviews
POSTGRES_PASSWORD=change-me

projects-article/movies-review-service/src/main/resources/application.yml:

yaml
spring:
  application:
    name: movies-review-service
  r2dbc:
    url: r2dbc:postgresql://localhost:5433/${POSTGRES_DB}
    username: ${POSTGRES_USER}
    password: ${POSTGRES_PASSWORD}
  sql:
    init:
      mode: always

server:
  port: 8081

spring.sql.init.mode: always is required because schema.sql is not run automatically on non-embedded databases. Run from WSL:

bash
# from the projects-article/ folder
cp .spring-boot-reactive-env.example .spring-boot-reactive-env
set -a; source ./.spring-boot-reactive-env; set +a   # export POSTGRES_*
docker compose -f compose-reactive.yml up -d --wait
cd movies-review-service
./gradlew bootRun

Code Blocks

Block 1: gRPC server, R2DBC, and protobuf plugin dependencies

movies-review-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-data-mongodb-reactive'
	implementation 'org.springframework.boot:spring-boot-starter-data-r2dbc'
	implementation 'org.springframework.boot:spring-boot-starter-grpc-server'
	implementation 'org.springframework.boot:spring-boot-starter-validation'
	implementation 'org.springframework.boot:spring-boot-starter-webflux'
	runtimeOnly 'org.postgresql:r2dbc-postgresql'
	testImplementation 'org.springframework.boot:spring-boot-starter-data-mongodb-reactive-test'
	testImplementation 'org.springframework.boot:spring-boot-starter-data-r2dbc-test'
	testImplementation 'org.springframework.boot:spring-boot-starter-grpc-client-test'
	testImplementation 'org.springframework.boot:spring-boot-starter-validation-test'
	testImplementation 'org.springframework.boot:spring-boot-starter-webflux-test'
	testImplementation 'org.springframework.boot:spring-boot-testcontainers'
	testImplementation 'org.testcontainers:testcontainers-postgresql'
	testImplementation 'org.testcontainers:testcontainers-r2dbc'
	testImplementation 'org.testcontainers:testcontainers-junit-jupiter'
	testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

protobuf {
	plugins {
		grpc {}
	}
}

Purpose: Add the gRPC server and R2DBC starters along with the Postgres driver, enable the protobuf plugin (the grpc {} stub version is managed by Boot), and set up test dependencies for Testcontainers.

Block 2: The .proto contract

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

proto
syntax = "proto3";

package dev.sch39.movies_review_service.grpc;

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

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

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: Define the contract for two unary RPCs as the source of the ReviewServiceGrpc code and message classes, so the server and client share a single type definition.

Block 3: A record that can be mapped to a table

movies-review-service/src/main/java/dev/sch39/movies_review_service/Review.java:

java
import org.springframework.data.relational.core.mapping.Table;

@Document
@Table("review")
public record Review(

Purpose: Add @Table to the same record so one type is mapped to the MongoDB document for the handler and to the review table for R2DBC.

Block 4: Table schema

movies-review-service/src/main/resources/schema.sql:

sql
CREATE TABLE IF NOT EXISTS review (
    review_id     TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
    movie_info_id BIGINT NOT NULL,
    comment       TEXT NOT NULL,
    rating        DOUBLE PRECISION NOT NULL
);

Purpose: Create the table with an id generated by Postgres, since R2DBC has no auto-DDL.

Block 5: gRPC service implementation with R2DBC

movies-review-service/src/main/java/dev/sch39/movies_review_service/ReviewGrpcService.java:

java
package dev.sch39.movies_review_service;

import static org.springframework.data.relational.core.query.Criteria.where;
import static org.springframework.data.relational.core.query.Query.query;

import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.stereotype.Service;

import dev.sch39.movies_review_service.grpc.AddReviewRequest;
import dev.sch39.movies_review_service.grpc.ListReviewsReply;
import dev.sch39.movies_review_service.grpc.ListReviewsRequest;
import dev.sch39.movies_review_service.grpc.ReviewReply;
import dev.sch39.movies_review_service.grpc.ReviewServiceGrpc;
import io.grpc.stub.StreamObserver;

@Service
public class ReviewGrpcService extends ReviewServiceGrpc.ReviewServiceImplBase {

    private final R2dbcEntityTemplate template;

    public ReviewGrpcService(R2dbcEntityTemplate template) {
        this.template = template;
    }

    @Override
    public void addReview(AddReviewRequest request, StreamObserver<ReviewReply> observer) {
        var review = new Review(null, request.getMovieInfoId(), request.getComment(), request.getRating());
        template.insert(review)
                .map(ReviewGrpcService::toReply)
                .subscribe(observer::onNext, observer::onError, observer::onCompleted);
    }

    @Override
    public void listReviews(ListReviewsRequest request, StreamObserver<ListReviewsReply> observer) {
        template.select(Review.class)
                .matching(query(where("movieInfoId").is(request.getMovieInfoId())))
                .all()
                .map(ReviewGrpcService::toReply)
                .collectList()
                .map(replies -> ListReviewsReply.newBuilder().addAllReviews(replies).build())
                .subscribe(observer::onNext, observer::onError, observer::onCompleted);
    }

    private static ReviewReply toReply(Review review) {
        return ReviewReply.newBuilder()
                .setReviewId(review.reviewId())
                .setMovieInfoId(review.movieInfoId())
                .setComment(review.comment())
                .setRating(review.rating())
                .build();
    }
}

Purpose: Connect StreamObserver to the Mono produced by R2DBC with subscribe(onNext, onError, onComplete), as the simplest bridge before it is covered fully in the next article(https://sch39.dev/articles/spring-boot-streamobserver-reactor-bridge).

Test Blocks

Test 1: AddReview returns an id from Postgres

movies-review-service/src/test/java/dev/sch39/movies_review_service/ReviewGrpcServiceTest.java:

java
package dev.sch39.movies_review_service;

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

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.testcontainers.service.connection.ServiceConnection;
import org.springframework.grpc.client.ImportGrpcClients;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.postgresql.PostgreSQLContainer;

import dev.sch39.movies_review_service.grpc.AddReviewRequest;
import dev.sch39.movies_review_service.grpc.ListReviewsRequest;
import dev.sch39.movies_review_service.grpc.ReviewServiceGrpc;

@SpringBootTest(properties = "spring.sql.init.mode=always")
@Testcontainers
@AutoConfigureTestGrpcTransport
@ImportGrpcClients(types = ReviewServiceGrpc.ReviewServiceBlockingStub.class)
class ReviewGrpcServiceTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17");

    @Autowired
    private ReviewServiceGrpc.ReviewServiceBlockingStub stub;

    @Test
    void addReviewReturnsIdGeneratedByPostgres() {
        var reply = stub.addReview(AddReviewRequest.newBuilder()
                .setMovieInfoId(1L).setComment("Great").setRating(9.0).build());

        System.out.println("reviewId=" + reply.getReviewId() + " comment=" + reply.getComment());
        assertFalse(reply.getReviewId().isBlank(), "generated review id");
        assertEquals("Great", reply.getComment(), "comment");
    }

Purpose: Prove that a single gRPC call goes through the contract, service, and R2DBC down to Postgres, and that the returned id is generated by the database.

Test 2: ListReviews filters per movie

movies-review-service/src/test/java/dev/sch39/movies_review_service/ReviewGrpcServiceTest.java:

java
    @Test
    void listReviewsReturnsOnlyRequestedMovie() {
        stub.addReview(AddReviewRequest.newBuilder().setMovieInfoId(42L).setComment("A").setRating(5.0).build());
        stub.addReview(AddReviewRequest.newBuilder().setMovieInfoId(42L).setComment("B").setRating(6.0).build());
        stub.addReview(AddReviewRequest.newBuilder().setMovieInfoId(43L).setComment("C").setRating(7.0).build());

        var reply = stub.listReviews(ListReviewsRequest.newBuilder().setMovieInfoId(42L).build());

        System.out.println("movie42 count=" + reply.getReviewsCount());
        assertEquals(2, reply.getReviewsCount(), "reviews for movie 42");
    }
}

Purpose: Prove that the movieInfoId filter maps to the movie_info_id column and that only reviews for the requested movie are returned.

Run Test

Run from the movies-review-service/ folder:

bash
./gradlew cleanTest test -i

Output:

text
...
RequestValidatorTest > invalidReviewErrorsWithSortedMessages() STANDARD_OUT
    status=400 BAD_REQUEST reason=comment must be present, movieInfoId must be present, rating must not be negative
...
ReviewGrpcServiceTest > addReviewReturnsIdGeneratedByPostgres() STANDARD_OUT
    reviewId=8758dbac-4136-44b6-87f7-125c52ec94c2 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 24s

Why It Works

Generated code: the com.google.protobuf plugin reads src/main/proto and generates the message classes and ReviewServiceGrpc. Since Boot 4.1 the protoc and gRPC plugin versions are managed by Boot, so the protobuf block only needs to declare grpc {} (Spring gRPC migration notes).

Service binding: the gRPC server is built from all beans of type BindableService. A ReviewServiceImplBase subclass annotated with @Service is automatically registered through component scan, with no port or additional server configuration (Spring gRPC, Server).

R2DBC and schema: R2dbcEntityTemplate executes queries reactively and maps the movieInfoId property name to the movie_info_id column. Boot runs schema.sql for the R2DBC ConnectionFactory, but by default only for embedded databases, so for Postgres you need spring.sql.init.mode=always (Spring Boot, Database Initialization).

Edge Cases

WebFlux stays: gRPC and WebFlux each bring their own Netty server. The runtime dependencies include both io.grpc:grpc-netty:1.84.1 and io.projectreactor.netty:reactor-netty-http:1.3.8, so both are on the classpath of a single service. The tests in this article do not open real ports, so the HTTP and gRPC port split is not proven here.

Tests use in-process transport: @AutoConfigureTestGrpcTransport connects the stub to the server without opening a network port, so the tests do not prove the behavior of real port 9090.

Errors without mapping: observer::onError receives a plain exception, and the client sees it as a StatusRuntimeException with status UNKNOWN. Mapping to NOT_FOUND or INVALID_ARGUMENT is covered in the next article(https://sch39.dev/articles/spring-boot-streamobserver-reactor-bridge).

Trade-offs

Strategy

Pro

Con

REST (functional endpoints)

Easy to test with curl, broad tooling

Contract is not enforced by types

gRPC unary

.proto contract and client/server code from a single source

Requires special tooling for debugging, curl is not enough

WebFlux kept

Existing tests still pass, HTTP and gRPC run side by side

Two Netty servers and more dependencies in one service

Best practice: Keep REST if there are HTTP consumers outside, and add gRPC for inter-service communication; remove WebFlux only when there are no more HTTP endpoints.

Gotchas I Ran Into

  • org.springframework.grpc.test.AutoConfigureTestGrpcTransport does not exist in Boot 4.1. Compile error: package org.springframework.grpc.test does not exist. The annotation lives in the org.springframework.boot.grpc.test.autoconfigure package.

  • Postgres in Testcontainers made the context fail with java.lang.NoClassDefFoundError: org/testcontainers/r2dbc/R2DBCDatabaseContainer until org.testcontainers:testcontainers-r2dbc was added as a test dependency.

  • Without spring.sql.init.mode=always, both tests failed on the client with io.grpc.StatusRuntimeException: UNKNOWN and no SQL message. The cause (the review table was not created because schema.sql only runs automatically for embedded databases) was matched against the Spring Boot docs, not from the server logs.

Production Checklist

  • Is the schema managed outside schema.sql? Use migrations (Flyway or Liquibase) for production, not spring.sql.init.mode=always.

  • Are the Postgres credentials in the repo? Move them to environment variables and provide a .env.example.

  • Is the gRPC server exposed without TLS? Enable TLS or restrict it to the internal network.

References