How Spring Boot bootstraps its embedded web server

A Spring Boot application starts its own web server from main: it picks the application type, creates the context, builds Tomcat from a factory bean and opens the port only when every bean is ready. This page runs that sequence event by event, builds the same server by hand for comparison, and then configures compression, limits, virtual threads and graceful shutdown.

Contents

How Spring Boot starts an embedded web server

A traditional Java web application is packaged as a WAR file and deployed into a server that is already running, such as Tomcat. Spring Boot reverses this: the server is a library inside the application, started from main. The application owns the server, decides its port and settings, and stops it when the application stops. One JAR runs the same way on a laptop, in a container and in production.

When SpringApplication.run starts, it works through these steps:

  1. Deciding the application type: Spring Boot looks at the classpath. With Spring MVC and the Servlet API present it creates a servlet web application; with only Spring WebFlux, a reactive one; with neither, a plain application without a server. spring.main.web-application-type overrides the guess.
  2. Preparing the environment: properties, profiles and logging are set up, before any bean exists.
  3. Creating the context: for a servlet application, an AnnotationConfigServletWebServerApplicationContext, which knows how to create a web server during its refresh.
  4. Creating the server: during the refresh, the context looks up the ServletWebServerFactory bean that auto-configuration provides, by default a TomcatServletWebServerFactory. Customizers apply server.* properties to it, and it builds an embedded Tomcat.
  5. Registering servlets and filters: every ServletContextInitializer bean is applied to the new servlet context. This is how the DispatcherServlet is mapped to / and how filter beans are added.
  6. Opening the port: at the end of the refresh, after all singleton beans have been created, the connector starts listening. Requests cannot arrive while beans are still being built.
Embedded servers in Spring Boot 4
ServerHow to get itNotes
Tomcat 11Included in spring-boot-starter-webmvcThe default; used by every example on this page except the Jetty one
Jetty 12Exclude spring-boot-starter-tomcat, add spring-boot-starter-jettySame server.* properties, plus server.jetty.*
UndertowNo longer availableRemoved in Spring Boot 4.0
Reactor NettyIncluded in spring-boot-starter-webfluxFor reactive applications only

The programs use Spring Boot 4.1 with Spring Framework 7.0 and Tomcat 11, with spring-boot-starter-webmvc only. The Jetty section near the end runs the same kind of application on Jetty 12.1, with Tomcat removed from its classpath.

The startup sequence, event by event

Spring Boot publishes an event at each stage of startup and shutdown, which makes the sequence visible. The listener is added to SpringApplication directly instead of as a bean, because a bean cannot receive events published before the context exists:

