Logo InterviewVault

Welcome back, Sujit Kumar Mishra

SKM

Revision Mode

Document technical questions and best-practice answers.

Cancel

REST API Rate Limiting

You have developed a REST API endpoint, and you need to restrict it so that no user/client can call the endpoint more than 10 times per second. If someone tries to access the API more than the allowed limit, the request should be blocked.


Question:

How would you implement this rate-limiting mechanism in a Spring Boot REST API? Explain the approach and technologies/libraries you would use.

To implement rate limiting in a Spring Boot REST API so that no user/client can call the endpoint more than 10 times per second, follow these simple steps:


1: Use a Rate Limiting Library

The easiest way is to use a library like Bucket4j or resilience4j. These libraries help you set limits without writing complex code.


2: How It Works

- For each user/client, you create a “bucket” that allows a maximum of 10 requests per second.

- Every time a user makes a request, the bucket checks if the limit is reached.

- If the bucket is empty (more than 10 requests in a second), the request is blocked.


3: Implementation Steps (with Bucket4j example)

- Add Bucket4j dependency in your pom.xml.

- Use a filter or interceptor to check the rate limit before processing the request.

- Identify the user/client (e.g., by IP address or API key).

- If the limit is exceeded, return HTTP 429 (Too Many Requests).


Sample Code:

// Add Bucket4j dependency
// In your filter/interceptor:
Bucket bucket = Bucket4j.builder()
    .addLimit(Bandwidth.simple(10, Duration.ofSeconds(1)))
    .build();

if (bucket.tryConsume(1)) {
    // Allow request
} else {
    // Block request, return 429 error
}


Summary:

1: Use Bucket4j or resilience4j for simple rate limiting.

2: Set 10 requests per second per user.

3: Block requests exceeding the limit with HTTP 429.

Ready for commit