Skip to content

Stagger rate-limited client refills - #519

Merged
fcostaoliveira merged 1 commit into
redis:masterfrom
thweetkomputer:fix/smooth-rate-limiting
Aug 26, 2026
Merged

fcostaoliveira merged 1 commit into
redis:masterfrom
thweetkomputer:fix/smooth-rate-limiting

Conversation

@thweetkomputer

@thweetkomputer thweetkomputer commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • spread rate-limited clients evenly across the existing refill interval
  • use the per-client phase only for the first timer, then preserve the existing refill cadence
  • apply the same logical-client phase to cluster shard connections
  • add unit coverage for phase calculation, including wraparound and overflow-sensitive inputs

Problem

Rate limiting currently gives every connection its full quota immediately and arms every refill timer with the same interval. Connections prepared together therefore refill together.

For example, 80 connections at 1,250 requests/sec each receive 25 requests every 20 ms. In steady state that can arrive as 2,000-request bursts every 20 ms even though the reported aggregate rate is exactly 100k requests/sec. The resulting server-side queueing makes latency percentiles describe the benchmark client's synchronized burst pattern as much as the server.

Implementation

Each logical client gets a deterministic phase:

phase = refill_interval * client_index / total_clients

The first timer fires after refill_interval + phase. In that callback the persistent event is re-armed with the original refill interval, preserving both the configured request rate and the existing steady-state quota behavior.

A single client has phase zero and follows the original path. On reconnect, a phase that has not fired yet is retried; after initialization, reconnects resume the ordinary interval without adding another phase delay.

Validation

Commands:

make format-check
make
make check

All pass, including the new rate_limiter_test.

Paired Redis 8.10.1 GET benchmark, 30 seconds, 8 threads, 10 connections/thread, pipeline 1, 128-byte values, --rate-limiting=1250 per connection:

metric baseline this PR change
throughput 99,994 QPS 99,954 QPS -0.04%
average latency 0.461 ms 0.053 ms -88.5%
p99 0.967 ms 0.199 ms -79.4%
p99.9 1.295 ms 0.367 ms -71.7%
p99.99 1.799 ms 0.551 ms -69.4%
client CPU 1.135 cores 0.917 cores -19.2%

A one-client check remained at the requested rate: 1,250.05 QPS before and 1,249.98 QPS after.

For comparison, current Valkey valkey-benchmark --rps 100000 against the same Redis instance produced 99,738 QPS and a p99.99 between 0.527 and 0.575 ms. This PR reaches the same tail-latency range without replacing memtier's low-overhead quota/refill design.

I also tested increasing refill frequency to 250 Hz. It regressed p99.99 to 1.143 ms because sub-millisecond phases coalesced in the event loop. Interleaving phases within every worker improved p99.99 slightly to 0.527 ms but raised client CPU to 1.471 cores, so neither higher-overhead variant is included here.


Note

Medium Risk
Changes core request-timing and refill behavior for rate-limited runs; incorrect phase math could skew throughput or burst patterns, but scope is isolated and covered by new unit tests.

Overview
Rate-limited logical clients no longer arm identical refill timers, which previously synchronized bursts across connections. Each client gets a deterministic phase via calculate_rate_limit_phase in rate_limiter.h (interval × client_index / total_clients), stored on client and passed into every shard_connection (including cluster shard connections created later).

shard_connection delays only the first libevent timer by refill_interval + phase, then re-arms the persistent timer with the normal interval in handle_timer_event so aggregate QPS and per-interval quotas stay the same while refills are spread across the window. Reconnect retries an unused phase once; after steady state, reconnect uses the ordinary interval.

Adds rate_limiter_test to make check with unit tests for edge cases (zero interval/clients, wraparound, wide multiplication).

Reviewed by Cursor Bugbot for commit 909f820. Bugbot is set up for automated code reviews on this repo. Configure here.

@thweetkomputer
thweetkomputer marked this pull request as ready for review August 26, 2026 01:10
@fcostaoliveira

Copy link
Copy Markdown
Collaborator