Java
package demo.startup;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.WebServer;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.boot.web.server.context.WebServerInitializedEvent;
import org.springframework.boot.availability.AvailabilityChangeEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.context.support.ServletRequestHandledEvent;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class StartupSequence {

    @RestController
    static class Hello {
        @GetMapping("/hello")
        public String hello() {
            return "hello";
        }
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(StartupSequence.class);
        app.setDefaultProperties(Map.of(
                "server.port", "0", "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        // Added here, not as a bean, so that it also sees the events before the context exists
        app.addListeners((ApplicationListener<ApplicationEvent>) event -> {
            String name = event.getClass().getSimpleName();
            String extra = "";
            if (event instanceof WebServerInitializedEvent) {
                extra = " (port is now known)";
            } else if (event instanceof AvailabilityChangeEvent<?> change) {
                extra = " -> " + change.getState();
            } else if (event instanceof ServletRequestHandledEvent) {
                return;   // one per request; left out to keep the output short
            }
            System.out.println("  event " + name + extra);
        });

        System.out.println("SpringApplication.run starts");
        ConfigurableApplicationContext context = app.run(args);
        System.out.println("SpringApplication.run returned");

        WebServer server = ((WebServerApplicationContext) context).getWebServer();
        System.out.println("context class: " + context.getClass().getSimpleName());
        System.out.println("web server   : " + server.getClass().getSimpleName());
        int status = HttpClient.newHttpClient().send(HttpRequest.newBuilder(
                URI.create("http://localhost:" + server.getPort() + "/hello")).build(),
                BodyHandlers.ofString()).statusCode();
        System.out.println("GET /hello -> " + status);

        System.out.println("closing the context");
        context.close();
        System.out.println("closed");
    }
}
Output
SpringApplication.run starts
  event ApplicationStartingEvent
  event ApplicationEnvironmentPreparedEvent
  event ApplicationContextInitializedEvent
  event ApplicationPreparedEvent
  event ServletWebServerInitializedEvent (port is now known)
  event ContextRefreshedEvent
  event ApplicationStartedEvent
  event AvailabilityChangeEvent -> CORRECT
  event ApplicationReadyEvent
  event AvailabilityChangeEvent -> ACCEPTING_TRAFFIC
SpringApplication.run returned
context class: AnnotationConfigServletWebServerApplicationContext
web server   : TomcatWebServer
GET /hello -> 200
closing the context
  event AvailabilityChangeEvent -> REFUSING_TRAFFIC
  event ContextClosedEvent
closed
  • ApplicationStartingEvent and ApplicationEnvironmentPreparedEvent came before any bean or context existed. Code that must run this early, such as a custom logging setup, has to be registered this way or in META-INF/spring.factories.
  • ApplicationContextInitializedEvent and ApplicationPreparedEvent mark the context created and its bean definitions loaded, still without a server.
  • ServletWebServerInitializedEvent arrived once Tomcat was listening, and is the first point where the real port of server.port=0 is known. Tests and service registries read the port from this event.
  • ApplicationStartedEvent came after the refresh, and ApplicationReadyEvent after the CommandLineRunner and ApplicationRunner beans had run, of which this program has none.
  • The two AvailabilityChangeEvents set the liveness state to CORRECT and then the readiness state to ACCEPTING_TRAFFIC. On close, readiness changed to REFUSING_TRAFFIC before the context closed. Kubernetes probes in Spring Boot Actuator report these states.
  • The context class was AnnotationConfigServletWebServerApplicationContext and the server a TomcatWebServer, as the type detection predicted.

The listener also receives a ServletRequestHandledEvent after every request, which the program leaves out. For work that should run once the application is ready, such as warming a cache, listen for ApplicationReadyEvent: by then the server is accepting requests and every bean is initialised.

What Spring Boot automates: a server built by hand

To see what the auto-configuration saves, this program builds the same kind of application without Spring Boot. It uses only Spring Framework and the embedded Tomcat library, both of which come with the webmvc starter:

Java
package demo.manual;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import java.io.File;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.file.Files;
import java.util.logging.LogManager;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

// The same kind of application as with Spring Boot, assembled by hand
public class ManualTomcat {

    @RestController
    static class Hello {
        @GetMapping("/hello")
        public String hello() {
            return "hello from a hand-built server";
        }
    }

    @Configuration
    @EnableWebMvc                // registers the MVC infrastructure beans
    @Import(Hello.class)
    static class WebConfig {}

    public static void main(String[] args) throws Exception {
        quietLogging();
        File baseDir = Files.createTempDirectory("tomcat").toFile();

        // 1. The Spring application context for the web layer
        var spring = new AnnotationConfigWebApplicationContext();
        spring.register(WebConfig.class);

        // 2. An embedded Tomcat with one connector on a free port
        Tomcat tomcat = new Tomcat();
        tomcat.setBaseDir(baseDir.getAbsolutePath());
        tomcat.setPort(0);
        tomcat.getConnector();                       // creates the default HTTP connector

        // 3. A servlet context with the DispatcherServlet mapped to "/"
        Context context = tomcat.addContext("", baseDir.getAbsolutePath());
        Tomcat.addServlet(context, "dispatcher", new DispatcherServlet(spring))
              .setLoadOnStartup(1);                  // refreshes the Spring context
        context.addServletMapping("/", "dispatcher");

        // 4. Start, call it, stop
        tomcat.start();
        int port = tomcat.getConnector().getLocalPort();
        System.out.println("Tomcat started, Spring context active: " + spring.isActive());
        System.out.println("beans in the context: " + spring.getBeanDefinitionCount());

        HttpResponse<String> r = HttpClient.newHttpClient().send(HttpRequest.newBuilder(
                URI.create("http://localhost:" + port + "/hello")).build(),
                BodyHandlers.ofString());
        System.out.println("GET /hello -> " + r.statusCode() + " " + r.body());

        stop(tomcat);
        FileSystemUtils.deleteRecursively(baseDir);
        System.out.println("stopped, Spring context active: " + spring.isActive());
    }

    // Spring Boot configures logging for you; here Tomcat (java.util.logging) and
    // Spring (through SLF4J and Logback) would otherwise log every step
    static void quietLogging() {
        LogManager.getLogManager().reset();
        var logback = (LoggerContext) LoggerFactory.getILoggerFactory();
        logback.getLogger("ROOT").setLevel(Level.WARN);
    }

    static void stop(Tomcat tomcat) throws LifecycleException {
        tomcat.stop();
        tomcat.destroy();
    }
}
Output
Tomcat started, Spring context active: true
beans in the context: 33
GET /hello -> 200 hello from a hand-built server
stopped, Spring context active: false
  • The program had to create the Spring context, the Tomcat instance, a base directory for Tomcat's work files, a connector, a servlet context and the DispatcherServlet, and map the servlet to /. Spring Boot performs each of these steps in its server factory.
  • @EnableWebMvc registered Spring MVC's infrastructure: the context held 33 bean definitions, counting the configuration class, the controller and Spring's internal processors. In a Spring Boot application, WebMvcAutoConfiguration provides the same beans with different defaults, such as the Jackson converter settings and static resource handling.
  • The Spring context was refreshed by the DispatcherServlet when Tomcat started it, because of setLoadOnStartup(1). In Spring Boot the order is reversed: the context starts first and creates the server.
  • Logging had to be quietened by hand. Tomcat logs through java.util.logging and Spring through SLF4J; Spring Boot routes both into one logging system and applies logging.level.*.

What the program lacks shows the rest of Spring Boot's work: no server.* properties, no error page at /error, no character encoding filter, no graceful shutdown, and no customizers. Building a server by hand is still useful in libraries and tests that must not depend on Spring Boot.

Configuring the server with properties and customizers

Most server settings are a property away, and the rest are reachable from code through a customizer. The program enables response compression, lowers the header size limit and sets Tomcat's Server header, which has no property of its own:

Java
package demo.settings;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.tomcat.servlet.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class ServerSettings {

    // Code-level access to Tomcat, for settings that have no property
    @Bean
    WebServerFactoryCustomizer<TomcatServletWebServerFactory> tomcatCustomizer() {
        return factory -> factory.addConnectorCustomizers(
                connector -> connector.setProperty("server", "shop-api"));
    }

    @RestController
    static class Endpoints {
        @GetMapping("/small")
        public String small() {
            return "a short answer";
        }

        @GetMapping("/report")
        public String report() {
            return "line of a long report\n".repeat(500);   // 11,000 characters
        }
    }

    static void get(HttpClient http, String url, String... headers) throws Exception {
        HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(url));
        if (headers.length > 0) {
            request.headers(headers);
        }
        HttpResponse<byte[]> r = http.send(request.build(), BodyHandlers.ofByteArray());
        System.out.println("GET " + url.substring(url.indexOf('/', 8))
                + (headers.length > 0 ? "  (" + headers[0] + ": "
                   + (headers[1].length() > 20 ? headers[1].length() + " chars" : headers[1])
                   + ")" : ""));
        System.out.println("  -> " + r.statusCode() + ", " + r.body().length + " bytes"
                + ", Content-Encoding: " + r.headers().firstValue("Content-Encoding").orElse("-")
                + ", Server: " + r.headers().firstValue("Server").orElse("-"));
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(ServerSettings.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN",
                            "server.compression.enabled=true",
                            "server.max-http-request-header-size=4KB")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            String base = "http://localhost:" + port;
            HttpClient http = HttpClient.newHttpClient();

            get(http, base + "/report");
            get(http, base + "/report", "Accept-Encoding", "gzip");
            get(http, base + "/small", "Accept-Encoding", "gzip");
            get(http, base + "/small", "X-Large-Header", "x".repeat(5000));
        }
    }
}
Output
GET /report
  -> 200, 11000 bytes, Content-Encoding: -, Server: shop-api
