BBackend CourseLeroy Labs
0/0
Search the course

Rate limiting with sliding windows, token buckets & Bucket4j

Fixed window, sliding window and token bucket algorithms, per-IP vs per-user keys, 429 + Retry-After, the X-Forwarded-For spoofing trap, and moving from in-memory to Redis when you scale.

● advancedHostel-Web-AppReport-Manager-2IR3D (Kontentt)SperoTek (in dev)

Why

Rate limits protect against brute force (login, OTP), credential stuffing, scraping, accidental client loops, cost blow-ups (paid APIs, email sends) and denial of service.

Algorithms

Algorithm How Pros Cons
Fixed window Count per minute bucket Trivial A burst at the boundary gives 2× the limit
Sliding log Keep a timestamp per request; drop those older than the window Exact Memory per request
Sliding window counter Weighted blend of the current and previous window Close to exact, cheap Approximate
Token bucket A bucket of N tokens refilled at R per second; each request takes one Allows bursts, smooth refill Slightly more complex
Leaky bucket A queue drained at a constant rate Smooths traffic Adds latency

Sliding log, as in Hostel

Map<String, Deque<Long>> hits = new ConcurrentHashMap<>();

boolean allow(String key, int limit, long windowMs) {
    long now = System.currentTimeMillis();
    Deque<Long> q = hits.computeIfAbsent(key, k -> new ArrayDeque<>());
    synchronized (q) {
        while (!q.isEmpty() && now - q.peekFirst() > windowMs) q.pollFirst();
        if (q.size() >= limit) return false;
        q.addLast(now);
        return true;
    }
}

Token bucket with Bucket4j, as in SperoTek

Bucket bucket = Bucket.builder()
    .addLimit(limit -> limit.capacity(10).refillGreedy(10, Duration.ofMinutes(1)))
    .build();

ConsumptionProbe p = bucket.tryConsumeAndReturnRemaining(1);
if (!p.isConsumed()) {
    response.setStatus(429);
    response.setHeader("Retry-After", String.valueOf(p.getNanosToWaitForRefill() / 1_000_000_000));
}

In your projects

Hostel-Web-Appconfig/ratelimit/RateLimitingFilter.java

A per-IP sliding window over ConcurrentHashMap<String, Deque<Long>>. The limits are /api/auth/login 10, /api/auth/password-reset 5 and /api/users (signup) 8. It returns 429 with an ApiError. It’s registered with .addFilterBefore(new RateLimitingFilter(), JwtAuthenticationFilter.class) and is deliberately not a @Component, so @WebMvcTest slices don’t pick it up. The Javadoc already notes that “Redis/Bucket4j would be needed to scale out”.

The analysis found it took the client IP from the first X-Forwarded-For value, which the client controls, so an attacker could send X-Forwarded-For: 1.2.3.(random) with every request and never hit the limit. Fixed in Hostel PR #1: the filter now uses request.getRemoteAddr() with server.forward-headers-strategy: native, so Tomcat resolves the real IP and trusts only private-network proxies such as the ALB.

SperoTek (in dev)shared/ratelimit/Bucket4jRateLimiter · RateLimitSecurityContributor · RateLimitProperties

Tiered buckets (auth, session, anonymous, standard, reporting), each configured from the environment. The bucket map is cleaned every minute by @Scheduled. Retry-After is exposed through CORS so the SPA can show “try again in 30 s”. Reports get their own tier because they are expensive.

IR3D (Kontentt)LinkPreviewController.java:48

A targeted limit on link preview, which makes outbound HTTP calls, so abuse would turn your server into a scraping proxy. It throws RateLimitExceededException("error.linkPreviewRateLimited"), which is translated through i18n.

Report-Manager-2PasswordResetService

One reset request per minute per email. The key is the email rather than the IP, which also protects victims from inbox flooding.

Scaling out

In-memory buckets are per instance. With three instances behind a load balancer, the effective limit is 3×, and it resets on every deploy.

Option Notes
In-memory (yours) Fine for a single instance
Bucket4j + Redis / Postgres (JCache, Lettuce, JDBC backends) Shared counters
API gateway / edge (Cloudflare Rate Limiting, AWS WAF, Nginx limit_req) Stops abuse before it reaches the JVM
Resilience4j RateLimiter Limits outbound calls to third-party APIs
  • Choosing keys: IP, user id, API token, email, or a combination like (route + user).
  • Return headers: RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset (IETF draft) and Retry-After.
  • Memory bound. Evict idle keys, as SperoTek’s scheduler does, or an attacker can grow the map until you run out of memory.

Check yourself

1. Hostel limiter reads the first X-Forwarded-For entry. Risk?
2. Which algorithm naturally allows short bursts while enforcing an average rate?
3. 3 instances, in-memory limit 10/min each. Effective limit?