Volume 3 Companion: The BackendPractice for Volume 3
0 / 0

Workbench / Volume 3 Companion: The Backend

V3·47

Spring Boot

Companion to Volume 3, chapter 47: how what Boot is, its wiring and configuration, running in production and testing and startup connect; new angles (readiness as a shop's "closing soon" sign, warm-up as a kitchen's first batch, a default as a decision someone made for you); what the chapter simplifies, measured on the build's stage 48 behind haproxy: a server that said "ready" while its first requests were twenty times slower than its later ones, a readiness signal that changed nothing during a restart until the server waited for the load balancer to notice (8 to 10 failed orders per restart, then none), a warm-up that warmed only the paths it ran, and a 44 ms stall on every kitchen page over 8 KB that an embedded server's defaults would have prevented; the theory behind them (probes, propagation delay, JIT warm-up, Nagle and delayed ACKs); how Boot flips readiness and then shuts Tomcat down, from its source; four debugging drills; interview questions with how to approach each.

6 sections · ~12 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 47 covers what Boot is (the problem it solves, what SpringApplication.run does), wiring and configuration (auto-configuration, starters, configuration properties, externalised configuration precedence, profiles), running in production (embedded servers, Actuator, health, liveness and readiness, metrics and tracing, graceful shutdown) and testing and startup (test slices, AOT and native images, container images), with Boot's peers in other ecosystems.

what Boot is wiring and configuration running in production testing and startup the problem wiring every service by hand SpringApplication.run environment, context, runners opinionated defaults override any Boot's peers Quarkus, Micronaut, Helidon auto-configuration @Conditional starters curated dependencies @ConfigurationProperties typed, validated precedence, profiles command line wins embedded server Tomcat, Jetty, Netty Actuator health, metrics, env liveness, readiness restart or route away graceful shutdown drain, then stop test slices @WebMvcTest, @DataJpaTest startup cost classes, beans, JIT AOT, native images build-time wiring container images layers, buildpacks solved by applies compare pulled in by configured by from plus exposes must lead limit cut by shipped as builds on: ch46 Spring Core · ch44 backend fundamentals (lifecycle) · goes on: ch48 Spring Web · ch54 backend testing · Vol 6 observability · Vol 8 deployment exercises: P1–P9 typed config, JSON strictness, problem details, virtual threads, an auto-configuration, Actuator, slices, shutdown, startup; C1–C3
Concept map of chapter 47, Spring Boot: what Boot is (the problem it solves, what SpringApplication.run does), wiring and configuration (auto-configuration, starters, configuration properties, externalised configuration precedence, profiles), running in production (embedded servers, Actuator, health, liveness and readiness, metrics and tracing, graceful shutdown) and testing and startup (test slices, AOT and native images, container images), with Boot's peers, and links such as conditions deciding what gets configured and readiness that must flip before shutdown.

The links worth remembering:

  • Boot is a set of decisions, made in advance. Auto-configuration, starters and defaults decide what most services would decide; every one can be overridden, and every one is worth knowing, because you're running with it.
  • Production features are about other systems. Health, readiness, metrics and graceful shutdown exist for load balancers, orchestrators and dashboards. They only work if the timing matches what those systems do.
  • Startup is a cost paid at the worst time: during deploys, scale-ups and recoveries.

Explain it differently

1. Readiness is a shop's "closing soon" sign. Hanging the sign doesn't empty the shop; it stops people walking in. You still have to wait until passers-by have seen it before you lock the door. A server that says "not ready" and stops in the same instant has hung the sign and locked the door together (Gaps 2).

2. Warm-up is a kitchen's first batch. The first dosas on a cold tawa are slow and uneven. A good cook makes a few before the doors open. But warming the tawa doesn't warm the oven: only the stations you used are ready (Gaps 1 and 3).

3. A default is a decision someone made for you. Tomcat sends small responses immediately (TCP_NODELAY); a socket opened by hand doesn't. Using an embedded server means inheriting hundreds of such decisions, mostly good; writing your own means making each one, or not noticing it (Gaps 4).

Gaps and misconceptions

What the chapter oversimplifies

All outputs are real, from OpenJDK 21.0.12, haproxy (checking every 500 ms) and the build's stage 47 and 48 servers (exp/48), unless stated.

1. Ready isn't warm. The chapter's readiness means the application context has started. For a JVM service, that's when class loading and the JIT begin in earnest. Time from launch until the health URL says 200, then 600 requests (the kitchen page, the menu page, a search, in turn) on one connection, median of three starts:

Terminal
# stage 47 build, /health
/health said 200 after 298 ms (median of 3 starts)
  requests   1-3    median  14.69 ms   slowest   29.23 ms
  requests   4-30   median   0.90 ms   slowest    7.63 ms
  requests  31-150  median   0.74 ms   slowest    6.80 ms
  requests 151-600  median   0.60 ms   slowest    4.50 ms