GET /report  (Accept-Encoding: gzip)
  -> 200, 86 bytes, Content-Encoding: gzip, Server: shop-api
GET /small  (Accept-Encoding: gzip)
  -> 200, 14 bytes, Content-Encoding: -, Server: shop-api
GET /small  (X-Large-Header: 5000 chars)
  -> 400, 435 bytes, Content-Encoding: -, Server: shop-api
  • Without Accept-Encoding, the 11,000-byte report was sent as it is. With Accept-Encoding: gzip, it arrived as 86 bytes with Content-Encoding: gzip. The report repeats one line 500 times, which compresses far better than typical data.
  • The 14-byte answer was not compressed even though the client accepted gzip, because it is below server.compression.min-response-size, 2KB by default. Compressing tiny responses costs more than it saves.
  • A request with a 5,000-character header broke server.max-http-request-header-size=4KB, and Tomcat rejected it with 400 before Spring saw it. The default is 8KB; large cookies or tokens are the usual reason to raise it.
  • Every response carried Server: shop-api, set by the WebServerFactoryCustomizer. Your customizers run after Spring Boot's own by default, so code wins over properties when both set the same thing.
Frequently used server properties and their defaults in Spring Boot 4.1
PropertyDefaultEffect
server.port8080Port to listen on; 0 picks a free one
server.addressAll interfacesNetwork address to bind to
server.servlet.context-pathNonePrefix for every URL, such as /shop
server.compression.enabledfalseGzip for text, JSON and XML responses
server.http2.enabledfalseHTTP/2, which also needs TLS for browsers
server.max-http-request-header-size8KBLargest request header block
server.tomcat.threads.max200Worker threads; ignored with virtual threads
server.tomcat.max-connections8192Open connections Tomcat will hold
server.tomcat.accept-count100Queue for connections beyond that
server.shutdowngracefulWhether in-flight requests may finish on shutdown

