Repository navigation
fix: schedule bounded cleanup of expired rate-limit buckets #301
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
amanthanvi
wants to merge
2
commits into
main
Choose a base branch
from
cursor/schedule-rate-limit-cleanup-8c8b
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| import { cronJobs } from "convex/server"; | ||
| import { internal } from "./_generated/api"; | ||
| import { CLEANUP_BATCH_LIMIT, CLEANUP_FOLLOWUP_LIMIT } from "./rateLimit"; | ||
|
|
||
| const crons = cronJobs(); | ||
|
|
||
| // Bucket keys embed the client identifier. Expired rows are removed on this | ||
| // one-minute schedule, in bounded batches. A backlog larger than one wave | ||
| // continues on the next tick rather than inside a single transaction. | ||
| crons.interval( | ||
| "delete expired rate limit buckets", | ||
| { minutes: 1 }, | ||
| internal.rateLimit.cleanupExpired, | ||
| { | ||
| maxBuckets: CLEANUP_BATCH_LIMIT, | ||
| followupsRemaining: CLEANUP_FOLLOWUP_LIMIT, | ||
| }, | ||
| ); | ||
|
|
||
| export default crons; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,163 @@ | ||
| /// <reference types="vite/client" /> | ||
| import { convexTest } from "convex-test"; | ||
| import { afterEach, describe, expect, it, vi } from "vitest"; | ||
| import { internal } from "./_generated/api"; | ||
| import rateLimitCrons from "./crons"; | ||
| import { | ||
| CLEANUP_BATCH_DEFAULT, | ||
| CLEANUP_BATCH_LIMIT, | ||
| CLEANUP_FOLLOWUP_LIMIT, | ||
| cleanupExpired, | ||
| } from "./rateLimit"; | ||
| import schema from "./schema"; | ||
|
|
||
| const modules = import.meta.glob("./**/*.ts"); | ||
|
|
||
| function harness() { | ||
| return convexTest(schema, modules); | ||
| } | ||
|
|
||
| function freezeNow() { | ||
| const now = Date.now(); | ||
| vi.useFakeTimers({ now }); | ||
| return now; | ||
| } | ||
|
|
||
| async function seedBuckets( | ||
| t: ReturnType<typeof harness>, | ||
| rows: Array<{ key: string; expiresAt: number }>, | ||
| ) { | ||
| await t.run(async (ctx) => { | ||
| for (const row of rows) { | ||
| await ctx.db.insert("rateLimitBuckets", { | ||
| key: row.key, | ||
| count: 1, | ||
| expiresAt: row.expiresAt, | ||
| }); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| async function remainingKeys(t: ReturnType<typeof harness>) { | ||
| const rows = await t.run(async (ctx) => ctx.db.query("rateLimitBuckets").take(CLEANUP_BATCH_LIMIT + 5)); | ||
| return rows.map((row) => row.key).sort(); | ||
| } | ||
|
|
||
| afterEach(() => { | ||
| vi.useRealTimers(); | ||
| }); | ||
|
|
||
| describe("expired rate-limit cleanup", () => { | ||
| it("stays internal and is scheduled every minute with a bounded batch", () => { | ||
| const registered = cleanupExpired as { isInternal?: boolean; isPublic?: boolean }; | ||
| expect(registered.isInternal).toBe(true); | ||
| expect(registered.isPublic).toBeUndefined(); | ||
|
|
||
| expect(Object.keys(rateLimitCrons.crons)).toEqual(["delete expired rate limit buckets"]); | ||
| expect(rateLimitCrons.crons["delete expired rate limit buckets"]).toEqual({ | ||
| name: "rateLimit:cleanupExpired", | ||
| args: [{ maxBuckets: CLEANUP_BATCH_LIMIT, followupsRemaining: CLEANUP_FOLLOWUP_LIMIT }], | ||
| schedule: { type: "interval", minutes: 1 }, | ||
| }); | ||
| }); | ||
|
|
||
| it("deletes expired identifier keys and keeps buckets still inside the window", async () => { | ||
| const now = freezeNow(); | ||
| const t = harness(); | ||
| await seedBuckets(t, [ | ||
| { key: "rl:page:203.0.113.8:1", expiresAt: now - 1_000 }, | ||
| { key: "rl:search:203.0.113.8:1", expiresAt: now - 60_000 }, | ||
| { key: "rl:page:203.0.113.9:2", expiresAt: now + 60_000 }, | ||
| ]); | ||
|
|
||
| expect(await t.mutation(internal.rateLimit.cleanupExpired, { followupsRemaining: 0 })).toEqual({ | ||
| deleted: 2, | ||
| hasMore: false, | ||
| scheduledFollowup: false, | ||
| }); | ||
| expect(await remainingKeys(t)).toEqual(["rl:page:203.0.113.9:2"]); | ||
| }); | ||
|
|
||
| it("does not schedule another batch when the last page is exactly full", async () => { | ||
| const now = freezeNow(); | ||
| const t = harness(); | ||
| await seedBuckets(t, [ | ||
| { key: "rl:page:203.0.113.1:1", expiresAt: now - 1 }, | ||
| { key: "rl:page:203.0.113.2:1", expiresAt: now - 1 }, | ||
| ]); | ||
|
|
||
| expect(await t.mutation(internal.rateLimit.cleanupExpired, { | ||
| maxBuckets: 2, | ||
| followupsRemaining: CLEANUP_FOLLOWUP_LIMIT, | ||
| })).toEqual({ deleted: 2, hasMore: false, scheduledFollowup: false }); | ||
| expect(await remainingKeys(t)).toEqual([]); | ||
| }); | ||
|
|
||
| it("drains a backlog across scheduled batches and leaves the live bucket", async () => { | ||
| const now = freezeNow(); | ||
| const t = harness(); | ||
| await seedBuckets(t, [ | ||
| ...[1, 2, 3, 4, 5].map((octet) => ({ | ||
| key: `rl:page:203.0.113.${octet}:1`, | ||
| expiresAt: now - 5_000, | ||
| })), | ||
| { key: "rl:search:203.0.113.9:2", expiresAt: now + 30_000 }, | ||
| ]); | ||
|
|
||
| expect(await t.mutation(internal.rateLimit.cleanupExpired, { maxBuckets: 2 })).toEqual({ | ||
| deleted: 2, | ||
| hasMore: true, | ||
| scheduledFollowup: true, | ||
| }); | ||
| await t.finishAllScheduledFunctions(() => { | ||
| vi.runAllTimers(); | ||
| }); | ||
| expect(await remainingKeys(t)).toEqual(["rl:search:203.0.113.9:2"]); | ||
| }); | ||
|
|
||
| it("stops chaining when the follow-up budget is exhausted", async () => { | ||
| const now = freezeNow(); | ||
| const t = harness(); | ||
| await seedBuckets(t, [1, 2, 3, 4, 5].map((octet) => ({ | ||
| key: `rl:search:198.51.100.${octet}:1`, | ||
| expiresAt: now - 5_000, | ||
| }))); | ||
|
|
||
| expect(await t.mutation(internal.rateLimit.cleanupExpired, { | ||
| maxBuckets: 2, | ||
| followupsRemaining: 1, | ||
| })).toEqual({ deleted: 2, hasMore: true, scheduledFollowup: true }); | ||
| await t.finishAllScheduledFunctions(() => { | ||
| vi.runAllTimers(); | ||
| }); | ||
| // Two batches of two, then the budget stops the chain. Index order is | ||
| // expiresAt then creation time, so the last inserted key remains. | ||
| expect(await remainingKeys(t)).toEqual(["rl:search:198.51.100.5:1"]); | ||
| }); | ||
|
|
||
| it("clamps an oversized page to the transaction cap and uses the default page otherwise", async () => { | ||
| const now = freezeNow(); | ||
| const t = harness(); | ||
| await seedBuckets(t, Array.from({ length: CLEANUP_BATCH_LIMIT + 1 }, (_, index) => ({ | ||
| key: `rl:page:192.0.2.${index}:1`, | ||
| expiresAt: now - 1, | ||
| }))); | ||
|
|
||
| expect(await t.mutation(internal.rateLimit.cleanupExpired, { | ||
| maxBuckets: 10_000, | ||
| followupsRemaining: 0, | ||
| })).toEqual({ deleted: CLEANUP_BATCH_LIMIT, hasMore: true, scheduledFollowup: false }); | ||
| expect(await remainingKeys(t)).toHaveLength(1); | ||
|
|
||
| const defaults = harness(); | ||
| await seedBuckets(defaults, Array.from({ length: CLEANUP_BATCH_DEFAULT + 1 }, (_, index) => ({ | ||
| key: `rl:page:192.0.2.${index}:9`, | ||
| expiresAt: now - 1, | ||
| }))); | ||
| expect(await defaults.mutation(internal.rateLimit.cleanupExpired, { followupsRemaining: 0 })).toEqual({ | ||
| deleted: CLEANUP_BATCH_DEFAULT, | ||
| hasMore: true, | ||
| scheduledFollowup: false, | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.