🤖 Automated first-pass review — a human maintainer's review is still required before merge.

Thanks for this — really thorough writeup and benchmark data, that's more validation than most PRs on this repo bring. Went through the diff.

The phase math in rate_limiter.h looks right — multiplication widened to uint64_t before the divide, client_index reduced mod total_clients, and the unit tests cover the wraparound/overflow cases I'd have asked about anyway (the 3999999999/4000000000 case in particular). The event_del/event_add dance in handle_timer_event to swap the persist interval after the first fire is the correct way to change an EV_PERSIST timer's cadence mid-flight, and m_request_rate_phase_pending correctly handles the case where a connection reconnects before its staggered first fire ever happens vs. after.

One question: make check here only runs the C++ unit tests (rate_limiter_test + prometheus_metrics_test, per Makefile.am's TESTS var) — did you happen to also run tests/tests_oss_simple_flow.py locally, specifically test_reconnect_interval_with_rate_limiting? That's the existing test that already exercises rate-limiting + reconnect together, which is exactly the phase-pending path you're touching here. I think CI runs it regardless so this isn't blocking, just curious if you'd already seen it pass.

Nitpicking: the config->clients * config->threads -> widened static_cast<unsigned long long> in setup_client is a real fix (avoids a 32-bit overflow before promotion) but isn't really about the phase change — fine to leave bundled since it's one line, just flagging it as a separate concern for next time.

Also a nice incidental catch: normalizing the timer into tv_sec/tv_usec via division/modulo instead of the old {0, (int) request_interval_microsecond} also fixes a latent invalid-timeval case if the interval ever exceeds 1s (very low rate-limit values). Not sure that's reachable in practice given how request_interval_microsecond gets computed, but if it is, this quietly fixes it too.

Nothing else stood out — the change doesn't touch any CLI flags or output/JSON format, is scoped to the rate-limiting path, and the benchmark numbers (latency percentiles dropping while throughput and CPU stay flat or improve) back up the claim well. Good first PR.

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving — went through the diff directly: the phase-staggering logic in calculate_rate_limit_phase() is correct (uint64_t-widened multiply before divide, safe on zero interval/zero clients), it's applied consistently through both client::setup_client and cluster_client::create_shard_connection, the phase only affects the first timer fire before handle_timer_event resets to the normal cadence (so it doesn't distort the configured rate long-term), and reconnect semantics are handled correctly per the PR description. Real benchmark data backs the tail-latency claim (p99.99 -69%, CPU -19%, throughput within noise), and the two more aggressive variants were tried and correctly rejected with data. CI is fully green (111/111, 1 skipped). Nice first PR.

@fcostaoliveira
fcostaoliveira merged commit 9572e2e into redis:master Aug 26, 2026
112 checks passed
@thweetkomputer
thweetkomputer deleted the fix/smooth-rate-limiting branch August 27, 2026 13:20
fcostaoliveira added a commit that referenced this pull request Oct 14, 2026
rate_limiter_test (#519) and socket_options_test (#541) were added to
check_PROGRAMS without matching .gitignore entries, so after `make check`
both binaries show up as untracked files. List them next to the other
three check programs; the five entries now match check_PROGRAMS in
Makefile.am.

Also ignore the genhtml report directory that `make code-coverage-capture`
writes (memtier_benchmark-<version>-coverage/). The .info file and the
gcov artifacts were already covered by *.info / *.gc*.

Fixes #623

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 14, 2026
rate_limiter_test (#519) and socket_options_test (#541) were added to
check_PROGRAMS without matching .gitignore entries, so after `make check`
both binaries show up as untracked files. List them next to the other
three check programs; the five entries now match check_PROGRAMS in
Makefile.am.

Also ignore the genhtml report directory that `make code-coverage-capture`
writes (memtier_benchmark-<version>-coverage/). The .info file and the
gcov artifacts were already covered by *.info / *.gc*.

Fixes #623

Co-authored-by: Claude Opus 5.5 <[email protected]>
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.

2 participants