Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(capture): correct rate limiter docs and comments (#107144)

Eli Reisman1e747cbe1a1f
diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rs
index ed5a7f994aa8..3feefb258e4c 100644
--- a/rust/capture/src/config.rs
+++ b/rust/capture/src/config.rs
@@ -117,7 +117,7 @@ pub struct Config {
#[envconfig(default = "60")]
pub global_rate_limit_window_interval_secs: u64,
- /// Max staleness before re-sync with Redis (seconds)
+ /// Base re-sync cadence (seconds). The pressure tier scales it
#[envconfig(default = "15")]
pub global_rate_limit_sync_interval_secs: u64,
@@ -138,27 +138,19 @@ pub struct Config {
#[envconfig(default = "5000000")]
pub global_rate_limit_token_distinctid_local_cache_max_entries: u64,
- /// Minimum effective event count before a key earns a Redis sync. Keys below
- /// this cannot be limited whatever other nodes report, so syncing them costs
- /// two Redis keys per tick for no enforcement value. With an unbounded key
- /// space this is what keeps the pipeline sized to enforceable keys rather
- /// than to total traffic. 0 syncs every key.
- ///
- /// The level is per-pod, so this must stay well under
- /// `threshold / pod_count` or a key sitting at the threshold but spread
- /// evenly across the fleet would never sync and could never be limited.
+ /// Minimum local event count before a key earns a Redis read; `0` reads every key. Keep
+ /// it well under `threshold / pod_count`, or a key at its limit spread across pods is read
+ /// more than a window late.
#[envconfig(default = "10")]
pub global_rate_limit_min_sync_floor: u64,
- /// Max keys drained from the pending-sync set per tick. Excess stays queued,
- /// so a backlog shows up as sync staleness rather than a tick that overruns
- /// its interval.
+ /// Max keys read, and max write entries sent, per tick. The rest wait, so a backlog
+ /// shows as staleness rather than a tick that overruns its interval.
#[envconfig(default = "20000")]
pub global_rate_limit_max_sync_keys_per_tick: usize,
- /// Max Redis keys per individual command. Reads cost two keys per entity, so
- /// an entity chunk is half this. Bounds how long any single command can take,
- /// which is what the per-command timeouts below are budgeting for.
+ /// Max Redis keys per command (a read costs two per entity), so one command fits the
+ /// Redis client's response timeout.
#[envconfig(default = "2000")]
pub global_rate_limit_max_keys_per_command: usize,
@@ -179,8 +171,8 @@ pub struct Config {
#[envconfig(default = "200000")]
pub global_rate_limit_max_pending_sync_entries: usize,
- /// How long a local cache entry survives regardless of access (seconds).
- /// Bounds how stale a key's cached count can be before it is rebuilt.
+ /// Seconds since a cache entry was last written before it is dropped. Every request
+ /// and read rewrites the entry, so at or above the idle timeout this never fires first.
#[envconfig(default = "600")]
pub global_rate_limit_local_cache_ttl_secs: u64,
@@ -198,11 +190,13 @@ pub struct Config {
/// limiting on its own unconfirmed counts. Unset uses each limiter's window; `0` disables.
pub global_rate_limit_max_read_outage_secs: Option<u64>,
- /// Timeout for a single global rate limiter Redis read command (milliseconds).
+ /// The limiter's cap on one Redis read command (milliseconds). The Redis
+ /// client's response timeout also applies, and the shorter one fires first.
#[envconfig(default = "250")]
pub global_rate_limit_read_timeout_ms: u64,
- /// Timeout for a single global rate limiter Redis write command (milliseconds).
+ /// The limiter's cap on one Redis write command (milliseconds). The Redis
+ /// client's response timeout also applies, and the shorter one fires first.
#[envconfig(default = "250")]
pub global_rate_limit_write_timeout_ms: u64,
@@ -224,17 +218,16 @@ pub struct Config {
/// Falls back to the shared redis_url if unset.
pub global_rate_limit_redis_url: Option<String>,
- /// Optional Redis reader URL for global rate limiter (replica).
- /// When set alongside global_rate_limit_redis_url, creates a ReadWriteClient
- /// that routes reads to replicas and writes to the primary.
+ /// Optional replica URL: with `global_rate_limit_redis_url` set, reads go here and writes
+ /// to the primary. A replica read that fails with a recoverable error retries on the primary.
pub global_rate_limit_redis_reader_url: Option<String>,
- /// Response timeout for dedicated global rate limiter Redis (milliseconds).
- /// Defaults to redis_response_timeout_ms if unset.
+ /// Response timeout (ms) for the dedicated limiter Redis, defaulting to
+ /// `redis_response_timeout_ms`; ignored unless `global_rate_limit_redis_url` is set.
pub global_rate_limit_redis_response_timeout_ms: Option<u64>,
- /// Connection timeout for dedicated global rate limiter Redis (milliseconds).
- /// Defaults to redis_connection_timeout_ms if unset.
+ /// Connection timeout (ms) for the dedicated limiter Redis, defaulting to
+ /// `redis_connection_timeout_ms`; ignored unless `global_rate_limit_redis_url` is set.
pub global_rate_limit_redis_connection_timeout_ms: Option<u64>,
/// Redis key holding the dynamic custom per-key rate-limit thresholds
@@ -472,16 +465,12 @@ pub struct Config {
#[envconfig(default = "false")]
pub capture_ingestion_warnings_kafka_tls: bool,
- /// Per-token byte/second budget for the AI lane. `0` disables the limiter.
- ///
- /// The budget is enforced fleet-wide by the global rate limiter, over the
- /// shared `GLOBAL_RATE_LIMIT_WINDOW_INTERVAL_SECS` sliding window, so the
- /// cap a token actually sees is this value times the window length. Within
- /// a window the token may spend the whole budget at once.
+ /// Per-token AI bytes per second, enforced fleet-wide as this times the AI byte window;
+ /// `0` (and import mode) disables it. A token may spend a whole window's budget at once.
#[envconfig(default = "0")]
pub ai_byte_limit_per_second: u64,
- /// CSV list of `token=bytesPerSecond` pairs raising specific tokens' budgets.
+ /// CSV list of `token=bytesPerSecond` pairs setting specific tokens' budgets.
/// Same unit as `ai_byte_limit_per_second`.
pub ai_byte_limit_overrides_csv: Option<String>,
diff --git a/rust/capture/src/global_rate_limiter.rs b/rust/capture/src/global_rate_limiter.rs
index 91b787876a03..9c56e1696e42 100644
--- a/rust/capture/src/global_rate_limiter.rs
+++ b/rust/capture/src/global_rate_limiter.rs
@@ -158,9 +158,8 @@ impl GlobalRateLimiter {
min_sync_floor: config.global_rate_limit_min_sync_floor,
redis_key_prefix: &prefix,
metrics_scope: &metrics_scope,
- // The token-only limiter is not wired to the dynamic refresh
- // source. (The hierarchical resolver is still set but is a no-op
- // for bare token keys, which have no `:distinct_id` suffix.)
+ // No dynamic source for the token-only limiter; its resolver's token
+ // fallback never fires for bare token keys.
enable_dynamic_source: false,
dry_run: config.global_rate_limit_dry_run,
},
@@ -174,15 +173,15 @@ impl GlobalRateLimiter {
/// events/window elsewhere caps bytes/window here. Callers pass an event's
/// serialized size as the count.
///
- /// Budgets are configured in bytes/second and scaled to the window, so the
- /// knob keeps the same meaning whatever `GLOBAL_RATE_LIMIT_WINDOW_INTERVAL_SECS`
- /// is set to.
+ /// Budgets are configured in bytes/second and scaled to the AI byte window
+ /// (see `ai_byte_limit_window`), so the knob keeps its meaning whatever that
+ /// window is set to.
pub fn new_ai_bytes(
config: &Config,
redis_instances: Vec<Arc<dyn Client + Send + Sync>>,
) -> anyhow::Result<Self> {
- // `build` refuses to boot on a zero window, so this scaling never
- // divides a budget down to nothing.
+ // `build` refuses to boot on a zero window, so this scaling never makes
+ // the budget zero.
let (window_secs, window_env_var) = ai_byte_limit_window(config);
let metrics_scope = format!("{}_ai_bytes", config.capture_mode.as_tag());
Self::build(
@@ -235,10 +234,8 @@ impl GlobalRateLimiter {
redis_instances: Vec<Arc<dyn Client + Send + Sync>>,
spec: LimiterSpec<'_>,
) -> anyhow::Result<Self> {
- // `leak_rate_for` divides the threshold by the window, so a zero window
- // gives every bucket an infinite leak rate and the limiter admits
- // everything. That is the opposite of what an operator setting a limit
- // asked for, and it fails silently, so refuse to boot on it.
+ // A zero window panics the background task on its first tick, so no read ever
+ // lands and pods limit on local counts alone. Refuse to boot instead.
if spec.window_secs == 0 {
anyhow::bail!(
"invalid configuration: {} must be greater than 0 (limiter {}); \
@@ -374,7 +371,7 @@ impl GlobalRateLimiter {
// No custom override for this key: enforce the global threshold.
EvalResult::NotApplicable => self.is_global_key_limited(key, count).await,
EvalResult::Limited(response) => Some(response),
- // Allowed / FailOpen on a key that HAS a custom override: not limited,
+ // Allowed on a key that HAS a custom override: not limited,
// and we must not re-check it against the global threshold.
_ => None,
};
@@ -1064,15 +1061,15 @@ mod tests {
#[tokio::test]
async fn test_static_csv_seed_resolves_hierarchically() {
- // Gap fix vs master: a static-CSV token-level override (dynamic source
- // OFF) now applies to that token's token:distinct_id keys too, because
- // the hierarchical resolver is always set — not just on the dynamic path.
+ // A static-CSV token-level override (dynamic source off) applies to that
+ // token's token:distinct_id keys too, because capture always sets the
+ // hierarchical resolver.
let limiter = GlobalRateLimiter::for_test_hierarchical_seeded(Some("phc_seed=7"));
assert!(limiter.is_custom_key("phc_seed"), "exact token override");
assert!(
limiter.is_custom_key("phc_seed:any_user"),
- "token override must apply to token:distinct_id (master only did exact match)"
+ "token override must apply to token:distinct_id"
);
assert!(
!limiter.is_custom_key("other_tok:any_user"),
diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rs
index 14a5f996fcd3..83eac5dbfed7 100644
--- a/rust/capture/src/setup.rs
+++ b/rust/capture/src/setup.rs
@@ -182,14 +182,8 @@ pub async fn build_components(
.expect("failed to create redis client"),
);
- // Each global limiter gets its own Redis client, from the same source: the
- // dedicated rate-limiter Redis when GLOBAL_RATE_LIMIT_REDIS_URL is set,
- // otherwise the shared one. A client owns one MultiplexedConnection, and
- // each limiter drives its own tick loop against it under a per-command
- // timeout, so sharing one would let a slow drain on either limiter eat the
- // other's budget. Key prefixes already keep their counts apart; this keeps
- // their pipelines apart too. Neither is built unless its limiter is on, so
- // a deployment running neither opens no connection.
+ // With GLOBAL_RATE_LIMIT_REDIS_URL set, each limiter gets its own client so a slow
+ // drain on one cannot eat the other's timeout budget; without it, both share the main client.
let ai_byte_limit_enabled = ai_byte_limit_per_second(&config) > 0;
let rate_limiter_redis = if config.global_rate_limit_enabled {
Some(
diff --git a/rust/common/limiters/GLOBAL_RATE_LIMITER.md b/rust/common/limiters/GLOBAL_RATE_LIMITER.md
index bc53be00fd01..3d36e9b47523 100644
--- a/rust/common/limiters/GLOBAL_RATE_LIMITER.md
+++ b/rust/common/limiters/GLOBAL_RATE_LIMITER.md
@@ -5,7 +5,7 @@
The global rate limiter enforces per-entity event throughput limits across a fleet of capture nodes.
It uses a **2-epoch sliding window counter** in Redis for global state,
a **leaky bucket local decay** model for zero-Redis-I/O hot-path decisions,
-a **unified background pipeline** that batches all Redis reads and writes into a single round-trip per tick,
+a **background tick** that sends each node's counts to Redis and reads back fleet counts in bounded, chunked commands,
and **pressure-tiered adaptive sync** to minimize read volume for low-utilization entities.
## Architecture
@@ -17,39 +17,37 @@ and **pressure-tiered adaptive sync** to minimize read volume for low-utilizatio
│ ┌────────────────────────────────────────────────────────────────┐ │
│ │ Hot Path (check_limit_internal) │ │
│ │ │ │
-│ │ 1. Lookup entity in local moka LRU cache │ │
-│ │ 2. Compute effective_level() via leaky bucket decay │ │
-│ │ 3. Compare against threshold → Allowed / Limited │ │
-│ │ 4. Increment local_pending on CacheEntry │ │
-│ │ 5. Enqueue UpdateRequest to mpsc channel │ │
-│ │ 6. Maybe push entity key to pending_sync (DashSet) │ │
+│ │ 1. Enqueue UpdateRequest to mpsc channel (count > 0) │ │
+│ │ 2. Lookup entity in the local moka cache │ │
+│ │ 3. Decide whether to push the key to pending_sync (DashSet) │ │
+│ │ 4. Add this request to local_pending on the CacheEntry │ │
+│ │ 5. Compare effective_level() against the threshold │ │
+│ │ → Allowed / Limited, with the read-outage guard │ │
│ │ │ │
│ │ ⚡ Zero Redis I/O — all decisions are local │ │
│ └───────────┬──────────────────────────────┬────────────────────┘ │
│ │ mpsc channel │ pending_sync set │
│ ▼ ▼ │
│ ┌────────────────────────────────────────────────────────────────┐ │
-│ │ Background Tick Loop (spawned tokio task) │ │
+│ │ Background task (spawned tokio task) │ │
│ │ │ │
-│ │ Every tick_interval (default 1s): │ │
+│ │ Between ticks: merge each UpdateRequest into write_batch │ │
+│ │ HashMap<(entity_key, epoch), count> │ │
│ │ │ │
-│ │ 1. Drain mpsc channel → aggregate into write_batch │ │
-│ │ HashMap<(entity_key, epoch), count> │ │
-│ │ │ │
-│ │ 2. Drain pending_sync set → sync_keys Vec │ │
-│ │ │ │
-│ │ 3. Build single Redis pipeline: │ │
-│ │ WRITES: INCRBY + EXPIREAT for each (key, epoch) │ │
-│ │ READS: MGET [curr_epoch, prev_epoch] per entity │ │
-│ │ │ │
-│ │ 4. Execute pipeline │ │
-│ │ │ │
-│ │ 5. Process read results: │ │
-│ │ - Compute weighted_count from 2-epoch response │ │
-│ │ - Measure drift vs local estimate │ │
-│ │ - Update CacheEntry (estimated_count, pressure, synced_at)│ │
-│ │ - Reset local_pending to 0 (Redis now includes our writes)│ │
-│ │ - Record tier transitions for observability │ │
+│ │ Every tick_interval (default 1s): │ │
+│ │ 1. Take up to max_sync_keys_per_tick keys from pending_sync │ │
+│ │ 2. Purge write entries whose epoch can no longer be read │ │
+│ │ 3. Take up to max_sync_keys_per_tick write entries │ │
+│ │ 4. Per Redis instance, writes first, then reads: │ │
+│ │ WRITES: INCRBY + EXPIREAT per (key, epoch), chunked │ │
+│ │ READS: MGET [curr_epoch, prev_epoch] per entity, chunked │ │
+│ │ 5. Apply each read chunk as it lands: │ │
+│ │ - Compute weighted_count from the 2-epoch response │ │
+│ │ - Measure drift vs local estimate │ │
+│ │ - Update CacheEntry (estimated_count, pressure, synced_at) │ │
+│ │ - Reset local_pending to 0 │ │
+│ │ - Record tier transitions for observability │ │
+│ │ 6. Record read health per instance │ │
│ └───────────────────────────┬────────────────────────────────────┘ │
│ │ │
└──────────────────────────────┼───────────────────────────────────────┘
@@ -116,14 +114,14 @@ due for a sync as soon as it clears `min_sync_floor`; a synced one waits out its
pressure tier. Collapsing the two delays a new key's first read by a full tier
interval, during which the node cannot see the fleet.
-**A known, tolerated race.** The request path's get-modify-insert can overwrite
-the entry a Redis read just refreshed. The effect is bounded: the clobbered
-entry is due for a sync at once (recovery is one tick), the stale estimate is
-never higher than the fresh one (it only under-counts), and the collision
-window is microseconds per event against one read per key every 7.5 to 60
-seconds. A fix via moka's per-key entry API cost ~0.3 µs per evaluation (+31%
-on this crate's bench) for no measurable change in decisions, so it is
-deliberately not applied.
+**A known, tolerated race.**
+The request path's get-modify-insert can overwrite the entry a Redis read just refreshed.
+The overwriting entry keeps the older estimate and the older `synced_at`, so it stays due for a sync, and the key's next request queues the read that corrects it.
+Until then its estimate can be lower or higher than the fresh read.
+It is higher when the key's previous epoch was over its threshold, because the window then drains faster than the leak rate.
+The collision window is microseconds per event against one read per key every 7.5 to 60 seconds.
+A fix via moka's per-key entry API cost ~0.3 µs per evaluation (+31% on this crate's bench) for no measurable change in decisions, so it is deliberately not applied.
+
Between syncs, the estimate **decays** at the configured leak rate:
```text
@@ -133,8 +131,9 @@ effective_level(entry, now) =
max(0, estimated_count - leak_rate × elapsed) + local_pending
```
-This models the natural drain of events from the sliding window,
-keeping the local estimate useful for much longer than a simple stale/fresh binary.
+This approximates the drain of the sliding window and keeps the local estimate useful for much longer than a simple stale/fresh binary.
+It matches the real drain only when the previous epoch held exactly the threshold.
+Below that the local estimate drains too fast, and above it too slowly.
**Once reads have failed for `max_read_outage`, `local_pending` cannot limit a key.**
`local_pending` is a correction to the last fleet count this node read, and only a successful read clears it.
@@ -186,33 +185,37 @@ To close even that gap, set `max_read_outage` to `window_interval - sync_interva
synced_at next sync
```
-### 3. Unified Background Pipeline
+### 3. Background Pipeline
-All Redis I/O is deferred to a single background tokio task.
-This means the hot path (request evaluation) **never blocks on Redis**.
+All counter I/O runs in one background tokio task per limiter, so the hot path (request evaluation) **never blocks on Redis**.
+A second task refreshes custom-key thresholds when a dynamic source is configured.
The background task uses `tokio::select!` over two sources:
```text
-┌───────────────────────────┐ ┌──────────────────────────┐
-│ mpsc channel (writes) │ │ tokio interval (tick) │
-│ │ │ │
-│ UpdateRequest { │ │ Every tick_interval: │
-│ key, count, timestamp │ │ → drain both sources │
-│ } │ │ → build pipeline │
-│ │ │ → execute │
-│ Aggregated into: │ │ → process results │
-│ HashMap<(key, epoch), │ │ │
-│ count> │ │ │
-└───────────────────────────┘ └──────────────────────────┘
+┌───────────────────────────┐ ┌──────────────────────────────┐
+│ mpsc channel (writes) │ │ tokio interval (tick) │
+│ │ │ │
+│ UpdateRequest { │ │ Every tick_interval: │
+│ key, count, timestamp │ │ → take bounded slices of │
+│ } │ │ pending_sync and writes │
+│ │ │ → send writes, then reads │
+│ Merged between ticks │ │ → apply read results │
+│ into: │ │ │
+│ HashMap<(key, epoch), │ │ │
+│ count> │ │ │
+└───────────────────────────┘ └──────────────────────────────┘
```
-The pipeline per tick consists of:
+The channel is not read while a tick runs, so updates wait in it until the tick ends.
-- **Writes**: `INCRBY key delta` + `EXPIREAT key deadline` for each `(entity, epoch)` with pending counts
-- **Reads**: `MGET [current_epoch_key, prev_epoch_key]` for each entity in `pending_sync`
+Each tick, per Redis instance:
-All operations go in a single Redis round-trip.
+- **Writes** go first: `INCRBY key delta` + `EXPIREAT key deadline` for each `(entity, epoch)` with pending counts.
+- **Reads** follow: `MGET [current_epoch_key, prev_epoch_key]` for each entity taken from `pending_sync`.
+- Writes go first because a read result resets the key's `local_pending`, so the read must already include this tick's writes.
+- Each side is split into commands of at most `max_keys_per_command` Redis keys, so a read command carries half that many entities.
+- At most `max_concurrent_commands` commands run at once per instance. A tick with both reads and writes costs at least two round trips, and more when the batch is large.
### 4. Adaptive Sync (Pressure Tiers)
@@ -226,10 +229,10 @@ The system assigns each entity a **pressure tier** based on how close it is to t
│ │
│ ┌───────────┐ ┌──────────────┐ ┌─────────┐ ┌───────────┐ │
│ │ Idle │ │ Low │ │ Normal │ │ Hot │ │
- │ │ < 10% │ │ 10% - 50% │ │50% - 80%│ │ > 80% │ │
+ │ │ < 10% │ │ 10% - 50% │ │50% - 80%│ │ ≥ 80% │ │
│ │ │ │ │ │ │ │ │ │
- │ │ No sync │ │ 4× interval │ │ 1× base │ │ ½× base │ │
- │ │ │ │ (60s) │ │ (15s) │ │ (7.5s) │ │
+ │ │ 4× base, │ │ 4× interval │ │ 1× base │ │ ½× base │ │
+ │ │above floor│ │ (60s) │ │ (15s) │ │ (7.5s) │ │
│ └───────────┘ └──────────────┘ └─────────┘ └───────────┘ │
│ │
│ 0% 10% 50% 80% 100% │
@@ -238,20 +241,35 @@ The system assigns each entity a **pressure tier** based on how close it is to t
└─────────────────────────────────────────────────────────────┘
```
-With typical power-law traffic distributions (~90% idle, ~8% low, ~1.5% normal, ~0.5% hot),
-this reduces pipeline read volume by **~95%** compared to syncing every entity at the base interval.
+A key below `min_sync_floor` does not sync at all, whatever its tier.
+An idle key above the floor syncs on the Low cadence, so a key that is hot across the fleet but cold on every node is still discovered.
-**Tier transitions are immediate.**
-If local traffic pushes an idle entity above the 10% boundary,
-it's promoted to Low on the very next request — no waiting for a stale sync interval.
+**The tier is recomputed on every request.**
+It uses the larger of the current `level / threshold` and the pressure at the last sync, so local traffic moves a key to a faster cadence at once.
+`tier_transitions_total` counts changes only when a read lands.
Tier boundaries are pressure-based (level / threshold), so they apply correctly to custom keys regardless of threshold magnitude. A custom key with a 100× higher limit than the default will sync at the same relative cadence when at equivalent pressure.
-**Tier-distribution gauges come from a throttled full scan.** `cache_size` is cheap (`entry_count`) and emits every tick. The per-tier `sync_tier_gauge` needs a full `cache.iter()` scan, so it runs only every `TIER_SCAN_INTERVAL_TICKS` (default 30): the distribution moves slowly and prod metrics dedup to 60s, so scanning every tick would be wasted work under load. The scan runs in the background tick task, off the per-event hot path.
+**Tier-distribution gauges come from a throttled full scan.** `cache_size` is cheap (`entry_count`) and emits every tick. The per-tier `sync_tier_gauge` needs a full `cache.iter()` scan, so it runs only every `TIER_SCAN_INTERVAL_TICKS` (a constant, 30): the distribution moves slowly and prod metrics dedup to 60s, so scanning every tick would be wasted work under load. The scan runs in the background tick task, off the per-event hot path.
+
+### 5. Timeouts
+
+Each Redis command runs under two timeouts, and the shorter one fires first:
+
+- The limiter's own timer, `global_read_timeout` or `global_write_timeout` (250ms by default).
+- The Redis client's response timeout. In capture it is `GLOBAL_RATE_LIMIT_REDIS_RESPONSE_TIMEOUT_MS`, else `REDIS_RESPONSE_TIMEOUT_MS` (100ms by default).
+
+A client timeout is counted under `cause="redis_write"` for writes and `cause="redis_error"` for reads.
+The `write_timeout` and `read_timeout` causes mean the limiter's own timer fired.
+With the read/write split client, a replica read that fails with a recoverable error, such as a timeout, is retried on the primary. So one read can use two client timeouts, and the limiter's read timer can still fire.
+
+A write that times out is not retried.
+If the command already reached Redis it still applies.
+If it was still queued in the client, the client drops it, so a timed-out write may or may not have counted.
## Data Model
-### CacheEntry (local moka LRU)
+### CacheEntry (local moka cache)
```rust
struct CacheEntry {
@@ -263,20 +281,21 @@ struct CacheEntry {
```
`local_pending` is reset to 0 when fresh data arrives from Redis.
-Since `estimated_count` already includes events this node wrote via INCRBY across prior ticks,
-preserving `local_pending` would double-count them.
-Events arriving during the MGET window (~100ms) are briefly lost from the local estimate
-but are written to Redis on the next tick — the under-count is negligible (<0.002% of threshold).
+Since `estimated_count` already includes the events this node wrote via INCRBY, preserving `local_pending` would double-count them.
+Events whose write has not landed when the read does drop out of the local estimate.
+That covers events counted after the tick took its write batch, and writes deferred past the per-tick cap.
+They appear in a later read once their write lands, unless their epoch ages out first and the tick purges them.
### Redis Key Model
```text
Key: {prefix}:{entity_key}:{epoch_number}
Value: integer counter (INCRBY)
-Dies: (epoch + 2) × window_interval + a per-key offset inside one window
+Dies: (epoch + 2) × window_interval + grace + a per-key offset inside one window
```
-Up to 3 keys per entity exist at any time. Reads consult 2 (current + previous
+`grace` is the part of `global_cache_ttl` above 2 × `window_interval`, and zero by default.
+With zero grace, up to 3 keys per entity exist at any time. Reads consult 2 (current + previous
epoch); the offset that spreads expiry can hold the generation before those
alive for up to one more window.
@@ -289,93 +308,68 @@ running value so an alert can compare them.
### Configuration
+Capture runs two limiters from these settings: the per-(token, distinct_id) limiter and the AI byte budget.
+Where the two read different env vars, both are listed.
+
#### Rate limiting behavior
| Parameter | Default | Env var (capture) | Description |
|---|---|---|---|
-| `global_threshold` | 1,000,000 | `GLOBAL_RATE_LIMIT_THRESHOLD` | Default limit per window per entity |
-| `window_interval` | 60s | `GLOBAL_RATE_LIMIT_WINDOW_INTERVAL_SECS` | Sliding window size for the 2-epoch counter |
-| `sync_interval` | 15s | `GLOBAL_RATE_LIMIT_SYNC_INTERVAL_SECS` | Base staleness before re-sync (adaptive tiers multiply this) |
+| `global_threshold` | 1,000,000 | `GLOBAL_RATE_LIMIT_TOKEN_DISTINCTID_THRESHOLD` (capture default 300,000); AI: `AI_BYTE_LIMIT_PER_SECOND` × the AI window | Default limit per window per key |
+| `window_interval` | 60s | `GLOBAL_RATE_LIMIT_WINDOW_INTERVAL_SECS`; AI: `AI_BYTE_LIMIT_WINDOW_INTERVAL_SECS`, else the former | Sliding window size for the 2-epoch counter |
+| `sync_interval` | 15s | `GLOBAL_RATE_LIMIT_SYNC_INTERVAL_SECS` | Base re-sync cadence. The pressure tier scales it |
| `tick_interval` | 1s | `GLOBAL_RATE_LIMIT_TICK_INTERVAL_MS` | Background pipeline cadence |
+| `min_sync_floor` | 10 | `GLOBAL_RATE_LIMIT_MIN_SYNC_FLOOR` (the AI limiter uses 0) | Minimum local level before a key is read. Capped at 1% of the key's threshold |
| `max_read_outage` | `window_interval` | `GLOBAL_RATE_LIMIT_MAX_READ_OUTAGE_SECS` | How long, in wall-clock time, reads to an instance must keep failing before its keys stop limiting on this node's unconfirmed counts. A replica read that the primary answers counts as a success. Derived from the configured window, not the default. `0` disables the guard |
-| `custom_keys` | empty | `GLOBAL_RATE_LIMIT_OVERRIDES_CSV` | Per-key threshold overrides (`key=limit,...`) |
+| `custom_keys` | empty | `GLOBAL_RATE_LIMIT_TOKEN_DISTINCTID_OVERRIDES_CSV`; AI: `AI_BYTE_LIMIT_OVERRIDES_CSV` | Per-key threshold overrides (`key=limit,...`) |
+| `custom_key_source` | none | `GLOBAL_RATE_LIMIT_CUSTOM_THRESHOLD_KEY` | Redis key of a JSON threshold map that replaces `custom_keys` once fetched. Per-(token, distinct_id) limiter only |
+| `custom_key_refresh_interval` | 60s | `GLOBAL_RATE_LIMIT_CUSTOM_THRESHOLD_REFRESH_SECS` | Refresh cadence for `custom_key_source` |
-#### Local cache (Moka)
+#### Throughput bounds
-These use sensible defaults derived from the rate limiting behavior settings above.
-They are not exposed as env vars in capture — change them in the library defaults
-only if you're also changing the window/sync intervals.
-
-| Parameter | Default | Description |
-|---|---|---|
-| `local_cache_max_entries` | 300,000 | Hard cap on entry count. ~400 bytes/entry → 300K ≈ 120 MB. Exposed as `GLOBAL_RATE_LIMIT_LOCAL_CACHE_MAX_ENTRIES` in capture |
-| `local_cache_ttl` | 600s | Absolute entry expiry. Should be long enough for leaky bucket decay to stay useful between syncs |
-| `local_cache_idle_timeout` | 300s | Entries not accessed within this window are evicted early. Hot keys are constantly re-inserted so they never idle-expire; cold keys reclaim slots faster than waiting for the full TTL |
+| Parameter | Default | Env var (capture) | Description |
+|---|---|---|---|
+| `max_sync_keys_per_tick` | 20,000 | `GLOBAL_RATE_LIMIT_MAX_SYNC_KEYS_PER_TICK` | Keys read per tick, and write entries sent per tick. The rest wait for later ticks |
+| `max_keys_per_command` | 2,000 | `GLOBAL_RATE_LIMIT_MAX_KEYS_PER_COMMAND` | Redis keys per command. A read costs two keys per entity |
+| `max_concurrent_commands` | 4 | `GLOBAL_RATE_LIMIT_MAX_CONCURRENT_COMMANDS` | Commands in flight at once per instance |
+| `max_write_batch_entries` | 200,000 | `GLOBAL_RATE_LIMIT_MAX_WRITE_BATCH_ENTRIES` | Buffered `(key, epoch)` entries. At the cap, updates for new keys drop and are counted |
+| `max_pending_sync_entries` | 200,000 | `GLOBAL_RATE_LIMIT_MAX_PENDING_SYNC_ENTRIES` | Queued syncs. At the cap, new sync requests drop and re-queue on the key's next request |
+| `channel_capacity` | 1,000,000 | — | mpsc channel buffer for async update requests |
-#### Redis
+#### Local cache (Moka)
-| Parameter | Default | Description |
-|---|---|---|
-| `global_cache_ttl` | 2 × `window_interval` | Sets the deadline on Redis epoch keys, applied as `EXPIREAT` rather than a relative TTL so a key's life follows its epoch instead of its last write. Any value above the two-window minimum becomes clock-skew grace. |
-| `global_read_timeout` | 100ms | Timeout for batched MGET reads |
-| `global_write_timeout` | 100ms | Timeout for batched INCRBY writes |
-| `redis_key_prefix` | `@posthog/global_rate_limiter` | Prefix for all Redis keys (capture derives from `capture_mode`) |
+| Parameter | Default | Env var (capture) | Description |
+|---|---|---|---|
+| `local_cache_max_entries` | 300,000 | `GLOBAL_RATE_LIMIT_TOKEN_DISTINCTID_LOCAL_CACHE_MAX_ENTRIES` (capture default 5,000,000); AI: `AI_BYTE_LIMIT_LOCAL_CACHE_MAX_ENTRIES` | Entry cap. Moka's default TinyLFU policy can refuse a new key at the cap, and that key then takes the always-allowed miss path |
+| `local_cache_ttl` | 600s | `GLOBAL_RATE_LIMIT_LOCAL_CACHE_TTL_SECS` | Time since the entry was last written. Every request and every read rewrites the entry, so this restarts each time. At or above `local_cache_idle_timeout` it never fires first |
+| `local_cache_idle_timeout` | 300s | `GLOBAL_RATE_LIMIT_LOCAL_CACHE_IDLE_TIMEOUT_SECS` | Evicts entries no request touched within this time. Hot keys never idle-expire; cold keys reclaim slots |
-#### Internal
+#### Redis
| Parameter | Default | Env var (capture) | Description |
|---|---|---|---|
-| `channel_capacity` | 1,000,000 | — | mpsc channel buffer for async update requests |
+| `global_cache_ttl` | 120s | — | Only the part above 2 × `window_interval` is used, as clock-skew grace. Keys expire at the absolute deadline from `epoch_expire_at`, so a smaller value cannot shorten their life |
+| `global_read_timeout` | 250ms | `GLOBAL_RATE_LIMIT_READ_TIMEOUT_MS` | The limiter's cap on one read command. See Timeouts |
+| `global_write_timeout` | 250ms | `GLOBAL_RATE_LIMIT_WRITE_TIMEOUT_MS` | The limiter's cap on one write command. See Timeouts |
+| `redis_key_prefix` | `@posthog/global_rate_limiter` | — | Prefix for all Redis keys. Capture derives the per-(token, distinct_id) prefix from `capture_mode`; the AI prefix carries none |
-#### How the TTL settings relate
+Capture connects each limiter to `GLOBAL_RATE_LIMIT_REDIS_URL`, with reads going to `GLOBAL_RATE_LIMIT_REDIS_READER_URL` when that is set.
+Without `GLOBAL_RATE_LIMIT_REDIS_URL`, both limiters share capture's main Redis client, and the `GLOBAL_RATE_LIMIT_REDIS_*_TIMEOUT_MS` settings do nothing.
-```text
- Time ──────────────────────────────────────────────────────────────────►
-
- │◄── window_interval (60s) ──►│
- │ │
- │ global_cache_ttl (2×window, clamped at construction) │
- │ Redis epoch keys expire after this. Below 2×window the previous │
- │ epoch key dies while reads still need it, and the estimate drops. │
- │◄─────────────────────────────────────────────────────────────────────►│
- │ │
- │ local_cache_idle_timeout (300s) │
- │ Cold keys (no traffic) evicted after this, reclaiming Moka slots │
- │◄─────────────────────────────────────────────────────────────────────►│
- │ │
- │ local_cache_ttl (600s) │
- │ Absolute expiry — even hot keys eventually re-sync from scratch │
- │◄─────────────────────────────────────────────────────────────────────►│
-```
+#### Clamps and tuning
-**Tuning guidance:**
-
-- `local_cache_idle_timeout` should be **shorter** than `local_cache_ttl`
- but **longer** than `sync_interval × 4` (the slowest adaptive tier interval)
- so that Low-tier keys aren't prematurely evicted between syncs.
-- Under high key cardinality with cold-skewed traffic,
- a shorter idle timeout reclaims slots faster, keeping the cache responsive.
-- `local_cache_ttl` acts as an upper bound on how stale an entry can get
- before being forced to re-sync from scratch on next access.
-- **`min_sync_floor` gates reads only.** Every event's count reaches Redis
- regardless of the floor; the floor only suppresses the `MGET` for keys too far
- under their threshold to be limited. Writes are bounded separately:
- `absorb_update` merges by `(key, epoch)` per tick, so write volume scales with
- distinct active keys, not event rate.
-- `global_cache_ttl` is an enforcement requirement, not only Redis hygiene: the
- previous epoch's key is read for a full window after its last write, and a
- TTL under 2 × `window_interval` zeroes `prev_count` early, understating the
- estimate. `new` clamps it up and warns. Much larger values only waste Redis
- memory on dead keys.
-
-**All three TTLs are clamped at construction**, because each one expiring inside
-the window it serves causes silent under-enforcement:
+`new()` clamps three settings and logs a warning when it does:
| Parameter | Clamped to at least | What an undersized value breaks |
|---|---|---|
| `local_cache_idle_timeout` | `window_interval` | Entries expire mid-window and the next request takes the always-allowed miss path |
-| `local_cache_ttl` | `window_interval` | Same, on the absolute expiry path |
-| `global_cache_ttl` | 2 × `window_interval` | The previous epoch key dies while reads still need it, so `prev_count` reads as 0 |
+| `local_cache_ttl` | `window_interval` | Same, for an entry that no request or read rewrites for that long |
+| `global_cache_ttl` | 2 × `window_interval` | Nothing, because expiry is absolute and a smaller value only removes grace. Capture never sets it, so the warning fires at startup whenever the window is above 60s |
+
+- An entry idles out only when no request touches it for `local_cache_idle_timeout`, so a key's sync cadence never evicts an active key.
+- Under high key cardinality with cold-skewed traffic, a shorter idle timeout reclaims slots faster.
+- **`min_sync_floor` gates reads only.** It never drops a count; it only suppresses the `MGET` for keys too far under their threshold to be limited. Counts can still be lost to a full channel, the write-batch cap, or a failed write.
+- Writes are bounded separately. `absorb_update` merges updates by `(key, epoch)` between ticks, so write volume scales with distinct active keys, not event rate.
## Request Flow
@@ -383,46 +377,55 @@ the window it serves causes silent under-enforcement:
Request arrives
│
▼
- ┌──────────────┐
- │ check_limit │
- │ │
- │ Cache hit? │──── No ──→ Insert fresh entry, queue sync, ALLOW
- │ │ (fail open on first contact)
- └──────┬───────┘
- │ Yes
+ ┌──────────────────────────┐
+ │ Custom mode, no override │──── Yes ──→ NOT APPLICABLE
+ └──────┬───────────────────┘
+ │ No
▼
- ┌──────────────────────┐
- │ effective_level() │
- │ │
- │ = max(0, est - drain)│
- │ + local_pending │
- │ + this request │
- └──────┬───────────────┘
- │
+ ┌──────────────────────────┐
+ │ Enqueue the count to the │ (any count > 0, limited or not)
+ │ mpsc channel │
+ └──────┬───────────────────┘
▼
- ┌──────────────────────┐
- │ level >= threshold? │──── Yes ──→ LIMITED (return response)
- └──────┬───────────────┘
- │ No
+ ┌──────────────────────────┐
+ │ Cache hit? │──── No ──→ Insert entry with this count,
+ └──────┬───────────────────┘ queue a sync if at or above
+ │ Yes the floor, ALLOW
▼
- ┌──────────────────────┐
- │ Sync needed? │
- │ (pressure-tiered) │──── Yes ──→ Push to pending_sync
- └──────┬───────────────┘
- │
+ ┌──────────────────────────┐
+ │ Below the floor? no sync │
+ │ Else due by tier cadence │──── Due ──→ Push to pending_sync
+ └──────┬───────────────────┘
▼
- ┌──────────────────────┐
- │ Enqueue update │
- │ to mpsc channel │
- └──────┬───────────────┘
- │
+ ┌──────────────────────────┐
+ │ Add this count to │
+ │ local_pending │
+ └──────┬───────────────────┘
+ ▼
+ ┌──────────────────────────┐
+ │ level >= threshold? │──── No ──→ ALLOW
+ └──────┬───────────────────┘
+ │ Yes
+ ▼
+ ┌──────────────────────────┐
+ │ Reads to the key's │
+ │ instance failing for │──── No ──→ LIMIT
+ │ max_read_outage? │
+ └──────┬───────────────────┘
+ │ Yes
▼
- ALLOWED
+ ┌──────────────────────────┐
+ │ Decayed fleet count │──── Yes ──→ LIMIT
+ │ >= threshold? │
+ └──────┬───────────────────┘
+ │ No
+ ▼
+ ALLOW (counted in outage_limit_skipped_total)
```
## Multi-Redis Partitioning
-When multiple Redis instances are configured, work is partitioned by consistent hashing:
+When multiple Redis instances are configured, work is split by a stable hash of the key, modulo the instance count:
```text
Entity keys Redis instances
@@ -440,8 +443,8 @@ When multiple Redis instances are configured, work is partitioned by consistent
### Before raising the instance count
-Partitioning is dormant at one instance: `select_redis_client` returns early and
-never hashes. Two things to know before that changes.
+Partitioning is dormant at one instance: `instance_index` returns 0 and never
+hashes. Two things to know before that changes.
1. **Salt any new per-key derivation.** `select_redis_client` and
`epoch_expire_at` both hash the entity key. If they share a hash, a shard
@@ -454,9 +457,16 @@ never hashes. Two things to know before that changes.
flight.** Pods on the old count and the new one route the same key to
different instances, so each sees part of its traffic. This under-counts and
therefore fails open, never over-enforces, and it clears once every pod
- agrees and the current epoch keys expire. Modulo sharding moves nearly every
- key on a count change; a consistent-hashing scheme would move about 1/N of
- them and shrink this window, but it cannot remove it.
+ agrees and the current epoch keys expire. Modulo sharding moves N/(N+1) of
+ the keys when the count goes from N to N+1; a consistent-hashing scheme would
+ move about 1/(N+1) of them and shrink this window, but it cannot remove it.
+
+## Redis load
+
+- The hot path issues no Redis I/O.
+- Writes: each tick sends one INCRBY and one EXPIREAT per distinct `(key, epoch)` this node saw since the last drain, up to `max_sync_keys_per_tick`.
+- Every node that saw a key writes it, so write volume grows with fleet size as well as with the number of active keys.
+- Reads: each tick reads two epoch keys per key that is at or above the floor and due by its tier, up to `max_sync_keys_per_tick`.
## Metrics
@@ -466,48 +476,43 @@ never hashes. Two things to know before that changes.
| `global_rate_limiter_cache_counts_total` | Counter | Cache hit/miss/sync_queued, exactly one per evaluation |
| `global_rate_limiter_outage_limit_skipped_total` | Counter | Limits withheld because the key's instance was in a read outage. It stays at zero while reads work |
| `global_rate_limiter_read_failing_seconds` | Gauge | Seconds since reads to one instance began failing, per `redis_idx`, set on each tick that reads. Zero while reads succeed. The guard engages once it reaches `max_read_outage` |
-| `global_rate_limiter_pipeline_ms` | Histogram | Redis pipeline latency |
-| `global_rate_limiter_tick_ms` | Histogram | Full tick duration |
-| `global_rate_limiter_pipeline_size` | Histogram | Entities per pipeline (read/write) |
-| `global_rate_limiter_pending_sync_size` | Gauge | Backpressure signal |
+| `global_rate_limiter_pipeline_ms` | Histogram | Latency of successful commands only, with no read/write label, so failed and timed-out commands are absent |
+| `global_rate_limiter_tick_ms` | Histogram | Duration of ticks that had work |
+| `global_rate_limiter_pipeline_size` | Histogram | Keys read and `(key, epoch)` entries written per tick, by `op` |
+| `global_rate_limiter_commands_per_tick` | Histogram | Commands issued per tick per instance after chunking, by `op` |
+| `global_rate_limiter_pending_sync_size` | Gauge | Keys read this tick, capped at `max_sync_keys_per_tick`. For the backlog, use `sync_deferred_size` |
+| `global_rate_limiter_sync_deferred_size` | Gauge | Keys still queued for sync after a tick took its slice |
+| `global_rate_limiter_write_deferred_size` | Gauge | `(key, epoch)` entries still batched after a tick took its slice |
+| `global_rate_limiter_sync_skipped_total` | Counter | Syncs not queued because the key is below the floor |
| `global_rate_limiter_sync_tier_gauge` | Gauge | Entity distribution across tiers (scanned every `TIER_SCAN_INTERVAL_TICKS`) |
-| `global_rate_limiter_tier_transitions_total` | Counter | Tier promotion/demotion events |
+| `global_rate_limiter_tier_transitions_total` | Counter | Tier changes, counted when a read lands |
| `global_rate_limiter_cache_size` | Gauge | Live local cache entry count vs cap |
| `global_rate_limiter_window_seconds` | Gauge | Configured `window_interval` per scope. Deployments that share a Redis key prefix must report the same value, or their epoch keys diverge and the shared counter splits |
| `global_rate_limiter_eviction_total` | Counter | Cache evictions by cause (size/expired/explicit) |
| `global_rate_limiter_estimate_drift` | Histogram | Local vs Redis accuracy |
| `global_rate_limiter_sync_staleness_ms` | Histogram | Real staleness at access time. A large share sits past one minute in normal operation, from idle keys that stopped syncing below the floor, so read its tail as expected rather than as an outage |
-| `global_rate_limiter_error_total` | Counter | Pipeline errors and timeouts |
-| `global_rate_limiter_records_total` | Counter | Total Redis commands issued |
-
-## Redis Load Reduction
-
-Compared to the previous N-bucket design:
-
-| Dimension | Old (N-bucket) | New (2-epoch + adaptive) |
-|---|---|---|
-| Keys per entity | 3 | 2 |
-| Redis round-trips per check | 1 (inline MGET) | 0 (hot path is local) |
-| Round-trips per tick | N/A | 1 (batched pipeline) |
-| Read volume per tick | N/A | ~296 entities (vs ~6,667 without adaptive) |
-| Total RT reduction | — | ~99% |
-| Read volume reduction | — | ~95% |
+| `global_rate_limiter_error_total` | Counter | By `step` and `cause`: failed commands (`redis_write`, `redis_error`, `write_timeout`, `read_timeout`, see Timeouts), drops at the caps (`channel_full`, `write_batch_full`, `pending_sync_full`), and `stale_epoch_purged` |
+| `global_rate_limiter_records_total` | Counter | Keys moved by successful commands, by `op`: write entries for writes, two result slots per entity for reads |
+| `global_rate_limiter_custom_thresholds_loaded` | Gauge | Custom thresholds applied at the last successful refresh |
+| `global_rate_limiter_custom_thresholds_last_refresh_timestamp` | Gauge | Unix time of the last successful refresh |
+| `global_rate_limiter_custom_thresholds_fetch_total` | Counter | Refresh fetches by `result`. Not scoped to a limiter |
## File Layout
```text
rust/common/limiters/
├── src/
-│ ├── global_rate_limiter.rs ← Core implementation + 31 unit tests
+│ ├── global_rate_limiter.rs ← Core implementation and unit tests
+│ ├── custom_key_source.rs ← Dynamic custom-key thresholds from Redis
│ └── ...
├── tests/
-│ └── global_rate_limiter_integration_tests.rs ← 9 real-Redis tests
+│ └── global_rate_limiter_integration_tests.rs ← Real-Redis tests
├── benches/
│ └── global_rate_limiter.rs ← Benchmarks
└── Cargo.toml
rust/capture/src/
├── global_rate_limiter.rs ← Capture service wrapper
-├── config.rs ← Env config (sync_interval, tick_interval)
+├── config.rs ← Env config for both capture limiters
└── prometheus.rs ← Histogram bucket registration
```
diff --git a/rust/common/limiters/src/custom_key_source.rs b/rust/common/limiters/src/custom_key_source.rs
index b25ce9bd29f5..7f081e1155da 100644
--- a/rust/common/limiters/src/custom_key_source.rs
+++ b/rust/common/limiters/src/custom_key_source.rs
@@ -15,11 +15,8 @@ const FETCH_COUNTER: &str = "global_rate_limiter_custom_thresholds_fetch_total";
/// A pluggable source of custom-key thresholds for the global rate limiter.
///
-/// The refresh loop calls `fetch` on a timer and atomically swaps the returned
-/// map into the limiter. `Ok(Some(map))` replaces the current thresholds,
-/// `Ok(None)` means "no thresholds configured" (clears them), and `Err` leaves
-/// the current map untouched (fail-static). Implementations own their own
-/// connection lifecycle, including reconnecting after a transient failure.
+/// Polled by the refresh loop: `Ok(Some(map))` replaces the thresholds, while `Ok(None)`
+/// (key absent) and `Err` keep the current map. Implementations own their reconnects.
#[async_trait]
pub trait CustomKeyThresholdSource: Send + Sync {
async fn fetch(&self) -> Result<Option<HashMap<String, u64>>, CustomRedisError>;
diff --git a/rust/common/limiters/src/global_rate_limiter.rs b/rust/common/limiters/src/global_rate_limiter.rs
index 1f65337967a3..896f8c2f96cf 100644
--- a/rust/common/limiters/src/global_rate_limiter.rs
+++ b/rust/common/limiters/src/global_rate_limiter.rs
@@ -76,13 +76,13 @@ const TIER_LABELS: [&str; 4] = ["idle", "low", "normal", "hot"];
/// Pressure tiers for adaptive sync scheduling
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PressureTier {
- /// < 10% capacity: skip sync entirely
+ /// < 10% capacity: no cadence of its own. Above `min_sync_floor` it syncs on the Low cadence
Idle,
/// 10-50% capacity: sync at 4x sync_interval
Low,
/// 50-80% capacity: sync at 1x sync_interval
Normal,
- /// > 80% capacity: sync at sync_interval / 2
+ /// >= 80% capacity: sync at sync_interval / 2
Hot,
}
@@ -122,7 +122,7 @@ impl PressureTier {
/// Compute the effective sync interval for a given pressure tier
pub fn tier_sync_interval(pressure: f64, base_sync_interval: Duration) -> Option<Duration> {
match PressureTier::from_pressure(pressure) {
- PressureTier::Idle => None, // skip sync entirely
+ PressureTier::Idle => None, // no cadence of its own; the caller uses the Low cadence
PressureTier::Low => Some(base_sync_interval.mul_f64(4.0)),
PressureTier::Normal => Some(base_sync_interval),
PressureTier::Hot => Some(base_sync_interval.div_f64(2.0)),
@@ -137,9 +137,9 @@ pub trait GlobalRateLimiter: Send + Sync {
/// - Consult the local cache with leaky bucket decay
/// - Enqueue an update to the key's count for async batch submission
/// - Push to pending_sync if sync interval exceeded
- /// - Fail open if the local cache is empty and no prior data exists
+ /// - Allow the request if the local cache has no entry for the key yet
///
- /// Returns `EvalResult` indicating whether the request is allowed, limited, or failed open
+ /// Returns `EvalResult` indicating whether the request is allowed or limited
async fn check_limit(
&self,
key: &str,
@@ -155,7 +155,7 @@ pub trait GlobalRateLimiter: Send + Sync {
/// - If the key is present in the map, the override threshold value is applied
/// - If the key is not present in the map, it is not subject to rate limiting
///
- /// Returns `EvalResult` indicating whether the request is allowed, limited, not applicable, or failed open
+ /// Returns `EvalResult` indicating whether the request is allowed, limited, or not applicable
async fn check_custom_limit(
&self,
key: &str,
@@ -177,15 +177,18 @@ pub struct GlobalRateLimiterConfig {
pub global_threshold: u64,
/// Sliding window size (e.g., 60 seconds) - defines the 2-epoch counter size
pub window_interval: Duration,
- /// Max staleness before re-sync with Redis (default 15s)
+ /// Base re-sync cadence (default 15s). The pressure tier scales it: Hot is
+ /// half, Normal is 1x, Low and Idle are 4x
pub sync_interval: Duration,
/// Background task cadence for pipeline reads + writes (default 1s)
pub tick_interval: Duration,
/// Redis key prefix (not including final separator)
pub redis_key_prefix: String,
- /// TTL for Redis epoch keys (2 * window_interval)
+ /// Epoch keys expire at an absolute deadline, so only the part of this above
+ /// 2 * window_interval is used, as clock-skew grace
pub global_cache_ttl: Duration,
- /// How long to cache locally in the moka LRU
+ /// Time since an entry was last written before moka drops it. Every request
+ /// and every read rewrites the entry, so this restarts each time
pub local_cache_ttl: Duration,
/// Evict entries not accessed within this window. Hot keys are constantly
/// re-inserted so they never idle-expire; cold keys reclaim slots faster
@@ -195,32 +198,20 @@ pub struct GlobalRateLimiterConfig {
pub global_read_timeout: Duration,
/// Timeout for global cache write operations
pub global_write_timeout: Duration,
- /// Maximum entries in the local LRU cache
+ /// Maximum entries in the local cache. Moka's TinyLFU policy can refuse a
+ /// new key at the cap
pub local_cache_max_entries: u64,
/// Capacity of the mpsc channel for async global cache updates
pub channel_capacity: usize,
- /// Minimum effective level before a key is worth a Redis round trip.
- ///
- /// A key far below its threshold cannot be limited no matter what the other
- /// nodes report, so syncing it buys nothing and costs two Redis keys per
- /// tick. With an unbounded key space (e.g. keyed on distinct_id) the
- /// one-shot keys dominate, so this floor is what keeps the pipeline sized to
- /// the keys that can actually be enforced rather than to total traffic.
- ///
- /// The level is per-node, so the ceiling on a safe value is
- /// `global_threshold / node_count` -- above that, a key sitting exactly at
- /// the threshold but spread evenly across the fleet would never sync and so
- /// could never be limited. Keep well under that: the saving is dominated by
- /// the single-event keys, so a small floor captures nearly all of it.
- ///
- /// Set to 0 to sync every key, restoring the pre-floor behavior.
+ /// Minimum local level before a key earns a Redis read, which keeps one-shot keys off
+ /// the pipeline; `0` reads every key. Keep it well under `global_threshold / node_count`,
+ /// or a key at its limit spread across the fleet is read more than a window late.
pub min_sync_floor: u64,
/// Wall-clock time reads to an instance must keep failing before its keys stop
/// limiting on this node's own counts. `None` uses `window_interval`; `Some(ZERO)` disables.
pub max_read_outage: Option<Duration>,
- /// Maximum keys drained from `pending_sync` per tick. The remainder stays
- /// queued for the next tick, so a backlog degrades into staleness instead of
- /// a tick loop that overruns its own interval.
+ /// Max keys read, and max write entries sent, per tick. The rest wait, so a backlog
+ /// becomes staleness instead of a tick that overruns its interval.
pub max_sync_keys_per_tick: usize,
/// Maximum Redis keys per individual command. Reads cost two keys per entity
/// (current + previous epoch), so an entity chunk is half this. Bounds how
@@ -230,12 +221,8 @@ pub struct GlobalRateLimiterConfig {
/// How many chunked commands may be in flight at once against one instance.
/// Trades tick wall-clock against instantaneous Redis load.
pub max_concurrent_commands: usize,
- /// Maximum distinct (key, epoch) entries held in the deferred write batch.
- /// Merges into existing entries are always accepted (they add no memory);
- /// at the cap, updates for new keys are dropped and counted. Without this,
- /// unique-key inflow faster than the per-tick drain grows the batch without
- /// bound -- the update channel's capacity does not help, because the
- /// receiver moves entries into this map as fast as they arrive.
+ /// Max distinct `(key, epoch)` entries buffered for writing; at the cap, updates for new
+ /// keys drop and are counted. The channel's capacity does not bound this map.
pub max_write_batch_entries: usize,
/// Maximum keys held in the pending-sync set. At the cap, new sync
/// requests are dropped and counted; the key's next request re-queues it
@@ -506,8 +493,7 @@ fn instance_index(key: &str, instances: usize) -> usize {
(hasher.finish() as usize) % instances
}
-/// Select a Redis client from the pool based on consistent key hashing.
-/// Returns (client_ref, index) tuple for metric tagging.
+/// The client that owns `key`, and its index for metric labels.
fn select_redis_client(
key: &str,
clients: &[Arc<dyn Client + Send + Sync>],
@@ -527,7 +513,7 @@ pub struct GlobalRateLimitResponse {
pub threshold: u64,
/// The sliding window interval
pub window_interval: Duration,
- /// Sync interval (how often we re-read from Redis)
+ /// Base sync interval; the key's pressure tier scales it
pub sync_interval: Duration,
/// Whether this limit was applied via a custom key override
pub is_custom_limited: bool,
@@ -551,11 +537,12 @@ pub enum EvalResult {
Limited(GlobalRateLimitResponse),
/// Key not subject to rate limiting (custom key mode, unregistered key)
NotApplicable,
- /// Failed open due to Redis error or timeout
+ /// Failed open due to Redis error or timeout. Not returned today, because
+ /// Redis failures happen in the background task and never reach a request.
FailOpen { reason: FailOpenReason },
}
-/// A distributed rate limiter using local LRU cache with leaky bucket decay,
+/// A distributed rate limiter using a local moka cache with leaky bucket decay,
/// 2-epoch sliding window counters in Redis, and a unified background pipeline
/// for batched reads + writes.
#[derive(Clone)]
@@ -639,7 +626,7 @@ impl GlobalRateLimiterImpl {
);
config.local_cache_idle_timeout = config.window_interval;
}
- // Same hazard for the hard TTL: an entry evicted mid-window discards the
+ // Same hazard for the TTL: an entry evicted mid-window discards the
// counts it was accumulating, and the next request follows the always-
// allowed miss path.
if config.local_cache_ttl < config.window_interval {
@@ -811,7 +798,7 @@ impl GlobalRateLimiterImpl {
(level, global_level, true)
} else {
- // Cache miss: no prior data, allow through and queue sync
+ // Cache miss: no prior data, allow through and queue a sync at or above the floor
metrics::counter!(GLOBAL_RATE_LIMITER_CACHE_COUNTER, "scope" => self.scope, "result" => "miss").increment(1);
// Insert a fresh entry so subsequent requests have local_pending tracked
@@ -856,19 +843,8 @@ impl GlobalRateLimiterImpl {
}
}
- /// True when `level` sits below the sync floor for this key's threshold,
- /// meaning a Redis round trip cannot change any enforcement decision.
- /// Records the skip so the saving is visible next to `cache_counts_total`.
- ///
- /// The configured floor is capped at 1% of the key's own threshold. The
- /// floor is a per-node level, so a fleet of N nodes can hide at most
- /// N * floor events from Redis; the cap keeps that bypass under N% of the
- /// threshold regardless of configuration. Without it, a custom threshold
- /// far below the global one (the exact keys overrides exist to clamp) could
- /// sit entirely below a floor tuned for the global threshold and never
- /// sync, making the override unenforceable.
- ///
- /// A configured floor of 0 disables the check entirely.
+ /// True, and counted, when `level` is below this key's floor, so a read cannot change the
+ /// decision. The floor is capped at 1% of the threshold to keep low custom limits enforceable.
fn sync_floor_blocks(&self, level: f64, threshold: u64) -> bool {
if self.config.min_sync_floor == 0 {
return false;
@@ -1023,14 +999,10 @@ impl GlobalRateLimiterImpl {
}
}
- /// Spawn the unified background tick loop that handles both reads and writes.
+ /// Spawn the background loop that handles both reads and writes.
///
- /// Every tick_interval:
- /// 1. Drain pending_sync (entities needing Redis read)
- /// 2. Drain pending_writes from channel (entities with local increments)
- /// 3. Build single Redis pipeline with reads + writes
- /// 4. Execute pipeline
- /// 5. Process read responses to update cache entries
+ /// Between ticks it merges each update into the write batch, and every
+ /// tick_interval it runs `tick`. The channel is not read while a tick runs.
fn spawn_background_task(
config: GlobalRateLimiterConfig,
redis_instances: Vec<Arc<dyn Client + Send + Sync>>,
@@ -1062,7 +1034,7 @@ impl GlobalRateLimiterImpl {
);
}
None => {
- // Channel closed, do final flush and exit
+ // Channel closed: run one last bounded tick and exit
if !write_batch.is_empty() {
Self::tick(
&config, &redis_instances, &cache,
@@ -1124,8 +1096,8 @@ impl GlobalRateLimiterImpl {
/// Execute one tick of the background pipeline.
///
- /// Drains pending reads + writes, builds a single pipeline, executes it,
- /// and processes read responses to update cache entries.
+ /// Takes bounded slices of the pending syncs and the write batch, purges
+ /// stale epochs, then sends chunked writes before chunked reads per instance.
#[allow(clippy::too_many_arguments)]
async fn tick(
config: &GlobalRateLimiterConfig,
@@ -1177,11 +1149,8 @@ impl GlobalRateLimiterImpl {
.increment(purged as u64);
}
- // Bound the write drain the same way. The deferred remainder stays in
- // `write_batch`, where new arrivals merge into it by (key, epoch), so no
- // count is lost -- it lands in the same epoch key up to a few ticks late.
- // Without the bound, a high-cardinality burst produces a write batch
- // whose waves consume the whole tick before reads run.
+ // Bound the write drain too, or a burst's write waves eat the whole tick before reads.
+ // The rest stays batched and lands a few ticks late, unless the purge above drops it.
let writes: HashMap<(String, i64), u64> =
if write_batch.len() <= config.max_sync_keys_per_tick {
std::mem::take(write_batch)
@@ -1357,8 +1326,9 @@ impl GlobalRateLimiterImpl {
Self::record_pipeline_error(scope, &redis_idx_str, "redis_write");
warn!(error = %e, records = chunk_len, "Failed to write rate limit batch to Redis");
// A dead MultiplexedConnection never recovers on its
- // own; ask the client to rebuild. Timeouts are
- // transient and never route here.
+ // own; ask the client to rebuild. The client's own
+ // response timeout also lands here, as a recoverable
+ // error that does not trigger a rebuild.
if e.is_unrecoverable_error() {
redis.heal().await;
}
@@ -1600,10 +1570,8 @@ impl GlobalRateLimiterImpl {
}
}
- // estimated_count from Redis already includes events this node wrote
- // across prior ticks. Reset local_pending to avoid double-counting.
- // Events arriving during the MGET window (~100ms) are lost from the
- // local estimate but will be written to Redis on the next tick.
+ // Redis already holds this node's written events, so reset local_pending to avoid
+ // double-counting. Events whose write has not landed drop out until a later read.
cache.insert(
key.clone(),
CacheEntry {
diff --git a/rust/common/limiters/tests/global_rate_limiter_integration_tests.rs b/rust/common/limiters/tests/global_rate_limiter_integration_tests.rs
index e8faff88d419..156d1271e26d 100644
--- a/rust/common/limiters/tests/global_rate_limiter_integration_tests.rs
+++ b/rust/common/limiters/tests/global_rate_limiter_integration_tests.rs
@@ -106,9 +106,10 @@ async fn test_epoch_key_ttl_expiry() {
};
let mut config = test_config("ttl_expiry");
- // `new()` clamps global_cache_ttl to 2x the window, so observing expiry
- // needs a short window. 2s (not 1s) keeps the tick's stale-epoch purge
- // 2-4s away from the write, safe on a loaded runner.
+ // Keys expire at an absolute deadline two windows after their epoch starts,
+ // plus up to one window of offset, so observing expiry needs a short window.
+ // 2s (not 1s) keeps the tick's stale-epoch purge 2-4s away from the write,
+ // safe on a loaded runner.
config.window_interval = Duration::from_secs(2);
config.global_cache_ttl = Duration::from_secs(4);
let redis_arc: Arc<dyn Client + Send + Sync> = Arc::new(redis.clone());