Scrivio Interview library
Spring Boot27 June 202617 min read

How to Scale a Spring Boot App to 1 Million Requests Per Minute

Why Spring Boot's Defaults Are a Throughput Trap#

Spring Boot is a Java framework for building web services, and its out-of-the-box configuration is tuned for developer convenience, not production throughput. This article explains the five configuration layers that determine how far a Spring Boot service can scale, and what to change in each one. As a concrete illustration of what's possible, one team documented scaling from 50,000 to 1.2 million requests per minute, with sub-100ms response times and no proportional increase in infrastructure cost, not by rewriting their application from scratch, but by systematically addressing five configuration layers the framework leaves at developer-friendly defaults1. That result is less surprising once you understand what those defaults actually do under load.

Spring Boot's default configuration is designed to make a new project run in seconds. Tomcat's embedded server starts with a fixed thread pool sized for moderate concurrency. HikariCP, the default JDBC connection pool since Spring Boot 2.x, ships with a maximum pool size of 10 connections2. There is no caching layer, no async offloading, and the deployment model assumes a single instance. Each of these choices is reasonable for local development; each becomes a hard ceiling under real traffic.

The problem with fixing only one layer is that you get a partial win and a false sense of progress. Add more CPU, and your threads will queue at the database pool. Tune the pool, and requests pile up waiting for blocking I/O to finish. Switch to reactive I/O, and a cache miss on every request sends you back to the database anyway. The layers are not independent performance improvements, they are sequential ceilings, and leaving any one at defaults negates the gains you made elsewhere1.

The five sections that follow each take one of these layers and show what to measure, what to change, and what to expect. The table below gives you a reference frame for the whole picture:

LayerDefault bottleneckDiagnostic signalPrimary fix
Reactive I/OBlocking Tomcat threads exhaust under concurrencyThread count pegged; CPU idleMigrate to WebFlux with a non-blocking event loop
Connection poolingHikariCP max-pool-size of 10 starves concurrent requestsHikariPool-1 - Connection is not available timeoutsTune pool size to match thread model and DB capacity
CachingEvery request hits the database or downstream serviceHigh DB query rate; repeated identical queriesAdd local (Caffeine) or distributed (Redis) cache at the right layer
Async processingSynchronous request handling blocks on slow operationsResponse latency tracks downstream latencyOffload to a message queue; return accepted immediately
Horizontal scalingSingle instance; session state prevents distributionOne node at 100% while others sit idleStateless design with load-balanced, auto-scaled instances

These are not interchangeable options where you pick your favourite. They address different parts of the request lifecycle, and a production system handling serious traffic needs all five in reasonable shape. The good news is that none of them require a rewrite, they are mostly configuration, architecture decisions, and the occasional dependency swap.

Diagram as text
flowchart TD
 A["Request"] -->|Reactive I/O| B["WebFlux Layer"]
 B -->|Connection| C["HikariCP Pool"]
 C -->|Query| D["Caching Layer"]
 D -->|Message| E["Async Queue"]
 E -->|Route| F["Load Balancer"]

 style B fill:#ff9999
 style C fill:#ffcc99
 style D fill:#ffff99
 style E fill:#99ff99
 style F fill:#99ccff

Layer 1, Reactive I/O with Spring WebFlux#

The throughput trap described above has a precise mechanical cause. Under Spring MVC with Tomcat, every incoming request claims an OS thread from a bounded pool, Tomcat's default is 200 threads. When those threads are mostly sitting blocked waiting for a database response or a downstream HTTP call, the CPU is largely idle while new requests queue behind the thread limit. Thread pool exhaustion arrives long before CPU saturation, which is why simply adding more CPU rarely moves the needle on a blocking stack.

Spring WebFlux, running on Netty, replaces that model entirely. Instead of one thread per request, Netty maintains a small pool of event-loop threads, typically equal to the number of CPU cores, and multiplexes all I/O across them. No thread blocks waiting for a response, when I/O is in flight, the event-loop thread picks up other work. The result is that thousands of concurrent requests can be in flight simultaneously on a handful of OS threads. WebFlux was introduced in September 2017 and has been a supported option in generated JHipster applications ever since, so it is well past early-adopter risk.

