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

Functional Endpoints: Routes, Manual Validation, and Streaming with Sinks

Oct 2026 · 7 min read

This article builds a movies-review-service with RouterFunction and HandlerFunction, runs Bean Validation manually because there are no annotated parameters, then broadcasts new reviews via Sinks and Server-Sent Events. Tests prove an invalid body yields 400, an unknown route yields 404, and two reviews sent after the client connects arrive in order on the SSE stream.

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

Problem

The annotated controller pattern from the previous article (@Valid @RequestBody, @ControllerAdvice) has no direct equivalent in functional endpoints: HandlerFunction only receives a ServerRequest, so there is no parameter that can be annotated with @Valid. The streaming feature also adds new traps, because the SSE response is not sent before the first event.

  1. Validation does not run on its own: the body is read via bodyToMono, so the constraints on the new record are only evaluated if you explicitly call the Validator.

  2. The stream appears to hang: the SSE headers are only sent together with the first event, so a test that waits for a response before sending events will time out.

Outcome

The reader can:

  • Build routes with RouterFunction, route(), and nest(), then separate the logic into a HandlerFunction.

  • Run Bean Validation manually and map its results to 400 via ResponseStatusException.

  • Broadcast events to many clients via Sinks.many().multicast() and test the SSE stream with WebTestClient.

Implementation

Folder Structure

text
movies-review-service/
├── build.gradle
└── src/
    ├── main/java/dev/sch39/movies_review_service/
    │   ├── Review.java
    │   ├── RequestValidator.java
    │   ├── ReviewHandler.java
    │   └── ReviewRouter.java
    └── test/java/dev/sch39/movies_review_service/
        ├── RequestValidatorTest.java
        └── ReviewRouterTest.java

Setup

Initialize a single project (run from the / folder). The default test is deleted because @SpringBootTest requires a running MongoDB.

bash
mkdir -p movies-review-service
cd movies-review-service

spring init --build=gradle --type=gradle-project --java-version=21 --group-id=dev.sch39 --artifact-id=movies-review-service --name=movies-review-service --extract . \
  && rm src/main/resources/application.properties \
  && printf 'spring:\n  application:\n    name: movies-review-service\nserver:\n  port: 8081\n' > src/main/resources/application.yml \
  && rm src/test/java/dev/sch39/movies_review_service/MoviesReviewServiceApplicationTests.java

Code Blocks

Block 1: WebFlux, validation, and reactive MongoDB dependencies

movies-review-service/build.gradle:

groovy
dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-data-mongodb-reactive'
	implementation 'org.springframework.boot:spring-boot-starter-validation'
	implementation 'org.springframework.boot:spring-boot-starter-webflux'
	testImplementation 'org.springframework.boot:spring-boot-starter-data-mongodb-reactive-test'
	testImplementation 'org.springframework.boot:spring-boot-starter-validation-test'
	testImplementation 'org.springframework.boot:spring-boot-starter-webflux-test'
	testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

Purpose: Add three starters along with their respective -test counterparts, matching the test module split in Boot 4.

Block 2: Constraints on the Review record

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

java
package dev.sch39.movies_review_service;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import jakarta.validation.constraints.DecimalMax;
import jakarta.validation.constraints.DecimalMin;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;

@Document
public record Review(
        @Id String reviewId,
        @NotNull(message = "movieInfoId must be present") Long movieInfoId,
        @NotBlank(message = "comment must be present") String comment,
        @NotNull(message = "rating must be present")
        @DecimalMin(value = "0.0", message = "rating must not be negative")
        @DecimalMax(value = "10.0", message = "rating must not be greater than 10") Double rating) {
}

Purpose: Declare the data rules on the record component, which are later evaluated manually by the validator.

Block 3: A manual validator that returns a Mono

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

java
package dev.sch39.movies_review_service;

import java.util.stream.Collectors;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import reactor.core.publisher.Mono;

@Component
public class RequestValidator {

    private final Validator validator;

    public RequestValidator(Validator validator) {
        this.validator = validator;
    }

    public <T> Mono<T> validate(T target) {
        var violations = validator.validate(target);
        if (violations.isEmpty()) {
            return Mono.just(target);
        }
        var message = violations.stream()
                .map(ConstraintViolation::getMessage)
                .sorted()
                .collect(Collectors.joining(", "));
        return Mono.error(new ResponseStatusException(HttpStatus.BAD_REQUEST, message));
    }
}

Purpose: Replace @Valid with an explicit Validator call whose result is a Mono.error with status 400, so it can be chained into the handler pipeline.