Virtual threads

Tomcat normally serves each request on a thread from a pool of platform threads, 200 by default. With Java 21's virtual threads, each request can get its own cheap thread instead, so requests that wait for a database or a remote service no longer use up the pool. The program asks the handler thread what it is, with the setting off and on:

Java
package demo.threads;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse.BodyHandlers;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class VirtualThreads {

    @RestController
    static class WhoAmI {
        @GetMapping("/thread")
        public String thread() {
            Thread t = Thread.currentThread();
            String name = t.getName().replaceAll("\\d+", "N");   // numbers vary per run
            return "virtual=" + t.isVirtual() + ", name pattern=" + name;
        }
    }

    static void run(boolean virtual) throws Exception {
        try (var context = new SpringApplicationBuilder(VirtualThreads.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN",
                            "spring.threads.virtual.enabled=" + virtual)
                .run()) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            String body = HttpClient.newHttpClient().send(HttpRequest.newBuilder(
                    URI.create("http://localhost:" + port + "/thread")).build(),
                    BodyHandlers.ofString()).body();
            System.out.println("spring.threads.virtual.enabled=" + virtual + " -> " + body);
        }
    }

    public static void main(String[] args) throws Exception {
        run(false);
        run(true);
    }
}
Output
spring.threads.virtual.enabled=false -> virtual=false, name pattern=http-nio-auto-N-exec-N
spring.threads.virtual.enabled=true -> virtual=true, name pattern=tomcat-handler-N
  • With the setting off, the request ran on a platform thread from Tomcat's pool, named http-nio-auto-N-exec-N. The auto part comes from the random port.
  • With spring.threads.virtual.enabled=true, the request ran on a virtual thread named tomcat-handler-N. The controller code did not change.

The same property also switches Spring's task executors and schedulers to virtual threads, and server.tomcat.threads.max then has no effect. Virtual threads help when requests spend most of their time waiting. They do not make CPU-heavy work faster, and a connection pool that is too small still limits throughput, because each virtual thread still waits for a connection. The property requires Java 21 or later.

Graceful shutdown

When an application is stopped for a deployment, requests in progress should finish instead of failing halfway. The program starts a request that takes 1.5 seconds, closes the context while it runs, and tries a new request during the shutdown, once with each shutdown mode:

