Repository navigation
T11a: client-side rate limiter - #10
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
Several active correctness and safety issues remain, including retrying lost non-idempotent responses, miscounting failed starts against the quota, and allowing rate-limiter configuration and request-ID overflow edge cases.
5 open issues
Timed-out POST retries can duplicate server-side effects · New Failed starts incorrectly consume rate-limit quota · New Bucket-count overflow can silently disable rate limiting · New Non-divisible bucket durations shorten configured windows · New Request ID overflow can return the reserved zero value · New
What changed in this PR
Adds a configurable dual-threshold client-side sliding-window rate limiter to the executor, along with process-wide request IDs and updated request correlation, retry behavior, and test coverage.
Changes:
- Implements tripwire and moving-average throttling that holds queued requests until the limiter clears.
- Integrates rate-limit configuration into executor promotion and adds fake-clock limiter tests.
- Adds request-ID generation, transport headers, logging and error correlation, documentation, and build updates.
| File | Description |
|---|---|
| tests/test_rate_limiter.cpp | Adds fake-clock unit tests covering limiter thresholds, windows, resets, disabled mode, and custom configurations. |
| tests/test_executor.cpp | Expands executor tests for request IDs, retries, concurrency, rate-limiter integration, and server rate-limit responses. |
| tests/CMakeLists.txt | Registers the rate-limiter test executable and its CTest entry. |
| src/core/request_id.cpp | Implements atomic process-wide request-ID generation and decimal formatting. |
| src/core/rate_limiter.h | Defines the internal sliding-window rate-limiter interface and state. |
| src/core/rate_limiter.cpp | Implements bucket advancement, threshold checks, expiry, clearing estimates, and configuration-derived limits. |
| src/core/executor.h | Adds rate-limiter ownership, request-ID state, and rate-limit-aware executor interfaces. |
| src/core/executor.cpp | Integrates throttling into request promotion and propagates request IDs through attempts, headers, logs, failures, and retries. |
| src/core/client.cpp | Passes the configured rate-limit policy into the executor. |
| README.md | Documents retry behavior and request deduplication semantics. |
| include/lootlocker/request_id.h | Adds the public request-ID value type and API. |
| CMakeLists.txt | Adds request-ID and rate-limiter implementations to the core library build. |
Review effort: Lite
The dual-threshold sliding window from D25, ported from the Unreal and Unity SDKs,
which share the algorithm:
- Tripwire: more than max_requests_per_tripwire in any rolling window.
- Moving average: the per-bucket average across the whole window exceeds
PerBucketLimit(), i.e. sustained traffic above moving_average_fraction of the
tripwire rate.
The soft cap exists because a pure tripwire lets a client sit at 279 requests a minute
for ever - abusive, but never tripping. The moving average catches sustained near-limit
behaviour the tripwire cannot see.
A tripped request is HELD, not dropped and not failed. It stays queued and is promoted
on a later Update() once the window clears, so the caller sees nothing. That is the
difference between a throttle and an error, and it is why the limiter is checked in the
promote phase rather than at submit: it counts requests actually sent, so a caller is
not throttled for queueing work it never got to send.
Server-side 429 is deliberately NOT the limiter's business. It is handled by the retry
policy, and there is a test that proves the two are separate - with the limiter
disabled, a 429 still retries and still reports RateLimited.
Two behaviours worth recording, both taken from the reference implementations rather
than invented:
- The limiter clears when every counted request has aged out of the MOVING-AVERAGE
window (180 s by default), not the tripwire window (60 s). A burst that trips the
hard cap backs the client off for the full window. My first test asserted the
shorter window and was wrong.
- A held request is not counted. Counting it would keep the limiter tripped by its
own backlog and the window would never drain.
Verified by sabotage: disabling the gate in the promote loop fails five assertions.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
01040c3 to
a369385
Compare
- The limiter recorded a request BEFORE calling Start, so a Start that returned 0
burned quota for a request that never left. Repeated failures could hold unrelated
queued requests, contradicting the "counts requests actually sent" contract. Split
into CanAcquire() and Commit(), and the executor commits only after the transfer
actually started. Verified by sabotage: with the old ordering only 3 of 10
requests are delivered, the rest held by a limiter that thinks it sent them.
- DeriveBucketCount could overflow int on the multiply, and a negative bucket count
takes the "disabled" fast path - silently turning the limiter off for a config that
looked valid. The multiply is now checked before it happens.
- A non-divisible policy silently shortened the window: 60 s with 7 s buckets became
an effective 56 s tripwire and 168 s moving average while the config still
advertised 60/180. Rejected rather than rounded, because a different rate limit
than the adopter asked for is worse than a clear refusal.
- RequestId::Next wrapped UINT64_MAX to 0, storing the invalid sentinel, so the NEXT
call returned RequestId(0) - indistinguishable from a rejected submission and
colliding with that map key. Now wraps to 1.
Both rejections make the limiter inert rather than misconfigured, which is the safe
direction: a broken policy must not throttle a game.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Six review comments, all acted on.
- One Executor constructor instead of three. There are no users yet, so there is
nothing to keep compatible, and three overloads that differ by a trailing argument
are harder to read than one ExecutorSettings struct.
- The limiter is now TICKED, not clock-reading. It used to call the clock from inside
CanAcquire(), which made a const-looking predicate mutate the whole module and meant
the window only advanced when someone happened to ask. The executor owns the clock
and pushes a delta into every tickable component; the limiter keeps a remainder
rather than an absolute timestamp, so sub-bucket time still carries forward.
- CanAcquire() is const, as its name says. It reads and reports; Commit() records. The
trip is detected in Commit, after the increment, so the request that REACHES the cap
is allowed and the next one is held - the cap is "more than 280", not "280".
- IsLimited() is derived (m_limited && m_total > 0) rather than stored. A stored flag
has to be cleared by something, and the only method that runs after a successful
check is Commit - so a caller that only ever checked saw a stale true for ever.
- Explicit names: numberOfBucketsTraversed rather than moved, ms_into_bucket rather
than elapsed.
- Atomics on every primitive, relaxed ordering. The SDK is single-threaded by contract
but not by enforcement: a game that called Update() from two threads would otherwise
corrupt the window silently, and a torn read is a wrong rate limit rather than a
crash - the kind of bug that shows up as "the limiter randomly trips" months later.
No locks: no invariant spans two fields, so a mutex would add contention to buy
nothing. The bucket array is a unique_ptr<atomic<int>[]> because std::atomic is
neither copyable nor movable, so a vector cannot hold it.
Two bugs found while doing this, both caught by the tests:
- Commit wrote to m_buckets[-1] when the limiter had not been ticked yet. That is a
stack overrun, not a wrong number - it crashed three test binaries with 0xc0000409.
Tick now initialises bucket 0 even with a zero delta, and Commit guards anyway.
- IsLimited() and CanAcquire() disagreed for exactly one request, because the check
tripped before the commit recorded it.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🟡 Changes recommended
Active moderate and critical findings remain in clock initialization, public configuration validation, and unbounded bucket allocation, leaving valid configurations potentially inert or unthrottled and risking catastrophic construction failures.
3 open issues
5 resolved since last review
Review effort: Lite
Four review comments, two of them real bugs.
- ValidateConfig never rejected a non-divisible window or an unbounded bucket count, so
a Client built with 60 s / 7 s buckets was considered valid and the limiter silently
became inert - unlimited traffic, with nothing to say so. Both are now rejected at
validation, where the adopter sees them, rather than degrading at construction. The
bucket count is bounded at 100000: the defaults derive 36, and even a 1-hour window
with 1 s buckets over 3 frames is 10,800, so anything past that is a typo.
- The executor used 0 as its "no previous tick" sentinel, but Clock only promises
monotonic milliseconds, not a non-zero origin. A clock that legitimately started at 0
left m_last_tick_ms at 0 for ever and computed a delta of 0 every time, so the
limiter's buckets never advanced and held requests stayed blocked indefinitely.
Initialisation is now a separate bool.
- A disabled limiter derives and allocates nothing. Deriving first and guarding the
allocation afterwards still attempted the allocation for a disabled policy with a huge
window, which in a no-exceptions build terminates the client.
- Formatting: kRelaxed names the memory order once instead of forty times, and the
accessors use implicit conversion where the ordering does not matter. Explicit
.load()/.store() is kept only where it does - the fetch_add in Commit, which is the
one place the read-modify-write matters.
Both bugs verified by sabotage: restoring the 0 sentinel leaves the held requests stuck at
3 of 5, and removing the divisibility check fails three assertions.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🟡 Changes recommended
A critical active issue remains because invalid oversized rate-limit configurations can still trigger an approximately 8 GiB allocation during client construction, potentially terminating the no-exceptions build.
1 open issue
3 resolved since last review
Review effort: Lite
ValidateConfig rejects an oversized rate-limit policy, but the client passed it straight to the executor anyway - so a rejected 2-billion-second window still derived 2 billion buckets and attempted an ~8 GiB allocation during Client construction. In a no-exceptions build that terminates the client, which defeats the point of validating. The client now disables the limiter when config_error is non-empty. The client is inert in that state anyway, so a disabled limiter is exactly right - and it means an invalid policy can never reach the allocator. This is the same class of bug as the previous round: validation rejecting something that construction then does anyway. Verified by sabotage - without the fix the test hangs trying to allocate 8 GiB rather than failing. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 Needs a closer look
Human assessment is needed because the change contains multiple nontrivial rate-limiter edge cases and consistency concerns that could affect behavior under valid extreme configurations.
No open issues 🎉
1 resolved since last review
Review effort: Lite