Block 4: Handler for POST and the SSE stream

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

java
package dev.sch39.movies_review_service;

import java.time.Duration;

import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ResponseStatusException;

import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;
import reactor.core.publisher.Sinks.EmitFailureHandler;

@Component
public class ReviewHandler {

    private final ReactiveMongoTemplate mongo;
    private final RequestValidator validator;
    private final Sinks.Many<Review> newReviews = Sinks.many().multicast().onBackpressureBuffer();

    public ReviewHandler(ReactiveMongoTemplate mongo, RequestValidator validator) {
        this.mongo = mongo;
        this.validator = validator;
    }

    public Mono<ServerResponse> addReview(ServerRequest request) {
        return request.bodyToMono(Review.class)
                .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.BAD_REQUEST, "body must not be empty")))
                .flatMap(validator::validate)
                .flatMap(mongo::save)
                .doOnNext(saved -> newReviews.emitNext(saved, EmitFailureHandler.busyLooping(Duration.ofMillis(200))))
                .flatMap(saved -> ServerResponse.status(HttpStatus.CREATED).bodyValue(saved));
    }

    public Mono<ServerResponse> streamReviews(ServerRequest request) {
        return ServerResponse.ok()
                .contentType(MediaType.TEXT_EVENT_STREAM)
                .body(newReviews.asFlux(), Review.class);
    }
}

Purpose: Chain body reading, validation, saving, and broadcasting to the Sinks in a single pipeline, then expose the same sink as an SSE Flux.

Block 5: Router with nest()

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

java
package dev.sch39.movies_review_service;

import static org.springframework.web.reactive.function.server.RequestPredicates.path;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;

@Configuration
public class ReviewRouter {

    @Bean
    public RouterFunction<ServerResponse> reviewRoute(ReviewHandler handler) {
        return route()
                .nest(path("/v1/reviews"), builder -> builder
                        .GET("/stream", handler::streamReviews)
                        .POST("", handler::addReview))
                .build();
    }
}

Purpose: Map the /v1/reviews path to the handlers as a RouterFunction bean, so other paths have no route.

Test Blocks

Test 1: Validator sorts violation messages

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

java
package dev.sch39.movies_review_service;

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

import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;

import jakarta.validation.Validation;
import reactor.test.StepVerifier;

class RequestValidatorTest {

    private final RequestValidator validator =
            new RequestValidator(Validation.buildDefaultValidatorFactory().getValidator());

    @Test
    void invalidReviewErrorsWithSortedMessages() {
        StepVerifier.create(validator.validate(new Review(null, null, " ", -1.0)))
                .expectErrorSatisfies(e -> {
                    var ex = (ResponseStatusException) e;
                    System.out.println("status=" + ex.getStatusCode() + " reason=" + ex.getReason());
                    assertEquals(HttpStatus.BAD_REQUEST, ex.getStatusCode(), "status");
                    assertEquals("comment must be present, movieInfoId must be present, rating must not be negative",
                            ex.getReason(), "reason");
                })
                .verify();
    }
}

Purpose: Prove that the manual validator rejects an invalid review with status 400 and the message of each violation in a stable order.

Test 2: An invalid body yields 400, an unknown route yields 404

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

java
package dev.sch39.movies_review_service;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webflux.test.autoconfigure.WebFluxTest;
import org.springframework.context.annotation.Import;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.reactive.server.WebTestClient;

import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import reactor.test.StepVerifier;

@WebFluxTest
@Import({ ReviewRouter.class, ReviewHandler.class, RequestValidator.class })
class ReviewRouterTest {

    @Autowired
    private WebTestClient client;

    @MockitoBean
    private ReactiveMongoTemplate mongo;

