Skip to content

[TT-18135] Rate limits using the Redis rate limiter allow extra requests when Gateways’ system clocks differ - #8823

Open
shults wants to merge 8 commits into
masterfrom
TT-18135-rate-limits-using-the-redis-rate-limiter-allow-extra-requests-when-gateways-system-clocks-differ
Open

shults wants to merge 8 commits into
masterfrom
TT-18135-rate-limits-using-the-redis-rate-limiter-allow-extra-requests-when-gateways-system-clocks-differ

Conversation

@shults

@shults shults commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Description

The Redis sliding log rate limiter used each Gateway's own time.Now() to prune and count entries, so a Gateway with a fast clock dropped entries written by slower ones. The Lua script now takes its clock from redis.call("TIME"), so every Gateway sharing a key counts the same window.

  • sliding_log_add.lua takes only max_allowed and per; it returns the Redis time so Reset is computed against it.
  • Scores and members stay nanosecond integers, so old and new Gateways read the same entries during a rolling upgrade.
  • Hits in the same microsecond get a unique member via ZADD NX and a ZCOUNT jump. This cannot happen in normal operation (scripts run one at a time and take longer than a microsecond); it covers a stepped-back Redis clock and mixed-version clusters. Collisions are logged at debug, running out of suffixes is an explicit error that blocks the request.
  • SlidingLog keeps only Do; the pipeline methods existed for tests only. enable_non_transactional_rate_limiter has had no effect since v5.13.0 (TT-6075 moved Do to the script) and is now marked deprecated.

Related Issue

https://tyktech.atlassian.net/browse/TT-18135

Motivation and Context

With skewed clocks a client could exceed its limit across Gateways, X-RateLimit-Remaining went back up and X-RateLimit-Reset moved backwards.

How This Has Been Tested

internal/rate tests moved to a testify suite: success flow, two nodes sharing a key with entries from earlier in the window, unique members, script error path, collision jump. Benchmarks for the happy path and for 0/1/10/100/998 collisions (collision branch costs ~3 µs over the Redis round trip).

Not covered: X-RateLimit-Reset in headers.go still builds the epoch from the serving Gateway's clock. Docs rate-limit.md still recommends enable_non_transactional_rate_limiter; separate docs PR.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Refactoring or add test (improvements in base code or adds test coverage to functionality)

Checklist

  • I ensured that the documentation is up to date
  • I explained why this PR updates go.mod in detail with reasoning why it's required
  • I would like a code coverage CI quality gate exception and have explained why

🤖 Generated with Claude Code

Ticket Details

TT-18135
Status In Test
Summary Rate limits using the Redis rate limiter allow extra requests when Gateways’ system clocks differ

Generated at: 2026-11-26 15:23:20

@shults
shults requested review from MaciekMis and pvormste October 22, 2026 10:39
MaciekMis
MaciekMis previously approved these changes Oct 27, 2026
Comment thread internal/rate/sliding_log.go Resolved
@github-actions

github-actions Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

🎯 Recommended Merge Targets

Based on JIRA ticket TT-18135: Rate limits using the Redis rate limiter allow extra requests when Gateways’ system clocks differ

Fix Version: Tyk 5.13.9

Required:

  • release-5.13 - Minor version branch for 5.13.x patches - required for creating Tyk 5.13.9
  • master - Main development branch - ensures fix is in all future releases

Fix Version: Tyk 5.17.0

⚠️ Warning: Expected release branches not found in repository

Required:

  • master - No matching release branches found. Fix will be included in future releases.

📋 Workflow

  1. Merge this PR to master first

  2. Cherry-pick to release branches by commenting on the merged PR:

    • /release to release-5.13
  3. Automated backport - The bot will automatically create backport PRs to the specified release branches

@probelabs

probelabs Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

This PR addresses a bug in the Redis-based sliding log rate limiter where rate limits could be exceeded if different Gateway instances had unsynchronized system clocks. The fix ensures consistent rate limit enforcement across a distributed environment by using the Redis server's clock as the single source of truth.

Key changes include:

  • The sliding_log_add.lua script now uses redis.call("TIME") to get a consistent timestamp, rather than relying on the time provided by each Gateway.
  • The Lua script is enhanced to handle microsecond-level collisions, which can occur in edge cases like a Redis clock rollback, by generating unique members for each request.
  • The Go client in internal/rate/sliding_log.go is refactored. The Do method no longer accepts a time.Time argument and now parses a more detailed response from the updated Lua script.
  • The test suite in internal/rate/sliding_log_test.go has been rewritten using testify/suite to validate the clock-skew fix and the new collision-handling logic.
  • The now-obsolete EnableNonTransactionalRateLimiter configuration option is marked as deprecated.

Files Changed Analysis

  • internal/rate/scripts/sliding_log_add.lua: Contains the core logic change. The script now fetches time directly from Redis and includes robust collision handling.
  • internal/rate/sliding_log.go: The Go client for the rate limiter is significantly refactored to support the new Lua script. The API is simplified by removing obsolete methods related to pipelining.
  • internal/rate/sliding_log_test.go: The test suite is completely rewritten to be more robust, with new tests specifically covering the clock-skew scenario and collision logic.
  • gateway/session_manager.go: The call to the rate limiter's Do method is updated to match its new signature.
  • config/rate_limit.go: The EnableNonTransactionalRateLimiter configuration option is marked as deprecated.

Architecture & Impact Assessment

  • What this PR accomplishes: It guarantees accurate and consistent rate limiting in a distributed multi-gateway environment by using Redis as a single source of time, preventing clients from exceeding their limits due to clock skew between nodes.
  • Key technical changes introduced: The responsibility for timekeeping is moved from the Gateway application layer to the Redis data layer. This enforces a consistent view of the time window for all Gateways. The Lua script is also made more resilient to race conditions and clock anomalies.
  • Affected system components: The change is scoped to the Rate Limiting subsystem, specifically when using the Redis or Sentinel sliding log limiter. Other rate-limiting strategies (e.g., in-memory) are unaffected.

Architectural Flow Change

sequenceDiagram
    participant G1 as "Gateway 1 (Clock t1)"
    participant G2 as "Gateway 2 (Clock t2)"
    participant R as Redis

    rect rgb(240, 240, 255)
    note over G1, R: Old Flow (Inconsistent Time)
    G1->>G1: Get local time (t1)
    G1->>R: Prune/Count using t1
    G2->>G2: Get local time (t2)
    G2->>R: Prune/Count using t2
    note right of R: Window is inconsistent if t1 ≠ t2
    end

    rect rgb(240, 240, 255)
    note over G1, R: New Flow (Consistent Time)
    G1->>R: Invoke sliding_log_add.lua
    activate R
    R->>R: Get Redis time (t_redis)
    R-->>G1: Return result based on t_redis
    deactivate R

    G2->>R: Invoke sliding_log_add.lua
    activate R
    R->>R: Get Redis time (t_redis)
    R-->>G2: Return result based on t_redis
    deactivate R
    note right of R: Both gateways use the same time source
    end
Loading

Scope Discovery & Context Expansion

  • The scope of this change is tightly focused on the Redis sliding log implementation. Other rate limiters are not affected.
  • While the underlying rate limit enforcement is now consistent, the X-RateLimit-Reset header sent to clients may still appear inconsistent. The rate limiter returns a Reset duration which is added to the local Gateway's clock (time.Now()) to create the final timestamp. A client hitting different Gateways might see this timestamp jump, even though the limit is correctly enforced. This was noted in review comments and represents a potential follow-up improvement.
  • The deprecation of enable_non_transactional_rate_limiter is a related code hygiene improvement, removing a now-obsolete configuration option.
Metadata
  • Review Effort: 3 / 5
  • Primary Label: bug

Powered by Visor from Probelabs

Last updated: 2026-11-26T15:26:00.975Z | Triggered by: pr_updated | Commit: 889ac45

💡 TIP: You can chat with Visor using /visor ask <your question>

@probelabs

probelabs Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Security Issues (1)

Severity Location Issue
🟡 Warning internal/rate/scripts/sliding_log_add.lua:34
The Lua script contains a `while true` loop that attempts to find a unique member for a Redis sorted set. If all 1000 possible suffixes (000-999) are exhausted for a given microsecond, the script returns an error. While unlikely, a malicious actor who can control the timing of requests with high precision, or a bug causing repeated attempts in the same microsecond, could trigger this loop to iterate many times, consuming Redis CPU and potentially leading to a denial of service for that specific rate-limiting key. The check `if seq > 999 then` provides an exit condition, but the loop itself could be a performance bottleneck under specific, albeit rare, conditions.
💡 SuggestionThe current implementation with a hard limit of 1000 is a reasonable defense. However, consider adding logging with rate limiting for the warning `sliding log ...: no free member at ...` to detect potential abuse. No immediate code change is required, but this behavior should be monitored.

✅ Performance Check Passed

No performance issues found – changes LGTM.

Quality Issues (1)

