Skip to content

[Bug] Invalid Syntax, Duplicate Declaration, and Missing References in Rate Limiter #3582

Description

@Sandeep6135

Description

The rate limiter module fails to compile due to two critical syntax/declaration issues:

  1. Duplicate Declaration: getRedis is imported from ./redis but is redefined as a local function, causing a duplicate declaration error.
  2. Invalid Multiple Catches: checkRateLimit contains multiple sequential catch blocks on a single try statement, which is invalid JavaScript syntax.
  3. Reference Error: The error handling block calls checkInMemoryFallback, but the defined fallback function is named checkRateLimitFallback.

Code Location

  • File: lib/rateLimit.js
// Line 2: duplicate import
import { getRedis } from "./redis";

// Line 30: duplicate definition
function getRedis() { ... }

// Line 150-226: invalid syntax
try {
  ...
} catch (mongoErr) {
  ...
} catch (err) {
  ...
}

Impact

Any routes importing the rate limiter completely fail to parse and build, leading to application crashes and test suite failures.

Recommended Fix

Delete the duplicate local definition of getRedis and clean up the nested/multiple catch block structure in checkRateLimit:

export async function checkRateLimit(userId) {
  const now = Date.now();
  const redis = getRedis();

  if (!redis) {
    return checkRateLimitFallback(userId);
  }

  try {
    const windowStart = now - RATE_LIMIT_WINDOW_MS;
    const redisKey = `rate_limit:user:${userId}`;
    const pipeline = redis.pipeline();
    pipeline.zremrangebyscore(redisKey, 0, windowStart);
    pipeline.zcard(redisKey);
    const uniqueMemberId = `${now}_${Math.random().toString(36).substring(2, 8)}`;
    pipeline.zadd(redisKey, { score: now, member: uniqueMemberId });
    pipeline.pexpire(redisKey, RATE_LIMIT_WINDOW_MS);

    const results = await pipeline.exec();
    const currentRequestCount = results[1];

    if (currentRequestCount >= MAX_REQUESTS_PER_WINDOW) {
      await redis.zrem(redisKey, uniqueMemberId);
      return { allowed: false, remaining: 0 };
    }

    return {
      allowed: true,
      remaining: Math.max(0, MAX_REQUESTS_PER_WINDOW - currentRequestCount - 1),
    };
  } catch (err) {
    const errMsg = err instanceof Error ? err.message : String(err);
    logger.error("Rate Limiter: Redis failed, tripping Circuit Breaker", { error: errMsg, userId });
    return checkRateLimitFallback(userId);
  }
}

Metadata

Metadata

Assignees

Labels

GSSoC'26Part of GirlScript Summer of Code 2026bugSomething isn't workingmentor:Ayushh-SharmaaGSSoC: Mentor — @Ayushh-Sharmaa

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions