Embedded Web Servers in Spring Boot: Tomcat, Jetty, Undertow
Configure embedded servers in Spring Boot: compare Tomcat, Jetty, and Undertow, tune thread pools, enable access logs, and switch implementations.
Spring Boot 3.2.3 manages the server versions used in these examples. Compare Tomcat, Jetty, and Undertow, configure their shared properties, and test graceful shutdown through your load balancer and orchestrator. Use the resolved dependency tree and workload measurements to check compatibility and capacity.
Embedded web servers in Spring Boot
The examples target the Spring Boot 3.2.x release train and use Spring Boot 3.2.3. Recheck the managed versions when moving to another release.
Introduction
Spring Boot can use Tomcat, Jetty, or Undertow for servlet applications. The Boot BOM manages compatible server dependencies; check the resolved versions before overriding them.
Switching the embedded server
Excluding the default
spring-boot-starter-web pulls in Tomcat by default. To swap it out, exclude Tomcat and add your preferred server’s starter.
Maven:
<dependencies>
<!-- Exclude Tomcat -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Use Jetty instead -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
</dependencies>
The same pattern works for Undertow, just swap the artifact ID to spring-boot-starter-undertow.
Dependency fallback
When using the Spring Boot 3.2.3 BOM, let it manage server dependencies unless you have a tested reason to override them. It manages Tomcat 10.1.19, Jetty 12.0.6, and Undertow 2.3.12.Final; see the version-matched dependency list. Check resolved versions with mvn dependency:tree or Gradle’s dependency report before deployment.
Spring Boot 3.2.3 supports Jetty 12 and its BOM manages Jetty 12.0.6, as shown in the dependency list above and servlet-container guidance. The compatibility example applies to a different, older Boot train whose BOM manages Jetty 11; forcing Jetty 12 into that train can combine versions the release did not test. For any override, verify the supported combination for the exact Boot release and run application-level regression tests.
Server configuration properties
All three servers share common configuration properties under the server prefix. Spring Boot normalizes these across implementations.
Common properties
server:
port: 8080
servlet:
context-path: /api
shutdown: graceful # graceful shutdown, not immediate
compression:
enabled: true
mime-types: text/html,text/xml,text/plain,text/css,application/javascript
min-response-size: 1024
# Connection timeout (all servers)
server:
connection-timeout: 20000 # ms, Tomcat/Undertow; Jetty uses idle-timeout
# Graceful shutdown
server:
shutdown: graceful
spring:
lifecycle:
timeout-per-shutdown-phase: 30s
In Spring Boot 3.2.3, graceful shutdown is supported by the embedded Jetty, Tomcat, and Undertow servers. Spring stops accepting new work according to the server implementation and waits for in-flight requests during the configured lifecycle timeout. The behavior depends on the server, application shutdown sequence, orchestrator, and termination timeout. Read the Spring Boot 3.2.3 graceful shutdown guidance.
To verify a rolling deployment, send a request that lasts longer than a typical request through the load balancer, mark one instance unready, and then send it SIGTERM. Confirm that new requests move to healthy instances and the in-flight request completes within the configured timeout. Repeat with the orchestrator’s termination grace period and load-balancer drain timeout in place; test an overlong request too, so the forced-stop boundary is known.
Tomcat-specific tuning
server:
tomcat:
threads:
max: 200
min-spare: 10
max-connections: 10000
accept-count: 100 # backlog queue size when all threads busy
connection-timeout: 20000 # ms to wait for request line + headers
idle-timeout: 60000 # ms for keep-alive connections
max-http-form-post-size: 2MB
accesslog:
enabled: true
directory: /var/log/tomcat
prefix: access_log
pattern: '%h %l %u %t "%r" %s %b %Dms'
Jetty-specific tuning
server:
jetty:
threads:
max: 200
min: 10
idle-timeout: 60000 # ms before an idle thread is shrunk
max-connections: 10000 # maximum queued connections
acceptors: -1 # -1 = auto-detect based on OS
selectors: -1
connection-idle-timeout: 30000 # ms before closing idle connections
Undertow-specific tuning
server:
undertow:
threads:
io: 4 # I/O threads (one per CPU core is typical)
worker: 200 # worker threads for request handling
max-connections: 10000
buffer-size: 16384 # bytes, must be power of 2
buffers-per-region: 20
direct-buffers: true # use off-heap memory for buffers
accesslog:
enabled: true
directory: /var/log/undertow
pattern: '%h %l %u %t "%r" %s %b "%{i,Referer}"'
Thread pool architecture
Each server handles threads differently, and understanding the difference shapes how you tune them.
graph LR
A[Incoming Request] --> B[Acceptor Thread<br/>Tomcat: Acceptor<br/>Jetty: Acceptor<br/>Undertow: XNIO Listener]
B --> C[Thread Pool<br/>Worker Threads]
C --> D[Application Code<br/>Servlet / Filter]
D --> E[Response]
F[I/O Threads<br/>Undertow only] --> C
style B stroke:#00fff9,color:#000
style C stroke:#ff00ff,color:#fff
Tomcat uses a pure thread-per-connection model historically but switched to NIO by default. It has a fixed thread pool for request handling and a separate acceptor pool for incoming connections.
Jetty uses a more flexible model with a thread pool for computation and a set of acceptors/selectors for I/O. Its QueuedThreadPool is the default and behaves well under load: tasks queue rather than reject when the pool is saturated.
Undertow splits threads into I/O threads and worker threads. I/O threads handle the NIO event loop and should match your CPU core count. Worker threads execute the actual request handling and should match your expected concurrency. Separating these means I/O operations never block request processing threads.
Choosing thread pool sizes
A common starting point:
| Server | I/O Threads | Worker Threads |
|---|---|---|
| Tomcat | N/A (handled internally) | 200 max |
| Jetty | N/A | 200 max |
| Undertow | CPU cores | 200 max |
These are not constants. If your application does blocking work (database calls, external HTTP), you need more worker threads. If it is purely non-blocking (reactive stack), fewer workers suffice.
Monitor actual thread usage with JMX or Micrometer. If activeCount consistently approaches maxThreads, you are saturating the pool.
Access logging
Access logs are essential for debugging, auditing, and traffic analysis. All three servers support them.
Tomcat
server:
tomcat:
accesslog:
enabled: true
directory: /var/log/myapp
prefix: access
suffix: .log
pattern: '%h %l %u %t "%r" %s %b %Dms "%{i,Referer}" "%{i,User-Agent}"'
file-date-format: .yyyy-MM-dd
rotate: true
Jetty
Jetty logs via Logback or Log4j2 by configuring the NCSARequestLog. Configuration is more involved than Tomcat:
import org.eclipse.jetty.server.NCSARequestLog;
import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
@Component
public class JettyAccessLogCustomizer implements WebServerFactoryCustomizer<JettyServletWebServerFactory> {
@Override
public void customize(JettyServletWebServerFactory factory) {
NCSARequestLog requestLog = new NCSARequestLog("/var/log/jetty/access.log");
requestLog.setAppend(true);
requestLog.setExtended(false);
requestLog.setLogCookies(false);
requestLog.setLogTimeZone("UTC");
factory.setRequestLog(requestLog);
}
}
Undertow
Undertow’s access log is configured via the UndertowServletWebServerFactory:
server:
undertow:
accesslog:
enabled: true
directory: /var/log/undertow
prefix: access
suffix: .log
pattern: '%h %l %u %t "%r" %s %b "%{i,Referer}"'
rotate: true
Undertow’s access log configuration is the most straightforward of the three.
When to use / when not to use
When to use Tomcat
Tomcat is the right choice when you want the most straightforward, well-documented servlet container experience. It is the Spring Boot default for a reason: the community has accumulated years of operational knowledge around it, tuning guides are plentiful, and most CI/CD pipelines have first-class Tomcat support. Use Tomcat for standard microservices where there is nothing unusual about the workload.
When not to use Tomcat
Tomcat is a thread-per-connection model under the hood (even with NIO, worker threads are tied to connections for servlet execution). If you are building a massively concurrent service handling tens of thousands of simultaneous idle connections (long-polling, WebSocket, SSE), Tomcat’s thread model becomes a liability. At that point, Undertow’s separated I/O and worker thread model will serve you better.
When to use Jetty
Jetty earns its place in memory-constrained environments. A Jetty-based Spring Boot JAR starts with a smaller heap footprint than the equivalent Tomcat build, which matters in Kubernetes environments with tight memory limits. Jetty also has a loyal following in the Eclipse community and among teams that have been operating it in production for years.
When not to use Jetty
Jetty’s access logging requires Java code to configure, unlike Tomcat and Undertow which support YAML-based access log configuration. If your ops team expects YAML-driven operational configuration and does not want to maintain a custom WebServerFactoryCustomizer, Jetty becomes an operational burden rather than a simplification.
When to use Undertow
Undertow shines for high-concurrency workloads where connections are long-lived and mostly idle. Its separated I/O thread pool (one per CPU core for NIO) means it never blocks acceptors waiting on slow clients. If you are building services that hold open connections for WebSocket, Server-Sent Events, or long-poll patterns, Undertow’s I/O model is purpose-built for exactly that.
When not to use Undertow
Undertow’s buffer size must be a power of 2, and misconfiguration causes silent failures at startup. If your team does not want to maintain yet another server-specific configuration constraint, Tomcat avoids this entirely. Undertow also has a smaller community than Tomcat, which means fewer tuning guides and fewer people available to debug unusual behavior.
Trade-off table
| Dimension | Tomcat | Jetty | Undertow |
|---|---|---|---|
| Startup memory | Medium (~60MB heap) | Low (~40MB heap) | Medium (~50MB heap) |
| Thread model | Thread pool (worker) | QueuedThreadPool | Separate I/O + worker threads |
| NIO support | Yes (since 7.x) | Yes | Yes |
| Access log via YAML | Yes | No (requires Java code) | Yes |
| WebSocket/SSE support | Good | Good | Excellent |
| Throughput (raw) | Good | Good | Best historically |
| Operational knowledge | Widely available | Moderate | Less common |
| Graceful shutdown | Yes | Yes | Yes |
| Max connections | max-connections |
max-connections |
max-connections |
Failure scenarios
Application starts but immediately returns 503
- Cause: All threads in the pool are busy and the backlog queue (
accept-countin Tomcat) is full. - Fix: Increase
server.tomcat.threads.max, increaseserver.tomcat.max-connections, or scale horizontally.
OutOfMemoryError: unable to create new native thread
- Cause: Thread pool size exceeds what the OS allows per process. Common on containers with low ulimits.
- Fix: Reduce max threads, reduce container memory limits, or increase the OS thread limit (
ulimit -u).
Access logs not writing
- Cause: Log directory does not exist or is not writable by the process.
- Fix: Create the directory and set permissions, or change the log path to a writable location.
Jetty access log requires custom code
- Cause: Unlike Tomcat and Undertow, Jetty does not support access log configuration via
application.ymlalone. - Fix: Implement
WebServerFactoryCustomizer<JettyServletWebServerFactory>to configure theNCSARequestLogprogrammatically.
Undertow buffer size error at startup
- Cause:
buffer-sizemust be a power of 2 (e.g., 16384, not 15000). - Fix: Use a valid power-of-2 value for
server.undertow.buffer-size.
Security notes
-
Disable server header: By default, servers expose their identity in responses (
Server: Apache-Coyote/1.1). Hide this in production:server: tomcat: remoteip: protocol-header: X-Forwarded-Proto # plus add server.use-forward-headers=trueFor all servers, set
server.include-native-tomcat-jni=disabledif you do not need JNI features. -
Limit request size: Prevent denial-of-service via large payloads:
server: tomcat: max-http-form-post-size: 2MB # or equivalent for Jetty/Undertow -
Connection timeouts: Set
connection-timeoutto prevent slow-client attacks tying up threads.
Common pitfalls / anti-patterns
- Setting max threads too high: More threads means more context switching. The sweet spot is workload-dependent: start conservative and increase while monitoring.
- Ignoring the backlog queue:
accept-count(Tomcat) controls how many connections queue when all threads are busy. If your load balancer times out before connections reach your app, increase this. - Jetty access log complexity: Teams expect YAML configuration and are surprised when Jetty requires Java code for access logging.
- Undertow buffer size not power of 2: A common startup error: always verify buffer sizes are
1024,2048,4096,8192,16384, etc. - Forgetting graceful shutdown: Without graceful shutdown, in-flight requests may be cut off when the server or orchestrator stops the process. The outcome depends on server configuration and how long the orchestrator waits before forcing termination.
Observability checklist
- Verify thread pool actual utilization with JMX/Micrometer (not just configured size)
- Enable access logs in production for all environments
- Confirm
server.shutdown=gracefuland set a reasonable shutdown timeout - Check
accept-count/ backlog queue size matches your load balancer’s retry behavior - Set
server.include-native-tomcat-jni=disabledif JNI is not needed - Validate
max-http-form-post-sizeis set to prevent large-payload DoS - Confirm log directories exist and are writable before deployment
- Test graceful shutdown behavior with a load test before going to production
Quick recap checklist
- Switch servers by excluding
spring-boot-starter-tomcatand addingspring-boot-starter-jettyorspring-boot-starter-undertow - Tomcat threads are configured via
server.tomcat.threads.max - Jetty uses
QueuedThreadPoolwhich queues tasks when saturated - Undertow splits I/O threads (CPU-bound) from worker threads (blocking work)
- Access logging is YAML-configurable for Tomcat and Undertow, requires Java code for Jetty
-
accept-count(Tomcat) controls the connection backlog queue size -
buffer-sizein Undertow must always be a power of 2 - Set
server.shutdown=gracefuland aspring.lifecycle.timeout-per-shutdown-phasevalue - Monitor actual thread pool utilization via JMX, not just configured values
Interview questions
You exclude the default server starter and add the one you want. In Maven, add an <exclusions> block under spring-boot-starter-web to remove spring-boot-starter-tomcat, then add either spring-boot-starter-jetty or spring-boot-starter-undertow as a separate dependency. Spring Boot's dependency management ensures compatible versions. No code changes are required: the framework auto-configures whichever server is on the classpath.
Undertow's I/O threads run the NIO event loop and handle non-blocking events. Worker threads execute servlet code, filters, and application logic, including blocking JDBC or HTTP calls. A slow database query can occupy a worker without blocking the event loop from accepting other connections. The typical configuration uses one I/O thread per CPU core and more worker threads for blocking work.
When all worker threads are busy, new connections queue in the backlog. In Tomcat this is controlled by accept-count, in Jetty by max-connections, and in Undertow by similar settings. If the queue fills before a thread becomes available, the server refuses new connections. A load balancer may return a 503 if it times out while the queue is full. Size the backlog with the load balancer's timeout and retry behavior in mind.
For Spring Boot 3.2.3, set server.shutdown=graceful and configure spring.lifecycle.timeout-per-shutdown-phase. During context shutdown, the embedded server stops accepting new work according to its implementation and allows in-flight requests to finish until the timeout. The orchestrator and load balancer must allow enough time for that sequence. Without the setting, a process stop can interrupt requests; with it, requests that exceed the timeout can still be terminated.
Undertow separates I/O threads from worker threads in servlet applications, which can help when many connections spend time waiting on I/O. For a WebFlux application, Spring Boot 3.2.3 uses Reactor Netty by default; choose another supported server only after checking the workload and configuration you need.
Unlike Tomcat's thread pool which can reject tasks when full, Jetty's QueuedThreadPool queues tasks when all threads are busy. This means a Jetty-based application will continue accepting connections up to the backlog limit rather than immediately rejecting them with a 503. The queue has a maximum size; once full, new connections are refused. This behavior is more graceful under sudden traffic spikes but requires careful monitoring: queued tasks consume memory and can lead to OOM if the queue grows unbounded.
Jetty has the smallest startup footprint at approximately 40MB heap, making it ideal for Kubernetes environments with tight memory limits. Tomcat sits at approximately 60MB heap by default. Undertow is in the middle at approximately 50MB heap. These numbers vary based on configured thread pool sizes, enabled features, and the application itself. In containerized environments where you pay for memory, Jetty's lower baseline can directly translate to cost savings through smaller resource requests.
Undertow uses direct memory buffers (off-heap) for I/O operations, and the underlying buffer pool implementation requires buffer sizes to be powers of 2 for efficient memory alignment and allocation. If you set a non-power-of-2 value like 15000 bytes, Undertow throws an exception at startup and refuses to start. Valid values are 512, 1024, 2048, 4096, 8192, 16384, or larger powers of 2. This is a common misconfiguration that teams encounter when porting settings from other servers that do not have this constraint.
Tomcat and Undertow expose access-log settings through Spring Boot properties. For Jetty, customize JettyServletWebServerFactory with a WebServerFactoryCustomizer. That Java configuration takes more code than YAML, but gives direct access to Jetty-specific settings.
max-threads defines how many worker threads handle requests simultaneously. max-connections controls how many connections the server accepts at the protocol level (NIO selector). accept-count is the OS-level backlog queue for connections that arrive when all worker threads are busy. The relationship: connections up to max-connections are accepted and distributed to worker threads. Once max-connections is reached, new connections queue in the accept-count backlog. If that fills, new connections are refused. A common mistake is setting accept-count lower than the load balancer's retry timeout, causing 503s during traffic spikes.
Spring Boot's WebServerFactoryCustomizer mechanism configures the server using properties under server.* and server-specific prefixes such as server.tomcat.*, server.jetty.*, and server.undertow.*. You can define a WebServerFactoryCustomizer<T> bean for settings that the properties do not expose. Spring Boot applies the customizer before creating the server.
Thread-per-request models keep a thread for the duration of a request, including time spent waiting on database or HTTP calls. At scale, this can exhaust the worker pool. NIO event loops use a small number of threads to handle many connections and dispatch work when I/O is ready. Tomcat uses NIO but still allocates worker threads for servlet execution. Undertow separates I/O threads from worker threads, so blocking work does not starve the event loop.
Use a tool like wrk, hey, or Apache Bench to generate load. Measure requests per second, latency percentiles (p50, p95, p99), and error rates under sustained concurrent load. For a fair comparison, use identical thread pool sizes and JVM settings across servers. Run warm-up iterations before measuring since JIT compilation affects early results. Undertow historically shows best raw throughput for connection-intensive workloads, but the differences are often dwarfed by application-level bottlenecks (database queries, external HTTP calls). Profile with JMC or async-profiler to identify whether the server or the application is the bottleneck.
For Spring Boot 3.2.3, server.shutdown=graceful starts graceful shutdown, while spring.lifecycle.timeout-per-shutdown-phase sets the lifecycle wait period. Jetty, Tomcat, and Undertow differ in how they reject new requests, and the orchestrator may force-stop the process when its own termination period expires. Requests that outlast the configured window can be interrupted. Test this through the real load balancer and orchestrator before relying on it in production.
All three servers support the same Spring Boot SSL properties: server.ssl.enabled=true, server.ssl.key-store, server.ssl.key-store-password, server.ssl.key-alias. Under the hood, Spring Boot configures the SSL context on each server's factory. For client certificates or specific cipher suites, use WebServerFactoryCustomizer to configure the underlying server's SSL API. Tomcat offers additional properties like server.tomcat.remoteip.protocol-header for behind-proxy SSL termination scenarios.
All three servers support WebSocket through the servlet specification (JSR-356) and their own proprietary APIs. Undertow has the most efficient WebSocket implementation for servlet-based applications because its I/O threads never block: long-lived WebSocket connections hold minimal resources. Tomcat's WebSocket support is solid and well-documented. Jetty offers excellent WebSocket support with additional features like the Jetty WebSocket API which provides more control than the servlet standard. For Server-Sent Events (SSE), all three work well since SSE is just HTTP with a long-lived response stream.
In Kubernetes environments, Jetty's lower memory footprint directly reduces the minimum heap requirement and thus the resource request you must declare. Undertow's separate I/O thread model works well when you have varying workloads since I/O threads stay active even if worker threads saturate. In environments with CPU limits, Undertow's I/O thread tuning becomes critical since I/O threads should match core count. For local development, Tomcat's more verbose logging and familiar error messages make debugging easier. For FIPS-compliant environments, Tomcat has better support for JSSE and FIPS-certified crypto modules.
Enable JMX and expose the thread pool metrics via Micrometer to Prometheus or your monitoring system. Key metrics to watch: activeCount (threads doing work), poolSize (current threads), queueSize (queued tasks for Jetty). If activeCount consistently approaches maxThreads while queue grows, you are saturated. In Tomcat, check ThreadPool JMX beans. In Undertow, monitor both I/O and worker thread pools separately: running out of I/O threads blocks new connections entirely. Set alerts when active threads exceed 80% of max for proactive alerting before 503s occur.
For Spring Boot 3.2.3 native-image builds, check the server's reflection metadata and any JNI or SSL libraries required by the application. Server choice affects build configuration and image size, so test the exact combination you plan to deploy.
In Tomcat, max-connections sets the NIO connector limit. New connections beyond that limit may wait in the OS-level accept-count backlog. In Jetty, max-connections is the maximum number of connections queued at the accept layer before refusing new connections. In Undertow, max-connections similarly controls the number of concurrent connections at the XNIO level. The semantics are similar but the internal mechanisms differ. Jetty also has acceptors and selectors count properties that control how many threads handle accepting and selecting on connections respectively.
Further reading
- Spring Boot 3.2.3 Reference Documentation: Embedded Web Servers and graceful shutdown
- Tomcat Architecture Documentation
- Jetty Documentation: Threading Model
- Undertow Documentation: Architecture
- Spring Boot 3.x Migration Guide: Servlet Containers
- Understanding Jetty’s QueuedThreadPool
- Undertow I/O and Worker Thread Configuration
Conclusion
Tomcat, Jetty, and Undertow differ in their configuration and I/O models. Tomcat is the Spring Boot default. Jetty or Undertow may fit a specific memory or servlet-concurrency constraint, but measure the application before choosing on performance grounds.
All three servers expose configuration through Spring Boot’s property prefixes. Switching dependencies often requires little application code, but server-specific behavior still needs regression testing. Tomcat and Jetty use worker pools; Undertow separates I/O threads from worker threads. This distinction matters when measuring capacity or debugging saturation.
Graceful shutdown can reduce interrupted requests during a deployment, but it depends on Spring configuration, the server, the orchestrator’s termination window, and load-balancer draining. Set server.shutdown=graceful, choose a lifecycle timeout from observed request durations, and test the full rolling-shutdown path. Avoid assuming that one timeout value guarantees every in-flight request will finish. Access logging also needs an operational plan; the configuration path differs by server and Boot release.
For a servlet application without a specific constraint, start with Tomcat. Test Jetty if memory use is a concern. For WebFlux, Reactor Netty is Spring Boot’s default; Undertow is an option for servlet workloads where separating I/O and worker threads fits the measured connection pattern.
Category
Related Posts
Spring Boot Build Tools: Maven & Gradle
Configure Maven and Gradle for Spring Boot projects—plugins, dependency management, packaging JARs and WARs, and build automation essentials.
JUnit 5 & Jupiter: Lifecycle, Nested & Parameterized Tests
Learn JUnit Jupiter 5.14.4 lifecycle rules, nested tests, and parameterized inputs, with runnable setup order and practical isolation guidance.
Mockito: Mocking, Stubbing, Verifications, Spy vs Mock
Learn Mockito fundamentals: create mocks and spies, stub behavior with when().thenReturn(), verify interactions, and choose between Spy vs Mock wisely.