The trade-off is programming style. Reactive APIs built on Project Reactor's Mono and Flux types require a non-blocking mental model throughout the call stack, you cannot call a blocking JDBC driver on an event-loop thread without stalling the entire loop. Teams that have primarily written imperative code often find this friction significant during migration.

Java 21 virtual threads (Project Loom, JEP 444) offer a third path that sidesteps that friction. A virtual thread is a lightweight thread managed by the JVM rather than the OS, so you can write ordinary blocking code and still support tens of thousands of concurrent requests without exhausting a fixed OS thread pool. Benchmark results from a dedicated bare-metal environment comparing Virtual Threads on Tomcat and Netty against WebFlux on Netty show that Virtual Threads on Netty matched or beat WebFlux across most scenarios and metrics, using blocking code rather than reactive Mono/Flux chains.3

The practical choice depends on your team's codebase, Java version, and tolerance for API migration. The table below captures the three models side by side:

ModelThread modelProgramming styleSpring Boot configBest for
Tomcat / Spring MVCOne OS thread per requestFamiliar imperative, blockingDefault; spring-boot-starter-webTeams on Java 17 or earlier; low-to-moderate concurrency
Netty / Spring WebFluxFixed event-loop threads, non-blockingReactive (Mono, Flux)spring-boot-starter-webflux; exclude TomcatI/O-heavy services willing to adopt reactive style
Virtual Threads (Java 21+)JVM-managed virtual threads, blocking OS calls unpinFamiliar imperative, blockingspring.threads.virtual.enabled=true in Spring Boot 3.2+Teams on Java 21+ wanting high concurrency without reactive refactor

For a greenfield service on Java 21 or later, enabling virtual threads is the lowest-friction starting point: one property change, no reactive API migration, and benchmark parity with WebFlux on Netty for most workloads. For a microservice that is almost entirely I/O-bound and already structured around reactive patterns, WebFlux on Netty remains a strong option. What both approaches share is that they remove thread exhaustion as the limiting factor, which means the next ceiling you will hit is almost always the database connection pool.

Diagram as text
sequenceDiagram
 participant Client
 participant MVC as "Spring MVC<br/>(Tomcat)"
 participant DB1 as "Database"
 
 participant WebFlux as "Spring WebFlux<br/>(Netty)"
 participant DB2 as "Database"
 
 rect rgb(200, 220, 255)
 Note over MVC,DB1: Blocking Model, 3 Threads
 Client->>MVC: Request 1
 activate MVC
 MVC->>DB1: Query (blocks Thread 1)
 activate DB1
 Client->>MVC: Request 2
 Note over MVC: Thread 2 blocked
 Client->>MVC: Request 3
 Note over MVC: Thread 3 blocked
 DB1-->>MVC: Result
 deactivate DB1
 deactivate MVC
 MVC-->>Client: Response 1
 end
 
 rect rgb(200, 255, 220)
 Note over WebFlux,DB2: Non-blocking Model, 1 Thread
 Client->>WebFlux: Request 1
 WebFlux->>DB2: Query (no block)
 Client->>WebFlux: Request 2
 WebFlux->>DB2: Query (no block)
 Client->>WebFlux: Request 3
 WebFlux->>DB2: Query (no block)
 DB2-->>WebFlux: Result 1
 WebFlux-->>Client: Response 1
 DB2-->>WebFlux: Result 2
 WebFlux-->>Client: Response 2
 DB2-->>WebFlux: Result 3
 WebFlux-->>Client: Response 3
 end

Layer 2, Connection Pool Tuning with HikariCP#

The most persistent myth in Spring Boot performance tuning is that adding more database connections will increase throughput. In practice, it often does the opposite. HikariCP ships with a maximumPoolSize of 102. For a lightly loaded service that's fine. For anything approaching serious concurrency, 10 connections is a serialization point: threads queue up waiting for a connection to free, latency climbs, and the throughput ceiling never moves no matter how many application instances you add.

The fix is not "set pool size to 500." The HikariCP maintainers are explicit on this: pool size should be driven by the number of CPU cores on the database server, not by the number of threads in your application4. A database with 8 cores can only process 8 queries truly in parallel. Giving it 200 concurrent connections doesn't add throughput, it adds context-switching overhead and lock contention inside the DB engine itself. The commonly referenced PostgreSQL team formula is a reasonable starting point:

