Skip to content

Commit

Permalink
feat: add sliding window rate limiter
Browse files Browse the repository at this point in the history
  • Loading branch information
cameri committed Nov 16, 2022
1 parent 6235e1a commit 42083a2
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/@types/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export interface IRateLimiterOptions {
period: number;
rate: number;
}

export interface IRateLimiter {
hit(key: string, step: number, options: IRateLimiterOptions): Promise<boolean>
}
35 changes: 35 additions & 0 deletions src/utils/sliding-window-rate-limiter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { IRateLimiter, IRateLimiterOptions } from '../@types/utils'
import { createLogger } from '../factories/logger-factory'
import { ICacheAdapter } from '../@types/adapters'

const debug = createLogger('sliding-window-rate-limiter')

export class SlidingWindowRateLimiter implements IRateLimiter {
public constructor(
private readonly cache: ICacheAdapter,
) {}

public async hit(
key: string,
step: number,
options: IRateLimiterOptions,
): Promise<boolean> {
const timestamp = Date.now()
const { period } = options

debug('add %d hits on %s bucket', step, key)

const [,, entries] = await Promise.all([
this.cache.removeRangeByScoreFromSortedSet(key, 0, timestamp - period),
this.cache.addToSortedSet(key, { [`${timestamp}:${step}`]: timestamp.toString() }),
this.cache.getRangeFromSortedSet(key, 0, -1),
this.cache.setKeyExpiry(key, period),
])

const hits = entries.reduce((acc, timestampAndStep) => acc + Number(timestampAndStep.split(':')[1]), 0)

debug('hit count on %s bucket: %d', key, hits)

return hits > options.rate
}
}

0 comments on commit 42083a2

Please sign in to comment.