Skip to main content

Spring Cloud Gateway Server MVC on Virtual Threads: Routes, Retry and Redis Rate Limiting (Spring Boot 4.2)

Build a Spring Cloud Gateway Server MVC 5.1 gateway on Spring Boot 4.2 with virtual threads: routes in Java and YAML, a retry filter, a Redis-backed Bucket4j rate limiter shared by two instances, and the failures worth reproducing (500 instead of 504, a hanging Redis outage, a missing store bean). Every number comes from a real run.

You need one front door for several backends. It should route, add or strip headers, retry a flaky call, and stop one noisy client from drowning everyone else. That is what an API gateway does, and until recently the Spring answer to it was Spring Cloud Gateway on WebFlux, which meant learning Mono and Flux before you could write a single route. Spring Cloud Gateway Server MVC is the same idea for people who write ordinary servlet applications. A request arrives on a thread and is handled top to bottom, so a stack trace reads like a stack trace and a filter is a plain function. Switch on virtual threads and that thread stops being expensive. This post builds one from scratch, runs it, and shows what happens when it goes wrong. Each section starts with the plain idea and ends with a fold-out for readers who want the next layer. Everything quoted below is real output from a companion module: gateway-mvc in the spring-boot-microservices-project repository. There is no separate documentation folder; the depth lives in the fold-outs on this page.
Versions tested. Spring Boot 4.2.0, Spring Cloud 2026.0.0 (which pins Spring Cloud Gateway 5.1.0), Bucket4j 8.23.0, JDK 25 (Temurin 25.0.5.1, LTS), Redis 7.0.15. The Spring Cloud 2026.0.0 BOM and the gateway 5.1.0 starter appear on Maven Central on 19 November 2026; versions were read from maven-metadata.xml and the BOM itself, not from release announcements.

A route is a predicate, some filters and a handler

A gateway route answers three questions. Which requests are mine? (the predicate: here, a GET to /api/hello). What should I change on the way in and out? (filters). Where does the request go? (the handler, which for a gateway is almost always “forward it over HTTP”). Server MVC builds routes out of Spring’s functional web types, so a route is just a RouterFunction you return from a @Bean method.
ClientGET /api/hello Tomcatone virtual thread PredicateGET + path match before filtersuri, stripPrefix http() handlercalls the backend Backend:9091 /hello after filtersX-Gateway-Thread The request goes right through predicate, before filters and handler; the response comes back left through the after filters. Everything runs on the same thread, top to bottom, like any servlet code. That is the whole appeal of the MVC flavour.
The diagram is the whole mental model. The only unusual part is that filters come in two kinds: before filters rewrite the request (set the backend URI, strip a prefix, add a header) and after filters rewrite the response. Both run on the one thread that Tomcat gave this request. Here is the smallest useful route, from src/main/java/com/ankurm/gwmvc/RoutesConfig.java. It sends GET /api/hello to the backend as GET /hello:
    @Bean
    RouterFunction<ServerResponse> plainRoutes(@Value("${demo.upstream:http://localhost:9091}") String upstream) {
        return route("hello")
                .GET("/api/hello", http())
                .before(uri(upstream))
                .before(stripPrefix(1))
                .filter(threadReport())
                .build()
        // ...more routes chained with .and(...)
The backend is a 90-line, dependency-free Java file, scripts/Upstream.java, so the demo has something real to call. Output from output/01-routes.txt:
$ curl -i localhost:8080/api/hello
HTTP/1.1 200 
X-Gateway-Thread: virtual
Content-Type: application/json

{"service":"upstream","message":"hello from the backend"}
The same route can live in YAML instead. This is the yaml-hello route from src/main/resources/application.yml; the property prefix is spring.cloud.gateway.server.webmvc.routes, which I confirmed from the jar’s spring-configuration-metadata.json:
  cloud:
    gateway:
      server:
        webmvc:
          routes:
            # The YAML flavour of a route: same predicates and filters, no Java.
            - id: yaml-hello
              uri: http://localhost:9091
              predicates:
                - Path=/yaml/**
              filters:
                - StripPrefix=1
                - AddRequestHeader=X-Gateway-Route, yaml-hello
$ curl -i localhost:8080/yaml/hello
HTTP/1.1 200 
Content-Type: application/json

{"service":"upstream","message":"hello from the backend"}
Going one level deeper: how the pieces map to Spring types A predicate is a Spring RequestPredicate; the extra ones the gateway adds live in GatewayRequestPredicates. A before filter is a Function<ServerRequest, ServerRequest> from BeforeFilterFunctions. An after filter is a response processor from AfterFilterFunctions. The handler is a HandlerFunction from HandlerFunctions; http() forwards over HTTP, and there are also fn(...), forward(...) and stream(...) variants. Anything path-shaped in the route URI is ignored, which is why the examples set the URI and then use stripPrefix or setPath separately. The one filter I wrote myself, threadReport(), is a HandlerFilterFunction.ofResponseProcessor that adds an X-Gateway-Thread header. You will see it again in the next section: it is how the gateway proves which kind of thread served the request.

Turn on virtual threads and 200 slow requests stop queueing

A traditional servlet server has a pool of threads. Each request holds one for as long as it takes, and a gateway spends most of its time waiting for a backend. Ten threads can therefore serve at most ten waiting requests; the eleventh queues. A virtual thread is a thread that costs almost nothing to park while it waits, so the pool stops being the limit. In Boot 4.2 it is one line, shown in the YAML above and quoted here from src/main/resources/application.yml:
  tomcat:
    threads:
      max: 10          # deliberately tiny so platform-thread starvation is visible in seconds

spring:
  application:
    name: gateway-mvc
  threads:
    virtual:
      enabled: true
I capped Tomcat at 10 threads on purpose, so the difference is visible in seconds. The test sends 200 requests at once to /api/slow?ms=500, where the backend sleeps half a second. The client is scripts/LoadClient.java, which prints status counts and elapsed time. A platform Spring profile turns virtual threads off, so the same jar runs both ways. Output from output/06-virtual-threads.txt:
## virtual threads (server.tomcat.threads.max=10)
$ curl -i localhost:8080/diag/thread
HTTP/1.1 200 
Content-Type: application/json

{"thread":"VirtualThread[#N,tomcat-handler-1]/runnable@ForkJoinPool-1-worker-1","virtual":true}

$ java scripts/LoadClient.java 'http://localhost:8080/api/slow?ms=500' 200
requests=200 statuses={200=200} elapsed_ms=2154
## platform threads (server.tomcat.threads.max=10)
$ curl -i localhost:8080/diag/thread
HTTP/1.1 200 
Content-Type: application/json

{"virtual":false,"thread":"Thread[#N,http-nio-8080-exec-3,5,main]"}

$ java scripts/LoadClient.java 'http://localhost:8080/api/slow?ms=500' 200
requests=200 statuses={200=200} elapsed_ms=10903
200 requests x 500 ms backend delay, Tomcat limited to 10 threads virtual threads 2154 ms platform threads 10903 ms With 10 threads, 200 sleeping requests need 20 rounds of 500 ms: about 10 seconds. Virtual threads do not wait for a free thread, so all 200 sleep at once. The 2.1 s is not 0.5 s because this was a cold JVM and a cold client; the gap, not the absolute number, is the point.
The chart says it: 200 half-second waits through 10 threads is 20 rounds, about 10 seconds, and that is what the platform run measured. With virtual threads all 200 wait together. The diagnostic endpoint /diag/thread (a local route in src/main/java/com/ankurm/gwmvc/RoutesConfig.java) prints the thread type, so you never have to guess which mode a running instance is in. Delete it before you ship.
Timing is indicative. The 2154 ms and 10903 ms figures drift between runs and the virtual run includes a cold JVM on both sides. What does not drift is the order of magnitude: the platform run is bounded by threads.max, the virtual run is not. Do not quote these as a benchmark.
Going one level deeper: what virtual threads do not fix Virtual threads remove the thread-count limit, not the other limits. The backend, the connection pool to it, Redis and the operating system still have capacity, and a gateway that suddenly accepts every request will pass that pressure straight to the backend. That is a good reason to keep the rate limiter in the next sections: concurrency is cheap now, so deciding who gets to use it matters more. In my run server.tomcat.threads.max=10 did not throttle the virtual run, which finished all 200 in about two seconds; with virtual threads on, the platform pool size is not what bounds you. I did not test thread pinning (a virtual thread stuck to its carrier inside a synchronized block or a native call), so I make no claim about it here. For a wider comparison of virtual threads, WebFlux and platform threads see the existing benchmark post below.

Check what the backend really receives, because two defaults will surprise you

Filters are easy to write and easy to get subtly wrong, so the habit worth building is to point a route at a backend that echoes its request headers. The backend’s /headers endpoint does exactly that, and the headers route adds an X-Gateway-Route header with addRequestHeader. I also sent a fake X-Forwarded-For: 1.2.3.4 from the client. From output/01-routes.txt:
# what the backend receives by default; note a client-supplied X-Forwarded-For is stripped
$ curl -s -H 'X-Forwarded-For: 1.2.3.4' localhost:8080/api/headers
accept: */*
accept-encoding: gzip,deflate
connection: Upgrade, HTTP2-Settings
host: localhost:9091
http2-settings: AAEAAEAAAAIAAAAAAAMAAAAAAAQBAAAAAAUAAEAAAAYABgAA
upgrade: h2c
user-agent: curl/8.5.0
x-gateway-route: headers
Two things are worth noticing. First, x-gateway-route: headers is there, so the before filter worked. Second, there is no Forwarded or X-Forwarded-* header at all, and the client-supplied X-Forwarded-For was dropped. That is deliberate and safe: a gateway should not pass on forwarded headers from a client it has no reason to trust. But if your backend builds absolute URLs or logs client addresses from those headers, it now sees nothing. Telling the gateway which proxies to trust brings them back:
# same request with spring.cloud.gateway.server.webmvc.trusted-proxies=.*
$ curl -s -H 'X-Forwarded-For: 1.2.3.4' localhost:8080/api/headers
forwarded: proto=http;host="localhost:8080";for="127.0.0.1:41308"
x-forwarded-for: 1.2.3.4,127.0.0.1
x-forwarded-host: localhost:8080
x-forwarded-port: 8080
x-forwarded-prefix: /api
x-forwarded-proto: http
x-gateway-route: headers
The property is spring.cloud.gateway.server.webmvc.trusted-proxies and it takes a regular expression. I used .* for the demo, which trusts everything; in production use the address pattern of your real load balancer. The first output also shows connection: Upgrade, HTTP2-Settings and upgrade: h2c. Those come from the HTTP client the gateway picked. The gateway’s post-processor looks for Apache HttpClient, Jetty, Reactor Netty and the JDK client; none of the first three is on this classpath, so the JDK client is used, and it offers an HTTP/2 cleartext upgrade to every backend. A backend that mishandles that header will misbehave only behind the gateway.
Fingerprint: a backend that works with curl directly but fails behind the gateway, with Upgrade: h2c in its logs. Put Apache HttpClient 5 on the classpath, or check how the backend handles the upgrade offer. I did not test either remedy here; I only observed the header.
Going one level deeper: configuring the HTTP client The gateway does not have its own HTTP client settings. The jar’s environment post-processor sets spring.http.clients.redirects and spring.http.clients.imperative.factory, which are Spring Boot’s shared client properties, so timeouts and the client choice are configured the Boot way. The next sections use spring.http.clients.read-timeout and show what a timeout looks like to the caller. The reference documentation page that I tried for the HTTP client configuration returned a client error when I fetched it, so the statements above come from the jar (property metadata and bytecode strings) and from running the module, not from that page.

Retry a flaky backend, and know which retry you are using

Backends fail in small ways: one 503 during a deploy, one dropped connection. A gateway can hide those by calling again. The flaky route in src/main/java/com/ankurm/gwmvc/RoutesConfig.java retries GET requests that come back with a 5xx, up to three times, waiting 50 ms and doubling up to 500 ms:
        return route("flaky")
                .GET("/api/flaky", http())
                .before(uri(upstream))
                .before(stripPrefix(1))
                .filter(retry(c -> c.setRetries(3)
                        .setSeries(java.util.Set.of(org.springframework.http.HttpStatus.Series.SERVER_ERROR))
                        .setMethods(java.util.Set.of(HttpMethod.GET))
                        .setBackoff(Duration.ofMillis(50), Duration.ofMillis(500), 2)))
                .build();
The backend’s /flaky endpoint returns 503 for its first two calls after a reset. The client makes one call and gets a 200. Then the script asks the backend how many calls it really saw. From output/02-retry.txt:
$ curl -i localhost:8080/api/flaky?failFirst=2
HTTP/1.1 200 
Content-Type: application/json

{"call":3,"result":"ok"}

# how many calls did the backend actually see? (failFirst=0 just returns the counter)
$ curl -i localhost:9091/flaky?failFirst=0
HTTP/1.1 200 OK
Content-type: application/json

{"call":4,"result":"ok"}
The client saw one clean response; the backend saw three requests (two failures and a success). Retrying is invisible to the caller, and that is both its value and its danger: it multiplies load on a backend that is already struggling. I limited it to GET for that reason; retrying a POST that is not idempotent can charge a customer twice. When the backend never recovers, the gateway gives up, and what it says is not what you might expect:
# now a backend that never recovers: after the 3 retries the gateway gives up with a 500, not the backend's 503
$ curl -i localhost:9091/flaky/reset
HTTP/1.1 200 OK
Content-type: application/json

{"reset":true}

$ curl -i localhost:8080/api/flaky?failFirst=99
HTTP/1.1 500 
Content-Type: application/json

{"timestamp":"2026-11-25T19:22:37.164Z","status":500,"error":"Internal Server Error","path":"/api/flaky"}

# the backend saw the original try plus 3 retries = 4 calls, so the counter now reads 5
$ curl -i localhost:9091/flaky?failFirst=99
HTTP/1.1 503 Service Unavailable
Content-type: application/json

{"call":5,"result":"unavailable"}

# log line behind that 500:
Request processing failed: org.springframework.core.retry.RetryException: Retry policy for operation ... (FrameworkRetryFilterFunctions lambda)
The backend returned 503 every time, but the caller gets a 500 from the gateway, with the exception hidden in the log. The backend counter reads 5 after the reset because it saw the first attempt plus three retries (4 calls) and then the extra call the script made to read the counter.
The retry you get depends on the classpath. The gateway ships two implementations: one on Spring Retry, one on the retry support in Spring Framework 7. RetryFilterFunctions.retry(...) picks one at startup. With Spring Retry absent it chose the Framework one; with debug logging on, startup prints the selection line you see in the output below. If you import GatewayRetryFilterFunctions.retry directly, you opt into Spring Retry whether it is there or not.
# which retry implementation did the gateway pick? (DEBUG log at startup)
Retry filter selection: Spring Retry on classpath=false, useFrameworkRetry=false, selected filter=FrameworkRetryFilterFunctions
And this is what the direct import does when Spring Retry is not on the classpath. The one-line change is made in a temporary copy by scripts/wrong-retry-import.sh; output from output/07-wrong-retry-import.txt:
# the one-line change in a temporary copy of RoutesConfig.java
8:import static org.springframework.cloud.gateway.server.mvc.filter.GatewayRetryFilterFunctions.retry;
# startup log:
Factory method 'retryRoute' threw exception with message: org/springframework/retry/RetryPolicy
Caused by: java.lang.NoClassDefFoundError: org/springframework/retry/RetryPolicy
The application does not start at all, which is at least loud. The fix is to call the dispatching RetryFilterFunctions.retry (what the route above uses), or add Spring Retry.
Going one level deeper: what can be retried, and the 500 on exhaustion The retry configuration has four dials that matter: how many retries, which status series count as failures (SERVER_ERROR here), which methods are safe to repeat, and the backoff. There is also a list of exception types, and a switch for caching the request body so it can be replayed. If a request has a body that cannot be replayed, retrying it is not possible, so retrying POST/PUT is a separate decision that needs setCacheBody(true) and an idempotent backend; I did not test body replay. The 500 on exhaustion is what I observed with the Framework implementation (a org.springframework.core.retry.RetryException in the log). If callers need the backend’s own 503, handle the exception on the route with onError, the same way the timeout example later in this post maps an exception to a status.

Rate limiting needs a store, and you have to provide it

A rate limiter answers one question per request: may this caller have one more? The rateLimit filter uses a token bucket. Each caller has a bucket with a fixed number of tokens. A request takes one; tokens trickle back over time; an empty bucket means the request is refused. The caller is identified by a key that you compute from the request. The filter does not bring a place to keep buckets. It uses the Bucket4j library and expects an AsyncProxyManager<String> bean, which is where buckets live. The reference page I read shows a Caffeine (in-memory) example and says nothing about Redis. I wired Redis through Bucket4j’s Lettuce module so several gateways can share one bucket; the code is src/main/java/com/ankurm/gwmvc/RateLimiterConfig.java:
    @Bean
    @ConditionalOnProperty(name = "demo.store", havingValue = "redis")
    AsyncProxyManager<String> redisProxyManager(@Value("${demo.redis-uri:redis://localhost:6379}") String uri) {
        RedisClient client = RedisClient.create(uri);
        ProxyManager<byte[]> pm = LettuceBasedProxyManager.builderFor(client)
                // let Redis forget a bucket once it would be full again anyway
                .withExpirationStrategy(
                        ExpirationAfterWriteStrategy.basedOnTimeForRefillingBucketUpToMax(Duration.ofMinutes(1)))
                .build();
        return pm.<String>withMapper(key -> key.getBytes(StandardCharsets.UTF_8)).asAsync();
    }

    @Bean
    @ConditionalOnProperty(name = "demo.store", havingValue = "caffeine", matchIfMissing = true)
    @SuppressWarnings({ "unchecked", "rawtypes" })
    AsyncProxyManager<String> caffeineProxyManager() {
        Caffeine builder = Caffeine.newBuilder().maximumSize(10_000);
        return new CaffeineProxyManager<String>(builder, Duration.ofMinutes(1)).asAsync();
    }
The route that uses it allows 5 requests per 10 seconds per X-Api-Key header:
        return route("limited")
                .GET("/api/limited", http())
                .before(uri(upstream))
                .before(stripPrefix(1))
                .filter(rateLimit(c -> {
                    c.setCapacity(5)
                            .setPeriod(Duration.ofSeconds(10))
                            .setKeyResolver(request -> request.headers().firstHeader("X-Api-Key"));
                    if (!rlTimeout.isZero()) {
                        c.setTimeout(rlTimeout); // how long to wait for the store before giving up
                    }
                }))
                .build();
Run it against the Caffeine store first (one JVM). Output from output/03-ratelimit.txt:
# 5 tokens per 10 seconds per X-Api-Key, Caffeine store
alice #1  HTTP/1.1 200  X-RateLimit-Remaining: 4 
alice #2  HTTP/1.1 200  X-RateLimit-Remaining: 3 
alice #3  HTTP/1.1 200  X-RateLimit-Remaining: 2 
alice #4  HTTP/1.1 200  X-RateLimit-Remaining: 1 
alice #5  HTTP/1.1 200  X-RateLimit-Remaining: 0 
alice #6  HTTP/1.1 429  X-RateLimit-Remaining: 0 
alice #7  HTTP/1.1 429  X-RateLimit-Remaining: 0 
# a different key has its own bucket
bob   #1  HTTP/1.1 200  X-RateLimit-Remaining: 4 
# no X-Api-Key: the key resolver returns null
$ curl -i localhost:8080/api/limited
HTTP/1.1 403 


# wait 11 seconds: the bucket refills
alice #8  HTTP/1.1 200  X-RateLimit-Remaining: 4 
Read it like a bucket. Alice starts with 5 tokens: the header counts down 4, 3, 2, 1, 0, and her sixth request is refused with 429. Bob has his own bucket. A request with no key gets 403, not 429: the key resolver returned null, so there was no bucket to charge and the filter refuses. After 11 seconds Alice’s bucket has refilled. Note that X-RateLimit-Remaining is also present on the 429; the reference page was unclear on that, and the run settles it. Now the point of Redis. Two gateway instances share one bucket, and the client alternates between them (diagram below, output from output/04-shared-redis.txt):
gateway :8080rateLimit(5 / 10 s) gateway :8081rateLimit(5 / 10 s) Rediskey: carolone shared bucket Backendsees 5 requests Each instance asks Redis, not its own memory, how many tokens are left. Requests 1 to 5 get through; the 6th is rejected with 429 whichever instance it hits.
The transcript, from output/04-shared-redis.txt:
# same key, alternating between two gateway instances that share Redis
carol #1 via :8081  HTTP/1.1 200  X-RateLimit-Remaining: 4 
carol #2 via :8080  HTTP/1.1 200  X-RateLimit-Remaining: 3 
carol #3 via :8081  HTTP/1.1 200  X-RateLimit-Remaining: 2 
carol #4 via :8080  HTTP/1.1 200  X-RateLimit-Remaining: 1 
carol #5 via :8081  HTTP/1.1 200  X-RateLimit-Remaining: 0 
carol #6 via :8080  HTTP/1.1 429  X-RateLimit-Remaining: 0 
Five requests go through, split across the two instances, and the sixth is refused no matter which one it lands on. With an in-memory store each instance would have allowed five, ten in total.
# what Redis holds
$ redis-cli --scan
carol
$ redis-cli pttl carol  (time to live in ms; the bucket expires once it would be full again)
positive TTL, as expected
Redis holds the bucket under the plain key carol, with a time-to-live, so idle buckets do not pile up.
Trap: the Redis key is exactly what your key resolver returns. There is no namespace. If another application, or another route with a different limit, uses the same Redis and the same key text, they will share and corrupt each other’s buckets. Return something like "limited:" + apiKey from the resolver. I observed the bare key; I did not test two routes colliding.
Going one level deeper: choosing the key, and what a null key means The key function is the most important line of the whole filter. Using the client address punishes everyone behind one office NAT; using the API key or the authenticated principal is fairer, and the reference page uses the principal name. A null key means 403 by default, which is the right fail-safe for an unauthenticated route but a surprising one if you forgot that some clients do not send the header. Per the reference page, the key resolver can currently be set only through the Java DSL, not through properties, which is why this route is not in the YAML. Bucket capacity and period are plain numbers here (5 and 10 s); the filter also exposes tokens-per-request, the status code returned when refused (429 by default) and the name of the remaining-tokens header (X-RateLimit-Remaining by default). For a deeper treatment of the algorithms themselves, and a servlet-filter version, see the two existing posts below.

When the backend or the store misbehaves, the caller gets a bare 500

The happy path is short. The days get lost in these four failures, so each one is reproduced by scripts/run-all.sh and quoted from output/05-failure-modes.txt.

A slow backend becomes a 500, not a 504

With spring.http.clients.read-timeout=1s and a backend that sleeps 3 seconds, the client sees an anonymous 500 and the log carries the real cause:
## A. read timeout: spring.http.clients.read-timeout=1s, backend sleeps 3s
$ curl -i localhost:8080/api/slow?ms=3000
HTTP/1.1 500 
Content-Type: application/json

{"timestamp":"2026-11-25T19:23:31.069Z","status":500,"error":"Internal Server Error","path":"/api/slow"}

# log line behind that 500:
Request processing failed: org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:9091/slow"
A 504 Gateway Timeout is the honest answer, and it is one onError away. The slow-mapped route maps the ResourceAccessException to a 504 with a small JSON body:
            .and(route("slow-mapped")
                .GET("/api/slow-mapped", http())
                .before(uri(upstream))
                .before(setPath("/slow"))
                // a read timeout surfaces as ResourceAccessException; without this it becomes a bare 500
                .onError(ResourceAccessException.class, (e, request) -> ServerResponse
                        .status(HttpStatus.GATEWAY_TIMEOUT)
                        .body(Map.of("error", "upstream did not answer in time")))
                .build())
Result (output/05-failure-modes.txt, section B):
## B. same timeout, route with onError(ResourceAccessException) mapped to 504
$ curl -i localhost:8080/api/slow-mapped?ms=3000
HTTP/1.1 504 
Content-Type: application/json

{"error":"upstream did not answer in time"}

Redis goes down and every limited request hangs

Without a timeout on the filter, a Redis outage does not produce an error; it produces silence. The client below gave up after 5 seconds with no response at all (HTTP code 000 is curl for “nothing came back”): Section C of output/05-failure-modes.txt:
## C. Redis stops while the gateway is up; no timeout configured on rateLimit()
$ curl --max-time 5 -H 'X-Api-Key: dave' localhost:8080/api/limited
curl exit after 5.001396s, http_code=000

Set a timeout and you get a fast 500 instead, and it recovers on its own

setTimeout on the filter bounds how long it waits for the store. With 300 ms the failure is fast, and when Redis returns the next request succeeds without restarting the gateway: Section D of output/05-failure-modes.txt; the property is read in src/main/java/com/ankurm/gwmvc/RoutesConfig.java:
## D. same outage, with demo.rl-timeout=300ms (setTimeout on the filter)
$ curl -H 'X-Api-Key: dave' localhost:8080/api/limited
http_code=500 time_total_under_1s=yes
# log line behind that 500:
Request processing failed: java.util.concurrent.TimeoutException
# Redis back: the next request works again, no restart needed
http_code=200
Note what this does: the limiter fails closed. While Redis is down, every limited route returns 500. Whether that is right depends on your system. If rate limiting protects a fragile backend, failing closed is safer; if the limiter is a courtesy, you would rather let requests through, and that needs your own code around the filter. I did not build the fail-open variant.

No store bean at all

Forget the AsyncProxyManager bean and the application starts normally, then fails on the first limited request: Section E of output/05-failure-modes.txt:
## E. no AsyncProxyManager bean at all (--demo.store=none)
$ curl -i -H 'X-Api-Key: erin' localhost:8080/api/limited
HTTP/1.1 500 
Content-Type: application/json

{"timestamp":"2026-11-25T19:24:09.127Z","status":500,"error":"Internal Server Error","path":"/api/limited"}

# log line behind that 500:
Request processing failed: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'io.github.bucket4j.distributed.proxy.AsyncProxyManager<?>' available
That is the worst kind of failure: a green startup and a broken route. A smoke test that sends one request through every limited route would catch it.
Going one level deeper: how to read these failures Every one of these ends as HTTP 500 with the same Spring Boot error body, so the status code tells you nothing; the exception class in the log is the real signal. ResourceAccessException means the HTTP client to the backend failed (timeout, connection refused). A TimeoutException from the rate limiter means the store did not answer in time. NoSuchBeanDefinitionException for AsyncProxyManager means the store bean is missing. RetryException means the retry filter gave up. Mapping each of these to a precise status is the same technique as the 504 above: an onError per exception type on the route. Whether to centralise that is a design choice I did not explore.

Should you use Server MVC instead of the reactive gateway?

Probably yes if your team writes servlet code, with two conditions. First, check that every filter you need exists. The navigation of the 5.1.0 reference lists roughly 35 Server MVC filters and, compared with the reactive gateway, shows no page for SaveSession, SecureHeaders or JsonToGrpc, and no pages for default filters, global filters, CORS configuration or an actuator API. That is the navigation of the reference as I read it, not a tested feature matrix, so check your own list. Second, decide what your limiter does when its store is down; the default is to fail closed with a 500. If you already run the reactive gateway happily, nothing here is a reason to migrate on its own.
The case for Server MVC is not raw speed. It is that routing code, filters and stack traces look like the rest of your Spring MVC services, that you can debug with an ordinary debugger, and that virtual threads remove the thread-pool ceiling that used to push people toward WebFlux. The case against is a smaller filter catalogue and a younger ecosystem of answers.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.