Skip to content

feat(rate-limiter): implement sliding window rate limiting algorithm#187

Merged
halvaradop merged 3 commits into
masterfrom
feat/add-sliding-window-alg
Jun 10, 2026
Merged

feat(rate-limiter): implement sliding window rate limiting algorithm#187
halvaradop merged 3 commits into
masterfrom
feat/add-sliding-window-alg

Conversation

@halvaradop

@halvaradop halvaradop commented Jun 10, 2026

Copy link
Copy Markdown
Member

Description

This pull request implements the Sliding Window rate-limiting algorithm.

The algorithm can be used through the centralized createRateLimiter API or directly via the dedicated createSlidingWindowAlgorithm function.

Unlike the Fixed Window algorithm, Sliding Window evaluates requests over a continuously moving time window, providing more accurate rate limiting and reducing traffic spikes that can occur at window boundaries.

Usage with createRateLimiter

import {
  createRateLimiter,
  createMemoryStorage,
} from "@aura-stack/rate-limiter"

const limiter = createRateLimiter({
  storage: createMemoryStorage(),
  rules: {
    signIn: {
      algorithm: "sliding-window",
      limit: 10,
      windowMs: 60_000,
      keyGenerator: (req: Request) =>
        req.headers.get("x-forwarded-for") ?? "unknown",
    },
  },
})

await limiter.signIn.check(
  new Request("http://incoming.request")
)

Direct Usage

import {
  createSlidingWindowAlgorithm,
  createMemoryStorage,
} from "@aura-stack/rate-limiter"

const signInLimiter = createSlidingWindowAlgorithm({
  algorithm: "sliding-window",
  limit: 10,
  windowMs: 60_000,
  storage: createMemoryStorage(),
  keyGenerator: (req: Request) =>
    req.headers.get("x-forwarded-for") ?? "unknown",
})

await signInLimiter.check(
  new Request("http://incoming.request")
)

Features

  • Sliding Window rate-limiting algorithm
  • Integration with createRateLimiter
  • Direct usage through createSlidingWindowAlgorithm
  • More accurate request counting across time windows
  • Reduced boundary spikes compared to Fixed Window
  • Compatible with all supported storage adapters
  • Custom request key generation
  • Configurable request limits and window durations

@vercel

vercel Bot commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
auth Skipped Skipped Jun 10, 2026 9:10pm

@coderabbitai

coderabbitai Bot commented Jun 10, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@halvaradop, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 50 minutes and 23 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 69b10ffa-0e65-4682-b26d-12d3203382b9

📥 Commits

Reviewing files that changed from the base of the PR and between 1f10a08 and 2b91989.

📒 Files selected for processing (3)
  • packages/rate-limiter/CHANGELOG.md
  • packages/rate-limiter/src/rate-limiter.ts
  • packages/rate-limiter/test/algorithms/sliding-window.test.ts
📝 Walkthrough

Walkthrough

This PR adds a new sliding-window rate-limiting algorithm to the rate-limiter package. The implementation uses dual buckets (current and previous) to efficiently estimate rolling-window request counts with O(1) complexity, supporting both mutating checks and non-mutating peeks. Type definitions, integration logic, and comprehensive tests complete the feature.

Changes

Sliding-window rate-limiting algorithm

Layer / File(s) Summary
Rate-limiter type contracts
packages/rate-limiter/src/types.ts
AlgorithmType adds "sliding-window". FixedWindowRule and LeakyBucketRule convert from type aliases to interfaces. New SlidingWindowRule interface with algorithm: "sliding-window", limit, and windowMs fields. RateLimiterRule union updated to include SlidingWindowRule.
Sliding-window algorithm implementation
packages/rate-limiter/src/algorithms/sliding-window.ts, packages/rate-limiter/src/algorithms/index.ts
createSlidingWindowAlgorithm factory implements O(1) dual-bucket algorithm with estimate function computing interpolated rolling counts. check() increments current bucket with windowMs * 2 TTL, computes ok vs limit, returns remaining/resetAt/retryAfter. peek() estimates without mutating storage. Module export from algorithms index.
Rate-limiter integration
packages/rate-limiter/src/rate-limiter.ts
Import expanded to include createSlidingWindowAlgorithm. buildAlgorithm switch adds "sliding-window" case instantiating the algorithm. resetKeys switch adds case encoding time-bucket keys from rule.windowMs and current timestamp.
Test suite for sliding-window algorithm
packages/rate-limiter/test/algorithms/sliding-window.test.ts
Vitest suite with fake timers and memory storage fixture. Peek suite validates non-consuming behavior, window carryover, expiration, per-key tracking, and boundary conditions. Check suite verifies allow/block enforcement, retryAfter timing, immediate consumption, and overflow blocking.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • aura-stack-ts/auth#131: Introduced the initial @aura-stack/rate-limiter package with token-bucket algorithm; this PR extends the public algorithm API with sliding-window support using the same type union and algorithm export patterns.

