GuardAPI Logo
GuardAPI

Fix API Rate Limit Exhaustion in Micronaut

API Rate Limit Exhaustion allows attackers to spam endpoints, leading to DoS or brute-force success. Micronaut doesn't have a built-in global rate limiter in the core, so leaving controllers unprotected is a massive oversight. We'll use a custom HttpFilter coupled with the Token Bucket algorithm to drop abusive traffic at the edge.

The Vulnerable Pattern

@Controller("/api")
public class UnprotectedController {
    @Get("/resource")
    public String getResource() {
        // No throttling logic here. An attacker can hit this 10k times per second
        // and exhaust thread pools or database connections.
        return "Data delivered.";
    }
}

The Secure Implementation

The vulnerable code lacks any request policing, allowing an adversary to saturate the application's resources. The secure implementation introduces a 'RateLimitFilter' which intercepts every request to the '/api' path. It identifies the client via their IP address and associates them with a 'Bucket' (using the Bucket4j library). We implement a Token Bucket strategy: the client gets 5 tokens per minute. Each request consumes one token; once the bucket is empty, the filter short-circuits the request and returns a 429 Too Many Requests status, preventing the request from ever reaching the controller logic.

@Filter("/api/**")
public class RateLimitFilter implements HttpServerFilter {
    private final Map buckets = new ConcurrentHashMap<>();
private Bucket createNewBucket() {
    return Bucket.builder()
        .addLimit(Bandwidth.classic(5, Refill.intervally(5, Duration.ofMinutes(1))))
        .build();
}

@Override
public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request, ServerFilterChain chain) {
    String remoteAddr = request.getRemoteAddress().getAddress().getHostAddress();
    Bucket bucket = buckets.computeIfAbsent(remoteAddr, k -> createNewBucket());

    if (bucket.tryConsume(1)) {
        return chain.proceed(request);
    }

    return Publishers.just(HttpResponse.status(HttpStatus.TOO_MANY_REQUESTS)
                     .body("Rate limit exceeded. Slow down, hacker."));
}

}

System Alert • ID: 1656
Target: Micronaut API
Potential Vulnerability

Your Micronaut API might be exposed to API Rate Limit Exhaustion

74% of Micronaut apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.