Properties
maximumPoolSize = (DB_CPU_cores * 2) + effective_spindle_count

For a modern cloud database with 8 vCPUs and SSD storage (spindle count effectively 1), that yields a starting value of around 17. Tune from there based on observed wait times and DB CPU utilization, not by guessing higher.

Query latency also shapes the right pool size directly. At an average query time of 2ms, a single connection can serve roughly 500 requests per second. At 10ms average, that same connection handles around 100 requests per second4. If your p50 query time is 5ms and you're targeting 1 million requests per minute (about 16,700 per second), you need at minimum 84 connections just to avoid queuing, before accounting for variance in query duration. Measure your actual query latency first; everything else follows from that number.

The HikariCP maintainers also recommend running a fixed-size pool for best performance, which means setting minimumIdle equal to maximumPoolSize4. A dynamic pool that ramps up under load introduces connection acquisition latency at exactly the moment you can least afford it. Here's a production-ready configuration in application.properties:

Properties
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=20
spring.datasource.hikari.connection-timeout=3000
spring.datasource.hikari.idle-timeout=600000
spring.datasource.hikari.max-lifetime=1800000

connectionTimeout is set to 3 seconds rather than the default 30. A thread waiting 30 seconds for a connection during a traffic spike is already holding server resources and will almost certainly time out from the client's perspective anyway, failing fast frees those resources sooner. maxLifetime at 30 minutes ensures connections are recycled before the database or any intermediate load balancer closes them from the other side, which prevents the stale-connection errors that show up as intermittent 500s in production.

One property worth noting: idleTimeout only has an effect when minimumIdle is less than maximumPoolSize. If you follow the fixed-size recommendation above, you can leave idleTimeout out of your configuration entirely.

A perfectly tuned pool still has a ceiling, though. If the same database rows are being fetched on every request, you are burning connection time on reads that could be served from memory. That's the problem caching addresses, and it often delivers a larger throughput gain than any amount of pool tuning.

Layer 3, Caching Strategy: Local vs. Distributed#

Every database query that returns the same result for the same input is a candidate for caching. At 1 million requests per minute, even a 5ms round-trip to the database, multiplied across thousands of repeated lookups per second, becomes the bottleneck. Spring Boot's caching abstraction makes it straightforward to intercept those lookups, the question is which cache tier belongs where.

Adding @EnableCaching to your application class activates Spring's caching layer, and from that point forward you can annotate individual methods with @Cacheable to store and serve their return values from cache.5 The annotation is implementation-agnostic, so switching from an in-process cache to Redis requires a dependency swap and a configuration change, not a rewrite of your service logic.5

The harder decision is choosing between the two tiers, and getting it wrong is expensive in opposite directions.

L1: Caffeine (in-process). Caffeine stores entries in the JVM heap. There is no serialization, no socket, no network stack, a cache hit resolves in under a microsecond. The trade-off is isolation: each application instance maintains its own copy of the cache. When one instance updates or evicts an entry, the others know nothing about it. In a deployment with ten replicas, you can have ten inconsistent views of the same cached value simultaneously.

L2: Redis (distributed). Redis stores entries in a shared network store that every replica reads from and writes to. A cache update on instance A is immediately visible to instance B. The cost is latency, a Redis round-trip typically adds 0.5-2ms, and a new infrastructure dependency.6

The table below captures how the two tiers differ across the axes that matter most when making this decision:

Cache tierImplementationLatencyConsistency across nodesInvalidation mechanismBest for
L1 (local)CaffeineSub-millisecond (in-JVM)None, each replica is independentTTL or manual eviction per instanceRead-heavy, low-churn reference data (enums, config, lookup tables)
L2 (distributed)Redis0.5-2ms network round-tripStrong, all replicas share one storeTTL, key delete, or pub/sub broadcastSession data, user records, anything that changes and must stay consistent

In practice, the two tiers complement each other rather than compete. A common pattern is to check Caffeine first (L1), fall back to Redis on a miss (L2), and fall back to the database only when Redis also misses. This keeps the hottest entries sub-millisecond while ensuring that a cold instance or a newly deployed replica still benefits from the shared Redis store without hammering the database.

