Workbench / Volume 3 Exercises: The Backend
V3·48
Spring Web MVC & WebFlux
Exercises for Volume 3, chapter 48: the DispatcherServlet; controllers and request mapping; validation; exception handling and ProblemDetail; filters, interceptors and advice; message converters and content negotiation; RestClient and @HttpExchange; why reactive programming exists; Reactive Streams and backpressure; Reactor's Mono and Flux; the event loop; when reactive is worth it and when virtual threads are simpler; and async streams in other languages. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.
Start here: how this chapter's exercises work
The four sets and the locking work as before. The code is Spring Boot 4.1.1 / Spring MVC 7 with Tomcat, and Reactor 3.8 on its own. The WebFlux jars weren't available here, so the WebFlux exercises use Reactor directly or give expected outputs. Every quoted output is real, and four of them catch experienced developers:
- P1.
GET /api/dishes/with a trailing slash returned 404. Spring 6+ no longer matches trailing slashes. A missing?limitand?limit=abcproduced problem details: "Required parameter 'limit' is not present." and "Failed to convert 'limit' with value: 'abc'". - P2. For a request whose exception was handled by
@RestControllerAdvice, the interceptor'safterCompletionsawex=none, not the exception. A request to an unmapped path still ran the interceptor, because the static-resource handler is a handler too. - P7.
flatMapover calls of 300, 100, 200 and 50 ms returned[k3, k1, k2, k0](completion order),concatMap[k0, k1, k2, k3]in 655 ms (sequential), andflatMapSequential[k0, k1, k2, k3]in 305 ms (concurrent, but kept in order). - P8. A
ThreadLocalwasnullafterMono.delay, while Reactor'sContextcarriedreq-42. AndonBackpressureDropwith a slow consumer dropped 198 of the first 248 values.
The chapter's lab already covered these, and the exercises build on them rather than repeat them:
- problem details for malformed JSON and 404s;
- 20 platform threads against virtual threads: p50 1,100 ms against 566 ms;
- a
RestClientwithout a timeout waiting 20 s, against 563 ms with one; Monolaziness (0 calls until subscribed, 2 after two subscriptions);limitRaterequests of 100, 75, 75, 75;zipwith a timeout fallback in 533 ms;- blocking calls on an event loop (1,012 ms) against
boundedElastic(106 ms).
Coverage map.
| Chapter component | Exercises |
|---|---|
| DispatcherServlet; request lifecycle | T1, P2 |
| controllers and mapping; binding | T2, P1 |
| validation | T3, P3 |
| exception handling; ProblemDetail | T3, P3 |
| filters vs interceptors vs advice | T4, P2 |
| message converters; negotiation; ETags | T5, P4 |
| RestClient; @HttpExchange; timeouts | T6, P5 |
| why reactive exists; Reactive Streams; backpressure | T7, P8 |
| Reactor Mono and Flux; operators; schedulers | T8, P7 |
| the event loop; blocking | T8, P6 |
| reactive vs virtual threads | T9, P6 |
| async streams in other languages | T9, P9 |
Theory
T1. The DispatcherServlet and the request lifecycle
- Trace a request through Spring MVC:
- the servlet container;
- the filter chain (Boot's filters plus yours, and Spring Security's);
DispatcherServlet;HandlerMapping, which finds the handler: a controller method, or the static-resource handler;- the interceptors'
preHandle; - the
HandlerAdapter, which does argument resolution and binding, then invokes the method; - return-value handling through message converters;
postHandle;- exception resolvers:
@ExceptionHandler,@ControllerAdvice,ResponseStatusException,DefaultHandlerExceptionResolver; afterCompletion;- the filters unwind.
P2's cleaned trail for a successful request was filter-in → interceptor-pre → handler → interceptor-after → filter-out 200.
2. Why did P2's /api/nothing (404) still run the interceptor? Why did the advice-handled exception show ex=none in afterCompletion? What does that mean for logging and metrics implemented in interceptors?
3. Where does each concern belong in this pipeline?
- request id;
- authentication;
- per-handler authorisation;
- per-endpoint metrics with route templates;
- transaction boundaries;
- response compression;
- error mapping.
T2. Controllers, request mapping and binding
- Explain mapping and binding:
-
@RequestMappingand its shortcuts; - path patterns (PathPatternParser:{id},{*rest}, regex{id:[a-z0-9_]+}); - matching onparams,headers,consumesandproduces; - no trailing-slash matching since Spring 6 (P1:/api/dishes/was 404); - no suffix pattern matching; - argument types (@PathVariable,@RequestParam,@RequestHeader,@RequestBody,@ModelAttribute,Principal,HttpServletRequest,Pageable). - Binding errors became problem details:
- a missing required
@RequestParamgave 400 "Required parameter 'limit' is not present." (P1); - a type mismatch gave 400 "Failed to convert 'limit' with value: 'abc'" (P1); - malformed JSON gave 400 "Failed to read request" (the lab).
How do you make these consistent with TiffinBox's error contract (codes, field paths: ch44's C2)?
3. Design controllers that stay thin: translate HTTP to use-case calls, DTOs in and out (ch44's T5), no business logic, no repositories directly. What about returning ResponseEntity against plain bodies, with @ResponseStatus, Location headers, ETags (T5), and Optional → 404?
T3. Validation and exception handling
- Bean Validation in MVC:
-
@Valid @RequestBodywith constraint annotations, givingMethodArgumentNotValidException(400); -@Validatedon the class plus constraints on@RequestParamand@PathVariable, givingHandlerMethodValidationException(Spring 6.1+ built-in method validation); - groups; - custom constraints (@ValidDishId); - messages and internationalisation.
How do these errors become the errors array in TiffinBox's problems?
2. Exception handling design:
- @ExceptionHandler in controllers against @RestControllerAdvice;
- ordering of multiple advices (@Order, basePackages);
- ResponseStatusException for quick cases;
- ErrorResponse and ProblemDetail types;
- handling exceptions from filters (outside the dispatcher: they need the /error path, or a filter-level handler).
3. Where do business rule violations come from (ch44's T6)? Map the domain exceptions (or Result errors: ch36) to problems in one place, and decide whether controllers should ever catch exceptions.
T4. Filters, interceptors and advice
- Compare where each runs and what it can see:
- servlet filters: everything, including static resources and 404s; no handler information; can wrap the request and response;
-
HandlerInterceptors: after handler selection; they know the handler and pattern; -@ControllerAdvice: exceptions, model attributes and binders for controllers; -ResponseBodyAdviceandRequestBodyAdvice: before and after body conversion; - AOP around controller or service methods.
P2 showed filter-out seeing the final status (409 after the advice).
2. Pick the right mechanism:
- request id;
- an access log with the route template;
- a per-kitchen rate limit after authentication;
- adding a Deprecation header to old endpoints (ch45's P6);
- wrapping every response in an envelope (should you?);
- measuring time per controller method;
- a tenant header check.
3. Ordering. Filter order (FilterRegistrationBean.setOrder; Spring Security at SecurityProperties.DEFAULT_FILTER_ORDER), interceptor registration order, and advice order. Write the ordering for TiffinBox's MVC services (ch44's P2's list).
T5. Message converters, content negotiation and ETags
- Explain
HttpMessageConverters: - Jackson JSON (application/json,application/*+json); - String, ByteArray, Resource; - optional XML; - selection byContent-Type(reading) andAcceptagainstproduces(writing).
P1's Accept: application/xml gave 406 "Acceptable representations: [application/json, application/+json]". Why is 406 correct, and how do you add CSV (ch45's T3) as a custom converter?
2. ETags in MVC. P4: ShallowEtagHeaderFilter produced ETag "08561161d430255e029f1cc5cbb9bbf14" and a 304 for If-None-Match. Explain why a shallow ETag saves bandwidth but not server work (the body is generated, then hashed), and compare it with deep ETags* from versions (ch45's T7): ResponseEntity.eTag(...), and WebRequest.checkNotModified(etag) to skip the work.
3. Streaming responses: StreamingResponseBody, ResponseBodyEmitter, SseEmitter (Server-Sent Events from MVC), and Resource with range requests. When do they block a thread (always, with platform threads; cheaply with virtual threads), and when should you choose WebFlux instead?
T6. HTTP clients: RestClient and @HttpExchange
- Compare
RestTemplate(maintenance mode),RestClient(Spring 6.1+, synchronous, fluent),WebClient(reactive) and@HttpExchangeinterface clients (P5:DishClient.get("d7")throughHttpServiceProxyFactoryandRestClientAdapterreturned{"id":"d7","name":"Idli","paise":4000}). When do you use each? - Client configuration that matters:
- timeouts (the lab: 20 s without, 563 ms with a 500 ms read timeout);
- connection pooling (
JdkClientHttpRequestFactory, Apache HttpClient 5, Reactor Netty); -RestClient.Builderfrom Boot (observability, converters); - status handlers (onStatusmapping 4xx/5xx to exceptions); - retries (only for idempotent calls: ch45's T6); - base URLs and authentication interceptors; - logging without secrets. - Write the TiffinBox
PaymentClientas an@HttpExchangeinterface with: - Boot-managed builder customisation; - timeouts from typed properties; - an idempotency-key header (ch45); - problem-detail error decoding into exceptions; - a circuit breaker (preview of ch52).
T7. Why reactive exists: Reactive Streams and backpressure
- Reactive programming came about because thread-per-request servers couldn't hold enough concurrent connections waiting on I/O (ch38, ch44's lab). Event loops and non-blocking I/O fixed that, but needed a composition model. Explain the Reactive Streams contract:
-
Publisher,Subscriber,SubscriptionandProcessor; -request(n)demand; - signals (onNext,onError,onComplete); - the rules (no more than requested, serial signals).
It's in the JDK as java.util.concurrent.Flow.
2. Backpressure strategies:
- demand-based pulling (the lab's limitRate(100) requested 100, then 75, 75, 75);
- buffering;
- dropping (P8: onBackpressureDrop received 50, the last value 197, with 198 dropped);
- latest-only;
- erroring (P8: OverflowException: The receiver is overrun by more signals than expected).
Which suits each TiffinBox stream: order events to a kitchen display, GPS pings from delivery partners, an analytics export, payments?
3. Hot and cold publishers:
- cold, where each subscriber triggers the work (the lab: 2 subscriptions, 2 database calls);
- cache() turning a cold Mono into a shared one (P8: menu1, menu1, source called once);
- share(), publish().refCount(), sinks.
What goes wrong if a cold Mono with side effects is subscribed twice by accident (double charges)?
T8. Reactor: Mono, Flux, operators, schedulers and the event loop
- Core operators:
-
map(sync); -flatMap(async, concurrent, unordered: P7's[k3, k1, k2, k0]); -concatMap(sequential, ordered: 655 ms); -flatMapSequential(concurrent, ordered output: 305 ms); -zipandzipWith; -merge; -switchMap; -filter; -reduce; -timeout; -onErrorResumeandonErrorReturn; -retryWhen(Retry.backoff…): P7's attempts at 28, 135, 336 and 737 ms, roughly 100, 200, 400 ms gaps.
P7's flatMap(…, 5) bounded concurrency. The counter saw up to 7 because doFinally ran after the operator had already requested the next inner, which is a measurement artefact worth understanding.
2. Schedulers. P7's subscribeOn(boundedElastic) ran the callable on boundedElastic, and publishOn(parallel) ran the map on parallel. Explain:
- parallel (CPU-bound, sized to cores);
- boundedElastic (blocking calls);
- single;
- immediate;
- why blocking on the event loop is disastrous (the lab: 20 blocking 100 ms calls took 1,012 ms on 2 event-loop threads against 106 ms on boundedElastic);
- BlockHound for detecting it.
3. Context. P8: a ThreadLocal set before Mono.delay was null afterwards, because the work moved threads, while contextWrite with deferContextual carried req-42. Explain how MDC, security context and tracing propagate in Reactor (Hooks.enableAutomaticContextPropagation() with Micrometer context propagation), and why debugging (stack traces, checkpoint(), Hooks.onOperatorDebug) is harder than with imperative code.
T9. Reactive against virtual threads, and async streams elsewhere
- The lab measured virtual threads at 465 req/s (p50 566 ms) against 20 platform threads at 188 req/s (p50 1,100 ms) for blocking work, with the same code. Weigh MVC plus virtual threads against WebFlux for: - the order API (JDBC, a few downstream calls); - the kitchen display stream (SSE to hundreds of tablets); - a GPS ingestion gateway (100,000 devices sending every 5 s); - a streaming export.
Where is reactive still worth its costs?
2. Async streams in other languages:
- Kotlin coroutines and Flow (cold, suspending, backpressure by suspension);
- JavaScript async iterators and Node streams (highWaterMark, pipe);
- Rust Stream with async/await;
- Go channels (bounded channels give backpressure by blocking);
- .NET IAsyncEnumerable and System.Threading.Channels;
- RxJS (Volume 2).
How does each express backpressure? 3. If TiffinBox already has a WebFlux service (ch38's S3), what's the migration path to MVC plus virtual threads, and what should stay reactive?
Programming exercises
P1. Mapping and binding edge cases
With Spring MVC, map GET /api/dishes/{id} and GET /api/dishes?limit= (a required int). Show:
- the trailing-slash 404;
- missing and mistyped parameters as problems;
- a malformed JSON body;
- a regex-constrained path variable rejecting bad ids.
Then customise the framework problems to include code and field paths, and add UrlHandlerFilter (Spring 6.2+) to redirect trailing slashes for a legacy client.
P2. Filters, interceptors and advice: who sees what
Register:
- a logging filter;
- an interceptor (preHandle and afterCompletion);
- a @RestControllerAdvice.
Record the order of calls for: - a successful request; - a handler exception resolved by the advice; - an unmapped path; - an exception thrown in a filter.
Explain each trail. Then implement the access log in the right place, with the route template, final status and duration, covering unmapped paths too.
P3. Validation into problem details
Add Bean Validation (spring-boot-starter-validation, unavailable offline here) to PlaceOrderRequest:
- @NotEmpty @Size(max = 20) List<@Valid Line>;
- @Min(1) @Max(5) qty;
- a custom @ValidDishId.
Add method validation on @RequestParam @Min(1) @Max(100) limit. Map MethodArgumentNotValidException and HandlerMethodValidationException to 422 problems with errors[{field, code}]. Write the expected responses and @WebMvcTest tests.
P4. Negotiation, CSV and ETags
Show:
- Accept: application/xml giving 406 with the acceptable list;
- ShallowEtagHeaderFilter giving 304.
Then:
- add a text/csv converter for an export endpoint;
- implement a deep ETag with WebRequest.checkNotModified, and count the database loads for 10 conditional requests (the shallow version loads 10 times, the deep version 0);
- add Vary: Accept.
P5. RestClient and @HttpExchange with timeouts and error decoding
Build DishClient as an @HttpExchange interface over Boot's RestClient.Builder (P5's call returned {"id":"d7","name":"Idli","paise":4000}). Then:
- add connect and read timeouts, and show a hanging endpoint failing fast (the lab: 563 ms against 20 s);
- add a status handler decoding problem bodies into typed exceptions;
- add an authentication interceptor that never logs the token;
- write a test with MockRestServiceServer.
P6. Blocking on the event loop, and virtual threads instead
Reproduce the lab's blocking experiment with Reactor: 20 blocking 100 ms calls on a 2-thread scheduler against boundedElastic. Add BlockHound (if available) to detect the blocking call. Then implement the same fan-out (20 calls, 100 ms each) three ways and compare code and timing:
- on MVC with virtual threads using RestClient in a structured or CompletableFuture fan-out;
- with Reactor Flux.flatMap(…, 20) and WebClient;
- naive sequential.
P7. Reactor operators: order, concurrency and retries
Measure:
- flatMap against concatMap against flatMapSequential for calls of 300, 100, 200 and 50 ms (P7);
- bounded concurrency with flatMap(…, 5), measured at a semaphore-protected fake resource;
- retryWhen(Retry.backoff(…)) attempt timings with and without jitter;
- timeout plus onErrorResume with a fallback.
Then implement the "order details" fan-out (ch38's C1) in Reactor with zip, a timeout per optional part, and fallbacks.
P8. Backpressure strategies and context
Produce a fast Flux.interval(1 ms) with a slow consumer (5 ms per item) and apply:
- onBackpressureError (P8: OverflowException);
- onBackpressureDrop (P8: 198 dropped);
- onBackpressureLatest;
- onBackpressureBuffer(100) with an overflow strategy.
Report the counts. Then demonstrate:
- a ThreadLocal lost after delay (P8: null);
- Context propagation (req-42);
- automatic MDC propagation with Hooks.enableAutomaticContextPropagation() (if context-propagation is available; otherwise expected output).
P9. Async streams in other languages
Implement "consume order events, drop stale GPS pings, never drop payments" in:
- Kotlin Flow (conflate for GPS, buffer for orders; described if Kotlin isn't available);
- Go (a buffered channel blocking for orders; select with default dropping GPS);
- Node streams (highWaterMark, and write() returning false);
- Python asyncio.Queue(maxsize=…).
Show the backpressure behaviour with a slow consumer in Go and Python (runnable here).
Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33–48)
C1. The order API's web layer, complete
Finish the web layer of ch47's C1:
- thin controllers;
- PathPatternParser routes;
- strict binding;
- validation with field paths (P3);
- one advice mapping domain errors and framework errors to TiffinBox problems (P1, P3);
- filters and interceptors in the documented order (T4, P2);
- the access log with route templates;
- deep ETags and If-Match (P4, ch45);
- an SSE endpoint for order status on virtual threads (T5);
- @HttpExchange clients for payments and maps with timeouts, decoding and circuit breakers (P5, ch52 preview).
Add @WebMvcTest coverage for every endpoint and error.
Combines: ch44's skeleton, ch45's API design, ch46's Spring rules, ch47's Boot defaults, and this chapter.
C2. A reactive GPS ingestion gateway
Build TiffinBox's delivery-partner GPS gateway with Reactor (WebFlux if available, otherwise Reactor plus Netty or a simulation):
- devices send pings every 5 s;
- the gateway keeps only the latest position per partner (onBackpressureLatest, a per-key latest map);
- it batches updates to a store every 500 ms (bufferTimeout);
- it publishes position changes to subscribers (an SSE map view);
- it drops stale pings older than 30 s.
Load test it with 10,000 simulated devices and report throughput, latency and memory.
Combines: Volume 1's networking, Volume 2's live UI streams, ch38's concurrency, ch41's measurement and ch45's rate limits, with this chapter's reactive streams.
C3. Migrate a WebFlux endpoint set to MVC with virtual threads
Take the notification service from ch38's S3 (WebFlux, WebClient, partly blocking libraries). Migrate three request and response endpoints to MVC with virtual threads (RestClient, @HttpExchange), keeping one streaming endpoint reactive. Run the same contract tests and load test before and after, and compare:
- p50 and p99;
- CPU and memory;
- lines of code;
- stack-trace readability (a forced error);
- BlockHound findings.
Combines: ch38's concurrency models and S3 decision, ch41's measurement, ch45's contract tests, ch47's Boot configuration, and this chapter.
What the chapter leaves out
Functional endpoints (RouterFunction)
Both MVC and WebFlux support functional routing:
route().GET("/orders/{id}", req -> ok().body(service.get(req.pathVariable("id")))).build()
There are no annotations and no reflection on handler methods, routes are composable, and it's friendlier to AOT and native images. Useful for small services and dynamic route registration. Annotations stay more common in teams. Both styles coexist.
WebSockets, STOMP and RSocket
Spring supports raw WebSocket handlers, STOMP messaging over WebSocket (@MessageMapping, a simple broker or a relay to RabbitMQ), and RSocket (reactive, bidirectional, with backpressure). For browser real-time UIs, SSE (one-way) is simpler (T5). WebSocket fits bidirectional interaction, such as kitchen acknowledgements or chat. Mind the scaling, because connections pin to instances, needing sticky sessions or a broker relay.
HTTP/2, HTTP/3 and gRPC in Spring
Tomcat and Netty support HTTP/2 (server.http2.enabled=true, usually behind TLS). HTTP/3 (QUIC) is available through Reactor Netty in recent versions, and is mostly terminated at edge proxies. gRPC in Spring is supported by the Spring gRPC project (ch45's T9), which uses the same observability and security conventions.
API versioning support in Spring Framework 7
Spring Framework 7 adds first-class API versioning: @RequestMapping(version = "1.1"), version resolution from a header, a path segment, a query parameter or the media type, and deprecation handling. It maps directly to ch45's versioning strategies. Configure it with ApiVersionConfigurer, and add Deprecation and Sunset headers through its deprecation handler.
Testing web layers
Use MockMvc (and the newer MockMvcTester with AssertJ), WebTestClient for WebFlux (and for MVC over a real server), @WebMvcTest slices (ch47's P7), contract testing with Spring Cloud Contract or Pact (ch54), and RestTestClient (Spring 7) for real-server HTTP tests. Test error contracts and negotiation, not just the happy path.
Senior exercises
S1. The web-layer standard
Write TiffinBox's Spring web-layer standard:
- MVC with virtual threads by default;
- WebFlux only for streaming services (with criteria);
- thin controllers;
- path patterns without trailing-slash reliance;
- binding and validation errors as problems with field paths;
- one advice;
- the filter, interceptor and advice order;
- the access log with route templates;
- deep ETags for hot reads;
- SSE with SseEmitter;
- @HttpExchange clients with timeouts and decoding;
- no blocking on event loops (BlockHound in reactive services);
- context propagation;
- testing rules.
Tie each to an output from this chapter.
S2. Review a web-layer pull request
A PR adds:
- a controller that injects OrderRepository and contains pricing logic;
- @GetMapping("/orders/") with a trailing slash;
- try { … } catch (Exception e) { return ResponseEntity.status(500).body(e.getMessage()); } in every method;
- a filter that logs request.getRequestURI() as a metric tag;
- WebClient.create().get()…block() inside an MVC controller;
- an SSE endpoint using new Thread() per client with an infinite loop and Thread.sleep(1000).
Write the review.
S3. Choose the stack for the GPS gateway and the order API
Following T9 and C2, decide: - the order API stack (MVC plus virtual threads against WebFlux); - the GPS gateway stack (WebFlux and Netty, MVC plus virtual threads, or a broker-first design with MQTT and Kafka); - the kitchen display streaming (SSE from MVC, or WebFlux).
Write the decision record with criteria, measurements needed, risks, and revisit triggers.
S4. Teach "MVC and reactive without myths" with five outputs
Prepare a 20-minute session using:
- the lab's platform-thread against virtual-thread results;
- the lab's blocking on the event loop (1,012 against 106 ms);
- P7's flatMap ordering;
- P8's lost ThreadLocal;
- P2's interceptor ex=none.
Message: each model has rules, and knowing them prevents incidents.
S5. Plan the web-layer platform features
As platform lead, plan the shared web-layer features in tiffinbox-spring-boot-starter (ch47's C2) for the next two quarters:
- the error contract (advice, framework error overrides, field paths);
- request id and access logs;
- rate limiting and deprecation interceptors;
- deep-ETag helpers;
- @HttpExchange client defaults (timeouts, decoding, authentication, observability, resilience);
- SSE helpers (registry, heartbeats, after-commit publishing);
- API versioning with Spring 7;
- BlockHound and context propagation for reactive services;
- test fixtures (shared error fixtures, MockRestServiceServer helpers).
Give milestones, adoption strategy and metrics.