Extracts the number of attempts used from the current metrics. Used by the adapter to provide state information to callers. This is the current attempt count within the configured limit.
The current tracking metrics
Current date/time for calculations (e.g., accounting for expired requests)
Number of attempts consumed in the current window
Calculates the expiration date for the current metrics. Determines when the rate limiter state should be automatically cleaned up.
This method is critical for persistence: data persisted beyond this date should be deleted. If this method returns a date in the past, the adapter should treat the rate limiter as expired and allow requests with fresh metrics calculation.
Common patterns:
Current date/time for calculating expiration
Date when this rate limiter state should expire and be cleaned up
Creates initial metrics for a new rate limiter. Called when initializing a rate limiter for the first time or after expiration. Should set up the data structures needed to track attempts in the current window.
Current date/time for initializing window boundaries
Fresh metrics object ready to track attempts
Determines if the rate limiter should block the current request. Evaluates current metrics against the configured limit. Returns true if the attempt limit has been exceeded (request should be blocked).
The current tracking metrics
Maximum allowed attempts in the window
Current date/time for window boundary checks
true if request should be blocked, false if allowed
Updates metrics to record a new attempt. Called each time a request is evaluated by the rate limiter. Must return a new metrics object; the input should not be mutated.
The returned metrics are stored and used for subsequent evaluations. For persistent storage, this updated state is serialized and persisted.
The metrics before this attempt
Current date/time for the attempt
New metrics object with the attempt recorded
Combined approach of
slidingLogsandfixedWindowwith lower storage costs thanslidingLogsand improved boundary behavior by calculating a weighted score between two windows.Pro:
Good performance allows this to scale to very high loads.
Con:
Nothing major.
IMPORT_PATH:
"@daiso-tech/core/rate-limiter/policies"