    @Test
    void invalidBodyIs400AndUnknownRouteIs404() {
        int invalid = client.post().uri("/v1/reviews")
                .bodyValue(new Review(null, null, "", -1.0))
                .exchange()
                .expectBody().returnResult().getStatus().value();
        int unknown = client.get().uri("/v1/unknown")
                .exchange()
                .expectBody().returnResult().getStatus().value();

        System.out.println("invalid=" + invalid + " unknown=" + unknown);
        assertEquals(400, invalid, "invalid body status");
        assertEquals(404, unknown, "unknown route status");
        verifyNoInteractions(mongo);
    }

Purpose: Prove that an invalid body stops at the validator without touching MongoDB, and that a path outside nest() has no route.

Test 3: The SSE stream receives reviews sent after the client connects

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

java
    @Test
    void streamEmitsReviewsAddedAfterSubscribe() {
        when(mongo.save(any(Review.class))).thenAnswer(inv -> Mono.just(inv.getArgument(0)));

        // SSE headers are only sent when the first event is written, so reviews are sent from another thread
        Schedulers.boundedElastic().schedule(() -> {
            sleep(500);
            postReview("first");
            postReview("second");
        });

        var stream = client.get().uri("/v1/reviews/stream")
                .accept(MediaType.TEXT_EVENT_STREAM)
                .exchange()
                .expectStatus().isOk()
                .returnResult(Review.class)
                .getResponseBody();

        StepVerifier.create(stream.take(2))
                .assertNext(r -> {
                    System.out.println("sse1=" + r.comment());
                    assertEquals("first", r.comment(), "first event");
                })
                .assertNext(r -> {
                    System.out.println("sse2=" + r.comment());
                    assertEquals("second", r.comment(), "second event");
                })
                .verifyComplete();
    }

    private static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    private void postReview(String comment) {
        client.post().uri("/v1/reviews")
                .bodyValue(new Review(null, 1L, comment, 7.5))
                .exchange()
                .expectStatus().isCreated();
    }
}

Purpose: Prove that reviews saved via POST are broadcast to an already-connected SSE client, in the same order.

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
...
ReviewRouterTest > streamEmitsReviewsAddedAfterSubscribe() STANDARD_OUT
    sse1=first
    sse2=second

ReviewRouterTest > invalidBodyIs400AndUnknownRouteIs404() STANDARD_OUT
    invalid=400 unknown=404
...
BUILD SUCCESSFUL in 9s

Why It Works

Functional endpoint: RouterFunction maps requests to HandlerFunction<ServerResponse> via predicates, and all routes are declared as beans. A request that matches no predicate has no handler, so /v1/unknown ends up as 404 without extra code.

Manual validation: HandlerFunction only receives a ServerRequest, so there is no parameter that can be annotated with @Valid. Validator.validate is called directly in RequestValidator, and the violation results are returned as Mono.error(ResponseStatusException) so they join the pipeline's error flow and are mapped to 400.

Sinks.many().multicast(): this sink only sends data pushed after a subscriber has subscribed, with backpressure per subscriber (Reactor reference). asFlux() turns it into a Flux that is returned as the text/event-stream body, so each emitNext from a POST becomes one SSE event on all connected clients.

Edge Cases

Reviews before the client connects: multicast does not replay. A review saved before the client opens /v1/reviews/stream is never sent to that client.

Empty body: bodyToMono completes without a value, and switchIfEmpty turns that into a 400 ResponseStatusException. Without switchIfEmpty, the pipeline completes empty and the handler returns no ServerResponse.

Concurrent emits: emitNext from several requests at once can fail as non-serialized. EmitFailureHandler.busyLooping retries the emit until it succeeds or the 200 ms limit is exceeded.

Trade-offs

Strategy

Pro

Con

Annotated controller

@Valid and @ControllerAdvice work automatically

Routing is scattered across annotations, hard to compose programmatically

Functional endpoints

Routes as values (can be composed, filtered, tested separately)

Validation and error mapping are written by hand

multicast().onBackpressureBuffer()

Honors each subscriber's backpressure, events are not lost when a subscriber is slow

The buffer holds events when a subscriber is slow

Best practice: Use functional endpoints when routes need to be composed programmatically or handlers need to be tested without the annotation context; for ordinary CRUD, an annotated controller means less code. For SSE, decide the slow-subscriber behavior (buffer or drop) deliberately.

Gotchas I Ran Into

  • ServerResponse.body(saved, Review.class) with a plain object (not a Publisher) fails with java.lang.IllegalArgumentException: 'producer' type is unknown to ReactiveAdapterRegistry. For a single value, use bodyValue(saved).

  • An SSE test that calls .exchange() and only then sends reviews times out with java.lang.IllegalStateException: Timeout on blocking read for 5000000000 NANOSECONDS, because the response headers are only sent together with the first event.

  • With Sinks.many().multicast().directBestEffort(), this SSE test fails with onError(reactor.core.Exceptions$OverflowException: Backpressure overflow during Sinks.Many#emitNext). Switching to onBackpressureBuffer() makes the test pass.

Production Checklist

  • Can the SSE endpoint have many slow clients? Decide on a sink strategy (bounded buffer, or drop) and limit the buffer size.

  • Is there a route that accepts a body? Make sure every path calls the validator and handles an empty body.

  • Do clients need to see older reviews on connect? Provide a separate read endpoint, because multicast does not replay.

References