File tree Expand file tree Collapse file tree 1 file changed +23
-0
lines changed
web/src/app/api/v1/ads/impression Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Original file line number Diff line number Diff line change @@ -29,6 +29,23 @@ const impressionRateLimiter = new Map<
2929 { count : number ; resetAt : number }
3030> ( )
3131
32+ /**
33+ * Clean up expired entries from the rate limiter to prevent memory leaks.
34+ * Called periodically during rate limit checks.
35+ */
36+ function cleanupExpiredEntries ( ) : void {
37+ const now = Date . now ( )
38+ for ( const [ userId , limit ] of impressionRateLimiter ) {
39+ if ( now >= limit . resetAt ) {
40+ impressionRateLimiter . delete ( userId )
41+ }
42+ }
43+ }
44+
45+ // Track last cleanup time to avoid cleaning up on every request
46+ let lastCleanupTime = 0
47+ const CLEANUP_INTERVAL_MS = 5 * 60 * 1000 // Clean up every 5 minutes
48+
3249/**
3350 * Check and update rate limit for a user.
3451 * Returns true if the request is allowed, false if rate limited.
@@ -37,6 +54,12 @@ function checkRateLimit(userId: string): boolean {
3754 const now = Date . now ( )
3855 const hourMs = 60 * 60 * 1000
3956
57+ // Periodically clean up expired entries to prevent memory leak
58+ if ( now - lastCleanupTime > CLEANUP_INTERVAL_MS ) {
59+ cleanupExpiredEntries ( )
60+ lastCleanupTime = now
61+ }
62+
4063 const userLimit = impressionRateLimiter . get ( userId )
4164
4265 if ( ! userLimit || now >= userLimit . resetAt ) {
You can’t perform that action at this time.
0 commit comments