Suggested labels

feature

Poem

🐰 A rabbit hops through time's sliding glass,
Counting moments as the windows pass,
Two buckets spinning—current, prior bright,
Rates stay smooth through quantum flight!
O(1) magic makes limiting light. ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the primary change: implementing a sliding window rate limiting algorithm in the rate-limiter package.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/add-sliding-window-alg

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/rate-limiter/test/algorithms/sliding-window.test.ts (1)

12-17: ⚡ Quick win

Consider restoring real timers in afterEach to prevent test pollution.

Adding vi.useRealTimers() ensures fake timers don't leak into other test files if test order changes.

♻️ Suggested addition
     beforeEach(() => {
         storage = createMemoryStorage()

         vi.useFakeTimers()
         vi.setSystemTime(0)
     })
+
+    afterEach(() => {
+        vi.useRealTimers()
+    })
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/rate-limiter/test/algorithms/sliding-window.test.ts` around lines 12
- 17, Add an afterEach block to restore real timers to avoid leaking fake timers
across tests: after the existing beforeEach that calls vi.useFakeTimers() and
vi.setSystemTime(0), add an afterEach that calls vi.useRealTimers() (and
optionally resets system time) so the fake timers set up in the beforeEach for
these sliding-window tests using createMemoryStorage() are cleaned up after each
test.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/rate-limiter/src/rate-limiter.ts`:
- Around line 38-39: The resetKeys implementation for the "sliding-window" case
is producing the wrong bucket timestamps and only returning one key; update
resetKeys to compute the current bucket using rule.windowMs (same formula as in
sliding-window.ts, i.e., floor(Date.now() / rule.windowMs) * rule.windowMs) and
also include the previous bucket (currentBucket - rule.windowMs), returning both
keys like `${key}:sw:${currentBucket}` and `${key}:sw:${previousBucket}` so
reset() deletes both buckets.

---

Nitpick comments:
In `@packages/rate-limiter/test/algorithms/sliding-window.test.ts`:
- Around line 12-17: Add an afterEach block to restore real timers to avoid
leaking fake timers across tests: after the existing beforeEach that calls
vi.useFakeTimers() and vi.setSystemTime(0), add an afterEach that calls
vi.useRealTimers() (and optionally resets system time) so the fake timers set up
in the beforeEach for these sliding-window tests using createMemoryStorage() are
cleaned up after each test.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: df52e74e-feb4-494d-b721-1a870d3660d2

📥 Commits

Reviewing files that changed from the base of the PR and between 947b5f0 and 1f10a08.

📒 Files selected for processing (11)
  • packages/elysia/package.json
  • packages/express/package.json
  • packages/hono/package.json
  • packages/next/package.json
  • packages/rate-limiter/src/algorithms/index.ts
  • packages/rate-limiter/src/algorithms/sliding-window.ts
  • packages/rate-limiter/src/rate-limiter.ts
  • packages/rate-limiter/src/types.ts
  • packages/rate-limiter/test/algorithms/sliding-window.test.ts
  • packages/react-router/package.json
  • packages/react/package.json

Comment thread packages/rate-limiter/src/rate-limiter.ts Outdated
@halvaradop halvaradop merged commit 9a8fb34 into master Jun 10, 2026
4 of 5 checks passed
@halvaradop halvaradop deleted the feat/add-sliding-window-alg branch June 10, 2026 21:10
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