wasAsked.

Design rate limits for login, search, and authenticated write endpoints in Spring Boot.

CRED · Full Stack Developer · 3-4-years · technical

Published

Year not specified · Java, Spring Security, Authentication & Security

Community answers

Posted by wasAsked editorial collection

Each endpoint type has a different risk, so give each its own policy. Login - Threats: brute force and credential stuffing. - Limit by IP and by username separately (for example 5 attempts per minute per account, 20 per minute per IP), with progressive delays or temporary lockout after repeated failures. - Add CAPTCHA or step-up challenges after a few failures, and alert on spikes. - Use generic error messages so attackers cannot discover which usernames exist. Search - Threats: scraping and expensive queries. - Token bucket per user (or IP for anonymous users): allow short bursts while typing, cap sustained rates (for example 30 requests per 10 seconds). - Cache popular queries and debounce on the client. Authenticated writes - Limit per user ID rather than IP, since many users can share one IP (offices, mobile carriers). - Stricter limits for costly or abusable actions: sending invitations, password reset emails, posting content, payments. Implementation in Spring Boot - Bucket4j for token-bucket limiting, implemented in a servlet Filter or HandlerInterceptor, backed by Redis (bucket4j-redis integrations) so limits are shared across instances: Bucket bucket = proxyManager.builder().build("login:" + username, () -> BucketConfiguration.builder().addLimit(Bandwidth.builder().capacity(5).refillGreedy(5, Duration.ofMinutes(1)).build()).build()); if (!bucket.tryConsume(1)) { response.setStatus(429); response.setHeader("Retry-After", "60"); return; } - Or Resilience4j RateLimiter for per-instance limits. - At the edge: Spring Cloud Gateway's RequestRateLimiter with Redis, an API gateway (Kong, AWS API Gateway), a WAF or CDN rules. Spring Security integration - Apply login limiting before authentication processing (a filter placed before the authentication filter) and record failures from AuthenticationFailureBadCredentialsEvent. - Behind a proxy, configure forwarded headers correctly (server.forward-headers-strategy) so you limit the real client IP, and do not trust X-Forwarded-For from untrusted sources. Operations - Return 429 Too Many Requests with Retry-After; log and monitor rejections; tune limits from real traffic; exempt internal health checks; offer higher limits to trusted API clients by plan.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics