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.

fix(flags): rate limit flag definitions 304s on a separate budget (#106364)

Phil Haackb1bdbc0cda87
diff --git a/docs/internal/feature-flags/rate-limiting.md b/docs/internal/feature-flags/rate-limiting.md
index 23a6457b1c95..57d15380607f 100644
--- a/docs/internal/feature-flags/rate-limiting.md
+++ b/docs/internal/feature-flags/rate-limiting.md
@@ -1,18 +1,36 @@
# Rate limiting
-The Rust feature flags service uses three independent rate limiters, all implemented in-process using the `governor` crate (token bucket algorithm):
+The Rust feature flags service uses five independent rate limiters, all implemented in-process using the `governor` crate (token bucket algorithm):
-| Limiter | Scope | Default config | Purpose |
-| ----------- | ------------- | -------------------------- | ---------------------------------- |
-| IP-based | Per source IP | 1250 burst / 50 per second | DDoS defense |
-| Token-based | Per API token | 625 burst / 10 per second | Per-project limits |
-| Definitions | Per team ID | 600 per minute | `/flags/definitions` rate limiting |
+| Limiter | Scope | Default config | Purpose |
+| ------------------------- | -------------------- | -------------------------- | -------------------------------------------------------------- |
+| IP-based | Per source IP | 1250 burst / 50 per second | DDoS defense |
+| Token-based | Per API token | 625 burst / 10 per second | Per-project limits |
+| Definitions (full) | Per team ID | 600 per minute | `/flags/definitions` full (200) responses |
+| Definitions (conditional) | Per team ID | 6000 per minute | `/flags/definitions` requests with an ETag in `If-None-Match` |
+| Remote config | Per personal API key | 600 per minute | `remote_config` requests authenticated with a personal API key |
-Rate limiting runs before body decoding and authentication in the `/flags` request pipeline. IP is checked first, then token. The definitions limiter is a simple allow/deny gate with no warn tier.
+Rate limiting runs before body decoding and authentication in the `/flags` request pipeline. IP is checked first, then token. The definitions and remote config limiters are simple allow/deny gates with no warn tier.
+
+The definitions limiters run after authentication. Each request spends one or both budgets:
+
+- A request with an ETag in `If-None-Match` is checked against the conditional limiter before the ETag read, so a request it refuses costs no Redis call. The handler cannot know whether the ETag matches until Redis answers, so a stale ETag also spends the conditional budget.
+- Any other request is checked against the full-response limiter before the ETag read. That includes a request whose `If-None-Match` is empty, because it cannot get a 304.
+- A request whose ETag does not match gets a full response, so the full-response limiter checks it too. When the full-response limiter refuses that request, the request has already read the ETag from Redis.
+
+Frequent SDK revalidation polls therefore do not exhaust the budget for full responses. `LOCAL_EVAL_RATE_LIMITS` overrides apply to the full-response limiter only, and `LOCAL_EVAL_CONDITIONAL_RATE_LIMITS` overrides apply to the conditional limiter only. Teams in `RATE_LIMITING_ALLOW_LIST_TEAMS` bypass both.
+
+Both limiters report to `flags_flag_definitions_requests_total`, `flags_flag_definitions_rate_limited_total` and `flags_flag_definitions_rate_limit_bypassed_total`, with a `budget` label of `full` or `conditional`:
+
+- A stale ETag counts once as a request, under `conditional`.
+- The full-response limiter counts a 429 it returns for a stale ETag, under `full`.
+- A stale ETag from an allowlisted team that is over both budgets counts twice as bypassed, once under each label. Each limiter records its own bypass.
+
+The remote config limiter runs after authentication. Requests authenticated with a secret API key are not rate limited, and teams in `RATE_LIMITING_ALLOW_LIST_TEAMS` bypass it.
## Warn-then-enforce model
-The `/flags` IP and token limiters use a three-outcome model: `Allowed`, `Warned`, or `Blocked`. The definitions limiter does not use this model.
+The `/flags` IP and token limiters use a three-outcome model: `Allowed`, `Warned`, or `Blocked`. The definitions limiters do not use this model.
- **Allowed**: Request is below all thresholds — served normally.
- **Warned**: Request exceeds the warn capacity but is below enforce. The request succeeds, but the response includes `X-PostHog-Rate-Limit-Warning: true` so callers can react proactively. A `rate_limit_warned` field is also set in the canonical request log.
@@ -63,20 +81,24 @@ A background task runs every 60 seconds (`RATE_LIMITER_CLEANUP_INTERVAL_SECS`) t
## Configuration reference
-| Variable | Default | Purpose |
-| ------------------------------------------ | ------- | ------------------------------------------------------------------ |
-| `FLAGS_RATE_LIMIT_ENABLED` | `false` | Enable token-based rate limiting |
-| `FLAGS_BUCKET_CAPACITY` | `625` | Token bucket enforce capacity (warn at 80% = 500) |
-| `FLAGS_BUCKET_REPLENISH_RATE` | `10.0` | Tokens per second |
-| `FLAGS_IP_RATE_LIMIT_ENABLED` | `false` | Enable IP-based rate limiting |
-| `FLAGS_IP_BURST_SIZE` | `1250` | IP bucket enforce capacity (warn at 80% = 1000) |
-| `FLAGS_IP_REPLENISH_RATE` | `50.0` | Requests per second per IP |
-| `FLAGS_WARN_CAPACITY_RATIO` | `0.8` | Warn tier as fraction of enforce capacity (0.0 disables warn tier) |
-| `FLAGS_RATE_LIMIT_LOG_ONLY` | `true` | _(deprecated)_ Set to `false` and use `FLAGS_WARN_CAPACITY_RATIO` |
-| `FLAGS_IP_RATE_LIMIT_LOG_ONLY` | `true` | _(deprecated)_ Set to `false` and use `FLAGS_WARN_CAPACITY_RATIO` |
-| `FLAGS_TOKEN_RATE_LIMIT_OVERRIDES` | (empty) | Per-token rate limit overrides as JSON (max 100) |
-| `RATE_LIMITER_CLEANUP_INTERVAL_SECS` | `60` | Stale entry cleanup interval |
-| `FLAG_DEFINITIONS_DEFAULT_RATE_PER_MINUTE` | `600` | Default rate for `/flags/definitions` |
+| Variable | Default | Purpose |
+| ---------------------------------------------- | ------- | ----------------------------------------------------------------------------------- |
+| `FLAGS_RATE_LIMIT_ENABLED` | `false` | Enable token-based rate limiting |
+| `FLAGS_BUCKET_CAPACITY` | `625` | Token bucket enforce capacity (warn at 80% = 500) |
+| `FLAGS_BUCKET_REPLENISH_RATE` | `10.0` | Tokens per second |
+| `FLAGS_IP_RATE_LIMIT_ENABLED` | `false` | Enable IP-based rate limiting |
+| `FLAGS_IP_BURST_SIZE` | `1250` | IP bucket enforce capacity (warn at 80% = 1000) |
+| `FLAGS_IP_REPLENISH_RATE` | `50.0` | Requests per second per IP |
+| `FLAGS_WARN_CAPACITY_RATIO` | `0.8` | Warn tier as fraction of enforce capacity (0.0 disables warn tier) |
+| `FLAGS_RATE_LIMIT_LOG_ONLY` | `true` | _(deprecated)_ Set to `false` and use `FLAGS_WARN_CAPACITY_RATIO` |
+| `FLAGS_IP_RATE_LIMIT_LOG_ONLY` | `true` | _(deprecated)_ Set to `false` and use `FLAGS_WARN_CAPACITY_RATIO` |
+| `FLAGS_TOKEN_RATE_LIMIT_OVERRIDES` | (empty) | Per-token rate limit overrides as JSON (max 100) |
+| `RATE_LIMITER_CLEANUP_INTERVAL_SECS` | `60` | Stale entry cleanup interval |
+| `FLAG_DEFINITIONS_DEFAULT_RATE_PER_MINUTE` | `600` | Default rate for `/flags/definitions` full responses |
+| `FLAG_DEFINITIONS_CONDITIONAL_RATE_PER_MINUTE` | `6000` | Per-team rate for `/flags/definitions` requests with an ETag in `If-None-Match` |
+| `LOCAL_EVAL_RATE_LIMITS` | (empty) | Per-team full-response overrides as JSON, e.g. `{"123": "1200/minute"}` |
+| `LOCAL_EVAL_CONDITIONAL_RATE_LIMITS` | (empty) | Per-team conditional overrides, in the same JSON format as `LOCAL_EVAL_RATE_LIMITS` |
+| `REMOTE_CONFIG_DEFAULT_RATE_PER_MINUTE` | `600` | Per-credential rate for `remote_config` requests |
## Key files
diff --git a/rust/feature-flags/src/api/flag_definitions.rs b/rust/feature-flags/src/api/flag_definitions.rs
index 5ed77bc83960..5c58fe2b65b9 100644
--- a/rust/feature-flags/src/api/flag_definitions.rs
+++ b/rust/feature-flags/src/api/flag_definitions.rs
@@ -52,7 +52,7 @@ static CONSTANCE_KEY: Lazy<String> = Lazy::new(|| constance_key("RATE_LIMITING_A
/// data for another TTL cycle.
async fn refresh_rate_limit_allowlist_if_stale(state: &AppState) {
if !state
- .flag_definitions_limiter
+ .flag_definitions_full_limiter
.claim_allowlist_refresh(ALLOWLIST_TTL_SECS)
{
return;
@@ -61,7 +61,10 @@ async fn refresh_rate_limit_allowlist_if_stale(state: &AppState) {
match fetch_allowlist_from_db(&state.database_pools.non_persons_reader).await {
Ok(Some(new_allowlist)) => {
state
- .flag_definitions_limiter
+ .flag_definitions_conditional_limiter
+ .update_allowlist(new_allowlist.clone());
+ state
+ .flag_definitions_full_limiter
.update_allowlist(new_allowlist);
}
Ok(None) => {
@@ -267,8 +270,19 @@ pub async fn flags_definitions(
// Refresh the rate limit allowlist from the database if stale (every ~60s)
refresh_rate_limit_allowlist_if_stale(&state).await;
- // Check rate limit for this team
- state.flag_definitions_limiter.check_rate_limit(team.id)?;
+ // This check runs before the ETag read so that a request it refuses costs no Redis
+ // call. The handler cannot tell a 304 from a full response until Redis answers.
+ // Whether If-None-Match carries an ETag therefore picks the budget.
+ let client_etag = extract_etag_from_header(headers.get("if-none-match"));
+ if client_etag.is_some() {
+ state
+ .flag_definitions_conditional_limiter
+ .check_rate_limit(team.id)?;
+ } else {
+ state
+ .flag_definitions_full_limiter
+ .check_rate_limit(team.id)?;
+ }
// Check billing quota — matches Django's DECIDE_FEATURE_FLAG_QUOTA_CHECK behavior.
if state
@@ -279,7 +293,6 @@ pub async fn flags_definitions(
return Err(FlagError::ClientFacing(ClientFacingError::BillingLimit));
}
- let client_etag = extract_etag_from_header(headers.get("if-none-match"));
let team_key = KeyType::team(team.clone());
let current_etag = match state
.flags_with_cohorts_hypercache_reader
@@ -338,6 +351,14 @@ pub async fn flags_definitions(
}
}
+ // A stale ETag gets a full response, so it spends the full-response budget too. The
+ // conditional limiter already counted this request.
+ if client_etag.is_some() {
+ state
+ .flag_definitions_full_limiter
+ .check_rate_limit_without_request_count(team.id)?;
+ }
+
let etag_result = if client_etag.is_some() {
"miss"
} else {
diff --git a/rust/feature-flags/src/api/flag_definitions_rate_limiter.rs b/rust/feature-flags/src/api/flag_definitions_rate_limiter.rs
index 2ade7c73baff..b8c51bc8c8ce 100644
--- a/rust/feature-flags/src/api/flag_definitions_rate_limiter.rs
+++ b/rust/feature-flags/src/api/flag_definitions_rate_limiter.rs
@@ -68,6 +68,9 @@ where
/// Prometheus metric name for rate limit bypassed requests
bypassed_counter: &'static str,
+
+ /// Fixed labels added to every metric this limiter emits, next to the `key` label
+ labels: &'static [(&'static str, &'static str)],
}
/// Type alias for flag definitions rate limiting (per-team)
@@ -178,9 +181,16 @@ where
request_counter,
limited_counter,
bypassed_counter,
+ labels: &[],
})
}
+ /// Two limiters that share metric names use these labels to keep their series apart.
+ pub fn with_labels(mut self, labels: &'static [(&'static str, &'static str)]) -> Self {
+ self.labels = labels;
+ self
+ }
+
/// Check if a request from the given key should be rate limited
///
/// # Arguments
@@ -189,6 +199,17 @@ where
/// # Returns
/// Ok(()) if request is allowed, Err(FlagError::ClientFacing(ClientFacingError::RateLimited)) if rate limited
pub fn check_rate_limit(&self, key: K) -> Result<(), FlagError> {
+ self.check(key, true)
+ }
+
+ /// Checks the key like [`Self::check_rate_limit`], but does not count the request. Use it
+ /// for a second check on a request that another limiter already counted, so the request
+ /// counter counts each request once. Rate-limited and bypassed requests still count.
+ pub fn check_rate_limit_without_request_count(&self, key: K) -> Result<(), FlagError> {
+ self.check(key, false)
+ }
+
+ fn check(&self, key: K, count_request: bool) -> Result<(), FlagError> {
// Check if key has a custom rate limiter
let custom_limiters = self.custom_limiters.read().unwrap();
let is_rate_limited = if let Some(custom_limiter) = custom_limiters.get(&key) {
@@ -199,12 +220,9 @@ where
self.default_limiter.check_key(&key).is_err()
};
- // Track all requests
- inc(
- self.request_counter,
- &[("key".to_string(), key.to_string())],
- 1,
- );
+ if count_request {
+ inc(self.request_counter, &self.metric_labels(&key), 1);
+ }
if is_rate_limited {
// Allowlisted keys bypass rate limiting when they would be limited.
@@ -212,20 +230,12 @@ where
// requests that exceed the limit but are allowed through.
let allowlist = self.allowlist.read().unwrap();
if allowlist.contains(&key) {
- inc(
- self.bypassed_counter,
- &[("key".to_string(), key.to_string())],
- 1,
- );
+ inc(self.bypassed_counter, &self.metric_labels(&key), 1);
return Ok(());
}
// Track rate-limited requests
- inc(
- self.limited_counter,
- &[("key".to_string(), key.to_string())],
- 1,
- );
+ inc(self.limited_counter, &self.metric_labels(&key), 1);
// Log rate limit event with key context
warn!(key = %key, "Request rate limited");
@@ -238,6 +248,16 @@ where
Ok(())
}
+ fn metric_labels(&self, key: &K) -> Vec<(String, String)> {
+ let mut labels = vec![("key".to_string(), key.to_string())];
+ labels.extend(
+ self.labels
+ .iter()
+ .map(|(name, value)| (name.to_string(), value.to_string())),
+ );
+ labels
+ }
+
/// Get the number of keys with custom rate limits configured
#[cfg(test)]
pub fn custom_rate_count(&self) -> usize {
diff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rs
index 3846f1240a5b..45d9b992048c 100644
--- a/rust/feature-flags/src/config.rs
+++ b/rust/feature-flags/src/config.rs
@@ -177,7 +177,7 @@ impl FromStr for TeamIdCollection {
}
/// Flag definitions rate limits configuration
-/// Parses JSON from LOCAL_EVAL_RATE_LIMITS environment variable
+/// Parses JSON from the LOCAL_EVAL_RATE_LIMITS and LOCAL_EVAL_CONDITIONAL_RATE_LIMITS environment variables
/// Format: {"team_id": "rate_string", ...}
/// Example: {"123": "1200/minute", "456": "2400/hour"}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
@@ -692,6 +692,22 @@ pub struct Config {
#[envconfig(from = "LOCAL_EVAL_RATE_LIMITS", default = "")]
pub flag_definitions_rate_limits: FlagDefinitionsRateLimits,
+ // Per-team rate limit for flag definitions requests with an ETag in If-None-Match
+ // (requests per minute). Most of these get a 304, which skips the payload read. They
+ // therefore get their own higher budget. A request whose ETag does not match also
+ // spends the budget for full responses.
+ #[envconfig(
+ from = "FLAG_DEFINITIONS_CONDITIONAL_RATE_PER_MINUTE",
+ default = "6000"
+ )]
+ pub flag_definitions_conditional_rate_per_minute: u32,
+
+ // Per-team overrides for the conditional budget, in the same JSON format as
+ // LOCAL_EVAL_RATE_LIMITS. Sharing LOCAL_EVAL_RATE_LIMITS would cap the revalidation polls
+ // of a team whose full-response override is below the conditional default.
+ #[envconfig(from = "LOCAL_EVAL_CONDITIONAL_RATE_LIMITS", default = "")]
+ pub flag_definitions_conditional_rate_limits: FlagDefinitionsRateLimits,
+
// Per-credential rate limit for the remote_config endpoint (requests per minute).
// Matches Django's RemoteConfigThrottle default of 600/minute. Django's per-project
// REMOTE_CONFIG_RATE_LIMITS override is not ported: it can't apply to a per-credential
@@ -1149,6 +1165,8 @@ impl Config {
flags_session_replay_quota_check: false,
flag_definitions_default_rate_per_minute: 600,
flag_definitions_rate_limits: FlagDefinitionsRateLimits::default(),
+ flag_definitions_conditional_rate_per_minute: 6000,
+ flag_definitions_conditional_rate_limits: FlagDefinitionsRateLimits::default(),
remote_config_default_rate_per_minute: 600,
rate_limiting_allow_list_teams: RateLimitingAllowList::default(),
flags_log_bodies_teams: BodyLogTeams::default(),
diff --git a/rust/feature-flags/src/router.rs b/rust/feature-flags/src/router.rs
index 3acebf3b9669..a11ded64e5b3 100644
--- a/rust/feature-flags/src/router.rs
+++ b/rust/feature-flags/src/router.rs
@@ -94,7 +94,10 @@ pub struct State {
pub feature_flags_billing_limiter: FeatureFlagsLimiter,
pub session_replay_billing_limiter: SessionReplayLimiter,
pub cookieless_manager: Arc<CookielessManager>,
- pub(crate) flag_definitions_limiter: FlagDefinitionsRateLimiter,
+ pub(crate) flag_definitions_full_limiter: FlagDefinitionsRateLimiter,
+ /// Per-team limiter for flag definitions requests with an ETag in If-None-Match.
+ /// Separate budget so ETag revalidation polls don't consume the full-response budget.
+ pub(crate) flag_definitions_conditional_limiter: FlagDefinitionsRateLimiter,
/// Per-credential limiter (keyed on the personal API key id) for the remote_config endpoint,
/// mirroring Django's RemoteConfigThrottle. Separate budget from flag definitions.
pub(crate) remote_config_limiter: RemoteConfigRateLimiter,
@@ -281,7 +284,7 @@ where
C: clock::Clock + Clone + Send + Sync + 'static,
{
// Initialize flag definitions rate limiter with default and custom team rates
- let flag_definitions_limiter = FlagDefinitionsRateLimiter::new(
+ let flag_definitions_full_limiter = FlagDefinitionsRateLimiter::new(
config.flag_definitions_default_rate_per_minute,
config.flag_definitions_rate_limits.0.clone(),
config.rate_limiting_allow_list_teams.0.clone(),
@@ -289,7 +292,20 @@ where
FLAG_DEFINITIONS_RATE_LIMITED_COUNTER,
FLAG_DEFINITIONS_RATE_LIMIT_BYPASSED_COUNTER,
)
- .expect("Failed to initialize flag definitions rate limiter");
+ .expect("Failed to initialize flag definitions rate limiter")
+ .with_labels(&[("budget", "full")]);
+
+ // Both limiters share metric names, so dashboards that sum the counters still see every request.
+ let flag_definitions_conditional_limiter = FlagDefinitionsRateLimiter::new(
+ config.flag_definitions_conditional_rate_per_minute,
+ config.flag_definitions_conditional_rate_limits.0.clone(),
+ config.rate_limiting_allow_list_teams.0.clone(),
+ FLAG_DEFINITIONS_REQUESTS_COUNTER,
+ FLAG_DEFINITIONS_RATE_LIMITED_COUNTER,
+ FLAG_DEFINITIONS_RATE_LIMIT_BYPASSED_COUNTER,
+ )
+ .expect("Failed to initialize flag definitions conditional rate limiter")
+ .with_labels(&[("budget", "conditional")]);
// Per-credential limiter for the remote_config endpoint (mirrors Django's
// RemoteConfigThrottle, which buckets per hashed bearer token). The team allowlist is
@@ -353,7 +369,8 @@ where
spawn_rate_limiter_cleanup_task(
flags_rate_limiter.clone(),
ip_rate_limiter.clone(),
- flag_definitions_limiter.clone(),
+ flag_definitions_full_limiter.clone(),
+ flag_definitions_conditional_limiter.clone(),
remote_config_limiter.clone(),
config.rate_limiter_cleanup_interval_secs,
);
@@ -405,7 +422,8 @@ where
feature_flags_billing_limiter,
session_replay_billing_limiter,
cookieless_manager,
- flag_definitions_limiter,
+ flag_definitions_full_limiter,
+ flag_definitions_conditional_limiter,
remote_config_limiter,
config: config.clone(),
flags_hypercache_reader,
@@ -636,7 +654,8 @@ fn resolve_rate_limit_capacities(
fn spawn_rate_limiter_cleanup_task<C>(
flags_rate_limiter: FlagsRateLimiter<C>,
ip_rate_limiter: IpRateLimiter<C>,
- flag_definitions_limiter: FlagDefinitionsRateLimiter,
+ flag_definitions_full_limiter: FlagDefinitionsRateLimiter,
+ flag_definitions_conditional_limiter: FlagDefinitionsRateLimiter,
remote_config_limiter: RemoteConfigRateLimiter,
cleanup_interval_secs: u64,
) where
@@ -651,21 +670,25 @@ fn spawn_rate_limiter_cleanup_task<C>(
// Remove stale entries and reclaim memory
flags_rate_limiter.cleanup();
ip_rate_limiter.cleanup();
- flag_definitions_limiter.cleanup();
+ flag_definitions_full_limiter.cleanup();
+ flag_definitions_conditional_limiter.cleanup();
remote_config_limiter.cleanup();
// Report metrics for monitoring
gauge!("flags_rate_limiter_token_entries").set(flags_rate_limiter.len() as f64);
gauge!("flags_rate_limiter_ip_entries").set(ip_rate_limiter.len() as f64);
- gauge!("flags_rate_limiter_definitions_entries")
- .set(flag_definitions_limiter.len() as f64);
+ gauge!("flags_rate_limiter_definitions_entries", "budget" => "full")
+ .set(flag_definitions_full_limiter.len() as f64);
+ gauge!("flags_rate_limiter_definitions_entries", "budget" => "conditional")
+ .set(flag_definitions_conditional_limiter.len() as f64);
gauge!("flags_rate_limiter_remote_config_entries")
.set(remote_config_limiter.len() as f64);
tracing::debug!(
token_entries = flags_rate_limiter.len(),
ip_entries = ip_rate_limiter.len(),
- definitions_entries = flag_definitions_limiter.len(),
+ definitions_full_entries = flag_definitions_full_limiter.len(),
+ definitions_conditional_entries = flag_definitions_conditional_limiter.len(),
remote_config_entries = remote_config_limiter.len(),
"Rate limiter cleanup completed"
);
diff --git a/rust/feature-flags/tests/test_flag_definitions.rs b/rust/feature-flags/tests/test_flag_definitions.rs
index c2887d93522e..fc7e449cf235 100644
--- a/rust/feature-flags/tests/test_flag_definitions.rs
+++ b/rust/feature-flags/tests/test_flag_definitions.rs
@@ -1595,6 +1595,7 @@ async fn test_flag_definitions_rate_limit_metrics_incremented() {
let mut config = Config::default_test_config();
config.flag_definitions_rate_limits =
format!(r#"{{"{}": "1/minute"}}"#, team.id).parse().unwrap();
+ config.flag_definitions_conditional_rate_per_minute = 1;
config.enable_metrics = true; // Enable metrics collection
// Populate cache
@@ -1605,21 +1606,15 @@ async fn test_flag_definitions_rate_limit_metrics_incremented() {
.await
.unwrap();
- // A second team whose `:etag` value cannot be decoded. Deleting `etag_read_failure_label`
+ // The rate-limited team's `:etag` value cannot be decoded. Deleting `etag_read_failure_label`
// left `redis_error` with no coverage, and this is the only test that can scrape /metrics.
- let (corrupt_team, corrupt_secret_token, _) = context
- .create_team_with_secret_token(None, None, None)
- .await
- .unwrap();
- context
- .populate_flag_definitions_cache(redis_client.clone(), corrupt_team.id)
- .await
- .unwrap();
+ // No other test writes an undecodable `:etag`, so other tests running in the same process
+ // cannot add to the `redis_error` count asserted below.
redis_client
.set_bytes(
format!(
"posthog:1:cache/teams/{}/feature_flags/flags_with_cohorts.json:etag",
- corrupt_team.id
+ team.id
),
b"not-a-pickle".to_vec(),
None,
@@ -1627,47 +1622,49 @@ async fn test_flag_definitions_rate_limit_metrics_incremented() {
.await
.unwrap();
+ let (other_team, other_secret_token, _) = context
+ .create_team_with_secret_token(None, None, None)
+ .await
+ .unwrap();
+ context
+ .populate_flag_definitions_cache(redis_client.clone(), other_team.id)
+ .await
+ .unwrap();
+
let server = common::ServerHandle::for_config(config.clone()).await;
let client = reqwest::Client::new();
- // Make first request (should succeed)
- let response = client
- .get(format!(
- "http://{}/flags/definitions?token={}",
- server.addr, team.api_token
- ))
- .header("Authorization", format!("Bearer {secret_token}"))
- .send()
- .await
- .unwrap();
+ let url = format!(
+ "http://{}/flags/definitions?token={}",
+ server.addr, team.api_token
+ );
+ let response = get_definitions(&client, &url, &secret_token, None).await;
assert_eq!(response.status(), 200);
- // Make second request (should be rate limited)
- let response = client
- .get(format!(
- "http://{}/flags/definitions?token={}",
- server.addr, team.api_token
- ))
- .header("Authorization", format!("Bearer {secret_token}"))
- .send()
- .await
- .unwrap();
-
+ let response = get_definitions(&client, &url, &secret_token, None).await;
assert_eq!(response.status(), 429);
- // The corrupt team is not rate limited, so this request reaches the ETag read.
- let corrupt_response = client
- .get(format!(
- "http://{}/flags/definitions?token={}",
- server.addr, corrupt_team.api_token
- ))
- .header("Authorization", format!("Bearer {corrupt_secret_token}"))
- .send()
- .await
- .unwrap();
+ let response = get_definitions(&client, &url, &secret_token, Some("W/\"stale\"")).await;
+ assert_eq!(
+ response.status(),
+ 429,
+ "A stale ETag should pass the conditional budget and be refused by the spent full-response budget"
+ );
+ let response = get_definitions(&client, &url, &secret_token, Some("W/\"stale\"")).await;
+ assert_eq!(
+ response.status(),
+ 429,
+ "The spent conditional budget should refuse a stale ETag before the ETag read"
+ );
- assert_eq!(corrupt_response.status(), 200);
+ // The second team is not rate limited, so this request reaches the ETag read.
+ let other_url = format!(
+ "http://{}/flags/definitions?token={}",
+ server.addr, other_team.api_token
+ );
+ let response = get_definitions(&client, &other_url, &other_secret_token, None).await;
+ assert_eq!(response.status(), 200);
// Fetch metrics from /metrics endpoint
let metrics_response = client
@@ -1677,27 +1674,53 @@ async fn test_flag_definitions_rate_limit_metrics_incremented() {
.unwrap();
let metrics_text = metrics_response.text().await.unwrap();
+ let metric_value = |prefix: &str, labels: &[&str]| {
+ metrics_text
+ .lines()
+ .find(|line| {
+ line.starts_with(prefix) && labels.iter().all(|label| line.contains(label))
+ })
+ .and_then(|line| line.rsplit(' ').next())
+ .and_then(|value| value.parse::<f64>().ok())
+ };
- // Verify that rate limit metrics are present
- assert!(
- metrics_text.contains("flags_flag_definitions_requests_total"),
- "Metrics should include request counter"
+ // Both limiters share metric names and differ only in the `budget` label, so a dashboard
+ // that sums a counter sees every request. A stale ETag passes both limiters but counts
+ // once as a request. The full-response limiter still counts the 429 it returns for it.
+ let team_key = format!(r#"key="{}""#, team.id);
+ let team_count = |metric: &str, budget: &str| {
+ metric_value(
+ &format!("{metric}{{"),
+ &[&team_key, &format!(r#"budget="{budget}""#)],
+ )
+ };
+ assert_eq!(
+ team_count("flags_flag_definitions_requests_total", "full"),
+ Some(2.0),
+ "A stale ETag should not count as a second request. Metrics: {metrics_text}"
);
- assert!(
- metrics_text.contains("flags_flag_definitions_rate_limited_total"),
- "Metrics should include rate limited counter"
+ assert_eq!(
+ team_count("flags_flag_definitions_requests_total", "conditional"),
+ Some(2.0),
+ "Requests with an ETag in If-None-Match should count under the conditional budget. Metrics: {metrics_text}"
+ );
+ assert_eq!(
+ team_count("flags_flag_definitions_rate_limited_total", "full"),
+ Some(2.0),
+ "The full-response limiter should count the 429 it returns for a stale ETag. Metrics: {metrics_text}"
+ );
+ assert_eq!(
+ team_count("flags_flag_definitions_rate_limited_total", "conditional"),
+ Some(1.0),
+ "429s from the conditional limiter should count under the conditional budget. Metrics: {metrics_text}"
);
// Runbook step 2 picks which cluster to query from this gauge, so assert the series and
// its value and not just the metric name. This config leaves the toggle off.
- let gauge_value = metrics_text
- .lines()
- .find(|line| {
- line.starts_with("flags_flag_definitions_reads_dedicated_redis{")
- && line.contains(r#"reason="disabled""#)
- })
- .and_then(|line| line.rsplit(' ').next())
- .and_then(|value| value.parse::<f64>().ok());
+ let gauge_value = metric_value(
+ "flags_flag_definitions_reads_dedicated_redis{",
+ &[r#"reason="disabled""#],
+ );
assert_eq!(
gauge_value,
Some(0.0),
@@ -1705,30 +1728,209 @@ async fn test_flag_definitions_rate_limit_metrics_incremented() {
);
// An absent ETag writes no log record, so this counter is the only trace that it
- // happened. populate_flag_definitions_cache writes no `:etag` key, so the first
- // request above took that path.
+ // happened. populate_flag_definitions_cache writes no `:etag` key for the second team.
assert!(
- metrics_text.lines().any(|line| line
- .starts_with("flags_flag_definitions_etag_total{")
- && line.contains(r#"result="redis_missing""#)),
- "An absent ETag should count as redis_missing rather than redis_error. Metrics: {metrics_text}"
+ metric_value(
+ "flags_flag_definitions_etag_total{",
+ &[r#"result="redis_missing""#]
+ )
+ .is_some(),
+ "An absent ETag should count as redis_missing. Metrics: {metrics_text}"
);
// Routing a decode failure back to Ok(None) would revert this to redis_missing, which sends
- // the on-call to rebuild a cache tier when the fault is corrupt data.
- assert!(
- metrics_text.lines().any(
- |line| line.starts_with("flags_flag_definitions_etag_total{")
- && line.contains(r#"result="redis_error""#)
- ),
- "An undecodable ETag should count as redis_error. Metrics: {metrics_text}"
+ // the on-call to rebuild a cache tier when the fault is corrupt data. Only the rate-limited
+ // team's 200 and its first stale ETag read its undecodable ETag. A limiter check that runs
+ // after the ETag read raises the count, because the refused requests then read Redis too.
+ let redis_error = metric_value(
+ "flags_flag_definitions_etag_total{",
+ &[r#"result="redis_error""#],
+ );
+ assert_eq!(
+ redis_error,
+ Some(2.0),
+ "An undecodable ETag should count as redis_error, and only the 200 and the first stale ETag should read it. Metrics: {metrics_text}"
);
+}
- // Verify key label is present in metrics (key is the generic label for team_id)
- let key_label = format!("key=\"{}\"", team.id);
- assert!(
- metrics_text.contains(&key_label),
- "Metrics should include key label. Metrics: {metrics_text}"
+async fn get_definitions(
+ client: &reqwest::Client,
+ url: &str,
+ secret_token: &str,
+ if_none_match: Option<&str>,
+) -> reqwest::Response {
+ let request = client
+ .get(url)
+ .header("Authorization", format!("Bearer {secret_token}"));
+ match if_none_match {
+ Some(etag) => request.header("If-None-Match", etag),
+ None => request,
+ }
+ .send()
+ .await
+ .unwrap()
+}
+
+#[tokio::test]
+async fn test_etag_304_does_not_consume_full_response_rate_limit() {
+ use feature_flags::{config::Config, utils::test_utils::TestContext};
+ use reqwest;
+
+ let mut config = Config::default_test_config();
+ let context = TestContext::new(Some(&config)).await;
+
+ let (team, secret_token, _) = context
+ .create_team_with_secret_token(None, None, None)
+ .await
+ .unwrap();
+
+ config.flag_definitions_rate_limits =
+ format!(r#"{{"{}": "1/minute"}}"#, team.id).parse().unwrap();
+
+ let etag_value = "a1b2c3d4e5f6g7h8";
+ context
+ .populate_cache_for_team_with_etag(team.id, etag_value)
+ .await
+ .unwrap();
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let client = reqwest::Client::new();
+ let url = format!(
+ "http://{}/flags/definitions?token={}",
+ server.addr, team.api_token
+ );
+
+ let matching_etag = format!("W/\"{etag_value}\"");
+
+ let response = get_definitions(&client, &url, &secret_token, None).await;
+ assert_eq!(response.status(), 200, "First full response should succeed");
+
+ // The full-response budget (1/minute) is now spent, but revalidation polls
+ // with a matching ETag draw from the separate conditional budget.
+ for _ in 0..3 {
+ let response = get_definitions(&client, &url, &secret_token, Some(&matching_etag)).await;
+ assert_eq!(
+ response.status(),
+ 304,
+ "Matching ETag should return 304 even when the full-response budget is spent"
+ );
+ }
+
+ let response = get_definitions(&client, &url, &secret_token, None).await;
+ assert_eq!(
+ response.status(),
+ 429,
+ "Full response should still be rate limited"
+ );
+}
+
+#[tokio::test]
+async fn test_etag_304_rate_limit_enforced() {
+ use feature_flags::{config::Config, utils::test_utils::TestContext};
+ use reqwest;
+
+ let mut config = Config::default_test_config();
+ config.flag_definitions_conditional_rate_per_minute = 1;
+ let context = TestContext::new(Some(&config)).await;
+
+ let (team, secret_token, _) = context
+ .create_team_with_secret_token(None, None, None)
+ .await
+ .unwrap();
+
+ let etag_value = "a1b2c3d4e5f6g7h8";
+ context
+ .populate_cache_for_team_with_etag(team.id, etag_value)
+ .await
+ .unwrap();
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let client = reqwest::Client::new();
+ let url = format!(
+ "http://{}/flags/definitions?token={}",
+ server.addr, team.api_token
+ );
+
+ let matching_etag = format!("W/\"{etag_value}\"");
+
+ let response = get_definitions(&client, &url, &secret_token, Some(&matching_etag)).await;
+ assert_eq!(response.status(), 304, "First 304 should succeed");
+
+ let response = get_definitions(&client, &url, &secret_token, Some(&matching_etag)).await;
+ let status = response.status();
+ let body = response.text().await.unwrap();
+ assert_eq!(
+ status, 429,
+ "Second 304 should be rate limited. Response body: {body}"
+ );
+
+ // The limiter runs before the ETag read. It cannot tell a stale ETag from a matching one.
+ let response = get_definitions(&client, &url, &secret_token, Some("W/\"stale\"")).await;
+ assert_eq!(
+ response.status(),
+ 429,
+ "A stale ETag should spend the conditional budget"
+ );
+
+ let response = get_definitions(&client, &url, &secret_token, None).await;
+ assert_eq!(
+ response.status(),
+ 200,
+ "Full response should not be limited by the conditional budget"
+ );
+}
+
+#[tokio::test]
+async fn test_stale_etag_200_spends_both_budgets() {
+ use feature_flags::{config::Config, utils::test_utils::TestContext};
+ use reqwest;
+
+ let mut config = Config::default_test_config();
+ let context = TestContext::new(Some(&config)).await;
+
+ let (team, secret_token, _) = context
+ .create_team_with_secret_token(None, None, None)
+ .await
+ .unwrap();
+
+ let one_per_minute = format!(r#"{{"{}": "1/minute"}}"#, team.id);
+ config.flag_definitions_rate_limits = one_per_minute.parse().unwrap();
+ config.flag_definitions_conditional_rate_limits = one_per_minute.parse().unwrap();
+
+ let etag_value = "a1b2c3d4e5f6g7h8";
+ context
+ .populate_cache_for_team_with_etag(team.id, etag_value)
+ .await
+ .unwrap();
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let client = reqwest::Client::new();
+ let url = format!(
+ "http://{}/flags/definitions?token={}",
+ server.addr, team.api_token
+ );
+
+ let matching_etag = format!("W/\"{etag_value}\"");
+
+ let response = get_definitions(&client, &url, &secret_token, Some("W/\"stale\"")).await;
+ assert_eq!(
+ response.status(),
+ 200,
+ "A stale ETag should get a full response"
+ );
+
+ let response = get_definitions(&client, &url, &secret_token, Some(&matching_etag)).await;
+ assert_eq!(
+ response.status(),
+ 429,
+ "The stale ETag should have spent the team's 1/minute conditional override"
+ );
+
+ let response = get_definitions(&client, &url, &secret_token, None).await;
+ assert_eq!(
+ response.status(),
+ 429,
+ "The stale ETag should have spent the team's 1/minute full-response override"
);
}
@@ -2386,7 +2588,7 @@ async fn test_flag_definitions_with_legacy_secret_token_fallback() {
/// share the same `posthog_instancesetting` row.
///
/// Scenarios tested:
-/// 1. Allowlisted team bypasses rate limit (200 instead of 429)
+/// 1. Allowlisted team bypasses both rate limits (200 or 304 instead of 429)
/// 2. Non-allowlisted team gets rate limited (429)
/// 3. With two teams, only the listed one bypasses
/// 4. Env var allowlist preserved when DB row is missing
@@ -2421,17 +2623,19 @@ async fn test_db_rate_limit_allowlist() {
config.flag_definitions_rate_limits = format!(r#"{{"{}": "1/minute"}}"#, team1.id)
.parse()
.unwrap();
+ config.flag_definitions_conditional_rate_per_minute = 1;
context
.set_instance_setting("RATE_LIMITING_ALLOW_LIST_TEAMS", &team1.id.to_string())
.await
.unwrap();
+ let etag_value = "a1b2c3d4e5f6g7h8";
let redis_client =
feature_flags::utils::test_utils::setup_redis_client(Some(config.redis_url.clone()))
.await;
context
- .populate_flag_definitions_cache(redis_client, team1.id)
+ .populate_cache_for_team_with_etag_on(redis_client, team1.id, etag_value)
.await
.unwrap();
@@ -2465,6 +2669,22 @@ async fn test_db_rate_limit_allowlist() {
200,
"Allowlisted team should bypass rate limit"
);
+
+ // The conditional budget (1/minute) would reject the second poll, but the
+ // DB-refreshed allowlist applies to the conditional limiter too
+ let url = format!(
+ "http://{}/flags/definitions?token={}",
+ server.addr, team1.api_token
+ );
+ let matching_etag = format!("W/\"{etag_value}\"");
+ for i in 0..2 {
+ let resp = get_definitions(&client, &url, &secret1, Some(&matching_etag)).await;
+ assert_eq!(
+ resp.status(),
+ 304,
+ "Allowlisted team should bypass the conditional rate limit (poll {i})"
+ );
+ }
}
// --- Scenario 2: non-allowlisted team gets rate limited ---
@@ -2596,6 +2816,7 @@ async fn test_db_rate_limit_allowlist() {
.parse()
.unwrap();
config.rate_limiting_allow_list_teams = team1.id.to_string().parse().unwrap();
+ config.flag_definitions_conditional_rate_per_minute = 1;
// Ensure no DB row exists — env var default should be kept
context
@@ -2606,8 +2827,9 @@ async fn test_db_rate_limit_allowlist() {
let redis_client =
feature_flags::utils::test_utils::setup_redis_client(Some(config.redis_url.clone()))
.await;
+ let etag_value = "a1b2c3d4e5f6g7h8";
context
- .populate_flag_definitions_cache(redis_client, team1.id)
+ .populate_cache_for_team_with_etag_on(redis_client, team1.id, etag_value)
.await
.unwrap();
@@ -2641,6 +2863,20 @@ async fn test_db_rate_limit_allowlist() {
200,
"Env var allowlist should be preserved when DB row is missing"
);
+
+ let url = format!(
+ "http://{}/flags/definitions?token={}",
+ server.addr, team1.api_token
+ );
+ let matching_etag = format!("W/\"{etag_value}\"");
+ for _ in 0..2 {
+ let resp = get_definitions(&client, &url, &secret1, Some(&matching_etag)).await;
+ assert_eq!(
+ resp.status(),
+ 304,
+ "Env var allowlist should bypass the conditional rate limit"
+ );
+ }
}
// --- Scenario 5: null DB value treated as empty allowlist ---