Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added .jules/bolt.md
Empty file.
10 changes: 6 additions & 4 deletions packages/cache/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,17 +132,21 @@ export class SlidingWindowRateLimiter {
const member = `${now}:${crypto.randomUUID()}`;
const cutoff = now - limit.windowMs;

// ⚑ Bolt: Consolidate all Redis operations into a single pipeline to reduce network round-trips.
// This reduces round-trips from 2 to 1 for allowed requests, and 3 to 2 for blocked requests.
const pipeline = this.redis.pipeline();
pipeline.zremrangebyscore(key, 0, cutoff);
pipeline.zadd(key, now, member);
pipeline.zcard(key);
pipeline.pexpire(key, limit.windowMs);
pipeline.zrange(key, 0, 0, "WITHSCORES");
const results = await pipeline.exec();

const count = Number(results?.[2]?.[1] ?? 0);
const oldestRaw = (results?.[4]?.[1] as string[]) ?? [];
const oldest = oldestRaw.length >= 2 ? Number(oldestRaw[1]) : now;

if (count <= limit.limit) {
const oldestRaw = await this.redis.zrange(key, 0, 0, "WITHSCORES");
const oldest = oldestRaw.length >= 2 ? Number(oldestRaw[1]) : now;
return {
allowed: true,
identifier,
Expand All @@ -154,8 +158,6 @@ export class SlidingWindowRateLimiter {
}

await this.redis.zrem(key, member);
const oldestRaw = await this.redis.zrange(key, 0, 0, "WITHSCORES");
const oldest = oldestRaw.length >= 2 ? Number(oldestRaw[1]) : now;
const stableCount = Math.max(0, count - 1);
return {
allowed: false,
Expand Down
Loading