Skip to content
Merged
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
13 changes: 12 additions & 1 deletion backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,15 @@ RATE_LIMIT_AUTH_MAX=10
RATE_LIMIT_OTP_MAX=5
RATE_LIMIT_BOT_MAX=30
RATE_LIMIT_USER_MAX=200
RATE_LIMIT_ADMIN_MAX=100
RATE_LIMIT_ADMIN_MAX=100

# ===========================================
# Redis (Optional — shared rate limiting)
# ===========================================
# If set, rate limit counters are shared across all app instances via Redis
# instead of per-instance in-memory storage. Falls back automatically to
# in-memory if unset, unreachable, or misconfigured — no code changes needed
# for local development.
# Free instance: https://console.upstash.com/ (use the TCP/node-redis
# connection string, which starts with rediss://, not the REST API URL+token)
REDIS_URL=rediss://default:password@your-instance.upstash.io:6379
45 changes: 39 additions & 6 deletions backend/middleware/rateLimiters.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,43 @@
import rateLimit from "express-rate-limit";
import { RedisStore } from "rate-limit-redis";
import { createClient } from "redis";
import logger from "../config/logger.js";

const WINDOW_MS = Number(process.env.RATE_LIMIT_WINDOW_MS) || 15 * 60 * 1000;

let redisClient = null;

if (process.env.REDIS_URL) {
try {
redisClient = createClient({
url: process.env.REDIS_URL,
socket: { connectTimeout: 5000, reconnectStrategy: false, },
});

redisClient.on("error", (err) => {
logger.error("Redis rate limiter connection error", { error: err.message });
});

await redisClient.connect();
logger.info("Rate limiting using shared Redis store");
} catch (err) {
logger.error("Failed to connect to Redis, falling back to in-memory rate limiting", {
error: err.message,
});
redisClient = null;
}
} else {
logger.info("REDIS_URL not set, using in-memory rate limiting (not shared across instances)");
}

const createRedisStore = (prefix) => {
if (!redisClient) return undefined;
return new RedisStore({
prefix: `rl:${prefix}:`,
sendCommand: (...args) => redisClient.sendCommand(args),
});
};

const sharedOptions = {
windowMs: WINDOW_MS,
standardHeaders: true,
Expand All @@ -19,31 +55,28 @@ const createIpLimiter = (max, name) =>
rateLimit({
...sharedOptions,
max: Number(process.env[name]) || max,
store: createRedisStore(name),
});

const createKeyLimiter = (max, name, keyGenerator) =>
rateLimit({
...sharedOptions,
max: Number(process.env[name]) || max,
keyGenerator,
store: createRedisStore(name),
});

export const globalIpLimiter = createIpLimiter(100, "RATE_LIMIT_GLOBAL_MAX");

export const authIpLimiter = createIpLimiter(10, "RATE_LIMIT_AUTH_MAX");

export const otpIpLimiter = createIpLimiter(5, "RATE_LIMIT_OTP_MAX");

export const botIpLimiter = createIpLimiter(30, "RATE_LIMIT_BOT_MAX");

export const userRateLimiter = createKeyLimiter(
200,
"RATE_LIMIT_USER_MAX",
(req) => req.userId,
);

export const adminRateLimiter = createKeyLimiter(
100,
"RATE_LIMIT_ADMIN_MAX",
(req) => req.adminEmail,
);
);
118 changes: 115 additions & 3 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,10 @@
"multer": "^2.0.1",
"nodemailer": "^8.0.7",
"nodemon": "^3.1.10",
"rate-limit-redis": "^6.0.0",
"razorpay": "^2.9.6",
"react-toastify": "^11.0.5",
"redis": "^6.1.0",
"sentiment": "^5.0.2",
"socket.io": "^4.8.3",
"swagger-jsdoc": "^6.2.8",
Expand Down
Loading