Throttling Spring Boot APIs with token buckets
Implementing rate limiting in a Spring Boot REST API caps how often a caller can send requests during a defined period. It protects application threads, database connections and downstream payment services from traffic bursts while returning a predictable HTTP 429 response when a quota is exhausted.
The caller identity matters as much as the counter. Australian mobile networks often place subscribers behind carrier-grade NAT, so an IP-only policy can accidentally throttle unrelated users in Sydney, Melbourne and regional centres. A verified API key or authenticated account identifier usually provides a fairer limit than request.getRemoteAddr().
For Australian retailers and SaaS products, the policy must survive peak sale periods, multi-region deployments and privacy obligations. ACSC security guidance supports throttling abusive authentication attempts, while request logs should follow the Australian Privacy Act by retaining only information needed for security and service analysis.
Why request quotas belong in the API
Rate limiting provides traffic control rather than merely improving performance. A fixed request quota limits total calls, while a concurrency limit controls how much work can remain in progress. Payment, report-generation and search endpoints may require different combinations of both controls.
Clients must treat a 429 response as a temporary condition. They should read the Retry-After header, pause for the specified interval and retry with exponential backoff and jitter. This avoids a thundering herd when a popular Australian promotion causes many mobile clients to reach the service simultaneously.
Selecting a throttling algorithm
Fixed-window counters are simple but allow a double burst around each window boundary. Sliding-window logs provide smoother limits at the cost of additional storage. Token buckets offer a practical balance: tokens refill at a steady rate, unused capacity accumulates and each request consumes one token.
A library-based implementation is demonstrated in the Bucket4j integration guide. Start with a token bucket, define separate capacities for authentication and transactional endpoints, and keep the policy consistent with the limits advertised to API consumers.
Building the Spring Boot filter
A Spring OncePerRequestFilter can resolve the client, consume a token and reject excess traffic before it reaches a controller. Health checks and preflight requests may need exemptions.
@Component
public class RateLimitFilter extends OncePerRequestFilter {
private final ConcurrentMap<String, Bucket> buckets =
new ConcurrentHashMap<>();
private Bucket createBucket() {
Bandwidth limit = Bandwidth.classic(
100,
Refill.greedy(100, Duration.ofMinutes(1))
);
return Bucket.builder().addLimit(limit).build();
}
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain
) throws ServletException, IOException {
String key = clientKeyProvider.resolve(request);
Bucket bucket = buckets.computeIfAbsent(key, ignored -> createBucket());
ConsumptionProbe probe = bucket.tryConsumeAndReturnRemaining(1);
if (!probe.isConsumed()) {
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
response.setHeader("Retry-After", "1");
response.setContentType("application/json");
response.getWriter().write(
"{\"error\":\"rate_limit_exceeded\"}"
);
return;
}
response.setHeader(
"X-RateLimit-Remaining",
String.valueOf(probe.getRemainingTokens())
);
chain.doFilter(request, response);
}
}
The clientKeyProvider should return a stable, non-reversible identifier rather than storing raw API keys in memory. This local-bucket example also needs an eviction policy, such as Caffeine expiry, to prevent unused client keys accumulating indefinitely. Distributed deployments require shared state instead.
Sharing limits across instances
An in-memory bucket grants every application instance its own quota, so a client could multiply its allowance simply by reaching another pod. Australian deployments spanning Sydney and Melbourne cloud regions should use Redis or another shared store, with atomic Lua scripting or transactions to prevent concurrent requests from consuming the same token.
Use UTC for window metadata and expiry calculations. Daylight-saving changes in New South Wales and Victoria must not create uneven limits or reset a client’s quota early. Store only the hashed client identifier, quota key and minimal metadata, and set expiry periods according to the refill interval.
Shared limiter outages require an explicit policy. A public catalogue endpoint may fail open to preserve availability, while an authentication endpoint may fail closed to prevent abuse. Track rejection counts, remaining capacity and limiter latency without logging credentials or personal information.
Comparing approaches and planning rollout
The right mechanism depends on traffic distribution, consistency requirements and operational overhead. A framework annotation may suit a single service, while a gateway or shared store offers stronger control across a larger platform.
| Mechanism | Shared state | Main advantage | Main limitation |
|---|---|---|---|
| In-memory token bucket | Single JVM | Low latency and simple setup | Limits reset between instances |
| Resilience4j limiter | Single JVM | Spring integration and metrics | Requires another shared backend for distributed use |
| Redis token bucket | Shared | Consistent limits across pods | Adds network latency |
| API gateway quota | Gateway | Rejects traffic before the application | Has less route-specific context |
| Database counter | Shared | Durable and straightforward | Creates database load and slower requests |
Canary the selected policy with realistic load tests, including bursts, concurrent requests and clients spread across Australian mobile and fixed-line connections. Observe false rejections before enforcing stricter limits, then increase quotas gradually as latency and 429 rates remain stable.
- Define separate request quotas for authentication, search, checkout and reporting endpoints.
- Identify authenticated clients by API key or account, using a hashed IP only as a fallback.
- Configure token-bucket capacity and refill rates independently for each service tier.
- Use Redis-backed limits whenever more than one application instance handles the API.
- Return 429 responses with
Retry-After,X-RateLimit-Remainingand a consistent JSON error body. - Load-test burst traffic from Australian network conditions before gradually tightening production limits.