Sub topic 1
How Spring MVC handles a request today
Spring MVC runs each HTTP request on one thread from start to finish. This chapter follows a request through that model and shows where the thread waits. It also shows how the size of the thread pool caps your throughput. The rest of the tutorial builds on this, because virtual threads change this model.
Prerequisites
This chapter assumes you can do the following:
- Read and write Java 21 code, including
ExecutorServiceand thejava.util.concurrentpackage. - Run a Spring Boot 3.2 or later MVC application on embedded Tomcat or Jetty.
- Recognize blocking I/O, such as a JDBC query or a call through a synchronous HTTP client.
- Edit
application.propertiesorapplication.yml.
The examples use Tomcat, which is the default server in spring-boot-starter-web. Jetty works the same way, with different property names.
The thread-per-request model
Spring MVC is built on the Servlet API, which is synchronous. A servlet container such as Tomcat assigns one worker thread to a request. That thread reads the request, runs your code, writes the response, and then returns to the pool. While your code runs, no other request can use that thread.
This is the thread-per-request model. Its main benefit is that the code is easy to write and debug:
- Your code runs top to bottom, so a stack trace shows the whole call path.
- A call such as
repository.findById(id)returns a value and does not need a callback. - Transactions, security context, and logging context are tied to the current thread.
The path of a request
On an embedded Tomcat with the default NIO connector, several kinds of threads take part:
- Acceptor thread. Accepts new TCP connections.
- Poller thread. Watches open connections and detects when a request has arrived. One poller can watch many idle connections.
- Worker threads. Named like
http-nio-8080-exec-1. They run the servlet filters,DispatcherServlet, and your controller.
Idle connections cost almost nothing. Only a request that is being processed holds a worker thread.
Inside the worker, DispatcherServlet does the following:
- It asks the
HandlerMappingbeans which controller method matches the URL and HTTP method. - It runs the handler interceptors'
preHandlemethods. - It calls the method through a
HandlerAdapter, which resolves arguments such as@PathVariableand@RequestBody. - It converts the return value into a response body with an
HttpMessageConverter. - It runs the remaining interceptors and returns control to Tomcat.
All five steps run on the same thread.
Where the thread waits
A typical request spends little time computing. Most of the elapsed time is spent waiting:
- A JDBC query waits for the database to answer.
- A
RestClientorRestTemplatecall waits for another service. - A file or socket read waits for the operating system.
During a wait, the worker thread uses no CPU, but it is still taken from the pool. This is what "blocking" means: the thread cannot do other work until the call returns.
You can see the effect with a small application. The /slow endpoint simulates a 2-second downstream call and reports which thread served it.
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@GetMapping("/slow")
String slow() throws InterruptedException {
Thread.sleep(2000); // stands in for a slow JDBC or HTTP call
return "done on " + Thread.currentThread().getName() + "\n";
}
}Shrink the worker pool so the effect is easy to see:
server.tomcat.threads.max=4
server.tomcat.threads.min-spare=4Start the application and send eight requests at once:
for i in $(seq 1 8); do
curl -s -o /dev/null -w "%{time_total}s\n" http://localhost:8080/slow &
done
waitFour requests finish after about 2 seconds. The other four finish after about 4 seconds, because they waited in line for a free worker. No CPU was busy during that time. The limit comes only from the pool size.
The limits that apply
Three limits shape what happens as load grows. The defaults below apply to Boot 3.2 with Tomcat.
| Property | Default | Meaning |
|---|---|---|
| `server.tomcat.threads.max` | 200 | Maximum number of worker threads |
| `server.tomcat.max-connections` | 8192 | Connections Tomcat accepts and keeps open (NIO) |
| `server.tomcat.accept-count` | 100 | Queue length for new connections once `max-connections` is reached |
A request moves through these in order. Tomcat accepts the connection while it is under max-connections. The request then waits for one of the 200 workers. When the pool is busy, requests wait inside Tomcat, and their latency grows even though your controller code has not slowed down. Beyond max-connections plus accept-count, new connections are refused or time out at the client.
Jetty uses server.jetty.threads.max, which also defaults to 200.
A capacity formula
You can estimate the maximum throughput of a blocking application with Little's Law. It relates the number of requests in progress, the arrival rate, and the time each request takes:
throughput (requests/second) = concurrent requests / latency (seconds)For a thread-per-request server, the number of concurrent requests cannot exceed the pool size. The following table uses 200 threads:
| Average latency | Maximum throughput with 200 threads |
|---|---|
| 50 ms | 4000 requests/second |
| 200 ms | 1000 requests/second |
| 2 s | 100 requests/second |
When a downstream service slows from 200 ms to 2 s, your capacity drops by a factor of ten. The CPU stays nearly idle while this happens. Operators often see low CPU, a full thread pool, and rising latency together. That combination points to blocked threads rather than a compute limit.
Why not just raise the limit?
Setting server.tomcat.threads.max=5000 looks like the obvious fix. It has costs:
- Every platform thread is an operating system thread. It reserves stack memory, 1 MB by default on 64-bit Linux, though only the used part is committed.
- The operating system scheduler switches between thousands of threads, which adds overhead.
- More threads can produce more simultaneous calls to the database or another service. A database with a pool of 20 connections gains nothing from 5000 waiting threads. The threads just wait for a connection instead.
The next chapter looks at these costs in detail. For now, remember that the pool size is a deliberate limit, and that it protects the rest of the system as well as the server.
Common mistakes
- Treating the 200 default as a concurrency guarantee. Other code can use up the workers, such as slow endpoints, health checks, or a single misbehaving downstream call. One slow endpoint can starve all the others because they share the same pool.
- Diagnosing slowness from CPU graphs. A thread pool saturated by blocking calls shows low CPU. Check busy worker threads with the
tomcat.threads.busymetric from Micrometer, or take a thread dump. - Assuming the controller's thread is private. Filters, interceptors, and
@Transactionalmethods all run on the worker. A slow filter holds the thread just as a slow controller does. - Blocking inside
@Asyncor scheduled code without sizing its pool. These run on separate executors with their own limits, which have different defaults from the web server's.
Exercise
A Spring MVC application on Tomcat uses the default settings. Each request calls a payment service that takes 500 ms on average, and the application does almost no other work. Roughly what is the maximum sustained throughput, and what would you expect to see in CPU usage and Tomcat metrics when the application hits that limit?
Show answer
With 200 worker threads and a 0.5 s latency, throughput is about 200 / 0.5 = 400 requests/second. At that limit CPU stays low because the threads are waiting on the payment service. The tomcat.threads.busy metric sits near 200, and extra requests queue inside Tomcat, so latency rises.