Java
package demo.shutdown;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class GracefulShutdown {

    static CountDownLatch requestStarted;

    @RestController
    static class SlowController {
        @GetMapping("/slow")
        public String slow() throws InterruptedException {
            requestStarted.countDown();
            Thread.sleep(1500);                 // an order that takes a while to save
            return "order saved";
        }
    }

    static String describe(CompletableFuture<HttpResponse<String>> call) {
        try {
            HttpResponse<String> r = call.join();
            return r.statusCode() + " " + r.body();
        } catch (RuntimeException e) {
            Throwable cause = e.getCause() == null ? e : e.getCause();
            return "failed: " + cause.getClass().getSimpleName();
        }
    }

    static void run(String mode) throws Exception {
        System.out.println("=== server.shutdown=" + mode);
        requestStarted = new CountDownLatch(1);
        var context = new SpringApplicationBuilder(GracefulShutdown.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=OFF", "server.shutdown=" + mode)
                .run();
        int port = ((WebServerApplicationContext) context).getWebServer().getPort();
        HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(1)).build();
        HttpRequest slow = HttpRequest.newBuilder(
                URI.create("http://localhost:" + port + "/slow")).build();

        var inFlight = http.sendAsync(slow, BodyHandlers.ofString());
        requestStarted.await();
        System.out.println("request in progress, closing the context");
        var closing = CompletableFuture.runAsync(context::close);

        Thread.sleep(300);                      // the shutdown has begun
        var late = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(1)).build()
                .sendAsync(slow, BodyHandlers.ofString());
        System.out.println("in-flight request: " + describe(inFlight));
        System.out.println("new request      : " + describe(late));
        closing.join();
        System.out.println("context closed");
    }

    public static void main(String[] args) throws Exception {
        run("graceful");
        run("immediate");
    }
}
Output
=== server.shutdown=graceful
request in progress, closing the context
in-flight request: 200 order saved
new request      : failed: ConnectException
context closed
=== server.shutdown=immediate
request in progress, closing the context
in-flight request: failed: IOException
new request      : failed: ConnectException
context closed
  • With graceful, the in-flight request completed with 200 order saved. Tomcat stopped accepting new connections at once, so the new request failed with ConnectException, and the context closed only after the slow request had finished.
  • With immediate, Tomcat closed the connection under the running request, and the client got an IOException instead of a response. In a real application, the order might have been saved without the client ever hearing about it.

Graceful shutdown has been the default since Spring Boot 3.4. It waits at most spring.lifecycle.timeout-per-shutdown-phase, 30 seconds by default, and then stops the server anyway. In Kubernetes, the readiness state changing to REFUSING_TRAFFIC, seen in the first example, lets the load balancer stop sending traffic while the last requests finish. Keep the pod's termination grace period longer than the shutdown timeout, or the container is killed before the wait ends.

Switching to Jetty

Spring Boot picks the server from the classpath. To use Jetty, exclude Tomcat from the web starter and add the Jetty starter:

XML
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webmvc</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

The exclusion matters. When this page's programs were first run with both servers on the classpath, every one of them started Jetty: the startup program reported JettyServletWebServer, and the virtual thread program printed Jetty's thread names. This program ran with the classpath above. It repeats the requests of the server settings program, with the same properties apart from one Jetty-only setting, and reads the Jetty objects behind Spring Boot's WebServer:

