Skip to content

Fix redis TTL to match limit reset timeΒ #351

@zoll

Description

@zoll

Currently redis ttl is set to max value even if request is made at the end of interval. This can be confusing to API users and is misleading.

I suggest a small change to the Increment async method to calculate how much time there is left to next interval.

public async Task<RateLimitCounter> IncrementAsync(string counterId, TimeSpan interval, Func<double>? RateIncrementer = null)
        {
            if (RateIncrementer == null) throw new ArgumentNullException(nameof(RateIncrementer));
            var now = DateTime.UtcNow;
            var numberOfIntervals = now.Ticks / interval.Ticks;
            var intervalStart = new DateTime(numberOfIntervals * interval.Ticks, DateTimeKind.Utc);
            var secondsToIntervalEnd = Convert.ToInt32(interval.TotalSeconds - (now - intervalStart).TotalSeconds);
            
            _logger.LogDebug("Calling Lua script. {counterId}, {timeout}, {delta}", counterId,secondsToIntervalEnd, 1D);
            var count = await _connectionMultiplexer.GetDatabase().ScriptEvaluateAsync(_atomicIncrement, new { key = new RedisKey(counterId), timeout = secondsToIntervalEnd, delta = RateIncrementer?.Invoke() ?? 1D });
            return new RateLimitCounter
            {
                Count = (double)count,
                Timestamp = intervalStart
            };
        }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions