Scrivio Interview library
Spring Boot21 May 202617 min read

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 meaningfully increasing infrastructure cost. The goal is a concrete, working path from default Spring MVC to a fully reactive, event-driven stack.

To set the scene: suppose your load test climbs past 60K requests per second, CPU sits at 22%, memory is comfortable, and the network is nowhere near saturated. And yet p99 latency is spiking and the server starts shedding connections. You add more heap. You bump EC2 instance size. The number barely moves. The hardware is not the problem, and no amount of vertical scaling will fix something that is an architectural constraint.

The root cause, in most default Spring Boot applications, is the thread-per-request model that Tomcat uses out of the box. Each incoming request occupies a thread from the pool for the entire duration of its work, including every millisecond it spends waiting on a database response, an HTTP call to a downstream service, or a cache lookup. When those threads are all occupied, new connections queue behind them. The CPU is free because the threads are sleeping on I/O, not computing, but the work cannot proceed because there are no threads available to carry it. This is the ceiling most teams hit somewhere between 50K and 100K RPS on a reasonably sized instance.

The good news is that this ceiling is not a law of physics. One engineering team scaled a Spring Boot service from 50,000 requests per second to over 1.2 million, handling peak load with sub-100ms response times, without meaningfully increasing infrastructure cost. The path there was not bigger machines; it was a sequence of architectural changes that removed the bottlenecks one by one.

There are four main levers to pull, and they build on each other: replacing the blocking I/O foundation with a reactive, event-loop model using Spring WebFlux; making database access genuinely non-blocking with R2DBC instead of JDBC; cutting redundant work with a distributed Redis cache; and decoupling write-heavy processing paths with a staged, Kafka-backed architecture. Each change addresses a specific failure mode. Each one is also meaningful on its own, so if your system cannot afford a full rewrite in one go, you can start with the layer that is causing the most pain right now.

Before any of that, it helps to be precise about what "stalling" actually looks like at the infrastructure level, because the symptoms often mislead teams into buying hardware when they should be changing code.

Switch the Foundation: Spring WebFlux and Non-Blocking I/O#

Spring MVC gives each incoming request its own thread. That thread blocks while waiting for the database, a downstream service, or a file read to complete. At moderate traffic this is invisible; at high load, you exhaust the thread pool and requests queue behind it. Spring WebFlux takes a different approach: it runs on Netty, which uses a small, fixed pool of event-loop threads. Instead of blocking, each operation registers a callback and frees the thread to handle the next connection. When the I/O completes, the event loop picks up where it left off.1

The unit of work in this model is a Mono or a Flux rather than a plain return value. A Mono<T> represents a single asynchronous result (or empty); a Flux<T> represents a sequence of them. Neither value is computed when you construct it. The computation is described as a pipeline of operators and then executed when a subscriber attaches, which in a WebFlux controller happens automatically when the framework subscribes on behalf of the incoming request.

The diagram below shows those two models side by side: on the left, 200 Tomcat threads each frozen inside a database call; on the right, four Netty event-loop threads cycling through thousands of in-flight connections, none of them waiting.

A basic WebFlux controller looks almost identical to a Spring MVC one, which makes the migration feel approachable:

Java
@RestController
@RequestMapping("/products")
public class ProductController {
private final ProductRepository repository;
public ProductController(ProductRepository repository) {
this.repository = repository;
}
@GetMapping("/{id}")
public Mono<Product> getById(@PathVariable String id) {
return repository.findById(id); // returns Mono, never blocks
}
@GetMapping
public Flux<Product> getAll() {
return repository.findAll(); // streams results as they arrive
}
}

The dependency swap in pom.xml is equally straightforward: replace spring-boot-starter-web with spring-boot-starter-webflux. Netty starts in place of Tomcat with no further configuration.

The critical rule is that nothing on an event-loop thread may block. Violate this and you lose every advantage you just gained. A synchronous JDBC call on an event-loop thread does not just slow that one request; it freezes the entire thread, which means every other connection multiplexed onto that thread stalls until the query returns. At 1M RPS, with only a handful of event-loop threads, one slow JDBC call can cascade into latency spikes across thousands of concurrent requests. That constraint is why the data layer, covered next, requires the same reactive treatment as the HTTP layer.

Diagram as text
flowchart LR
 A["Incoming Requests"] -->|N requests| B["Blocked Threads"]
 B --> C["Thread Pool Queue"]
 C -->|Overflow| D["Overflowing Queue"]
 
 A2["Incoming Connections"] -->|Handled by| B2["Worker Threads"]
 B2 --> C2["Non-Blocking I/O"]
 C2 --> D2["Event Loop"]
 
 D2 -->|Handles| E["Concurrent Connections"]
 D -->|Requests Through| E

Keeping the Pipeline Reactive: R2DBC and Async Data Access#

Switching to WebFlux buys you a non-blocking HTTP layer, but that gain evaporates the moment your code touches a database through JDBC. JDBC is synchronous by design: it blocks the calling thread while the database does its work. On a Netty event loop, a single slow query can stall the entire thread and starve every other request waiting on it. R2DBC closes that gap. It is a reactive, non-blocking database driver specification built for exactly this kind of event-loop architecture.

The cost of ignoring this is quantifiable. In a write-heavy load test against a Spring R2DBC application running without connection pooling, only 140 requests completed and the 95th-percentile latency hit 2.33 seconds.2 That is what happens when every incoming request pays the full price of opening a new database connection: a network handshake, authentication, and resource allocation on both sides of the wire. At low traffic it is merely wasteful; at high throughput it becomes a wall.

Connection pooling solves this by keeping a set of already-authenticated connections alive and handing them out to incoming operations. With R2DBC, the pool implementation of choice is r2dbc-pool, which integrates cleanly with Spring Boot's auto-configuration. A minimal but production-relevant configuration looks like this:

YAML
spring:
r2dbc:
url: r2dbc:postgresql://localhost:5432/mydb
username: user
password: secret
pool:
initial-size: 10
max-size: 50
max-idle-time: 30m
validation-query: SELECT 1

initial-size controls how many connections are established at startup, so the first wave of traffic does not pay connection-creation cost. max-size is the ceiling: requests that arrive when all connections are busy will queue rather than spin up a new connection, which is the behavior you want to prevent the database from being overwhelmed. Setting validation-query ensures that stale connections are caught before they are handed to a query rather than failing mid-request.

On the application side, your repository layer stays idiomatic. Spring Data R2DBC repositories return Mono and Flux instead of domain objects directly, which keeps the reactive chain intact from the HTTP handler all the way to the database round-trip:

Java
public interface OrderRepository extends ReactiveCrudRepository<Order, Long> {
Flux<Order> findByCustomerId(Long customerId);
}

No blocking calls, no block() anywhere in the chain. If you find yourself calling block() to adapt a reactive result into a synchronous one, that is a sign the blocking boundary has crept back in and you should trace it to its source.

Even with a well-configured pool, database latency is still real latency. A query that takes 5ms under load will consume a pool connection for those 5ms, and at 1M RPS the math on connection availability becomes tight quickly. That is the natural transition point to caching: if a large fraction of your reads can be served without touching the database at all, pool pressure drops dramatically and the remaining queries get faster connections.

Eliminate Redundant Work: Distributed Caching with Redis#

Even with R2DBC keeping your database pipeline non-blocking, the database is still the most expensive leg of any read request. Every round-trip adds network latency, consumes a connection from your pool, and burns CPU on query parsing and index traversal. At high request volumes, even a well-tuned PostgreSQL cluster will start to buckle if you send it every read your service receives.

The standard answer is a cache layer, and Redis is the right tool here. What matters for a reactive pipeline is that you use Spring Data's ReactiveRedisTemplate rather than the blocking RedisTemplate. The blocking variant reintroduces exactly the problem you solved with WebFlux: a thread sits idle waiting for a network response from Redis, and at 1M RPS that adds up fast.

The pattern you want is cache-aside: check Redis first, return the cached value if it exists, and only fall back to the database on a miss. With ReactiveRedisTemplate, the entire flow stays on the event loop:

Java
@Service
public class ProductService {
private final ReactiveRedisTemplate<String, Product> redisTemplate;
private final ProductRepository productRepository;
public ProductService(ReactiveRedisTemplate<String, Product> redisTemplate,
ProductRepository productRepository) {
this.redisTemplate = redisTemplate;
this.productRepository = productRepository;
}
public Mono<Product> findById(String id) {
String cacheKey = "product:" + id;
return redisTemplate.opsForValue()
.get(cacheKey)
.switchIfEmpty(
productRepository.findById(id)
.flatMap(product ->
redisTemplate.opsForValue()
.set(cacheKey, product, Duration.ofMinutes(10))
.thenReturn(product)
)
);
}
}

switchIfEmpty fires only when Redis returns an empty signal, meaning a cache miss. On a hit, the database is never touched. The TTL argument to set is important: without it, stale entries accumulate and memory pressure on Redis climbs steadily. Ten minutes is a reasonable starting point for product data; session or rate-limit data might use a shorter window.

To make this work, you need ReactiveRedisTemplate configured as a bean with a proper serializer. Jackson2JsonRedisSerializer works well for complex domain objects:

Java
@Bean
public ReactiveRedisTemplate<String, Product> reactiveRedisTemplate(
ReactiveRedisConnectionFactory factory) {
Jackson2JsonRedisSerializer<Product> serializer =
new Jackson2JsonRedisSerializer<>(Product.class);
RedisSerializationContext<String, Product> context =
RedisSerializationContext.<String, Product>newSerializationContext(
new StringRedisSerializer())
.value(serializer)
.build();
return new ReactiveRedisTemplate<>(factory, context);
}

In practice, this setup can absorb the vast majority of your read traffic before a single query reaches the database. Hot data, such as product catalogues, user profiles, feature flags, and configuration, gets served from Redis memory in under a millisecond, leaving your R2DBC connection pool available for genuine writes and cache-miss reads.

One thing worth watching is cache stampede. If a popular key expires and hundreds of in-flight requests all miss simultaneously, they pile onto the database together. A simple mitigation is to jitter your TTLs slightly by adding a small random offset on write, so keys don't all expire in the same second. For extremely hot keys, a single-flight pattern using Mono.cache() or Reactor's replay() operator can ensure only one database call is made per miss window.

With reads largely absorbed by Redis, the remaining scaling challenge is write-heavy and asynchronous workloads, where the database still has to accept every mutation. That is where an event-driven layer changes the calculus entirely.

Decouple and Buffer: Staged Event-Driven Architecture with Kafka#

Even a fully reactive WebFlux handler has a ceiling when the work it needs to do, such as writing to a database, calling downstream services, or triggering fan-out notifications, takes longer than the time budget per request at 1M RPS. If each inbound request must complete a 5ms database write before it can return, your theoretical maximum is 200K RPS per core regardless of how non-blocking your I/O is. The fix is to stop treating ingestion and processing as the same step.

A Staged Event-Driven Architecture (SEDA) separates those two concerns. The ingestion layer accepts the request, validates it minimally, publishes a message to Kafka, and immediately returns an acknowledgment to the caller. A downstream consumer group processes those messages at whatever rate it can sustain, independently of the ingestion rate. Because Kafka acts as a durable buffer, a temporary spike in inbound traffic does not propagate as backpressure into your processing tier. This pattern was one of the primary architectural drivers behind scaling a Spring Boot service from 50K to over 1.2M requests per second with sub-100ms response times.

The diagram below shows this flow: HTTP requests hit the WebFlux ingestion layer, which publishes to a Kafka topic; a separate consumer group reads from that topic and performs the heavier processing, writing results to the database and downstream services.

On the producer side, Spring Boot's ReactiveKafkaProducerTemplate keeps the pipeline non-blocking end-to-end. A minimal reactive producer looks like this:

Python
# Equivalent Java, shown here as pseudocode for clarity
# In your Spring Boot service:
#
# @Service
# class EventPublisher(ReactiveKafkaProducerTemplate<String, OrderEvent>) {
#
# fun publish(event: OrderEvent): Mono<Void> =
# template.send("orders", event.id, event)
#.doOnSuccess { result ->
# log.debug("offset: {}", result.recordMetadata().offset())
# }
#.then()
# }
Java
@Service
public class EventPublisher {
private final ReactiveKafkaProducerTemplate<String, OrderEvent> template;
public Mono<Void> publish(OrderEvent event) {
return template.send("orders", event.id(), event)
.doOnSuccess(r -> log.debug(
"ack offset={}", r.recordMetadata().offset()))
.then();
}
}

The handler calls publish() and returns immediately. No thread blocks waiting for a database commit, so the event loop thread is free for the next request within microseconds.

A few configuration choices make a material difference at high volume. Setting acks=1 instead of acks=all cuts producer latency roughly in half for workloads where losing a message on a broker crash is acceptable. Batching is controlled by linger.ms and batch.size: a linger.ms of 5 and a batch.size of 64KB lets Kafka amortize network round trips across many messages, which matters when you are pushing hundreds of thousands of small events per second. On the consumer side, scaling the consumer group's partition count is the primary throughput lever. Kafka's parallelism is bounded by partition count, so a topic with 32 partitions can be consumed by up to 32 instances simultaneously.

The architectural win here is not just raw throughput. Because the consumer tier is decoupled, you can scale it independently, redeploy it without dropping inbound traffic, and replay messages from an earlier offset if a downstream system had an outage. That operational flexibility is worth as much as the performance headroom, especially in systems where processing logic changes more often than ingestion logic does.

Diagram as text
flowchart LR
 A["HTTP request"] --> B["WebFlux handler"]
 B -->|publish event| C["Kafka producer"]
 C --> D["Kafka topic"]
 D --> E["Kafka consumer group"]
 E --> F["DB write"]
 E --> G["Notification"]
 E --> H["Analytics"]
 B -->|backpressure| D
 C -->|async buffering| D

Thread Pool Sizing, Backpressure, and the Config Knobs That Matter#

Once you have WebFlux, R2DBC, Redis, and Kafka all wired up, the next failure mode is subtler: the architecture is right but the numbers are wrong. Default pool sizes and scheduler configs were chosen for safety on modest hardware, not for 1M RPS. Getting those numbers right is mostly arithmetic, not guesswork.

Netty worker threads. Netty's default event loop count is 2 × CPU cores. For a pure reactive pipeline this is often enough, because event loop threads should never block. If you have any blocking call that unavoidably sneaks through (a legacy SDK, a JDBC fallback), wrap it with Schedulers.boundedElastic() so it offloads to a separate pool and never ties up a worker thread. The config property you want is:

YAML
spring:
netty:
worker-threads: 16 # 2× on an 8-core host; raise to 4× if profiling shows CPU idle

R2DBC connection pool. The pool max size is the single most common misconfiguration. A starting formula: max-size = (target RPS / average queries per request) × average query latency in seconds. For 500K RPS, two queries per request, and 2ms average query time, that works out to 2,000 connections. Most teams leave this at the default of 10 and wonder why latency spikes.

YAML
spring:
r2dbc:
pool:
initial-size: 50
max-size: 2000
max-idle-time: 30m
validation-query: SELECT 1

Backpressure in Reactor. Backpressure is what prevents your event loops from becoming a memory sink when a downstream system is slower than the inbound rate. The most reliable place to enforce it is at the HTTP layer with limitRate:

Java
Flux.from(inboundRequests)
.limitRate(1024) // request 1024 elements at a time from upstream
.flatMap(this::processRequest, 256) // max 256 in-flight concurrently
.subscribe();

The limitRate call controls how many demand signals propagate upstream; the concurrency argument to flatMap caps in-flight work. Both numbers belong in your configuration properties so you can tune them without a redeploy.

The NIO thread-pool deadlock you want to avoid. With NIO-based connections, three task types share the executor: I/O selector processing, read dispatching, and message assembly. Assembly threads can block waiting for the rest of a large message to arrive.3 If you use a fixed pool with CallerRunsPolicy and a short queue, a specific sequence can lock everything up: the pool exhausts, the selector thread gets an OP_READ event, runs the read itself, then tries to fire an assembler, but the queue is full and the rejection policy sends execution back to the selector thread, which is now blocked. The fix is either a larger queue, an unbounded pool for assembly threads, or, in a pure WebFlux stack, never routing work through that executor at all.

Kafka consumer threads. Each consumer in a consumer group gets its own thread. Set spring.kafka.listener.concurrency to the number of partitions you assigned to that topic, and no higher. Extra threads beyond the partition count will sit idle.

Taken together, these settings form a short checklist you can apply to any new service before its first load test. The next section covers how to validate that everything is working as expected, and how to find whichever bottleneck you haven't eliminated yet.

Validating the Architecture: Load Testing and Finding the Next Bottleneck#

All the architecture changes in the previous sections are worthless until you can measure them. Intuition about where your bottleneck lives is almost always wrong, and the only way to build confidence before production traffic arrives is to generate the load yourself and read the results layer by layer.

K6 is a good fit for this work. It is scriptable in JavaScript, ships with a clean summary of p95 and p99 latencies, and makes it easy to ramp virtual users in stages so you can watch throughput climb until something breaks. A simple write-heavy smoke test against your reactive endpoint looks like this:

JavaScript
import http from 'k6/http';
import { check } from 'k6';
export const options = {
stages: [
{ duration: '30s', target: 500 },
{ duration: '2m', target: 5000 },
{ duration: '30s', target: 0 },
],
};
export default function () {
const res = http.post(
'http://localhost:8080/api/events',
JSON.stringify({ type: 'page_view', ts: Date.now() }),
{ headers: { 'Content-Type': 'application/json' } }
);
check(res, { 'status 200': (r) => r.status === 200 });
}

Run this before and after each architectural change. Without R2DBC connection pooling, a write-heavy test like this will show 95th-percentile latencies climbing past two seconds and completed request counts that are embarrassingly low, often in the low hundreds over a 30-second window.2 Those numbers are the signal, not the noise.

The pattern that actually works when scaling to 1M RPS is identifying bottlenecks layer by layer, applying a targeted fix, and re-measuring before moving on. Engineers who skip this loop tend to over-provision compute while leaving a misconfigured R2DBC pool or a missing Redis TTL quietly throttling everything above them.

Read your K6 summary in this order. If throughput plateaus and p99 latency is below 50ms, your ceiling is likely the event-loop thread count or Netty worker configuration; revisit the scheduler and pool settings from the previous section. If p99 climbs steeply while throughput is still rising, the database or cache layer is struggling under concurrency; check your R2DBC pool maxSize and Redis connection count. If you see a wall of 5xx errors instead of latency growth, backpressure is not configured, and Kafka or your reactive pipeline is dropping work rather than buffering it.

One failure mode that catches engineers even after applying every fix here is forgetting that the bottleneck moves. You tune the thread pool, and suddenly the database is the ceiling. You widen the connection pool, and now Redis saturates. You add Redis, and now Kafka's consumer lag becomes the metric that matters. Each optimization shifts the constraint to the next layer, so a single load test run cannot tell you whether you are done. The teams that reach and sustain 1M RPS treat load testing as a continuous loop, not a final exam.

The concrete next step is to set up K6 in your CI pipeline with a throughput threshold, something like http_req_duration{p(99)}<100 combined with a minimum http_reqs rate, so that any regression in your reactive pipeline or pool configuration fails a build before it reaches production. Running a repeatable load test after every meaningful change is what separates an architecture that reaches 1M RPS once from one that stays there.

Sources

  1. Non-Blocking I/O Operation with Spring WebFlux - GeeksforGeeksgeeksforgeeks.org
  2. Configuring Connection Pooling with Spring R2DBC - DEV Communitydev.to
  3. About Non-blocking I/O (NIO) :: Spring Integrationdocs.spring.io

Keep reading

Spring Boot27 June 2026

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

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...

17 min readRead the article
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