Skip to content

Commit 9f941d8

Browse files
committed
Implement cleanup mechanism in RateLimiter for efficient request tracking
- Added a cleanupOldEntries method in backend/src/utils/security.utils.ts to remove old entries from the requests map when it exceeds a defined threshold. - Enhanced the RateLimiter class to maintain efficient tracking of user requests by cleaning up inactive user IDs, ensuring optimal memory usage and performance.
1 parent 38a5216 commit 9f941d8

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

backend/src/utils/security.utils.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,11 +268,13 @@ export const sanitizeMedicalData = <T extends Record<string, any>>(data: T): T =
268268

269269
/**
270270
* Rate limiting implementation using a rolling window
271+
* Uses authenticated user IDs to track request frequency
271272
*/
272273
export class RateLimiter {
273274
private requests: Map<string, number[]> = new Map();
274275
private readonly windowMs: number;
275276
private readonly maxRequests: number;
277+
private readonly cleanupThreshold: number = 10000;
276278

277279
constructor(windowMs = 60000, maxRequests = 20) {
278280
this.windowMs = windowMs;
@@ -303,6 +305,40 @@ export class RateLimiter {
303305
timestamps.push(now);
304306
this.requests.set(userId, timestamps);
305307

308+
// Clean up old entries if the map has grown too large
309+
this.cleanupOldEntries(now);
310+
306311
return true;
307312
}
313+
314+
/**
315+
* Cleans up old entries from the requests map when total size exceeds threshold
316+
* @param currentTime The current timestamp to calculate window
317+
*/
318+
private cleanupOldEntries(currentTime: number): void {
319+
if (this.requests.size >= this.cleanupThreshold) {
320+
const windowStart = currentTime - this.windowMs;
321+
322+
// Identify users with no recent requests
323+
const usersToRemove: string[] = [];
324+
325+
this.requests.forEach((timestamps, userId) => {
326+
// Filter to only keep timestamps within the window
327+
const activeTimestamps = timestamps.filter(time => time > windowStart);
328+
329+
if (activeTimestamps.length === 0) {
330+
// If no active timestamps remain, mark this user for removal
331+
usersToRemove.push(userId);
332+
} else if (activeTimestamps.length !== timestamps.length) {
333+
// If we filtered some timestamps, update the array
334+
this.requests.set(userId, activeTimestamps);
335+
}
336+
});
337+
338+
// Remove entries for users with no recent activity
339+
usersToRemove.forEach(userId => {
340+
this.requests.delete(userId);
341+
});
342+
}
343+
}
308344
}

0 commit comments

Comments
 (0)