fix: ratelimiter fixed
Build and Deploy / lint-frontend (push) Canceled after 0s
Build and Deploy / build-backend (push) Canceled after 0s
Build and Deploy / build-frontend (push) Canceled after 0s
Build and Deploy / deploy (push) Canceled after 0s
Build and Deploy / test-backend (push) Canceled after 10s

This commit is contained in:
Ivan Rezchikov
2026-09-18 16:02:48 +03:00
parent 63badb0857
commit af2358811a
@@ -66,23 +66,34 @@ func (r *RateLimiter) Allow(ctx context.Context, key string, cfg RateLimitConfig
}
}
pipe := r.redis.Pipeline()
incrCmd := pipe.Incr(ctx, counterKey)
pipe.Expire(ctx, counterKey, cfg.Window)
if _, err := pipe.Exec(ctx); err != nil {
// Fixed-window counter: only the request that brings the counter to 1
// sets the TTL, so a burst never extends the window and the counter is
// guaranteed to reset after cfg.Window even under sustained traffic.
count64, err := r.redis.Incr(ctx, counterKey).Result()
if err != nil {
return false, 0, fmt.Errorf("rate limiter: %w", err)
}
if count64 == 1 {
if err := r.redis.Expire(ctx, counterKey, cfg.Window).Err(); err != nil {
return false, 0, fmt.Errorf("rate limiter: %w", err)
}
}
count := int(incrCmd.Val())
remaining := max(cfg.Max-count, 0)
count := int(count64)
if count > cfg.Max {
if cfg.BlockFor > 0 {
_ = r.redis.Set(ctx, blockKey, 1, cfg.BlockFor).Err()
// Reset the counter when blocking so that once the block expires
// the client is not instantly re-blocked by the stale count.
_ = r.redis.Del(ctx, counterKey).Err()
if err := r.redis.Set(ctx, blockKey, 1, cfg.BlockFor).Err(); err != nil {
return false, 0, fmt.Errorf("rate limiter: %w", err)
}
}
return false, 0, nil
}
remaining := max(cfg.Max-count, 0)
return true, remaining, nil
}