0
0
Rest APIprogramming~5 mins

Fixed window algorithm in Rest API

Choose your learning style9 modes available
Introduction

The fixed window algorithm helps control how many times someone can use an API in a set time. It stops too many requests all at once.

You want to limit users to 100 requests per minute to keep your server safe.
You want to stop a user from sending too many login attempts in a short time.
You want to make sure your API is fair and no one uses it too much.
You want to protect your service from accidental overload during busy times.
Syntax
Rest API
1. Set a fixed time window (like 1 minute).
2. Count requests in that window.
3. If count is below limit, allow request and increase count.
4. If count reaches limit, block requests until next window.
The window resets after the fixed time ends, starting count from zero again.
This method is simple but can cause bursts of requests at window edges.
Examples
This example shows a 1-minute window where only 10 requests are allowed.
Rest API
Window size: 60 seconds
Limit: 10 requests
Count requests from 12:00:00 to 12:00:59
If count < 10, allow request
At 12:01:00, reset count to 0
This example limits requests per hour for a bigger time window.
Rest API
Window size: 1 hour
Limit: 1000 requests
Count requests from 1:00 PM to 1:59 PM
Block requests after 1000 until 2:00 PM
Sample Program

This program creates a fixed window rate limiter that allows 3 requests every 10 seconds. It prints if each request is allowed or blocked.

Rest API
from time import time

class FixedWindowRateLimiter:
    def __init__(self, limit, window_size_seconds):
        self.limit = limit
        self.window_size = window_size_seconds
        self.window_start = int(time())
        self.request_count = 0

    def allow_request(self):
        current_time = int(time())
        if current_time - self.window_start >= self.window_size:
            self.window_start = current_time
            self.request_count = 0
        if self.request_count < self.limit:
            self.request_count += 1
            return True
        else:
            return False

# Example usage
limiter = FixedWindowRateLimiter(limit=3, window_size_seconds=10)

for i in range(5):
    allowed = limiter.allow_request()
    print(f"Request {i+1} allowed? {allowed}")
OutputSuccess
Important Notes

The fixed window algorithm is easy to understand and implement.

It can cause a burst of allowed requests at the edge of windows, which might be a problem for some uses.

For smoother control, other algorithms like sliding window can be used.

Summary

The fixed window algorithm limits requests in fixed time blocks.

It counts requests and blocks when the limit is reached.

It is simple but can allow bursts at window edges.