Workbench / Volume 3 Companion: The Backend
V3·48
Spring Web — MVC and WebFlux
Companion to Volume 3, chapter 48: how Spring MVC, the code around a handler, reactive programming and choosing between them connect; new angles (binding as a customs desk, a request's instant as a receipt's time stamp, deprecation as a road closure sign); what the chapter simplifies, measured on the build's stage 49: a lenient body format that accepted orders for kitchens that don't exist, one request that read the clock three times and logged an order priced before 11:00 as received after it, an error format that can't change under clients that show errors to people, and a deprecation that changed nothing until the senders moved (54 of 57 POSTs in the browser suite used the old format, all of them our own); the theory behind them (parse, don't validate; time as an input; content negotiation; the expand and contract cycle); how Spring Framework 7 sends Deprecation and Sunset headers and falls back to problem details, from its source; four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 48 covers Spring MVC (the DispatcherServlet, request mapping, binding and validation, exception handling with ProblemDetail), what runs around the handler (filters, interceptors and advice, message converters and content negotiation, HTTP clients), reactive programming (why it exists, Reactive Streams and backpressure, Reactor's Mono and Flux, the event loop) and choosing (reactive against virtual threads, async streams in other languages).
The links worth remembering:
- Binding is the boundary. Everything after it handles typed values; everything before it handles bytes. What binding doesn't check, nothing downstream knows to check.
- A request is a unit: of identity (its id), of time (its instant), of failure (one problem, with every field's error), of contract (what the client sent and what it accepts).
- Reactive and virtual threads answer the same question, how to wait cheaply, for different shapes of work: streams with backpressure, or calls that block.
Explain it differently
1. Binding is a customs desk. Bytes arrive from anywhere; the desk lets through only what it can name: this field, this type, this range. A desk that waves through "a parcel for kitchen k07" has passed the problem to whoever later finds no such kitchen (Gaps 1).
2. A request's instant is the time stamp on a receipt. One receipt has one time, printed once. If the price were worked out at 10:59:59.999 and the time printed at 11:00:00.000, the receipt would contradict itself (Gaps 2).
3. Deprecation is a road closure sign. The sign alone moves nobody; drivers who never read signs find out on the day. You count the traffic, call the regular drivers, and close the road when the count is zero (Gaps 4).
Gaps and misconceptions
What the chapter oversimplifies
All outputs are real, from OpenJDK 21.0.12 and the build's stage 48 and 49 servers (exp/49), unless stated.
1. A lenient format can't be validated into a strict one. The chapter binds JSON into a record and validates it. TiffinBox's orders arrived as text since stage 2 (kitchen k7, then d1 2 lines), parsed by hand. What did it accept?
# stage 48: POST /orders with a text body
the same dish twice 201 order o1 at k7: d1 x1, d1 x2, total 26850 paise
a kitchen that does not exist 201 order o3 at k999999: d1 x1, total 8950 paise
k07, not k7 201 order o4 at k07: d1 x1, total 8950 paise
two problems 400 unknown dish d999
An order for kitchen k07 is a different kitchen from k7: it went to a screen nobody watched. The order form had a list of kitchens (k1 to k12) since stage 13; the API never checked it. Stage 49 takes a PlaceOrder in JSON, bound field by field with every problem reported at once:
# stage 49: POST /orders with application/json
a kitchen that does not exist 400 {"title":"The order can't be placed","status":400,"detail":"kitchenId: there's no kitchen k999999 (kitchens are k1 to k12)", …}
quantity as a string 400 … "lines[0].quantity: must be a number, got \"2\"" …
a duplicate key 400 … "body: isn't valid JSON: duplicate key \"kitchenId\" at offset 18" …
four problems 400 {"title":"The order can't be placed","status":400,"detail":"4 problems with the request body","errors":[
{"field":"kitchenId","message":"there's no kitchen seven (kitchens are k1 to k12)"},
{"field":"lines[0].dishId","message":"there's no dish d999 on the menu"},
{"field":"lines[1].quantity","message":"must be 1 to 20, got 100"},
{"field":"lines[2].dishId","message":"is required"}]}
Typing helps because it gives every value a name to check against (kitchenId, lines[1].quantity); the hand parser had positions in a string. Duplicate keys are refused because parsers disagree about them (first wins, last wins, error), so two services reading the same body could act on different kitchens.
2. One request, three times. The chapter's handlers take what they need as parameters, but the time isn't one of them; code reads a clock where it needs one. A clock that moves 1 ms per reading, starting just before 11:00 in Kolkata (the breakfast rule's boundary), shows each reading:
# stage 48
POST /orders (i2): 201, the clock was read 3 times: 2026-11-20T05:29:59.999Z, 2026-11-20T05:30:00Z, 2026-11-20T05:30:00.001Z
the order's "at": 2026-11-20T05:29:59.999Z; discount rules ["Breakfast at k7"]
access log "t": 2026-11-20T05:30:00.001Z
the log's received-at for o2: 2026-11-20T05:30:00Z
The order was priced as a breakfast order (10:59:59.999), and the log says it was received at 11:00:00.000. Anyone replaying the log by received-at would price it without the discount. In production the readings are microseconds apart, so this happens rarely, and only at a boundary: the hardest kind of bug to reproduce. Stage 49 reads the clock once per request, into a RequestContext every handler gets:
# stage 49
POST /orders (i2): 201, the clock was read once: 2026-11-20T05:29:59.997Z
the order's "at": 2026-11-20T05:29:59.997Z; discount rules ["Breakfast at k7"]
access log "t": 2026-11-20T05:29:59.997Z
3. Changing the error format is a breaking change. The chapter makes every error a Problem Detail. TiffinBox's kitchen screens show a refused tap's error text to the cook (HttpError used the response body as the message since stage 19). Tapping "ready" on an order the kitchen hasn't accepted, as text and as JSON:
$ curl -X POST /orders/o1/events -d 'ready'
409 text/plain; charset=utf-8
kitchen hasn't accepted the order
$ curl -X POST /orders/o1/events -H 'Content-Type: application/json' -d '{"event":"ready"}'
409 application/problem+json; charset=utf-8
{"title":"The order can't change that way","status":409,"detail":"kitchen hasn't accepted the order"}
A screen that displays the body would show the cook the second one.
So TiffinBox negotiates: a client that sends JSON or asks for application/problem+json gets problem details; any other client gets the plain text it always got. The golden master, which pins 47 exchanges, stayed identical. The kitchen client was changed to read detail from a problem before it started asking for them. Spring falls back to problem details when nothing in Accept matches (Code walkthrough), so in Spring the same care means checking what your clients send in Accept.
4. A deprecation does nothing until the senders move. Stage 49 keeps the text bodies working and marks every response to them with Deprecation, Sunset and Link headers. The access log counts each use. The browser suite (44 tests) against the stage 49 server:
# before the clients moved
POST /orders 45 requests, 45 with a deprecated text body
POST /orders/{id}/events 9 requests, 9 with a deprecated text body
all POSTs 57 requests, 54 with a deprecated text body
# after: the kitchen views' sender, the suite's seeding, simulate and canary send JSON
all POSTs 57 requests, 0 with a deprecated text body
Every deprecated request came from TiffinBox's own code: the suite's seeding through the API, and cooks' taps from the kitchen views. Searching the repository for the format found the same in Main simulate, the canary and the release check's own requests. No browser reads Deprecation headers; no person reads them in a working client. Clients move because someone finds them (the access log), changes them, and checks the count is zero. The kitchen's outbox holds taps written by older pages; the sender converts them when it sends them, so even queued taps leave in the new format. The release check now fails if it sends a deprecated body itself.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "Validation makes any input format safe." | Only what the format names can be checked. | Gaps 1 |
| "Duplicate JSON keys are harmless." | Parsers disagree on which one wins. | Gaps 1 |
| "Now is now." | Each reading is a different time; a request needs one. | Gaps 2 |
| "Problem details are always better." | For clients that read them; others display them. | Gaps 3, Code walkthrough |
| "Deprecation headers tell clients to move." | They label; counting and changing the clients moves them. | Gaps 4 |
| "Controllers are the architecture." | They translate; the rules live in a service you can test without HTTP. | Theory 1 |
Theoretical gaps: the ideas behind the chapter
1. Layers translate. A controller turns HTTP (headers, bytes, status codes) into a typed command and an outcome back into HTTP; the service decides. TiffinBox's stage 49 split shows it: Server went from 681 lines to 520 (sockets, streams, static files), Orders (175 lines) holds the rules and takes typed commands and an instant, OrdersApi (78 lines) translates. OrdersTest places orders and applies events with no socket at all, and the HTML checkout now calls Orders directly instead of writing the API's text body and posting it to itself.
2. Parse, don't validate. A validator checks a value and hands back the same loose type; a parser returns a type that can only hold valid values (PlaceOrder with real Dishes). Code after the parser can't receive a string kitchen id it hasn't checked, because it never receives a string. Spring's binding plus Bean Validation is a parser if the target type is strict (records, no setters, no defaults that hide missing fields).
3. Time is an input. A function that reads a clock has an input nobody passes. Reading it once per request and passing it down makes every part of the request agree, and makes the request reproducible: the same request with the same instant gives the same answer. Spring has no built-in request instant; a request-scoped bean, an argument resolver or a filter that stores it are the usual ways.
4. Content negotiation, both directions. Content-Type says what a body is; Accept says what the client can read. A server that changes formats safely keys the new format on something the client sent: new clients opt in, old clients see nothing new.
5. Expand, then contract. Add the new format alongside the old (expand), move every client while measuring use, and remove the old only when use is zero (contract). The Sunset date is a promise to clients, not a switch: if the count isn't zero by then, the date moves or the remaining clients are called.
Applying it
Code walkthrough
Gaps 3 and 4 have Spring counterparts. From spring-projects/spring-framework, main at commit 7ce40c8 (18 November 2026).
Deprecation and Sunset headers
Spring Framework 7 added API versioning; deprecating a version sends the headers TiffinBox sends. spring-web/src/main/java/org/springframework/web/accept/StandardApiVersionDeprecationHandler.java:
private static final DateTimeFormatter HTTP_DATE_FORMATTER =
DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US).withZone(ZoneId.of("GMT"));
...
@Override
public void handleVersion(
Comparable<?> requestVersion, Object handler,
HttpServletRequest request, HttpServletResponse response) {
for (VersionInfo info : this.infos.values()) {
if (info.match(requestVersion, request)) {
if (info.deprecationDate() != null) {
response.setHeader("Deprecation", info.deprecationDate());
}
if (info.deprecationLink() != null) {
response.addHeader(HttpHeaders.LINK, info.deprecationLink());
}
if (info.sunsetDate() != null) {
response.setHeader("Sunset", info.sunsetDate());
}
...
public VersionInfo withDeprecationDate(ZonedDateTime deprecationDate) {
return new VersionInfo(version(), requestPredicate(),
"@" + deprecationDate.toInstant().getEpochSecond(), deprecationLink(),
sunsetDate(), sunsetLink());
}
Deprecation is @ and seconds since the epoch (RFC 9745); Sunset is an HTTP date (RFC 8594). Spring attaches them per API version, optionally narrowed by a request predicate. TiffinBox deprecates a request format within one version, which is the expand-and-contract way (stage 46's ADR-0048); a predicate on Content-Type would express it in Spring. Neither counts uses: that's an access-log or metrics job.
Problem details when nothing matches
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodProcessor.java, in writeWithMessageConverters:
List<MediaType> compatibleMediaTypes = determineCompatibleMediaTypes(acceptableTypes, producibleTypes);
// For ProblemDetail, fall back on RFC 9457 format
if (compatibleMediaTypes.isEmpty() && ProblemDetail.class.isAssignableFrom(valueType)) {
compatibleMediaTypes = determineCompatibleMediaTypes(PROBLEM_MEDIA_TYPES, producibleTypes);
}
When the client's Accept matches nothing the converters can write, an ordinary body is a 406, but a ProblemDetail is sent as application/problem+json (or XML) anyway: an error should reach the client in some form. That's right for API clients, and it's Gaps 3's risk for clients that display error bodies: they get JSON whatever they asked for.
Debugging drills
D1. Orders that nobody cooks
A few orders a week are never prepared. They're in the database with a valid status; the kitchen staff say they never saw them.
D2. A discount that depends on how you look
A customer complains they were charged full price for a breakfast order. The order record shows the discount; the nightly revenue report, which uses the log's received-at times, says no discount applied.
D3. JSON on the kitchen screen
After a release that "made errors consistent", kitchen screens show {"title":"Conflict","status":409,…} instead of a sentence.
D4. The sunset that wasn't
A team deprecated a field six months ago with Deprecation and Sunset headers. Removing it on the sunset date broke three internal services.
Career-oriented
Interview prep
Mid-level 1: binding a request body
Question. "A client sends {"quantity": "2"} to an endpoint expecting an integer. What happens in Spring, and what do you want to happen?"
How to get there. What Jackson does by default, and what the contract says.
Mid-level 2: where does it go?
Question. "We need a request id on every log line and every response, including 404s for unknown paths. Filter, interceptor or advice?"
How to get there. Which of them sees requests that match no handler?
Senior 1: changing an error format
Question. "Your API returns errors as plain text. Design the move to RFC 9457 problem details without breaking anyone."
How to get there. Who reads the errors, and how would each know which format to expect?
Senior 2: one time per request
Question. "Some of our records disagree about when things happened by a millisecond, and it matters at boundaries. How do you fix it across a Spring service?"
How to get there. Where is the clock read, and how many times per request?
Staff 1: deprecations across an organisation
Question. "You run an API platform with 200 internal consumers. Design how deprecations are announced, tracked and completed."
How to get there. What makes a deprecation finish?
Staff 2: MVC or WebFlux for the platform
Question. "Teams ask whether new services should be MVC or WebFlux. What's your default and why?"
How to get there. What each costs in code, debugging and hiring, against what each gives under load.