: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(capture): let the rate limiter shard across two Redis clusters (#117238)
Eli Reisman5012488f1432
diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rsindex ab193b961bad..9c3d89cd6880 100644--- a/rust/capture/src/config.rs+++ b/rust/capture/src/config.rs@@ -230,6 +230,17 @@ pub struct Config {/// `redis_connection_timeout_ms`; ignored unless `global_rate_limit_redis_url` is set.pub global_rate_limit_redis_connection_timeout_ms: Option<u64>,+ /// Redis clusters the per-(token, distinct_id) limiter shards its keys across: `1` uses+ /// `global_rate_limit_redis_url` only, `2` adds the shard 1 URLs. The AI byte limiter always uses the first.+ #[envconfig(default = "1")]+ pub global_rate_limit_redis_shards: usize,++ /// Writer URL of the second limiter cluster. Capture connects to it only when `global_rate_limit_redis_shards` is 2.+ pub global_rate_limit_redis_shard_1_url: Option<String>,++ /// Replica URL of the second limiter cluster, used like `global_rate_limit_redis_reader_url`.+ pub global_rate_limit_redis_shard_1_reader_url: Option<String>,+/// Redis key holding the dynamic custom per-key rate-limit thresholds/// (JSON object of `{key: threshold}`), written by Django. When set, the/// per-(token, distinct_id) limiter refreshes its custom thresholds fromdiff --git a/rust/capture/src/global_rate_limiter.rs b/rust/capture/src/global_rate_limiter.rsindex 9c56e1696e42..0713574379c6 100644--- a/rust/capture/src/global_rate_limiter.rs+++ b/rust/capture/src/global_rate_limiter.rs@@ -99,6 +99,13 @@ pub fn ai_byte_limit_window(config: &Config) -> (u64, &'static str) {}}+/// Writer and optional replica URL of one limiter Redis cluster.+#[derive(Debug, PartialEq)]+struct RedisClusterUrls<'a> {+ writer: &'a str,+ reader: Option<&'a str>,+}+pub struct GlobalRateLimiter {limiter: Box<dyn CommonGlobalRateLimiter>,dry_run: bool,@@ -420,14 +427,83 @@ impl GlobalRateLimiter {self.limiter.is_custom_key(key)}+ /// Clients for the per-(token, distinct_id) limiter, one per shard in shard order. Without+ /// `GLOBAL_RATE_LIMIT_REDIS_URL` the limiter shares the main client.+ pub async fn build_redis_shards(+ config: &Config,+ shared_redis: Arc<dyn Client + Send + Sync>,+ ) -> anyhow::Result<Vec<Arc<dyn Client + Send + Sync>>> {+ let clusters = Self::redis_shard_urls(config)?;+ if clusters.is_empty() {+ return Ok(vec![shared_redis]);+ }+ if clusters.len() > 1 {+ info!(+ shards = clusters.len(),+ "Global rate limiter sharding keys across Redis clusters"+ );+ }+ let mut clients = Vec::with_capacity(clusters.len());+ for cluster in clusters {+ clients.push(Self::connect_redis(config, cluster).await?);+ }+ Ok(clients)+ }++ /// Client for a limiter that never shards (the AI byte limiter): the first cluster, or the+ /// main client without `GLOBAL_RATE_LIMIT_REDIS_URL`.pub async fn build_redis_client(config: &Config,shared_redis: Arc<dyn Client + Send + Sync>,) -> anyhow::Result<Arc<dyn Client + Send + Sync>> {- let Some(ref writer_url) = config.global_rate_limit_redis_url else {- return Ok(shared_redis);- };+ match Self::first_cluster_urls(config) {+ Some(cluster) => Self::connect_redis(config, cluster).await,+ None => Ok(shared_redis),+ }+ }++ fn first_cluster_urls(config: &Config) -> Option<RedisClusterUrls<'_>> {+ config+ .global_rate_limit_redis_url+ .as_deref()+ .map(|writer| RedisClusterUrls {+ writer,+ reader: config.global_rate_limit_redis_reader_url.as_deref(),+ })+ }++ /// The order of the returned clusters is the routing table, so every pod must list them the same way.+ fn redis_shard_urls(config: &Config) -> anyhow::Result<Vec<RedisClusterUrls<'_>>> {+ let first = Self::first_cluster_urls(config);+ match config.global_rate_limit_redis_shards {+ 1 => Ok(first.into_iter().collect()),+ 2 => {+ let Some(first) = first else {+ anyhow::bail!(+ "GLOBAL_RATE_LIMIT_REDIS_SHARDS=2 requires GLOBAL_RATE_LIMIT_REDIS_URL"+ );+ };+ let Some(writer) = config.global_rate_limit_redis_shard_1_url.as_deref() else {+ anyhow::bail!(+ "GLOBAL_RATE_LIMIT_REDIS_SHARDS=2 requires GLOBAL_RATE_LIMIT_REDIS_SHARD_1_URL"+ );+ };+ Ok(vec![+ first,+ RedisClusterUrls {+ writer,+ reader: config.global_rate_limit_redis_shard_1_reader_url.as_deref(),+ },+ ])+ }+ n => anyhow::bail!("GLOBAL_RATE_LIMIT_REDIS_SHARDS must be 1 or 2, got {n}"),+ }+ }+ async fn connect_redis(+ config: &Config,+ cluster: RedisClusterUrls<'_>,+ ) -> anyhow::Result<Arc<dyn Client + Send + Sync>> {let response_timeout = config.global_rate_limit_redis_response_timeout_ms.unwrap_or(config.redis_response_timeout_ms);@@ -445,11 +521,11 @@ impl GlobalRateLimiter {Some(Duration::from_millis(connection_timeout))};- if let Some(ref reader_url) = config.global_rate_limit_redis_reader_url {+ if let Some(reader_url) = cluster.reader {info!("Global rate limiter using read/write split Redis client");let rw_config = common_redis::ReadWriteClientConfig::new(- writer_url.clone(),- reader_url.clone(),+ cluster.writer.to_string(),+ reader_url.to_string(),common_redis::CompressionConfig::disabled(),common_redis::RedisValueFormat::default(),response_timeout,@@ -459,7 +535,7 @@ impl GlobalRateLimiter {} else {Ok(Arc::new(common_redis::RedisClient::with_config(- writer_url.clone(),+ cluster.writer.to_string(),common_redis::CompressionConfig::disabled(),common_redis::RedisValueFormat::default(),response_timeout,@@ -706,6 +782,76 @@ mod tests {use std::sync::Mutex;use std::time::Duration;+ fn shard_config(extra: &[(&str, &str)]) -> Config {+ let env: HashMap<String, String> = [+ ("REDIS_URL", "redis://localhost:6379/"),+ ("CAPTURE_MODE", "events"),+ (+ "CAPTURE_OUTPUT_ANALYTICS_MAIN_TOPIC",+ "events_plugin_ingestion",+ ),+ ]+ .iter()+ .chain(extra.iter())+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect();+ envconfig::Envconfig::init_from_hashmap(&env).expect("test config")+ }++ #[rstest]+ #[case::no_dedicated_redis(&[], &[])]+ #[case::shard_1_ignored_until_enabled(+ &[+ ("GLOBAL_RATE_LIMIT_REDIS_URL", "redis://a"),+ ("GLOBAL_RATE_LIMIT_REDIS_SHARD_1_URL", "redis://b"),+ ],+ &[("redis://a", None)],+ )]+ #[case::two_shards_in_order(+ &[+ ("GLOBAL_RATE_LIMIT_REDIS_SHARDS", "2"),+ ("GLOBAL_RATE_LIMIT_REDIS_URL", "redis://a"),+ ("GLOBAL_RATE_LIMIT_REDIS_READER_URL", "redis://a-replica"),+ ("GLOBAL_RATE_LIMIT_REDIS_SHARD_1_URL", "redis://b"),+ ("GLOBAL_RATE_LIMIT_REDIS_SHARD_1_READER_URL", "redis://b-replica"),+ ],+ &[("redis://a", Some("redis://a-replica")), ("redis://b", Some("redis://b-replica"))],+ )]+ fn redis_shard_urls_follow_the_shard_count(+ #[case] env: &[(&str, &str)],+ #[case] want: &[(&str, Option<&str>)],+ ) {+ let config = shard_config(env);+ let got: Vec<(&str, Option<&str>)> = GlobalRateLimiter::redis_shard_urls(&config)+ .expect("valid shard config")+ .into_iter()+ .map(|c| (c.writer, c.reader))+ .collect();+ assert_eq!(got, want);+ }++ #[rstest]+ #[case::shard_1_url_missing(+ &[("GLOBAL_RATE_LIMIT_REDIS_SHARDS", "2"), ("GLOBAL_RATE_LIMIT_REDIS_URL", "redis://a")],+ "GLOBAL_RATE_LIMIT_REDIS_SHARD_1_URL",+ )]+ #[case::first_url_missing(+ &[("GLOBAL_RATE_LIMIT_REDIS_SHARDS", "2"), ("GLOBAL_RATE_LIMIT_REDIS_SHARD_1_URL", "redis://b")],+ "requires GLOBAL_RATE_LIMIT_REDIS_URL",+ )]+ #[case::unsupported_count(&[("GLOBAL_RATE_LIMIT_REDIS_SHARDS", "3")], "must be 1 or 2")]+ fn redis_shard_urls_reject_an_incomplete_shard_config(+ #[case] env: &[(&str, &str)],+ #[case] expected: &str,+ ) {+ let err = GlobalRateLimiter::redis_shard_urls(&shard_config(env))+ .expect_err("invalid shard config must fail startup");+ assert!(+ err.to_string().contains(expected),+ "expected {expected:?} in {err}"+ );+ }+type CallLog = Arc<Mutex<Vec<&'static str>>>;struct MockLimiter {diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rsindex 36361c112deb..610bc0e0284d 100644--- a/rust/capture/src/setup.rs+++ b/rust/capture/src/setup.rs@@ -162,10 +162,11 @@ pub async fn build_components(// 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.+ // Only the per-(token, distinct_id) limiter shards across GLOBAL_RATE_LIMIT_REDIS_SHARDS clusters.let ai_byte_limit_enabled = ai_byte_limit_per_second(&config) > 0;let rate_limiter_redis = if config.global_rate_limit_enabled {Some(- GlobalRateLimiter::build_redis_client(&config, redis_client.clone())+ GlobalRateLimiter::build_redis_shards(&config, redis_client.clone()).await.expect("failed to create rate limiter redis client"),)@@ -187,7 +188,7 @@ pub async fn build_components(// source into the limiter, which spawns and manages the refresh task itself.let global_rate_limiter_token_distinctid = rate_limiter_redis.as_ref().map(|redis| {Arc::new(- GlobalRateLimiter::new_token_distinct_id(&config, vec![redis.clone()])+ GlobalRateLimiter::new_token_distinct_id(&config, redis.clone()).expect("failed to create global rate limiter"),)});diff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rsindex 731ad14147ca..a428966c70cb 100644--- a/rust/capture/src/v1/quota_limiter_shim.rs+++ b/rust/capture/src/v1/quota_limiter_shim.rs@@ -145,6 +145,9 @@ mod tests {global_rate_limit_token_overrides_csv: None,global_rate_limit_token_local_cache_max_entries: 300_000,global_rate_limit_redis_url: None,+ global_rate_limit_redis_shards: 1,+ global_rate_limit_redis_shard_1_url: None,+ global_rate_limit_redis_shard_1_reader_url: None,global_rate_limit_redis_reader_url: None,global_rate_limit_max_read_outage_secs: None,global_rate_limit_redis_response_timeout_ms: None,diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rsindex 47e74431155f..e9be12c9f2f0 100644--- a/rust/capture/tests/common/utils.rs+++ b/rust/capture/tests/common/utils.rs@@ -81,6 +81,9 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {global_rate_limit_token_overrides_csv: None,global_rate_limit_token_local_cache_max_entries: 300_000,global_rate_limit_redis_url: None,+ global_rate_limit_redis_shards: 1,+ global_rate_limit_redis_shard_1_url: None,+ global_rate_limit_redis_shard_1_reader_url: None,global_rate_limit_redis_reader_url: None,global_rate_limit_redis_response_timeout_ms: None,global_rate_limit_redis_connection_timeout_ms: None,diff --git a/rust/common/limiters/GLOBAL_RATE_LIMITER.md b/rust/common/limiters/GLOBAL_RATE_LIMITER.mdindex 0ca35860883a..9fe24482e572 100644--- a/rust/common/limiters/GLOBAL_RATE_LIMITER.md+++ b/rust/common/limiters/GLOBAL_RATE_LIMITER.md@@ -358,6 +358,9 @@ Where the two read different env vars, both are listed.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.+The per-(token, distinct_id) limiter can shard its keys across two clusters. `GLOBAL_RATE_LIMIT_REDIS_SHARDS=2` adds `GLOBAL_RATE_LIMIT_REDIS_SHARD_1_URL` and its optional `GLOBAL_RATE_LIMIT_REDIS_SHARD_1_READER_URL` as the second instance.+Capture connects to the second cluster only when the shard count is 2, so the URLs can ship before the switch. A shard count of 2 without both writer URLs fails startup.+The AI byte limiter always uses the first cluster.#### Clamps and tuning@@ -463,6 +466,11 @@ hashes. Two things to know before that changes.agrees and the current epoch keys expire. Modulo sharding moves N/(N+1) ofthe keys when the count goes from N to N+1; a consistent-hashing scheme wouldmove about 1/(N+1) of them and shrink this window, but it cannot remove it.+3. **In capture, change only `GLOBAL_RATE_LIMIT_REDIS_SHARDS`, and in one+ rollout.** Every pod must list the clusters in the same order, which the+ numbered URL variables fix. Ship the shard 1 URLs first with the count at 1,+ then change the count. Changing it back moves the keys back with the same+ transient.## Redis loaddiff --git a/rust/common/limiters/src/global_rate_limiter.rs b/rust/common/limiters/src/global_rate_limiter.rsindex b35c2023960b..cdde781106f3 100644--- a/rust/common/limiters/src/global_rate_limiter.rs+++ b/rust/common/limiters/src/global_rate_limiter.rs@@ -1839,10 +1839,10 @@ mod tests {#[test]fn test_epoch_expire_at_spread_survives_sharding() {- // `select_redis_client` shards on `DefaultHasher` of the same key. If- // the expiry offset used that hash too, a shard count sharing a factor- // with the window would leave each shard only a fraction of the- // offsets, and the expiry burst would come back per shard.+ // `select_redis_client` shards on a hash of the same key. If the expiry+ // offset used that hash too, a shard count sharing a factor with the+ // window would leave each shard only a fraction of the offsets, and the+ // expiry burst would come back per shard.let window = Duration::from_secs(120);let ttl = Duration::from_secs(240);for shards in [2usize, 3, 4, 8] {@@ -1850,9 +1850,7 @@ mod tests {std::collections::HashMap::new();for i in 0..4000 {let key = format!("key{i}");- let mut h = DefaultHasher::new();- key.hash(&mut h);- let shard = (h.finish() as usize) % shards;+ let shard = instance_index(&key, shards);per_shard.entry(shard).or_default()