Skip to content

[12.x] Add sliding window algorithm support to rate limiter#59193

Open
SanderMuller wants to merge 2 commits intolaravel:12.xfrom
SanderMuller:feature/sliding-window-rate-limiter
Open

[12.x] Add sliding window algorithm support to rate limiter#59193
SanderMuller wants to merge 2 commits intolaravel:12.xfrom
SanderMuller:feature/sliding-window-rate-limiter

Conversation

@SanderMuller
Copy link
Contributor

Summary

Adds opt-in sliding window rate limiting to Laravel's rate limiter.
Fixed window limiting is susceptible to burst attacks at window boundaries.
A client can exhaust the limit at the end of one window and again at the start of the next, effectively doubling throughput in a short period.
Sliding window smooths this by weighting the previous window's count into the current calculation.

Formula

effectiveAttempts = floor(overlapRatio × previousWindowHits) + currentWindowHits

where overlapRatio = 1 - (elapsed / windowSize)

Usage

// Opt-in via fluent method on the existing Limit class
RateLimiter::for('api', function (Request $request) {
    return Limit::perMinute(60)
        ->by($request->user()?->id)
        ->slidingWindow();
});

Works with all existing Limit features: after() callbacks, response() callbacks, by() keys, and mixed limit arrays (fixed + sliding in the same limiter).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant