asyncio-redis-rate-limit icon indicating copy to clipboard operation
asyncio-redis-rate-limit copied to clipboard

Document semantics of rate limit window

Open cpsnowden opened this issue 9 months ago • 0 comments

From reading the code, the following comment indicates that Redis Pattern: Rate Limiter 1 is being used which is confusing as the cache key does not contain the timestamp.

    async def _run_pipeline(
        self,
        cache_key: str,
        pipeline: AnyPipeline,
    ) -> int:
        # https://redis.io/commands/incr/#pattern-rate-limiter-1
        current_rate, _ = await pipeline_expire(
            pipeline.incr(cache_key),
            cache_key,
            self._rate_spec.seconds,
        ).execute()
        return current_rate

My understanding is that in-fact a variation of Redis Pattern: Rate Limiter 2 is being used as a by-product of the NX command.

Is this understanding correct? If so - would be useful to update the comment.

Attaching the reference patterns

Pattern 1

FUNCTION LIMIT_API_CALL(ip)
ts = CURRENT_UNIX_TIME()
keyname = ip+":"+ts
MULTI
    INCR(keyname)
    EXPIRE(keyname,10)
EXEC
current = RESPONSE_OF_INCR_WITHIN_MULTI
IF current > 10 THEN
    ERROR "too many requests per second"
ELSE
    PERFORM_API_CALL()
END

Pattern 2

FUNCTION LIMIT_API_CALL(ip):
current = GET(ip)
IF current != NULL AND current > 10 THEN
    ERROR "too many requests per second"
ELSE
    value = INCR(ip)
    IF value == 1 THEN
        EXPIRE(ip,1)
    END
    PERFORM_API_CALL()
END

cpsnowden avatar Sep 27 '23 21:09 cpsnowden