The first requests took twenty times as long as later ones. For TiffinBox that's 15 ms; for a Spring application with thousands of classes, the first requests after a deploy often take seconds, and they're the ones that time out. Stage 48 runs a warm-up (read-only pages, through the router, in the process) before saying ready:

Terminal
# stage 48 build, warm-up 1000 (the default), /health/ready
/health/ready said 200 after 631 ms (median of 3 starts)
  requests   1-3    median   0.82 ms   slowest    1.02 ms

Ready 330 ms later, and no slow first requests. That trade (a later "ready" for no cold users) is only possible because traffic waits for readiness.

2. Saying "not ready" doesn't help unless you wait. The chapter's graceful shutdown finishes requests in flight. With two instances behind haproxy and eight clients placing orders, one instance was stopped with SIGTERM:

Terminal
# stage 47 build, haproxy checks /health
  instance a exited 370 ms after SIGTERM
  2786 orders sent by 8 clients: 201 x2776, 503 x8, RemoteDisconnected x2

Between the server closing its socket and haproxy's next check, haproxy kept sending it orders, and they failed (one of three runs lost only one order). Adding a readiness endpoint alone changed nothing:

Terminal
# stage 48 build, haproxy checks /health/ready, but --drain=0s
  instance a exited 359 ms after SIGTERM
  3057 orders sent by 8 clients: 201 x3048, 503 x8, RemoteDisconnected x1

The server said "not ready" and stopped in the same instant, so haproxy learned both at once. With a drain (say "not ready", keep serving for 2 s, then stop):

Terminal
# stage 48 build, haproxy checks /health/ready, drain 2s (the default)
  instance a exited 2353 ms after SIGTERM
  7477 orders sent by 8 clients: 201 x7477
  instance a exited 2384 ms after SIGTERM
  7603 orders sent by 8 clients: 201 x7603

No failed orders in three runs. Boot flips readiness and shuts down in the same way (Code walkthrough), which is why its documentation recommends a preStop sleep in Kubernetes: the wait has to come from somewhere.

3. A warm-up warms what it runs. Stage 48's warm-up only reads pages, because it must not create orders. After it, a fresh server's first order placements:

Terminal
warm-up 1000 (read-only pages): POST /orders     first 3 median   4.03 ms | requests 50-200 median  1.32 ms
warm-up 1000 (read-only pages): GET /kitchen/k1  first 3 median   1.98 ms | requests 50-200 median  0.90 ms

The first orders still took three times as long as later ones: their code (parsing, pricing, the log's encoder, the writer thread's hand-off) hadn't run. Warming a write path needs a way to exercise it without effects (a dry-run mode, a test tenant, or replaying recorded requests against a scratch log), or the JVM's newer help: CDS archives with profiles and, in recent JDKs, ahead-of-time method profiling (JEP 515, JDK 25), and Boot's AOT and native images (Theory 3).

4. A default you didn't know you relied on. Measuring the warm-up turned up something else: kitchen pages over 8 KB took 44 ms on a kept-alive connection.

Terminal
# stage 48 before TCP_NODELAY
   0 open orders: page  1,970 bytes, median   0.75 ms
  10 open orders: page  7,110 bytes, median   0.85 ms
  20 open orders: page 12,270 bytes, median  43.99 ms
  40 open orders: page 22,590 bytes, median  44.00 ms
# stage 48 with TCP_NODELAY
  20 open orders: page 12,270 bytes, median   1.31 ms
  40 open orders: page 22,590 bytes, median   1.47 ms

A response bigger than the server's 8 KB output buffer went out as two writes, headers and then body, and Nagle's algorithm held the second until the client acknowledged the first, which the client delayed by 40 ms. Chapter 45's lab showed the effect; TiffinBox had it on its busiest page since its first stages, hidden because the tests' kitchens had few orders. Tomcat, Jetty and Netty-based servers set TCP_NODELAY by default, one of the many decisions an embedded server makes for you. TiffinBox now sets it on every accepted socket.

Common misconceptions

Misconception What's actually true Where it's shown
"Started means ready means fast." The first requests run cold code. Gaps 1
"A readiness probe makes deploys safe." Only if the server waits for it to be seen before stopping. Gaps 2, Code walkthrough
"Graceful shutdown means no failed requests." It finishes requests that arrived; others may still be on their way. Gaps 2
"Warm-up warms the application." It warms the code it runs. Gaps 3
"Small pages are fast pages." A page just over a buffer size can wait for a delayed ACK. Gaps 4
"Relaxed binding catches typos." A misspelt property or variable matches nothing, silently. Exercises P1

Theoretical gaps: the ideas behind the chapter

1. Probes are for a controller, not for you. Liveness answers "should this process be restarted?" (only if it can't recover by itself, so never check dependencies there); readiness answers "should traffic go here now?" (warming up, overloaded, draining); startup probes give slow starters time before liveness counts. Each is read by something with its own interval and threshold, and a state change takes effect only after that delay.

2. Propagation delay sets the drain. A load balancer checking every i seconds, marking a server down after f failures, needs up to i × f seconds (plus its own update) to stop routing. Kubernetes adds the time for endpoint changes to reach every kube-proxy or ingress. The drain must be at least that long; haproxy here: 0.5 s × 1, so 2 s is generous.

3. JIT warm-up and its alternatives. HotSpot interprets code first, compiles hot methods at tier 3 with profiling, then at tier 4 (C2) with optimisations based on the profile. Until then, code runs slower. Options: warm up with representative traffic before readiness; reduce class loading (CDS, AppCDS, chapter 42's companion); keep profiles across runs (JDK 25's ahead-of-time method profiling, Project Leyden); compile ahead of time (GraalVM native image, Boot's AOT processing), trading peak performance and dynamism for startup.

4. Nagle and delayed ACKs. Nagle's algorithm (RFC 896) holds back a small segment while earlier data is unacknowledged; delayed ACK (RFC 1122) lets a receiver wait up to 500 ms (commonly 40 ms on Linux) before acknowledging. Together, a write-write-read pattern stalls for the delayed-ACK timer. The fix is to write a response in one write, or disable Nagle (TCP_NODELAY), which request-response servers almost always do.

Applying it

Code walkthrough

Gaps 2 explains why Boot users add a preStop sleep. From spring-projects/spring-boot, main at commit 7844ec9 (19 November 2026).

Readiness flips as the context closes

module/spring-boot-web-server/src/main/java/org/springframework/boot/web/server/servlet/context/ServletWebServerApplicationContext.java:

Java
	@Override
	protected void doClose() {
		if (isActive()) {
			AvailabilityChangeEvent.publish(this, ReadinessState.REFUSING_TRAFFIC);
		}
		super.doClose();
		WebServer webServer = this.webServer;
		if (webServer != null) {
			webServer.destroy();
		}
	}

On close, Boot publishes REFUSING_TRAFFIC (so /actuator/health/readiness starts answering 503) and continues straight into super.doClose(), which runs the lifecycle's stop phase, including the web server's graceful shutdown. There's no wait between the two.

Tomcat stops accepting at once

module/spring-boot-tomcat/src/main/java/org/springframework/boot/tomcat/GracefulShutdown.java:

Java
	private void doShutdown(GracefulShutdownCallback callback, CountDownLatch shutdownUnderway) {
		try {
			List<Connector> connectors = getConnectors();
			connectors.forEach(this::close);
			GracefulShutdownResult result = awaitInactiveOrAborted(shutdownUnderway);
			...

	private void close(Connector connector) {
		connector.pause();
		connector.getProtocolHandler().closeServerSocketGraceful();
	}

Graceful shutdown pauses each connector and closes its server socket, then waits for active requests to finish (checking every 50 ms, up to spring.lifecycle.timeout-per-shutdown-phase). New connections are refused from the first moment. That's correct for requests already inside, and it's Gaps 2's --drain=0s case for requests the load balancer is still sending. The gap between "readiness says 503" and "the socket is closed" is a few milliseconds, so the wait has to be added outside: a Kubernetes preStop hook that sleeps, or Boot's own option where available. TiffinBox does it in its shutdown hook: drain(), sleep, close().

Debugging drills

D1. Errors on every deploy

A Boot service on Kubernetes with readiness and liveness probes and server.shutdown=graceful still shows a few hundred 502s from the ingress on every rolling deploy.

D2. Timeouts right after each deploy

After each deploy, the p99 latency spikes for a minute and some calls from another service time out, though readiness probes pass.

D3. A warm-up that didn't help writes

A team added a warm-up that calls the read endpoints; reads are fast after deploys now, but the first payments after each deploy still time out.

D4. 40 ms on some pages, not others

A hand-written HTTP endpoint (or a gateway plugin) answers small requests in 1 ms, but some larger responses take 41 to 45 ms, consistently, on kept-alive connections only.

Career-oriented

Interview prep

Mid-level 1: how auto-configuration decides

Question. "How does Spring Boot decide to configure a DataSource for you, and how do you make it stop?"

How to get there. Conditions on the class path, on existing beans and on properties.

Mid-level 2: liveness or readiness

Question. "The database is down. Should the liveness probe fail?"

How to get there. What would restarting fix?

Senior 1: zero-downtime deploys

Question. "Design the deploy procedure for a Boot service so that a rolling deploy causes no failed requests."

How to get there. Follow traffic during startup and shutdown, and give each step the time the other systems need.

Senior 2: startup time

Question. "Our Boot service takes 40 seconds to start and autoscaling is too slow. What do you do?"

How to get there. Measure where the time goes, then remove, defer or precompute.

Staff 1: what the platform decides for every service

Question. "You own the Boot service template for 80 teams. Which production behaviours does the template guarantee, and how?"

How to get there. The things every team gets wrong alone, made default and tested.

Staff 2: framework defaults as risk

Question. "A Boot upgrade changes some defaults. How do you make sure a default change can't silently hurt production?"

How to get there. Find the defaults you rely on, and test them.