Cache invalidation deserves a specific mention because it is where most caching bugs originate. TTL-based expiry is simple and requires no coordination, but it means stale data lives in cache for the full TTL window. @CacheEvict lets you evict a specific key on writes, which is more precise, but it only evicts from the cache the current instance knows about. If you're using Caffeine across multiple replicas, you need a sidecar mechanism (a Redis pub/sub channel is common) to broadcast the eviction. With Redis as your L2, the eviction is automatically visible everywhere.

Caching absorbs repeated reads effectively, but it does nothing for write-heavy workloads or request patterns where many downstream operations fan out from a single inbound call. That kind of pressure calls for async processing.

Layer 4, Async Offloading with a Message Queue#

Even with reactive I/O, tuned connection pools, and an effective caching layer, some work simply cannot be fast. Sending a confirmation email, generating a PDF report, updating an analytics ledger, triggering a third-party webhook, these operations are too slow or too unreliable to block the HTTP response thread. The pattern that resolves this tension is straightforward: accept the request, enqueue the work, acknowledge the caller immediately, and let a separate consumer process the job at its own pace.1

The HTTP handler becomes a thin intake layer. It validates the payload, writes a message to a queue or topic, and returns a 202 Accepted within a few milliseconds regardless of how long the downstream work takes. The calling client gets a fast response; the durable work continues in the background without any connection to the original request thread. At 1 million requests per minute, this separation is not a convenience, it is the difference between a stable 5ms p99 and a latency curve that spikes whenever a slow downstream call hits the hot path.1

Spring Boot gives you three practical mechanisms for this, and choosing the wrong one for the workload is a common mistake.

MechanismDurabilityRouting flexibilityFailure behaviourBest for
KafkaDurable (log-backed, configurable retention)Topic/partition-based; replay supportedMessages survive restarts; consumer lag is observableHigh-volume event streams, audit logs, replay scenarios
RabbitMQDurable queues with optional persistenceFlexible exchanges, routing keys, dead-letter queuesMessages held until acknowledged; DLQ on repeated failureTask queues, work distribution, complex routing
@AsyncNone (in-memory only)None, runs on a shared thread poolLost on JVM crash or uncaught exceptionFire-and-forget tasks where loss is acceptable (metrics, non-critical notifications)

@Async is the lightest option. Annotate a method, configure a ThreadPoolTaskExecutor with a bounded queue and thread count that match your CPU budget, and Spring offloads the call to a managed pool without touching your broker infrastructure.1 The catch is right there in the table: if the JVM crashes or the thread pool queue overflows, those tasks vanish. For anything that must complete, order processing, payment events, inventory updates, you need a broker.

Java
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(8);
executor.setMaxPoolSize(32);
executor.setQueueCapacity(500);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}

When durability matters, Kafka and RabbitMQ both give you at-least-once delivery guarantees, independent consumer scaling, and a durable log that survives application restarts.1 Kafka is the natural fit when you need replay, observable consumer lag, or high fan-out, a single topic can feed multiple consumer groups without republishing. RabbitMQ wins when you need sophisticated routing, per-message TTLs, or dead-letter queues with automatic retry policies, which are built into the AMQP model without extra infrastructure.

One configuration detail that matters at scale: set spring.kafka.producer.acks=all and spring.kafka.consumer.enable-auto-commit=false if you choose Kafka. Auto-commit is the async-offloading equivalent of HikariCP's default pool size, a default that looks fine until the JVM restarts mid-batch and you discover you silently skipped several thousand messages. Manual offset commits after successful processing are a few extra lines and the only way to make at-least-once a real guarantee rather than a marketing claim.

Diagram as text
flowchart LR
 subgraph req["Request Thread"]
 A["HTTP Request"] --> B["Controller"]
 B --> C["Enqueue to<br/>Kafka/RabbitMQ"]
 C --> D["HTTP 202<br/>Accepted"]
 end
 subgraph cons["Consumer Thread"]
 E["Consumer Service"] --> F["Process Message"]
 F --> G["Write Result"]
 end
 D -.->|decoupled| E
 style req fill:#e1f5ff
 style cons fill:#f3e5f5

Layer 5, Horizontal Scaling and Stateless Design#

Vertical scaling, adding more CPU cores and RAM to a single instance, has a ceiling, and you hit it faster than you might expect under reactive I/O because Netty's event loop already saturates the cores efficiently. The only path past that ceiling is running multiple identical instances behind a load balancer and distributing work across them. That sounds straightforward, but it breaks immediately if your application holds any state in memory that a second instance cannot see.

The most common offender is HTTP session data. If a user's session lives in a HashMap inside one JVM, any request routed to a different instance will fail or force you to use sticky sessions, which defeats load distribution. The fix is to externalize session storage to Redis using Spring Session. With spring-session-data-redis on the classpath and a single @EnableRedisHttpSession annotation, the framework transparently reads and writes session data from Redis on every request.6 All instances share the same session store, and any instance can serve any request.

Local Caffeine caches introduce a subtler problem. A cache invalidation event, say, a product price update, only clears the cache on the instance that received it. The other instances keep serving stale data until their TTL expires. At 1 million requests per minute across many nodes, that inconsistency window matters. The pragmatic fix is to use a shorter TTL for data that changes frequently, or to publish invalidation events to a Redis pub/sub channel that each instance subscribes to on startup. The distributed cache described in Layer 3 does not have this problem because all instances read from the same store.6

On the infrastructure side, your load balancer strategy matters. Round-robin works once sessions are externalized. For WebFlux services with variable response times, least-connections is a better choice because it routes new requests to whichever instance has the fewest in flight rather than blindly cycling through the pool. Pair this with Kubernetes Horizontal Pod Autoscaler (HPA) targeting CPU utilization at around 60-70%, leaving headroom so that a traffic spike triggers scale-out before any instance becomes saturated rather than after.1 With all five layers in place, throughput scales roughly linearly with the number of instances.1


Reading the Signals: Which Layer to Fix First#

The five layers are not equally urgent for every application, and tuning the wrong one first wastes weeks. The symptom-to-layer mapping in the table above is a useful starting point, but the real diagnostic value comes from what your JVM is actually doing at the moment traffic spikes.

Start with a thread dump. On a running instance, run:

Shell
jcmd <pid> Thread.print > thread-dump.txt
grep -c "WAITING" thread-dump.txt
grep -c "BLOCKED" thread-dump.txt

A high WAITING count with stack frames inside Tomcat's NIO acceptor means reactive migration. A high BLOCKED count with frames inside HikariCP means pool tuning. Match the count to the layer above, fix that layer first, measure again, and only then decide whether the next layer needs attention.

Sources

  1. How I Optimized a Spring Boot Application to Handle 1M Requests ...dev.to
  2. Master HikariCP in Spring Boot 3.x: Complete Guide to High-Performance Database Connection Pooling - DEV Communitydev.to
  3. GitHub - chrisgleissner/loom-webflux-benchmarks: Benchmarks of Spring Boot REST service comparing Java 21 Virtual Threads (Project Loom) with WebFlux (Project Reactor). ยท GitHubgithub.com
  4. java - Best practices for Spring Boot connection pool configuration - Stack Overflowstackoverflow.com
  5. Optimizing Spring Boot Applications with Caching Strategies - DEV Communitydev.to
  6. Understanding distributed caching for fast appsredis.io

Keep reading

Spring Boot22 May 2026

How Spring Security works with JWT, OAuth2, and SSO

Spring Security is a framework that intercepts every HTTP request entering your application and enforces authentication and authorization rules before that request ever reaches a...

14 min readRead the article
Spring Boot21 May 2026

30 Seconds of Nothing: Why Spring Boot's Startup Log Tells You Almost Nothing

You audit every @PostConstruct method. You strip out the ones doing redundant work. You rerun the app, watch the terminal, and see: Started Application in 34.2 seconds. That...

16 min readRead the article
Spring Boot21 May 2026

Why Your Spring Boot Service Stalls at 80K RPS (And It's Not the Hardware)

This tutorial walks through a sequence of architectural changes that can take a Spring Boot service from a typical ceiling of 50-80K requests per second to over 1M RPS, without...

17 min readRead the article