Implements T11a: the dual-threshold sliding-window rate limiter from D25, ported from the Unreal and Unity SDKs (which share the algorithm).
Two thresholds, because one is not enough:
max_requests_per_tripwirein any rolling window.PerBucketLimit(), i.e. sustained traffic abovemoving_average_fractionof the tripwire rate.The soft cap exists because a pure tripwire lets a client sit at 279 requests a minute for ever — abusive, but never tripping. The moving average catches sustained near-limit behaviour the tripwire cannot see.
A tripped request is held, not dropped and not failed. It stays queued and is promoted on a later
Update()once the window clears, so the caller sees nothing. That is the difference between a throttle and an error.The limiter is checked in the promote phase rather than at submit, because it counts requests actually sent — a caller should not be throttled for queueing work it never got to send.
Server-side 429 is deliberately not the limiter's business. It is handled by the retry policy, and there is a test proving the two are separate: with the limiter disabled, a 429 still retries and still reports
RateLimited.Two behaviours taken from the reference implementations rather than invented:
Verification: 11 limiter tests plus 2 executor integration tests. All 12 suites pass in both curl and no-curl configurations, zero warnings, boundary checks clean. Sabotage-tested: disabling the gate in the promote loop fails five assertions.
One thing worth your eye: the limiter is constructed from
Config::rate_limitand shares the executor's clock, so a test drives both with one fake. That meansRateLimitConfigis now actually read — it was a declared field that nothing consulted, likeConfig::transportwas before T11.