Java
package demo.jetty;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.jetty.JettyWebServer;
import org.springframework.boot.web.server.WebServer;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class JettyServer {

    @RestController
    static class Endpoints {
        @GetMapping("/small")
        public String small() {
            return "a short answer from " + Thread.currentThread().getName()
                    .replaceAll("\\d+", "N");
        }

        @GetMapping("/report")
        public String report() {
            return "line of a long report\n".repeat(500);   // 11,000 characters
        }
    }

    static void get(HttpClient http, String url, String... headers) throws Exception {
        HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(url));
        if (headers.length > 0) {
            request.headers(headers);
        }
        HttpResponse<byte[]> r = http.send(request.build(), BodyHandlers.ofByteArray());
        System.out.println("GET " + url.substring(url.indexOf('/', 8))
                + (headers.length > 0 ? "  (" + headers[0] + ": "
                   + (headers[1].length() > 20 ? headers[1].length() + " chars" : headers[1])
                   + ")" : ""));
        String body = r.body().length < 60 ? ", body: " + new String(r.body()) : "";
        System.out.println("  -> " + r.statusCode() + ", " + r.body().length + " bytes"
                + ", Content-Encoding: " + r.headers().firstValue("Content-Encoding").orElse("-")
                + ", Server: " + r.headers().firstValue("Server").orElse("-") + body);
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(JettyServer.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN",
                            "server.compression.enabled=true",
                            "server.max-http-request-header-size=4KB",
                            "server.jetty.threads.max=50")
                .run(args)) {
            WebServer webServer = ((WebServerApplicationContext) context).getWebServer();
            Server jetty = ((JettyWebServer) webServer).getServer();
            QueuedThreadPool pool = (QueuedThreadPool) jetty.getThreadPool();
            System.out.println("WebServer: " + webServer.getClass().getSimpleName()
                    + ", Jetty " + Server.getVersion());
            System.out.println("Thread pool: " + pool.getClass().getSimpleName()
                    + ", min " + pool.getMinThreads() + ", max " + pool.getMaxThreads());

            String base = "http://localhost:" + webServer.getPort();
            HttpClient http = HttpClient.newHttpClient();
            get(http, base + "/report");
            get(http, base + "/report", "Accept-Encoding", "gzip");
            get(http, base + "/small", "Accept-Encoding", "gzip");
            get(http, base + "/small", "X-Large-Header", "x".repeat(5000));
        }
    }
}
Output
WebServer: JettyServletWebServer, Jetty 12.1.14
Thread pool: QueuedThreadPool, min 8, max 50
GET /report
  -> 200, 11000 bytes, Content-Encoding: -, Server: -
GET /report  (Accept-Encoding: gzip)
  -> 200, 86 bytes, Content-Encoding: gzip, Server: -
GET /small  (Accept-Encoding: gzip)
  -> 200, 26 bytes, Content-Encoding: -, Server: -, body: a short answer from qtpN-N
GET /small  (X-Large-Header: 5000 chars)
  -> 431, 392 bytes, Content-Encoding: -, Server: -
  • The web server was JettyServletWebServer, running Jetty 12.1.14. getServer() gives the Jetty Server, the counterpart of reaching Tomcat through a customizer.
  • Jetty uses a QueuedThreadPool. server.jetty.threads.max=50 set its maximum, and the minimum stayed at Spring Boot's default of 8. Requests ran on threads named qtpN-N, not http-nio-...-exec-N.
  • server.compression.enabled worked unchanged: the 11,000-byte report came back as 86 bytes of gzip when the client asked for it, and the short answer was not compressed.
  • The 5,000-character header, over the 4 KB limit from server.max-http-request-header-size, was rejected with 431 Request Header Fields Too Large. Tomcat answered the same request with 400, so clients and tests that check the exact status see a difference.
  • No Server header was sent. The Tomcat customizer that set shop-api applies to TomcatServletWebServerFactory only; on Jetty, the same thing needs a WebServerFactoryCustomizer<JettyServletWebServerFactory>, or the portable server.server-header property.

The common server.* properties, graceful shutdown and spring.threads.virtual.enabled work on both servers; the first run mentioned above showed Jetty's virtual threads named jetty-N. What differs is everything under server.tomcat.* and server.jetty.*, the customizer types, and error details such as the 431 status.

Choosing server settings

Common needs and what to use
NeedUse
Run the server on a free port in testsserver.port=0 and read the port from WebServerApplicationContext
Code that runs once the application can serve requestsA listener for ApplicationReadyEvent
A setting with no propertyA WebServerFactoryCustomizer with a connector or context customizer
Smaller text and JSON responsesserver.compression.enabled=true
Many requests waiting on I/Ospring.threads.virtual.enabled=true on Java 21 or later
Deployments without failed requestsGraceful shutdown, the default, with a suitable timeout
A different serverJetty instead of Tomcat; Undertow is gone in Boot 4
No server at all, such as a batch jobspring.main.web-application-type=none

For what runs inside the server once it is up, see Spring Boot filters and Spring Boot @RestController.