diff --git a/kotosoft-id-backend/internal/services/ratelimiter.go b/kotosoft-id-backend/internal/services/ratelimiter.go index f794e63..45e5377 100644 --- a/kotosoft-id-backend/internal/services/ratelimiter.go +++ b/kotosoft-id-backend/internal/services/ratelimiter.go @@ -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 }