Severity Location Issue
🟡 Warning internal/rate/sliding_log.go:89
The `Do` method successfully centralizes rate limit enforcement using Redis time but loses this consistency when communicating the reset time to clients. It returns a `Reset` duration, which callers add to their local (and potentially skewed) system clock to generate the `X-RateLimit-Reset` header. This can cause the reset timestamp to appear inconsistent to clients hitting multiple gateways.
💡 SuggestionTo ensure full consistency, consider modifying the `Stats` struct and the `Do` method's return signature to also provide the Redis server time (`nowNano` from the Lua script). Callers could then compute the absolute reset time based on this authoritative timestamp, eliminating any client-facing inconsistency caused by gateway clock skew. As this was noted as out-of-scope in the PR description, this should be tracked for a future improvement.

Powered by Visor from Probelabs

Last updated: 2026-11-26T15:25:26.326Z | Triggered by: pr_updated | Commit: 889ac45

💡 TIP: You can chat with Visor using /visor ask <your question>

@github-actions

github-actions Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

API Changes

--- prev.txt	2026-11-26 15:24:25.893887443 +0000
+++ current.txt	2026-11-26 15:24:17.143848375 +0000
@@ -8936,7 +8936,8 @@
 	// Redis Rate Limiter, or the Sentinel Rate Limiter, as both algorithms implement a sliding log.
 	EnableRateLimitSmoothing bool `json:"enable_rate_limit_smoothing"`
 
-	// An enhancement for the Redis and Sentinel rate limiters, that offers a significant improvement in performance by not using transactions on Redis rate-limit buckets.
+	// Deprecated: ignored since v5.13.0. The Redis and Sentinel rate limiters run a single Lua script,
+	// so there is no transaction left to skip. The option is kept so existing configurations still load.
 	EnableNonTransactionalRateLimiter bool `json:"enable_non_transactional_rate_limiter"`
 
 	// How frequently a distributed rate limiter synchronises information between the Gateway nodes. Default: 2 seconds.

@CLAassistant

CLAassistant commented Nov 16, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@buger

This comment has been minimized.

@shults
shults force-pushed the TT-18135-rate-limits-using-the-redis-rate-limiter-allow-extra-requests-when-gateways-system-clocks-differ branch from c80cd8c to c7711d3 Compare November 18, 2026 15:00
@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

📚 Documentation preview

This PR changes generated documentation (component: gateway).

cc @TykTechnologies/pms — advisory review requested; this does not block merging.

Rendered docs diff
diff -ruN out-base/gateway-config.mdx out-head/gateway-config.mdx
--- out-base/gateway-config.mdx	2026-11-26 15:23:40.573877593 +0000
+++ out-head/gateway-config.mdx	2026-11-26 15:23:42.113646379 +0000
@@ -989,7 +989,8 @@
 ENV: <b>TYK_GW_ENABLENONTRANSACTIONALRATELIMITER</b><br />
 Type: `bool`<br />
 
-An enhancement for the Redis and Sentinel rate limiters, that offers a significant improvement in performance by not using transactions on Redis rate-limit buckets.
+Deprecated: ignored since v5.13.0. The Redis and Sentinel rate limiters run a single Lua script,
+so there is no transaction left to skip. The option is kept so existing configurations still load.
 
 ### drl_notification_frequency
 ENV: <b>TYK_GW_DRLNOTIFICATIONFREQUENCY</b><br />

MaciekMis
MaciekMis previously approved these changes Nov 18, 2026
shults and others added 2 commits November 18, 2026 18:36
NewSlidingLogRedis runs per request and allocated a logrus.Logger each
time only to have WithLogger replace it. Use one package-level instance.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@shults
shults force-pushed the TT-18135-rate-limits-using-the-redis-rate-limiter-allow-extra-requests-when-gateways-system-clocks-differ branch from c7711d3 to 0cccd27 Compare November 18, 2026 17:39
…limiter-allow-extra-requests-when-gateways-system-clocks-differ
…limiter-allow-extra-requests-when-gateways-system-clocks-differ
@sentinelone-cnapp-eu1

Copy link
Copy Markdown

SentinelOne CNS Hardcoded Secret Detector
✅ Congratulations, your code is safe

SentinelOne CNS is a cloud-agnostic, agentless CSPM & CWPP solution that continuously detects and prevents vulnerabilities that have the highest probability of being exploited in Azure, AWS, Google Cloud, and Kubernetes.

@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Passed Quality Gate passed

Issues
1 New issue
0 Accepted issues

Measures
0 Security Hotspots
100.0% Coverage on New Code
0.0% Duplication on New Code

See analysis details on SonarQube Cloud

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants