A rate-limiting filter in Spring MVC is a servlet filter that counts requests per client (usually per IP address or API key) and answers with HTTP 429 Too Many Requests once the client exceeds its quota. Extend OncePerRequestFilter, keep a counter or token bucket per client, and register the filter as a Spring bean. For production use a library such as Bucket4j, and a shared store such as Redis when you run more than one instance.
You can limit traffic at an API gateway, a reverse proxy such as NGINX, or inside the application. A filter in the application is useful when limits depend on application data (user, plan, endpoint) or when you have no gateway. A filter runs before the DispatcherServlet, so rejected requests never reach your controllers.
Common algorithms:
| Algorithm | Behaviour | Trade-off |
|---|---|---|
| Fixed window | N requests per time window | Simple, but allows bursts at window edges |
| Sliding window | Counts requests over a moving period | Smoother, more state |
| Token bucket | Tokens refill at a steady rate, bursts allowed up to capacity | Most widely used |
This version is dependency-free and easy to read. It keeps one counter per client in memory.
Because the class is a @Component and extends OncePerRequestFilter, Spring Boot registers it automatically for all requests. The 101st request in a minute gets:
This sketch has two weaknesses: the map grows forever because old entries are never removed, and the counters live in one JVM. Add a scheduled cleanup (or use a Caffeine cache with expireAfterAccess) and use a shared store for multiple instances.
Bucket4j implements token buckets correctly and supports distributed backends. Add the com.bucket4j:bucket4j_jdk17-core dependency (check Maven Central for the current version) and create one bucket per key.
The bucket allows bursts of 20 requests and refills 10 tokens per second. The builder API above is the current Bucket4j style; older tutorials use Bandwidth.classic, which is deprecated.
To apply the filter to selected paths, override shouldNotFilter:
Alternatively, register it with a FilterRegistrationBean and call addUrlPatterns("/api/*"). If you use Spring Security, place the filter relative to the security chain with http.addFilterBefore(...) so that limits apply to unauthenticated requests too.
getRemoteAddr() returns the proxy address. Configure server.forward-headers-strategy=framework so Spring resolves the real client IP, and only trust forwarded headers from your own proxy.429 with a Retry-After header and log or count rejections in your metrics.RequestRateLimiter filter if you already run a gateway.Return 429 Too Many Requests and include a Retry-After header so clients know when to try again.
A servlet filter runs earlier and rejects requests before Spring MVC handler mapping. An interceptor has access to handler details such as annotations, which helps when limits are declared per endpoint.
Not accurately: each instance counts separately, so the effective limit is multiplied. Use a shared store such as Redis.
It helps against abusive clients, but large attacks should be stopped upstream by a CDN, a web application firewall or the load balancer.
Implement rate limiting in Spring MVC with a OncePerRequestFilter that tracks a counter or token bucket per client and returns 429 with Retry-After when the quota is used up. Use Bucket4j instead of hand-rolled counters, resolve the real client address behind proxies, and use shared storage when the application runs on several instances.