Skip to content

Cookbook

frosxt edited this page Jan 19, 2026 · 1 revision

Cookbook

This page provides code snippets for common rate limiting patterns.

API Rate Limiting (Per IP)

Protect a REST API by limiting each IP address to 10 requests per second.

// Define the limit: 10 req/s
TokenBucketSpec apiRule = TokenBucketSpec.builder()
    .capacity(10)
    .refillTokens(10)
    .refillPeriod(Duration.ofSeconds(1))
    .build();

// Expire keys after 1 hour of inactivity to save memory
KeyedStoreSpec<String> storeConfig = KeyedStoreSpec.<String>builder()
    .evictionPolicy(EvictionPolicy.EXPIRE_AFTER_ACCESS)
    .expireAfterAccess(Duration.ofHours(1))
    .build();

KeyedRateLimiter<String> ipLimiter = BucketGuards.keyedTokenBucket(apiRule, storeConfig);

// In your request filter/handler:
public void handleRequest(Request req, Response res) {
    String ip = req.getRemoteAddr();
    
    if (ipLimiter.tryAcquire(ip).granted()) {
        next.handle(req, res);
    } else {
        res.status(429);
        res.send("Too Many Requests");
    }
}

Database Protection (Global)

Prevent your application from overwhelming a database by limiting the total number of expensive queries per second.

// Allow 50 queries/sec, with a burst up to 100
TokenBucketSpec dbRule = TokenBucketSpec.builder()
    .capacity(100)
    .refillTokens(50)
    .refillPeriod(Duration.ofSeconds(1))
    .build();

RateLimiter queryLimiter = BucketGuards.tokenBucket(dbRule);

public Data queryDatabase() {
    // Blocks the thread if limits are exceeded, smoothing the load
    queryLimiter.acquire(); 
    return database.executeComplexQuery();
}

Login Brute-Force Protection

Limit failed login attempts per user account.

// 5 attempts allowed immediately. Refills 1 attempt every 30 minutes.
TokenBucketSpec loginRule = TokenBucketSpec.builder()
    .capacity(5)
    .refillTokens(1)
    .refillPeriod(Duration.ofMinutes(30))
    .build();

KeyedRateLimiter<String> loginLimiter = BucketGuards.keyedTokenBucket(loginRule, KeyedStoreSpec.builder().build());

public void login(String username, String password) {
    // Rate limit the attempts
    if (!loginLimiter.tryAcquire(username).granted()) {
        throw new SecurityException("Too many login attempts. Please wait.");
    }
    
    authService.authenticate(username, password);
}

Clone this wiki locally