Skip to content

redisRateLimiter 高并发下存在竞态条件导致限流失效 #2841

Open

Description

@lanfunoe

例行检查

  • 我已确认目前没有类似 issue
  • 我已确认我已升级到最新版本
  • 我已完整查看过项目 README,尤其是常见问题部分
  • 我理解并愿意跟进此 issue,协助测试和提供反馈
  • 我理解并认可上述内容,并理解项目维护者精力有限,不遵循规则的 issue 可能会被无视或直接关闭

问题描述

middleware/rate-limit.go 中的 redisRateLimiter 函数存在竞态条件(Race Condition),高并发场景下限流会失效。

listLength, err := rdb.LLen(ctx, key).Result()  // 步骤1: 检查
// ...
if listLength < int64(maxRequestNum) {
    rdb.LPush(ctx, key, time.Now().Format(timeFormat))  // 步骤2: 写入
    rdb.Expire(ctx, key, common.RateLimitKeyExpirationDuration)
}

LLen 和 LPush 之间不是原子操作,多个并发请求可能同时读到相同的 listLength,然后都执行 LPush,导致实际放行请求数超过 maxRequestNum。

同样的问题也存在于 else 分支(L35-64):LIndex 读取和后续的 LPush/LTrim 写入之间也存在竞态窗口。

影响范围:所有使用 rateLimitFactory 的限流中间件,包括 GlobalAPIRateLimit()、CriticalRateLimit()(登录、注册等敏感接口)等。

复现步骤

  1. 配置 maxRequestNum=3, duration=60
  2. 确保当前 Redis 中对应 key 的 List 长度为 2
  3. 使用压测工具(如 wrk、ab)同时发送 10+ 个并发请求到受限流保护的接口
  4. 观察 Redis 中 List 长度或实际放行的请求数

预期结果

  • 只有 1 个请求被放行
  • 其余请求返回 429 Too Many Requests

修复方案

使用 Lua 脚本保证原子性或者 redis_rate 库 ?


Activity

  1. added
    bug
    on Feb 4, 2026
  2. changed the title [-][Bug] redisRateLimiter 高并发下存在竞态条件导致限流失效[/-] [+]redisRateLimiter 高并发下存在竞态条件导致限流失效[/+] on Feb 4, 2026
  3. seefs001 commented on Feb 5, 2026

    @seefs001
    Collaborator

    用Lua脚本应该能保持现在的行为不变,另一个库的配置就不一定了。

  4. lanfunoe commented on Feb 5, 2026

    @lanfunoe
    ContributorAuthor

    用Lua脚本应该能保持现在的行为不变,另一个库的配置就不一定了。

    行,晚上有空我给他写了

  5. seefs001 commented on Feb 5, 2026

    @seefs001
    Collaborator

    用Lua脚本应该能保持现在的行为不变,另一个库的配置就不一定了。

    行,晚上有空我给他写了

    记得要测试,业务代码迁移到lua脚本得保持一致

  6. lanfunoe commented on Feb 5, 2026

    @lanfunoe
    ContributorAuthor

    用Lua脚本应该能保持现在的行为不变,另一个库的配置就不一定了。

    行,晚上有空我给他写了

    记得要测试,业务代码迁移到lua脚本得保持一致

    ok

  7. new-api-reviewer-bot commented on Aug 6, 2026

    @new-api-reviewer-bot

    [Bot Review]

    This issue has been automatically marked as stale due to inactivity. If this is still relevant, please reply within 7 days — otherwise it will be closed automatically.

  8. added 2 commits that reference this issue on Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugstale

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions