Implementing Interface Rate Limiting with Spring Interceptor and Redis (Demo)
This article demonstrates a step‑by‑step implementation of API request throttling in a Spring backend using an Interceptor and Redis, covering the underlying principle, configurable limits, custom annotations, reflection‑based flexibility, and practical considerations such as path parameters and real‑IP handling.
The article presents a demo that implements interface rate limiting (anti‑brush) by using a Spring HandlerInterceptor together with Redis to track request frequencies.
The core idea is to concatenate the client IP address and request URI to form a unique key, then intercept each request, retrieve the access count from Redis, and block the request when the configured threshold is exceeded.
The main interceptor code ( AccessLimintInterceptor) declares a RedisTemplate<String, Object>, reads configuration values ( second, time, lockTime) via @Value, defines lock and count key prefixes, and implements the preHandle method that performs the counting, locking, and exception throwing logic.
Configuration parameters allow dynamic adjustment of the time window, maximum allowed accesses, and lock duration, while the lock key prevents further access during the lock period.
Testing screenshots illustrate normal access and excessive‑access scenarios, confirming that the interceptor correctly limits requests.
To achieve per‑endpoint flexibility, the author proposes two solutions: configuring interceptor mapping rules for specific URLs, or defining a custom annotation ( @AccessLimit) that can be placed on controller classes or methods. The interceptor is then enhanced to read the annotation via reflection, allowing different second, maxTime, and forbiddenTime values per endpoint.
The article also discusses limitations of the sliding‑window logic, issues with path‑parameter‑based URIs (which can cause distinct requests to be treated as different keys), and suggests using method names or class‑method combinations as alternative identifiers.
Finally, it notes that request.getRemoteAddr() may not return the real client IP when behind proxies, and hints at using forwarded‑header techniques for accurate IP detection.
Overall, the piece provides a comprehensive guide for backend developers to implement configurable, annotation‑driven API rate limiting in Spring applications.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
