-
Notifications
You must be signed in to change notification settings - Fork 1
imp(): move rate limiting to grouper #576
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
f383184
7f670e2
2f14cb3
c7905d2
ea8c5e8
f53a5e2
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,8 @@ | ||
| # Url for connecting to Redis | ||
| REDIS_URL=redis://redis:6379 | ||
|
|
||
| # How often to refresh project rate limits from MongoDB (seconds) | ||
| PROJECTS_LIMITS_UPDATE_PERIOD=3600 | ||
|
|
||
| # Redis hash key for per-project rate limit counters | ||
| REDIS_RATE_LIMITS_KEY=rate_limits |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -22,10 +22,12 @@ import { MS_IN_SEC } from '../../../lib/utils/consts'; | |
| import TimeMs from '../../../lib/utils/time'; | ||
| import DataFilter from './data-filter'; | ||
| import RedisHelper from './redisHelper'; | ||
| import ProjectLimitsCache from './projectLimitsCache'; | ||
| import { computeDelta } from './utils/repetitionDiff'; | ||
| import { bucketTimestampMs } from './utils/bucketTimestamp'; | ||
| import { rightTrim } from '../../../lib/utils/string'; | ||
| import { hasValue } from '../../../lib/utils/hasValue'; | ||
| import { positiveIntEnv } from '../../../lib/utils/positiveIntEnv'; | ||
| import GrouperMetrics from './metrics/grouperMetrics'; | ||
| import GrouperMemoryMonitor from './metrics/memoryMonitor'; | ||
| import SlowHandleDiagnostics, { SlowHandleSession } from './metrics/slowHandleDiagnostics'; | ||
|
|
@@ -63,6 +65,11 @@ const DAILY_METRICS_RETENTION_DAYS = 90; | |
| */ | ||
| const MAX_CODE_LINE_LENGTH = 140; | ||
|
|
||
| /** | ||
| * Default interval for refreshing project limits cache (in seconds) | ||
| */ | ||
| const DEFAULT_PROJECTS_LIMITS_UPDATE_PERIOD_SECONDS = 3600; | ||
|
|
||
| /** | ||
| * Worker for handling Javascript events | ||
| */ | ||
|
|
@@ -92,6 +99,16 @@ export default class GrouperWorker extends Worker { | |
| */ | ||
| private redis = new RedisHelper(); | ||
|
|
||
| /** | ||
| * Cached project rate limits loaded from accounts MongoDB | ||
| */ | ||
| private projectLimitsCache: ProjectLimitsCache; | ||
|
|
||
| /** | ||
| * Interval for periodic project limits cache refresh | ||
| */ | ||
| private projectLimitsRefreshInterval: NodeJS.Timeout | null = null; | ||
|
|
||
| /** | ||
| * Prometheus metrics facade. | ||
| */ | ||
|
|
@@ -117,6 +134,14 @@ export default class GrouperWorker extends Worker { | |
| */ | ||
| private handledTasksCount = 0; | ||
|
|
||
| /** | ||
| * Create grouper worker instance | ||
| */ | ||
| constructor() { | ||
| super(); | ||
| this.projectLimitsCache = new ProjectLimitsCache(this.accountsDb); | ||
| } | ||
|
|
||
| /** | ||
| * Start consuming messages | ||
| */ | ||
|
|
@@ -131,6 +156,21 @@ export default class GrouperWorker extends Worker { | |
| await this.redis.initialize(); | ||
| console.log('redis initialized'); | ||
|
|
||
| await this.projectLimitsCache.refresh(); | ||
|
|
||
| const limitsUpdatePeriodSeconds = positiveIntEnv( | ||
| process.env.PROJECTS_LIMITS_UPDATE_PERIOD, | ||
| DEFAULT_PROJECTS_LIMITS_UPDATE_PERIOD_SECONDS, | ||
| ); | ||
|
|
||
| this.projectLimitsRefreshInterval = setInterval(() => { | ||
| /* eslint-disable-next-line no-void */ | ||
| void this.projectLimitsCache.refresh() | ||
| .catch((error) => { | ||
| this.logger.error('Failed to refresh project limits cache', error); | ||
| }); | ||
| }, limitsUpdatePeriodSeconds * MS_IN_SEC); | ||
|
Comment on lines
+166
to
+172
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. logic rewritten to memoize and on-demand cache updates |
||
|
|
||
| /** | ||
| * Start periodic cache cleanup to prevent memory leaks from unbounded cache growth | ||
| * Runs every 30 seconds to clear old cache entries | ||
|
|
@@ -155,6 +195,11 @@ export default class GrouperWorker extends Worker { | |
| this.cacheCleanupInterval = null; | ||
| } | ||
|
|
||
| if (this.projectLimitsRefreshInterval) { | ||
| clearInterval(this.projectLimitsRefreshInterval); | ||
| this.projectLimitsRefreshInterval = null; | ||
| } | ||
|
|
||
| this.memoryMonitor.logShutdown(this.handledTasksCount); | ||
| await super.finish(); | ||
| this.prepareCache(); | ||
|
|
@@ -170,6 +215,16 @@ export default class GrouperWorker extends Worker { | |
| */ | ||
| public async handle(task: GroupWorkerTask<ErrorsCatcherType>): Promise<void> { | ||
| try { | ||
| const withinLimit = await this.checkRateLimit(task.projectId); | ||
|
|
||
| if (!withinLimit) { | ||
| this.grouperMetrics.incrementRateLimitedTotal(); | ||
| await this.recordProjectMetrics(task.projectId, 'events-rate-limited'); | ||
| this.logger.info(`[rate-limit] project=${task.projectId} title="${task.payload?.title}" dropped`); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| await this.grouperMetrics.observeHandleDuration(async () => { | ||
| await this.handleInternal(task); | ||
| }); | ||
|
|
@@ -180,6 +235,30 @@ export default class GrouperWorker extends Worker { | |
| } | ||
| } | ||
|
|
||
| /** | ||
| * Check and update per-project rate limit in Redis. | ||
| * | ||
| * @param projectId - project id | ||
| */ | ||
| private async checkRateLimit(projectId: string): Promise<boolean> { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I’m not fond of the constant addition of new methods to the grouper index file. Let’s adhere to the principle of separation of concerns and create a separate ReteLimitter file that will encapsulate all the necessary logic. |
||
| const limits = this.projectLimitsCache.getProjectLimits(projectId); | ||
|
|
||
| if (!limits) { | ||
| this.logger.warn(`Project ${projectId} is not in the projects limits cache`); | ||
| } | ||
|
|
||
| const eventsLimit = limits?.eventsLimit ?? 0; | ||
| const eventsPeriod = limits?.eventsPeriod ?? 0; | ||
|
|
||
| try { | ||
| return await this.redis.updateRateLimit(projectId, eventsLimit, eventsPeriod); | ||
| } catch (error) { | ||
| this.logger.error(`Failed to update rate limit for project ${projectId}`, error); | ||
|
|
||
| return false; | ||
| } | ||
|
Comment on lines
+255
to
+259
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. seems ok |
||
| } | ||
|
|
||
| /** | ||
| * Internal task handling function | ||
| * | ||
|
|
@@ -301,7 +380,7 @@ export default class GrouperWorker extends Worker { | |
| this.grouperMetrics.incrementDuplicateRetriesTotal(); | ||
| this.logger.info(`[saveEvent] project=${task.projectId} title="${task.payload.title}" duplicate key, retrying as repetition`); | ||
|
|
||
| await this.handle(task); | ||
| await this.handleInternal(task); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we already have 2 cache mechanics:
Let's use one of them and do not implement another one.