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.

feat(error-tracking): rate-limit exception events in cymbal (#65984)

Aleksander Błaszkiewiczac2625a0c41d
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.yml
index fa0e75bbaed3..be32322e672e 100644
--- a/.github/workflows/ci-rust.yml
+++ b/.github/workflows/ci-rust.yml
@@ -411,6 +411,14 @@ jobs:
extra_args="-- --test-threads=4"
fi
cargo test -p "$pkg" $extra_args
+ # Error-tracking rate-limiter e2e tests are #[ignore]'d (they need a real Redis
+ # via testcontainers/Docker, absent in some environments). This job has Docker,
+ # so run them here, single-threaded to avoid concurrent-container flakes. The
+ # `rate_limiting` filter matches nothing on branches without these tests, so it
+ # stays safe for unrebased PRs.
+ if [ "$pkg" = "cymbal" ]; then
+ cargo test -p cymbal rate_limiting -- --ignored --test-threads=1
+ fi
echo "::endgroup::"
done
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 30591c24c333..ec0d1a9fcbf2 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2835,6 +2835,7 @@ dependencies = [
"sqlx",
"subtle",
"symbolic",
+ "testcontainers",
"thiserror 2.0.18",
"tiktoken-rs",
"tokio",
diff --git a/rust/common/kafka/src/kafka_messages/app_metrics2.rs b/rust/common/kafka/src/kafka_messages/app_metrics2.rs
index fd5182dae687..63d76cfc4290 100644
--- a/rust/common/kafka/src/kafka_messages/app_metrics2.rs
+++ b/rust/common/kafka/src/kafka_messages/app_metrics2.rs
@@ -8,6 +8,7 @@ use super::{deserialize_datetime, serialize_datetime};
pub enum Source {
Hoghooks,
Cyclotron,
+ Exceptions,
}
#[derive(Deserialize, Serialize, Debug, PartialEq, Clone)]
@@ -17,6 +18,8 @@ pub enum Kind {
Failure,
Canceled,
Unknown,
+ #[serde(rename = "rate_limiting")]
+ RateLimiting,
}
#[derive(Deserialize, Serialize, Debug, PartialEq, Clone)]
diff --git a/rust/common/redis/src/client.rs b/rust/common/redis/src/client.rs
index 2c96a26f1854..7dbfcef3814b 100644
--- a/rust/common/redis/src/client.rs
+++ b/rust/common/redis/src/client.rs
@@ -219,6 +219,30 @@ impl RedisClient {
Self::maybe_compress(bytes, &self.compression)
}
+
+ /// Evaluate a Lua script (EVALSHA with EVAL fallback) and decode the reply
+ /// as a list of integers. Used by the error-tracking rate limiter, whose
+ /// fused script returns `{ issue_admitted, team_admitted }`. Bypasses this
+ /// client's value (de)serialization and compression — the script operates
+ /// on raw Redis types directly.
+ pub async fn eval_int_vec(
+ &self,
+ script: &str,
+ keys: Vec<String>,
+ args: Vec<String>,
+ ) -> Result<Vec<i64>, CustomRedisError> {
+ let script = redis::Script::new(script);
+ let mut invocation = script.prepare_invoke();
+ for key in keys {
+ invocation.key(key);
+ }
+ for arg in args {
+ invocation.arg(arg);
+ }
+ let mut conn = self.connection.clone();
+ let result: Vec<i64> = invocation.invoke_async(&mut conn).await?;
+ Ok(result)
+ }
}
#[async_trait]
diff --git a/rust/cymbal/Cargo.toml b/rust/cymbal/Cargo.toml
index 12bd493911ea..ec6fa635136b 100644
--- a/rust/cymbal/Cargo.toml
+++ b/rust/cymbal/Cargo.toml
@@ -62,6 +62,7 @@ insta = { version = "1.46.0", features = ["json", "redactions"] }
tower.workspace = true
# For decompressing the committed native ELF test fixture
zstd = "0.13"
+testcontainers = { workspace = true }
[lints]
workspace = true
diff --git a/rust/cymbal/src/core/error.rs b/rust/cymbal/src/core/error.rs
index 2595f3179585..897fbf3a4625 100644
--- a/rust/cymbal/src/core/error.rs
+++ b/rust/cymbal/src/core/error.rs
@@ -228,6 +228,10 @@ pub enum EventError {
Suppressed(Uuid),
#[error("Suppressed by rule: {0}")]
SuppressedByRule(Uuid),
+ #[error("Rate limited (per-issue): {0}")]
+ RateLimitedPerIssue(Uuid),
+ #[error("Rate limited (project): team {0}")]
+ RateLimitedProject(i32),
}
impl JsResolveErr {
diff --git a/rust/cymbal/src/core/metric_consts.rs b/rust/cymbal/src/core/metric_consts.rs
index 6c92b232ae3e..5e6a9134b0cf 100644
--- a/rust/cymbal/src/core/metric_consts.rs
+++ b/rust/cymbal/src/core/metric_consts.rs
@@ -113,6 +113,9 @@ pub const RESOLUTION_STAGE: &str = "cymbal_stack_processing_time";
pub const LINKING_STAGE: &str = "cymbal_issue_processing_time";
pub const GROUPING_STAGE: &str = "cymbal_exception_grouping_stage";
pub const ALERTING_STAGE: &str = "cymbal_exception_alerting_stage";
+pub const RATE_LIMITING_STAGE: &str = "cymbal_rate_limiting_stage";
+pub const RATE_LIMIT_OUTCOMES: &str = "cymbal_error_tracking_rate_limiter_outcomes";
+pub const RATE_LIMIT_FAIL_OPEN: &str = "cymbal_error_tracking_rate_limiter_fail_open";
pub const SPIKE_ALERT_STAGE: &str = "cymbal_spike_detection_time";
// Operators
diff --git a/rust/cymbal/src/modes/processing/app_context.rs b/rust/cymbal/src/modes/processing/app_context.rs
index a24a464dd6b2..c34c635985ed 100644
--- a/rust/cymbal/src/modes/processing/app_context.rs
+++ b/rust/cymbal/src/modes/processing/app_context.rs
@@ -4,7 +4,7 @@ use health::HealthRegistry;
use moka::future::{Cache, CacheBuilder};
use rdkafka::producer::FutureProducer;
use sqlx::{postgres::PgPoolOptions, PgPool};
-use std::{sync::Arc, time::Duration};
+use std::{collections::HashSet, sync::Arc, time::Duration};
use tokio::{sync::Semaphore, task::JoinHandle};
use tracing::info;
use uuid::Uuid;
@@ -15,6 +15,7 @@ use crate::{
error::UnhandledError,
modes::processing::config::{init_global_state, ProcessingConfig},
signals::{MaybeSignalClient, SignalClient},
+ stages::rate_limiting::RedisRateLimiter,
stages::resolution::remote::{
dns::TokioDnsResolver, pool::EndpointPool, resolver::RemoteResolutionContext,
RemoteResolutionConfig,
@@ -46,6 +47,12 @@ pub struct AppContext {
pub team_manager: TeamManager,
pub issue_buckets_redis_client: Arc<dyn RedisClientTrait + Send + Sync>,
+ // Error-tracking rate limiter. `None` when disabled (the default), in which
+ // case `RateLimitingStage` is a pass-through no-op.
+ pub rate_limiter: Option<Arc<RedisRateLimiter>>,
+ // Team allowlist for the rate limiter: `None` = all teams, `Some(set)` = only
+ // these. Parsed from ERROR_TRACKING_RATE_LIMITER_ENABLED_TEAM_IDS.
+ pub rate_limiter_enabled_team_ids: Option<HashSet<i32>>,
pub signal_client: MaybeSignalClient,
// Shared `(team_id, fingerprint) -> issue_id` mapping cache. Lives on AppContext so
// it persists across requests — only the stable mapping is cached, never the Issue
@@ -165,6 +172,10 @@ impl AppContext {
let (remote_resolution, remote_resolution_refresh_task) =
build_remote_resolution(config).await?;
+ let rate_limiter = build_rate_limiter(config).await?;
+ let rate_limiter_enabled_team_ids =
+ parse_team_id_allowlist(&config.error_tracking_rate_limiter_enabled_team_ids);
+
Ok(Self {
health_registry,
immediate_producer,
@@ -176,6 +187,8 @@ impl AppContext {
process_request_limiter,
team_manager,
issue_buckets_redis_client,
+ rate_limiter,
+ rate_limiter_enabled_team_ids,
signal_client,
symbol_resolver,
issue_cache,
@@ -185,6 +198,55 @@ impl AppContext {
}
}
+async fn build_rate_limiter(
+ config: &ProcessingConfig,
+) -> Result<Option<Arc<RedisRateLimiter>>, UnhandledError> {
+ if !config.error_tracking_rate_limiter_enabled {
+ return Ok(None);
+ }
+
+ // Dedicated connection to the rate-limiter Redis. Defaults to localhost,
+ // which is shared with the issue-buckets Redis in local dev.
+ let client = RedisClient::with_config(
+ config.error_tracking_rate_limiter_redis_url.clone(),
+ common_redis::CompressionConfig::disabled(),
+ common_redis::RedisValueFormat::Utf8,
+ if config.redis_response_timeout_ms == 0 {
+ None
+ } else {
+ Some(Duration::from_millis(config.redis_response_timeout_ms))
+ },
+ if config.redis_connection_timeout_ms == 0 {
+ None
+ } else {
+ Some(Duration::from_millis(config.redis_connection_timeout_ms))
+ },
+ )
+ .await?;
+
+ info!("Error-tracking rate limiter enabled");
+
+ Ok(Some(Arc::new(RedisRateLimiter::new(
+ Arc::new(client),
+ config.error_tracking_rate_limiter_key_prefix.clone(),
+ config.error_tracking_rate_limiter_bucket_ttl_seconds,
+ ))))
+}
+
+/// Parse a comma-separated team-id allowlist. `None` (empty input) means the
+/// rate limiter applies to all teams; `Some(set)` restricts it to those teams.
+fn parse_team_id_allowlist(value: &str) -> Option<HashSet<i32>> {
+ if value.is_empty() {
+ return None;
+ }
+ Some(
+ value
+ .split(',')
+ .filter_map(|s| s.trim().parse::<i32>().ok())
+ .collect(),
+ )
+}
+
async fn build_remote_resolution(
config: &ProcessingConfig,
) -> Result<(Option<RemoteResolutionContext>, Option<JoinHandle<()>>), UnhandledError> {
diff --git a/rust/cymbal/src/modes/processing/config.rs b/rust/cymbal/src/modes/processing/config.rs
index 46260a05718e..0c2125e75c78 100644
--- a/rust/cymbal/src/modes/processing/config.rs
+++ b/rust/cymbal/src/modes/processing/config.rs
@@ -107,6 +107,35 @@ pub struct ProcessingConfig {
#[envconfig(default = "5000")]
pub redis_connection_timeout_ms: u64,
+ #[envconfig(from = "ERROR_TRACKING_CYMBAL_RATE_LIMITER_ENABLED", default = "false")]
+ pub error_tracking_rate_limiter_enabled: bool,
+
+ #[envconfig(
+ from = "ERROR_TRACKING_CYMBAL_RATE_LIMITER_REDIS_URL",
+ default = "redis://localhost:6379/"
+ )]
+ pub error_tracking_rate_limiter_redis_url: String,
+
+ #[envconfig(
+ from = "ERROR_TRACKING_CYMBAL_RATE_LIMITER_KEY_PREFIX",
+ default = "@posthog/error-tracking-cymbal-rate-limiter"
+ )]
+ pub error_tracking_rate_limiter_key_prefix: String,
+
+ #[envconfig(
+ from = "ERROR_TRACKING_CYMBAL_RATE_LIMITER_BUCKET_TTL_SECONDS",
+ default = "86400"
+ )]
+ pub error_tracking_rate_limiter_bucket_ttl_seconds: u64,
+
+ // Comma separated list of team IDs the error-tracking rate limiter applies to.
+ // If empty, it applies to all teams (that have limits configured).
+ #[envconfig(
+ from = "ERROR_TRACKING_CYMBAL_RATE_LIMITER_ENABLED_TEAM_IDS",
+ default = ""
+ )]
+ pub error_tracking_rate_limiter_enabled_team_ids: String,
+
// Comma separated list of team IDs that can receive spike alerts.
// If empty, all teams can receive alerts
#[envconfig(default = "")]
diff --git a/rust/cymbal/src/modes/processing/rules/mod.rs b/rust/cymbal/src/modes/processing/rules/mod.rs
index 92e3f1a2e167..0b83c6f43534 100644
--- a/rust/cymbal/src/modes/processing/rules/mod.rs
+++ b/rust/cymbal/src/modes/processing/rules/mod.rs
@@ -4,5 +4,6 @@
pub mod assignment;
pub mod grouping;
+pub mod rate_limit;
pub mod spike;
pub mod suppression;
diff --git a/rust/cymbal/src/modes/processing/rules/rate_limit.rs b/rust/cymbal/src/modes/processing/rules/rate_limit.rs
new file mode 100644
index 000000000000..ce5f12bd4996
--- /dev/null
+++ b/rust/cymbal/src/modes/processing/rules/rate_limit.rs
@@ -0,0 +1,105 @@
+use sqlx::Row;
+
+/// Per-team error-tracking rate-limit configuration, loaded from
+/// `posthog_errortrackingsettings`. Two independent limits, matching the Node.js
+/// limiter: a per-issue cap and a project-wide (team) cap. A `None` value for a
+/// limit means that limit is disabled for the team.
+#[derive(Debug, Clone, Default)]
+pub struct RateLimitSettings {
+ pub project_value: Option<i32>,
+ pub project_bucket_minutes: Option<i32>,
+ pub per_issue_value: Option<i32>,
+ pub per_issue_bucket_minutes: Option<i32>,
+}
+
+/// Token-bucket parameters for one limit: `max` is the burst size (bucket
+/// capacity), `rate` is the steady refill in tokens/second.
+#[derive(Debug, Clone, Copy)]
+pub struct BucketParams {
+ pub max: f64,
+ pub rate: f64,
+}
+
+impl RateLimitSettings {
+ fn to_bucket_params(value: Option<i32>, minutes: Option<i32>) -> Option<BucketParams> {
+ let value = value?;
+ if value <= 0 {
+ return None;
+ }
+ // "value events per `minutes` minutes" → bucket size `value`,
+ // refill `value / (minutes * 60)` tokens per second.
+ let minutes = minutes.unwrap_or(60).max(1);
+ Some(BucketParams {
+ max: value as f64,
+ rate: value as f64 / (minutes as f64 * 60.0),
+ })
+ }
+
+ pub fn per_issue(&self) -> Option<BucketParams> {
+ Self::to_bucket_params(self.per_issue_value, self.per_issue_bucket_minutes)
+ }
+
+ pub fn project(&self) -> Option<BucketParams> {
+ Self::to_bucket_params(self.project_value, self.project_bucket_minutes)
+ }
+
+ pub async fn load_for_team<'c, E>(conn: E, team_id: i32) -> Result<Option<Self>, sqlx::Error>
+ where
+ E: sqlx::Executor<'c, Database = sqlx::Postgres>,
+ {
+ let row = sqlx::query(
+ "SELECT project_rate_limit_value, project_rate_limit_bucket_size_minutes, \
+ per_issue_rate_limit_value, per_issue_rate_limit_bucket_size_minutes \
+ FROM posthog_errortrackingsettings WHERE team_id = $1",
+ )
+ .bind(team_id)
+ .fetch_optional(conn)
+ .await?;
+
+ row.map(|r| {
+ Ok(Self {
+ project_value: r.try_get("project_rate_limit_value")?,
+ project_bucket_minutes: r.try_get("project_rate_limit_bucket_size_minutes")?,
+ per_issue_value: r.try_get("per_issue_rate_limit_value")?,
+ per_issue_bucket_minutes: r.try_get("per_issue_rate_limit_bucket_size_minutes")?,
+ })
+ })
+ .transpose()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn disabled_when_value_missing_or_nonpositive() {
+ let s = RateLimitSettings::default();
+ assert!(s.per_issue().is_none());
+ assert!(s.project().is_none());
+
+ let s = RateLimitSettings {
+ project_value: Some(0),
+ ..Default::default()
+ };
+ assert!(s.project().is_none());
+ }
+
+ #[test]
+ fn bucket_params_from_value_and_minutes() {
+ let s = RateLimitSettings {
+ project_value: Some(120),
+ project_bucket_minutes: Some(2),
+ per_issue_value: Some(60),
+ per_issue_bucket_minutes: None, // defaults to 60 minutes
+ };
+
+ let project = s.project().unwrap();
+ assert_eq!(project.max, 120.0);
+ assert!((project.rate - 1.0).abs() < 1e-9); // 120 / (2*60) = 1/s
+
+ let per_issue = s.per_issue().unwrap();
+ assert_eq!(per_issue.max, 60.0);
+ assert!((per_issue.rate - (60.0 / 3600.0)).abs() < 1e-9);
+ }
+}
diff --git a/rust/cymbal/src/modes/processing/stages/http_pipeline.rs b/rust/cymbal/src/modes/processing/stages/http_pipeline.rs
index 558670e1787d..1d4183f64379 100644
--- a/rust/cymbal/src/modes/processing/stages/http_pipeline.rs
+++ b/rust/cymbal/src/modes/processing/stages/http_pipeline.rs
@@ -54,7 +54,10 @@ fn handle_result(
Some(original)
}
Err(err) => match err {
- EventError::Suppressed(_) | EventError::SuppressedByRule(_) => None,
+ EventError::Suppressed(_)
+ | EventError::SuppressedByRule(_)
+ | EventError::RateLimitedPerIssue(_)
+ | EventError::RateLimitedProject(_) => None,
err => {
original.attach_error(err.to_string())?;
Some(original)
diff --git a/rust/cymbal/src/modes/processing/stages/mod.rs b/rust/cymbal/src/modes/processing/stages/mod.rs
index 791ba97dde4f..610fa5fc6a3e 100644
--- a/rust/cymbal/src/modes/processing/stages/mod.rs
+++ b/rust/cymbal/src/modes/processing/stages/mod.rs
@@ -5,4 +5,5 @@ pub mod linking;
pub mod pipeline;
pub mod post_processing;
pub mod pre_processing;
+pub mod rate_limiting;
pub mod resolution;
diff --git a/rust/cymbal/src/modes/processing/stages/pipeline.rs b/rust/cymbal/src/modes/processing/stages/pipeline.rs
index 04d364b19096..1985b2425d43 100644
--- a/rust/cymbal/src/modes/processing/stages/pipeline.rs
+++ b/rust/cymbal/src/modes/processing/stages/pipeline.rs
@@ -12,6 +12,7 @@ use crate::{
linking::LinkingStage,
post_processing::{PostProcessingHandler, PostProcessingStage},
pre_processing::{PreProcessingContext, PreProcessingStage},
+ rate_limiting::RateLimitingStage,
resolution::ResolutionStage,
},
types::{
@@ -55,6 +56,10 @@ impl Stage for ExceptionEventPipeline {
// Link events to issues and suppress
.apply_stage(LinkingStage::from(&self.app_context))
.await?
+ // Drop rate-limited events as soon as issue_id is known — before
+ // alerting/enrichment, so spike detection never counts them.
+ .apply_stage(RateLimitingStage::from(&self.app_context))
+ .await?
// Send internal events for alerting
.apply_stage(AlertingStage::from(&self.app_context))
.await
diff --git a/rust/cymbal/src/modes/processing/stages/rate_limiting/limiter.rs b/rust/cymbal/src/modes/processing/stages/rate_limiting/limiter.rs
new file mode 100644
index 000000000000..c42b5c8fba1c
--- /dev/null
+++ b/rust/cymbal/src/modes/processing/stages/rate_limiting/limiter.rs
@@ -0,0 +1,655 @@
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use chrono::Utc;
+use common_redis::{CustomRedisError, RedisClient};
+use uuid::Uuid;
+
+use crate::modes::processing::rules::rate_limit::BucketParams;
+
+/// Outcome of one fused rate-limit call for a single issue group of `n` events.
+/// `issue_admitted <= n` passed the per-issue limit; `team_admitted <= issue_admitted`
+/// additionally passed the project limit. Everything beyond is dropped.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct RateLimitDecision {
+ pub issue_admitted: u32,
+ pub team_admitted: u32,
+}
+
+/// Fused per-issue → per-team token bucket. Both keys carry a `{team_id}` hash
+/// tag so a Redis Cluster colocates them on one slot. Per-issue is charged
+/// first; the team bucket is debited only by what survives the per-issue limit,
+/// so a per-issue drop never costs project budget. A limit whose `max` is
+/// negative is disabled (admits everything offered to it).
+pub const RATE_LIMIT_LUA: &str = r#"
+local function take(key, want, max, rate, ttl, now)
+ if want <= 0 then return 0 end
+ if max < 0 then return want end
+
+ local cur = redis.call('hmget', key, 'ts', 'pool')
+ local tokens
+ if cur[1] == false then
+ tokens = max
+ else
+ local elapsed = now - tonumber(cur[1])
+ if elapsed < 0 then elapsed = 0 end
+ tokens = tonumber(cur[2]) + elapsed * rate
+ if tokens > max then tokens = max end
+ end
+
+ local admit = math.floor(tokens)
+ if admit > want then admit = want end
+
+ -- Never regress `ts`. `now` is each pod's wall clock, so a pod with a lagging
+ -- clock (now < stored ts) must not drag the timestamp backward, or the next
+ -- forward call would compute an inflated `elapsed` and over-refill the bucket.
+ -- Matches the non-regression guard in the Node.js token-bucket scripts.
+ local ts_to_write = now
+ if cur[1] ~= false and now < tonumber(cur[1]) then
+ ts_to_write = tonumber(cur[1])
+ end
+
+ redis.call('hset', key, 'ts', ts_to_write, 'pool', tokens - admit)
+
+ -- EXPIRE dispatch dominated this primitive's Redis CPU in prod, so refresh the TTL
+ -- only on creation or once the remaining TTL drops below ttl/2, and write a 2x
+ -- ceiling for headroom (mirrors the Node.js v3 token-bucket script). PTTL's -1 (no
+ -- TTL) and -2 (missing key) are both below the threshold, so a lost TTL re-arms.
+ if cur[1] == false or redis.call('pttl', key) < (ttl * 500) then
+ redis.call('expire', key, ttl * 2)
+ end
+ return admit
+end
+
+local now = tonumber(ARGV[1])
+local n = tonumber(ARGV[2])
+
+local issue_admitted = take(KEYS[1], n, tonumber(ARGV[3]), tonumber(ARGV[4]), tonumber(ARGV[5]), now)
+local team_admitted = take(KEYS[2], issue_admitted, tonumber(ARGV[6]), tonumber(ARGV[7]), tonumber(ARGV[8]), now)
+
+return { issue_admitted, team_admitted }
+"#;
+
+/// The single Redis operation the limiter needs: run the Lua script and decode
+/// its integer-array reply. Behind a trait so the rate-limiting stage can be
+/// unit-tested with an in-memory fake — including a failing one, to prove the
+/// stage fails open. Production uses the real `RedisClient`.
+#[async_trait]
+pub trait ScriptRunner: Send + Sync {
+ async fn eval_int_vec(
+ &self,
+ script: &str,
+ keys: Vec<String>,
+ args: Vec<String>,
+ ) -> Result<Vec<i64>, CustomRedisError>;
+}
+
+#[async_trait]
+impl ScriptRunner for RedisClient {
+ async fn eval_int_vec(
+ &self,
+ script: &str,
+ keys: Vec<String>,
+ args: Vec<String>,
+ ) -> Result<Vec<i64>, CustomRedisError> {
+ RedisClient::eval_int_vec(self, script, keys, args).await
+ }
+}
+
+pub struct RedisRateLimiter {
+ redis: Arc<dyn ScriptRunner>,
+ key_prefix: String,
+ bucket_ttl_seconds: u64,
+}
+
+impl RedisRateLimiter {
+ pub fn new(redis: Arc<dyn ScriptRunner>, key_prefix: String, bucket_ttl_seconds: u64) -> Self {
+ Self {
+ redis,
+ key_prefix,
+ bucket_ttl_seconds,
+ }
+ }
+
+ fn issue_key(&self, team_id: i32, issue_id: Option<Uuid>) -> String {
+ match issue_id {
+ Some(id) => format!("{}/{{{team_id}}}/issue/{id}", self.key_prefix),
+ None => format!("{}/{{{team_id}}}/issue/none", self.key_prefix),
+ }
+ }
+
+ fn team_key(&self, team_id: i32) -> String {
+ format!("{}/{{{team_id}}}/project", self.key_prefix)
+ }
+}
+
+impl RedisRateLimiter {
+ /// Charge `n` events for a team's (optional) issue against the configured
+ /// per-issue and project limits, and report how many each limit admitted.
+ pub async fn admit(
+ &self,
+ team_id: i32,
+ issue_id: Option<Uuid>,
+ per_issue: Option<BucketParams>,
+ project: Option<BucketParams>,
+ n: u32,
+ ) -> Result<RateLimitDecision, CustomRedisError> {
+ // Negative max disables a limit inside the script.
+ let (issue_max, issue_rate) = per_issue.map_or((-1.0, 0.0), |t| (t.max, t.rate));
+ let (team_max, team_rate) = project.map_or((-1.0, 0.0), |t| (t.max, t.rate));
+ let now = Utc::now().timestamp();
+
+ let keys = vec![self.issue_key(team_id, issue_id), self.team_key(team_id)];
+ let args = vec![
+ now.to_string(),
+ n.to_string(),
+ issue_max.to_string(),
+ issue_rate.to_string(),
+ self.bucket_ttl_seconds.to_string(),
+ team_max.to_string(),
+ team_rate.to_string(),
+ self.bucket_ttl_seconds.to_string(),
+ ];
+
+ let res = self.redis.eval_int_vec(RATE_LIMIT_LUA, keys, args).await?;
+
+ // Defensive clamps: team_admitted <= issue_admitted <= n.
+ let issue_admitted = (res.first().copied().unwrap_or(0).max(0) as u32).min(n);
+ let team_admitted = (res.get(1).copied().unwrap_or(0).max(0) as u32).min(issue_admitted);
+ Ok(RateLimitDecision {
+ issue_admitted,
+ team_admitted,
+ })
+ }
+}
+
+/// Rate-limiter tests against a real `redis:7-alpine` (via testcontainers), in
+/// two layers:
+///
+/// - [`script`] — semi-unit tests that call `RATE_LIMIT_LUA` directly with an
+/// explicit clock, pinning down the token-bucket primitive: capacity, refill,
+/// the `floor` on partial tokens, disabling, and the per-issue→project order.
+/// - [`scenarios`] — real-world stories told through a small DSL on top of the
+/// public `admit` API, built up from a single limit to multiple teams.
+///
+/// Ignored by default (need Docker, slower). Run with:
+/// ```sh
+/// cargo test -p cymbal limiter::tests -- --ignored --test-threads=1
+/// ```
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use common_redis::{CompressionConfig, RedisValueFormat};
+ use std::time::Duration;
+ use testcontainers::core::{IntoContainerPort, WaitFor};
+ use testcontainers::runners::AsyncRunner;
+ use testcontainers::{ContainerAsync, GenericImage};
+
+ /// Boot a throwaway Redis and return a connected client. The readiness banner
+ /// can land a hair before the socket accepts, so we probe with a trivial
+ /// script until it answers — otherwise the first command occasionally races
+ /// the container and flakes with "connection refused".
+ async fn start_redis() -> (Arc<RedisClient>, ContainerAsync<GenericImage>) {
+ let container = GenericImage::new("redis", "7-alpine")
+ .with_exposed_port(6379.tcp())
+ .with_wait_for(WaitFor::message_on_stdout("Ready to accept connections"))
+ .start()
+ .await
+ .unwrap();
+ let host = container.get_host().await.unwrap();
+ let port = container.get_host_port_ipv4(6379).await.unwrap();
+ let url = format!("redis://{host}:{port}");
+
+ for _ in 0..20 {
+ if let Ok(client) = RedisClient::with_config(
+ url.clone(),
+ CompressionConfig::disabled(),
+ RedisValueFormat::Utf8,
+ None,
+ None,
+ )
+ .await
+ {
+ if client
+ .eval_int_vec("return {1, 1}", vec![], vec![])
+ .await
+ .is_ok()
+ {
+ return (Arc::new(client), container);
+ }
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ panic!("redis container never became ready");
+ }
+
+ // ===================================================================
+ // Layer 1 — semi-unit tests: the token-bucket script, called directly.
+ // ===================================================================
+ mod script {
+ use super::*;
+
+ /// One token bucket's script inputs. `max < 0` disables the limit.
+ #[derive(Clone, Copy)]
+ struct Bucket {
+ max: f64,
+ rate: f64,
+ }
+
+ /// A bucket big enough to never be the binding limit in a test.
+ fn unlimited() -> Bucket {
+ Bucket {
+ max: 1e9,
+ rate: 0.0,
+ }
+ }
+
+ /// A disabled limit — admits everything offered to it.
+ fn disabled() -> Bucket {
+ Bucket {
+ max: -1.0,
+ rate: 0.0,
+ }
+ }
+
+ /// Inputs for one direct evaluation of `RATE_LIMIT_LUA`. Named fields so
+ /// every number at the call site says what it is. It's `Copy`, so a test
+ /// can set up a base and tweak one field: `Charge { now: 1003, ..base }`.
+ #[derive(Clone, Copy)]
+ struct Charge {
+ team_id: i32,
+ issue: &'static str,
+ now: i64,
+ n: u32,
+ per_issue: Bucket,
+ project: Bucket,
+ }
+
+ /// Evaluate the fused script directly with an explicit clock (so refill is
+ /// deterministic — the public `admit` uses wall-clock time). Returns
+ /// `(issue_admitted, team_admitted)`.
+ async fn charge(client: &RedisClient, c: Charge) -> (i64, i64) {
+ let keys = vec![
+ format!("test/{{{}}}/issue/{}", c.team_id, c.issue),
+ format!("test/{{{}}}/project", c.team_id),
+ ];
+ let args = vec![
+ c.now.to_string(),
+ c.n.to_string(),
+ c.per_issue.max.to_string(),
+ c.per_issue.rate.to_string(),
+ "3600".to_string(),
+ c.project.max.to_string(),
+ c.project.rate.to_string(),
+ "3600".to_string(),
+ ];
+ let res = client
+ .eval_int_vec(RATE_LIMIT_LUA, keys, args)
+ .await
+ .unwrap();
+ (res[0], res[1])
+ }
+
+ #[tokio::test]
+ #[ignore]
+ async fn fresh_bucket_admits_up_to_capacity() {
+ let (client, _c) = start_redis().await;
+ // 10 offered into a fresh per-issue bucket of capacity 5 (project
+ // unlimited). A fresh bucket starts full, so exactly 5 pass.
+ let admitted = charge(
+ &client,
+ Charge {
+ team_id: 1,
+ issue: "a",
+ now: 1000,
+ n: 10,
+ per_issue: Bucket {
+ max: 5.0,
+ rate: 0.0,
+ },
+ project: unlimited(),
+ },
+ )
+ .await;
+ assert_eq!(admitted.0, 5);
+ }
+
+ #[tokio::test]
+ #[ignore]
+ async fn depletes_then_refills_proportional_to_elapsed_time() {
+ let (client, _c) = start_redis().await;
+ // Capacity 5, refilling 1 token/sec. Only `now` changes between calls.
+ let base = Charge {
+ team_id: 2,
+ issue: "a",
+ now: 1000,
+ n: 10,
+ per_issue: Bucket {
+ max: 5.0,
+ rate: 1.0,
+ },
+ project: unlimited(),
+ };
+ assert_eq!(charge(&client, base).await.0, 5); // drains the bucket
+ assert_eq!(charge(&client, base).await.0, 0); // same second: empty
+ assert_eq!(charge(&client, Charge { now: 1003, ..base }).await.0, 3);
+ // +3s -> +3 tokens
+ }
+
+ #[tokio::test]
+ #[ignore]
+ async fn refill_is_capped_at_capacity() {
+ let (client, _c) = start_redis().await;
+ // Capacity 5, refill 1/sec. Drain, then jump far ahead: unclamped that
+ // would be millions of tokens, but the bucket clamps to `max`.
+ let base = Charge {
+ team_id: 3,
+ issue: "a",
+ now: 1000,
+ n: 10,
+ per_issue: Bucket {
+ max: 5.0,
+ rate: 1.0,
+ },
+ project: unlimited(),
+ };
+ assert_eq!(charge(&client, base).await.0, 5);
+ assert_eq!(
+ charge(
+ &client,
+ Charge {
+ now: 1_001_000_000,
+ ..base
+ }
+ )
+ .await
+ .0,
+ 5
+ );
+ }
+
+ #[tokio::test]
+ #[ignore]
+ async fn creates_bucket_with_double_ttl_ceiling() {
+ let (client, _c) = start_redis().await;
+ // `charge` passes ttl = 3600; a freshly created bucket must get the 2x
+ // ceiling (7200s), proving the conditional EXPIRE armed the key. A key
+ // with no TTL (-1) would be a Redis memory leak.
+ let base = Charge {
+ team_id: 30,
+ issue: "a",
+ now: 1000,
+ n: 1,
+ per_issue: Bucket {
+ max: 5.0,
+ rate: 0.0,
+ },
+ project: unlimited(),
+ };
+ charge(&client, base).await;
+
+ let key = format!("test/{{{}}}/issue/{}", base.team_id, base.issue);
+ let pttl_ms = client
+ .eval_int_vec("return {redis.call('pttl', KEYS[1])}", vec![key], vec![])
+ .await
+ .unwrap()[0];
+ // Between 1x and 2x ttl (ms): the 2x ceiling, not the old unconditional 1x.
+ assert!(
+ pttl_ms > 3_600_000 && pttl_ms <= 7_200_000,
+ "expected a ~7200s TTL, got {pttl_ms}ms"
+ );
+ }
+
+ #[tokio::test]
+ #[ignore]
+ async fn partial_tokens_carry_over_but_admit_floors() {
+ let (client, _c) = start_redis().await;
+ // Capacity 10, refilling 0.5 tokens/sec.
+ let base = Charge {
+ team_id: 4,
+ issue: "a",
+ now: 1000,
+ n: 10,
+ per_issue: Bucket {
+ max: 10.0,
+ rate: 0.5,
+ },
+ project: unlimited(),
+ };
+ assert_eq!(charge(&client, base).await.0, 10); // drain at t=1000
+ // +1s -> 0.5 tokens -> floor -> admit 0, but the 0.5 stays in the pool.
+ assert_eq!(charge(&client, Charge { now: 1001, ..base }).await.0, 0);
+ // +1s more -> 0.5 carried + 0.5 fresh = 1.0 -> admit 1.
+ assert_eq!(charge(&client, Charge { now: 1002, ..base }).await.0, 1);
+ }
+
+ #[tokio::test]
+ #[ignore]
+ async fn negative_max_disables_the_limit() {
+ let (client, _c) = start_redis().await;
+ // Per-issue disabled admits everything; the project cap of 4 still
+ // applies to the full batch.
+ let admitted = charge(
+ &client,
+ Charge {
+ team_id: 5,
+ issue: "a",
+ now: 1000,
+ n: 10,
+ per_issue: disabled(),
+ project: Bucket {
+ max: 4.0,
+ rate: 0.0,
+ },
+ },
+ )
+ .await;
+ assert_eq!(admitted, (10, 4));
+ }
+
+ #[tokio::test]
+ #[ignore]
+ async fn charges_issue_bucket_before_project_bucket() {
+ let (client, _c) = start_redis().await;
+ // Per-issue cap 5, project cap 3. The issue bucket trims 10 -> 5, then
+ // the project bucket sees only those 5 and admits 3: team <= issue <= n.
+ let base = Charge {
+ team_id: 6,
+ issue: "a",
+ now: 1000,
+ n: 10,
+ per_issue: Bucket {
+ max: 5.0,
+ rate: 0.0,
+ },
+ project: Bucket {
+ max: 3.0,
+ rate: 0.0,
+ },
+ };
+ assert_eq!(charge(&client, base).await, (5, 3));
+ // A different issue on the same team draws on the *shared* project
+ // bucket, which is already drained — so nothing survives.
+ assert_eq!(charge(&client, Charge { issue: "b", ..base }).await, (5, 0));
+ }
+ }
+
+ // ===================================================================
+ // Layer 2 — real-world scenarios, told through a small readable DSL.
+ //
+ // Limits here are fixed budgets with refill disabled, so each story is
+ // about how a budget is *shared* (across issues, across teams), not about
+ // timing. Read these top to bottom.
+ // ===================================================================
+ mod scenarios {
+ use super::*;
+ use std::sync::atomic::{AtomicI32, Ordering};
+
+ /// One Redis-backed limiter plus a fresh team-id allocator. Hand out teams
+ /// with `harness.team()`, configure their limits, then send events.
+ struct TestHarness {
+ limiter: Arc<RedisRateLimiter>,
+ next_team_id: AtomicI32,
+ _container: ContainerAsync<GenericImage>,
+ }
+
+ impl TestHarness {
+ async fn new() -> Self {
+ let (client, container) = start_redis().await;
+ Self {
+ limiter: Arc::new(RedisRateLimiter::new(client, "et-scenario".into(), 3600)),
+ next_team_id: AtomicI32::new(1),
+ _container: container,
+ }
+ }
+
+ /// A new team with no limits configured yet.
+ fn team(&self) -> Team {
+ Team {
+ limiter: self.limiter.clone(),
+ team_id: self.next_team_id.fetch_add(1, Ordering::Relaxed),
+ per_issue: None,
+ project: None,
+ }
+ }
+ }
+
+ /// A team with its configured limits. `send` returns how many events the
+ /// limiter accepted, so a test reads like "send 10, expect 3 accepted".
+ struct Team {
+ limiter: Arc<RedisRateLimiter>,
+ team_id: i32,
+ per_issue: Option<BucketParams>,
+ project: Option<BucketParams>,
+ }
+
+ impl Team {
+ /// Cap the *whole team* to `capacity` events (shared across all issues).
+ fn with_project_limit(mut self, capacity: u32) -> Self {
+ self.project = Some(budget(capacity));
+ self
+ }
+
+ /// Cap *each issue* to `capacity` events independently.
+ fn with_issue_limit(mut self, capacity: u32) -> Self {
+ self.per_issue = Some(budget(capacity));
+ self
+ }
+
+ /// Send `n` events for `issue`; returns how many were accepted (passed
+ /// both the per-issue and project limits).
+ async fn send(&self, issue: Issue, n: u32) -> u32 {
+ self.limiter
+ .admit(self.team_id, Some(issue.0), self.per_issue, self.project, n)
+ .await
+ .unwrap()
+ .team_admitted
+ }
+ }
+
+ /// A fixed budget of `capacity` events with refill disabled.
+ fn budget(capacity: u32) -> BucketParams {
+ BucketParams {
+ max: capacity as f64,
+ rate: 0.0,
+ }
+ }
+
+ /// A distinct issue. Bind it to a name (`let issue_a = Issue::new();`) so
+ /// scenarios read naturally.
+ #[derive(Clone, Copy)]
+ struct Issue(Uuid);
+
+ impl Issue {
+ fn new() -> Self {
+ Self(Uuid::now_v7())
+ }
+ }
+
+ #[tokio::test]
+ #[ignore]
+ async fn a_project_limit_caps_total_volume_across_all_issues() {
+ let harness = TestHarness::new().await;
+ // The team allows 5 events total, regardless of which issue they hit.
+ let team = harness.team().with_project_limit(5);
+ let (issue_a, issue_b) = (Issue::new(), Issue::new());
+
+ // The shared budget is spent in arrival order, across any issue...
+ assert_eq!(team.send(issue_a, 3).await, 3);
+ assert_eq!(team.send(issue_b, 2).await, 2);
+ // ...and once it's gone, everything else is dropped.
+ assert_eq!(team.send(issue_a, 5).await, 0);
+ assert_eq!(team.send(issue_b, 5).await, 0);
+ }
+
+ #[tokio::test]
+ #[ignore]
+ async fn an_issue_limit_applies_separately_to_each_issue() {
+ let harness = TestHarness::new().await;
+ // Each issue gets 3 events; there is no team-wide cap.
+ let team = harness.team().with_issue_limit(3);
+ let (issue_a, issue_b) = (Issue::new(), Issue::new());
+
+ // Every issue has its own budget...
+ assert_eq!(team.send(issue_a, 10).await, 3);
+ assert_eq!(team.send(issue_b, 10).await, 3);
+ // ...and a noisy issue can't borrow from another's.
+ assert_eq!(team.send(issue_a, 10).await, 0);
+ }
+
+ #[tokio::test]
+ #[ignore]
+ async fn mixed_limits_charge_per_issue_first_then_the_project_budget() {
+ let harness = TestHarness::new().await;
+ // Each issue is capped at 3, and the team as a whole at 5.
+ let team = harness.team().with_issue_limit(3).with_project_limit(5);
+ let (issue_a, issue_b, issue_c) = (Issue::new(), Issue::new(), Issue::new());
+
+ // Issue A is trimmed to 3 by its own limit (the team still has room).
+ assert_eq!(team.send(issue_a, 10).await, 3);
+ // Issue B's own limit allows 3, but only 2 of the team budget remain.
+ assert_eq!(team.send(issue_b, 10).await, 2);
+ // Team budget exhausted: a brand-new issue gets nothing, even though its
+ // own per-issue budget is untouched.
+ assert_eq!(team.send(issue_c, 10).await, 0);
+ }
+
+ #[tokio::test]
+ #[ignore]
+ async fn each_team_has_its_own_independent_budget() {
+ let harness = TestHarness::new().await;
+ // Two teams, each capped at 4 events.
+ let team_one = harness.team().with_project_limit(4);
+ let team_two = harness.team().with_project_limit(4);
+ let issue = Issue::new();
+
+ // Team one spends its whole budget...
+ assert_eq!(team_one.send(issue, 10).await, 4);
+ assert_eq!(team_one.send(issue, 10).await, 0);
+ // ...which leaves team two completely untouched.
+ assert_eq!(team_two.send(issue, 10).await, 4);
+ }
+
+ #[tokio::test]
+ #[ignore]
+ async fn a_busy_issue_cannot_starve_the_rest_of_the_team_or_other_teams() {
+ let harness = TestHarness::new().await;
+ // A larger team: 5 per issue, 8 across the whole project.
+ let big = harness.team().with_issue_limit(5).with_project_limit(8);
+ let (a, b, c) = (Issue::new(), Issue::new(), Issue::new());
+
+ // Two issues fill the team budget (5 + 3 = 8); the project cap is the
+ // real ceiling, so the third issue is shut out despite its free
+ // per-issue budget.
+ assert_eq!(big.send(a, 5).await, 5);
+ assert_eq!(big.send(b, 5).await, 3);
+ assert_eq!(big.send(c, 5).await, 0);
+
+ // A second, smaller team (2 per issue, 3 project) is wholly unaffected
+ // by the big team draining its own buckets.
+ let small = harness.team().with_issue_limit(2).with_project_limit(3);
+ assert_eq!(small.send(a, 10).await, 2);
+ assert_eq!(small.send(b, 10).await, 1);
+ }
+ }
+}
diff --git a/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs b/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs
new file mode 100644
index 000000000000..9bf19897b133
--- /dev/null
+++ b/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs
@@ -0,0 +1,625 @@
+mod limiter;
+
+use std::collections::{HashMap, HashSet};
+use std::sync::Arc;
+
+use chrono::Utc;
+use common_kafka::kafka_messages::app_metrics2::{AppMetric2, Kind, Source};
+use common_kafka::kafka_producer::send_iter_to_kafka;
+use common_kafka::APP_METRICS2_TOPIC;
+use metrics::counter;
+use tracing::warn;
+use uuid::Uuid;
+
+use crate::{
+ app_context::AppContext,
+ error::EventError,
+ metric_consts::{RATE_LIMITING_STAGE, RATE_LIMIT_FAIL_OPEN, RATE_LIMIT_OUTCOMES},
+ stages::pipeline::ExceptionEventPipelineItem,
+ types::{
+ batch::Batch,
+ stage::{Stage, StageResult},
+ },
+};
+
+use crate::modes::processing::rules::rate_limit::RateLimitSettings;
+
+pub use limiter::{RateLimitDecision, RedisRateLimiter, ScriptRunner, RATE_LIMIT_LUA};
+
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+enum LimitKind {
+ PerIssue,
+ Project,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+enum Outcome {
+ Allowed,
+ RateLimited,
+}
+
+impl LimitKind {
+ fn label(self) -> &'static str {
+ match self {
+ LimitKind::PerIssue => "per_issue",
+ LimitKind::Project => "project",
+ }
+ }
+}
+
+impl Outcome {
+ fn label(self) -> &'static str {
+ match self {
+ Outcome::Allowed => "allowed",
+ Outcome::RateLimited => "rate_limited",
+ }
+ }
+}
+
+/// Tally key for one `app_metrics2` row. Per-issue rows carry their issue id so
+/// each issue gets its own `app_source_id` (matching the Node.js limiter, which
+/// keys per-issue metrics by the bare Cymbal issue id); project rows use `None`
+/// and aggregate per team under `{team}:exceptions:global`.
+type OutcomeKey = (i32, LimitKind, Option<Uuid>, Outcome);
+
+/// Drops rate-limited exception events as soon as their `issue_id` is known
+/// (right after `LinkingStage`, before `AlertingStage`). Marked-dropped events
+/// become `Err`, so spike detection skips them and post-processing turns them
+/// into `null`. A no-op when the limiter is disabled.
+#[derive(Clone)]
+pub struct RateLimitingStage {
+ ctx: Arc<AppContext>,
+}
+
+impl From<&Arc<AppContext>> for RateLimitingStage {
+ fn from(ctx: &Arc<AppContext>) -> Self {
+ Self { ctx: ctx.clone() }
+ }
+}
+
+impl Stage for RateLimitingStage {
+ type Input = ExceptionEventPipelineItem;
+ type Output = ExceptionEventPipelineItem;
+
+ fn name(&self) -> &'static str {
+ RATE_LIMITING_STAGE
+ }
+
+ async fn process(self, batch: Batch<Self::Input>) -> StageResult<Self> {
+ let Some(limiter) = self.ctx.rate_limiter.clone() else {
+ return Ok(batch); // limiter disabled — pass everything through
+ };
+
+ let mut items: Vec<ExceptionEventPipelineItem> = batch.into();
+
+ // Teams of the surviving (Ok) events. Suppressed / failed events are
+ // already Err and are never charged.
+ let team_ids: HashSet<i32> = items
+ .iter()
+ .filter_map(|item| item.as_ref().ok().map(|props| props.team_id))
+ .collect();
+ if team_ids.is_empty() {
+ return Ok(Batch::from(items));
+ }
+
+ let settings = self
+ .ctx
+ .team_manager
+ .get_rate_limit_settings(&self.ctx.posthog_pool, team_ids)
+ .await;
+
+ let outcomes = apply_rate_limits(
+ &limiter,
+ &settings,
+ self.ctx.rate_limiter_enabled_team_ids.as_ref(),
+ &mut items,
+ )
+ .await;
+
+ self.emit_metrics(&outcomes).await;
+
+ Ok(Batch::from(items))
+ }
+}
+
+/// Core of `RateLimitingStage::process`, split out so it can be unit-tested with
+/// an in-memory `ScriptRunner` (the stage itself needs a full `AppContext`).
+///
+/// Groups the surviving (`Ok`) events by (team_id, issue_id), charges each group
+/// against the team's configured limits, and flips over-limit events to `Err` in
+/// place — length and input order are preserved, so post-processing still
+/// reattaches original events by index. Returns per-(team, limit, outcome)
+/// tallies for metrics. Fails open per group: a limiter error keeps that group's
+/// events and records a fail-open metric.
+async fn apply_rate_limits(
+ limiter: &RedisRateLimiter,
+ settings: &HashMap<i32, RateLimitSettings>,
+ enabled_teams: Option<&HashSet<i32>>,
+ items: &mut [ExceptionEventPipelineItem],
+) -> HashMap<OutcomeKey, u32> {
+ // Group surviving (Ok) events by (team_id, issue_id). Vec<usize> stays in input order.
+ let mut groups: HashMap<(i32, Option<Uuid>), Vec<usize>> = HashMap::new();
+ for (idx, item) in items.iter().enumerate() {
+ if let Ok(props) = item {
+ groups
+ .entry((props.team_id, props.issue_id))
+ .or_default()
+ .push(idx);
+ }
+ }
+
+ let mut outcomes: HashMap<OutcomeKey, u32> = HashMap::new();
+ let mut drops: Vec<(usize, EventError)> = Vec::new();
+
+ // Group iteration order is nondeterministic (HashMap), and that's fine: per-issue
+ // buckets are independent, and the shared project bucket admits the same *total*
+ // whichever issue draws first — so every emitted metric is order-independent. Order
+ // only shuffles which issue wins the project budget when it's the binding limit, and
+ // those events are dropped either way. Within a group, input order is preserved
+ // (indices pushed in order above; classify_group keeps the lowest first).
+ for ((team_id, issue_id), indices) in groups {
+ // Team allowlist: when set, only listed teams are rate-limited.
+ if enabled_teams.is_some_and(|allowed| !allowed.contains(&team_id)) {
+ continue;
+ }
+
+ let Some(team_settings) = settings.get(&team_id) else {
+ continue; // no row → team hasn't opted in
+ };
+
+ // Per-issue limit only applies when we actually have an issue to key on.
+ let per_issue = issue_id.and(team_settings.per_issue());
+ let project = team_settings.project();
+ if per_issue.is_none() && project.is_none() {
+ continue;
+ }
+
+ let n = indices.len() as u32;
+ let decision = match limiter
+ .admit(team_id, issue_id, per_issue, project, n)
+ .await
+ {
+ Ok(decision) => decision,
+ Err(e) => {
+ // Fail open: keep everything, but record it so we can alert on it.
+ warn!("error-tracking rate limiter failed open for team {team_id}: {e}");
+ counter!(RATE_LIMIT_FAIL_OPEN).increment(n as u64);
+ continue;
+ }
+ };
+
+ let group = classify_group(
+ team_id,
+ issue_id,
+ &indices,
+ decision,
+ per_issue.is_some(),
+ project.is_some(),
+ );
+ drops.extend(group.drops);
+ if let Some((allowed, limited)) = group.per_issue {
+ add_outcome(
+ &mut outcomes,
+ team_id,
+ LimitKind::PerIssue,
+ issue_id,
+ allowed,
+ limited,
+ );
+ }
+ if let Some((allowed, limited)) = group.project {
+ // Project rows aggregate across issues, so they carry no issue id.
+ add_outcome(
+ &mut outcomes,
+ team_id,
+ LimitKind::Project,
+ None,
+ allowed,
+ limited,
+ );
+ }
+ }
+
+ // Flip dropped slots Ok -> Err in place; length and order are preserved
+ // (post-processing reattaches original events by index).
+ for (idx, err) in drops {
+ if let Some(slot) = items.get_mut(idx) {
+ *slot = Err(err);
+ }
+ }
+
+ outcomes
+}
+
+impl RateLimitingStage {
+ async fn emit_metrics(&self, outcomes: &HashMap<OutcomeKey, u32>) {
+ if outcomes.is_empty() {
+ return;
+ }
+ let now = Utc::now();
+ let mut app_metrics: Vec<AppMetric2> = Vec::with_capacity(outcomes.len());
+
+ for (&(team_id, kind, issue_id, outcome), &count) in outcomes {
+ counter!(
+ RATE_LIMIT_OUTCOMES,
+ "limit" => kind.label(),
+ "outcome" => outcome.label(),
+ )
+ .increment(count as u64);
+
+ // Match the Node.js limiter's `app_metrics2` keys exactly: per-issue
+ // rows are keyed by the bare Cymbal issue id; project rows by
+ // `{team}:exceptions:global`.
+ let app_source_id = match kind {
+ LimitKind::PerIssue => issue_id
+ .expect("per-issue outcomes always carry an issue id")
+ .to_string(),
+ LimitKind::Project => format!("{team_id}:exceptions:global"),
+ };
+
+ app_metrics.push(AppMetric2 {
+ team_id: team_id as u32,
+ timestamp: now,
+ app_source: Source::Exceptions,
+ app_source_id,
+ instance_id: None,
+ metric_kind: Kind::RateLimiting,
+ metric_name: outcome.label().to_string(),
+ count,
+ });
+ }
+
+ let results = send_iter_to_kafka(
+ &self.ctx.immediate_producer,
+ APP_METRICS2_TOPIC,
+ app_metrics,
+ )
+ .await;
+ for result in results {
+ if let Err(e) = result {
+ warn!("failed to emit error-tracking rate-limit app_metric: {e}");
+ }
+ }
+ }
+}
+
+struct GroupOutcome {
+ drops: Vec<(usize, EventError)>,
+ /// `(allowed, rate_limited)` for the per-issue limit, when enabled.
+ per_issue: Option<(u32, u32)>,
+ /// `(allowed, rate_limited)` for the project limit, when enabled. Only the
+ /// per-issue survivors are offered to it.
+ project: Option<(u32, u32)>,
+}
+
+/// Pure fan-out: given a limit decision, assign each of the `n` events (in input
+/// order) to keep / project-drop / per-issue-drop, and tally per-limit outcomes.
+///
+/// Order within the group:
+/// `[0, team_admitted)` kept
+/// `[team_admitted, issue_admitted)` dropped by the project limit
+/// `[issue_admitted, n)` dropped by the per-issue limit
+fn classify_group(
+ team_id: i32,
+ issue_id: Option<Uuid>,
+ indices: &[usize],
+ decision: RateLimitDecision,
+ per_issue_enabled: bool,
+ project_enabled: bool,
+) -> GroupOutcome {
+ let n = indices.len() as u32;
+ let issue_admitted = decision.issue_admitted as usize;
+ let team_admitted = decision.team_admitted as usize;
+
+ let mut drops = Vec::new();
+ for (pos, &idx) in indices.iter().enumerate() {
+ if pos >= issue_admitted {
+ drops.push((
+ idx,
+ EventError::RateLimitedPerIssue(issue_id.unwrap_or_default()),
+ ));
+ } else if pos >= team_admitted {
+ drops.push((idx, EventError::RateLimitedProject(team_id)));
+ }
+ }
+
+ let per_issue =
+ per_issue_enabled.then(|| (decision.issue_admitted, n - decision.issue_admitted));
+ let project = project_enabled.then(|| {
+ (
+ decision.team_admitted,
+ decision.issue_admitted - decision.team_admitted,
+ )
+ });
+
+ GroupOutcome {
+ drops,
+ per_issue,
+ project,
+ }
+}
+
+fn add_outcome(
+ outcomes: &mut HashMap<OutcomeKey, u32>,
+ team_id: i32,
+ kind: LimitKind,
+ issue_id: Option<Uuid>,
+ allowed: u32,
+ limited: u32,
+) {
+ if allowed > 0 {
+ *outcomes
+ .entry((team_id, kind, issue_id, Outcome::Allowed))
+ .or_insert(0) += allowed;
+ }
+ if limited > 0 {
+ *outcomes
+ .entry((team_id, kind, issue_id, Outcome::RateLimited))
+ .or_insert(0) += limited;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::modes::processing::types::exception_properties::ExceptionProperties;
+ use crate::modes::processing::types::ExceptionList;
+ use async_trait::async_trait;
+ use common_redis::CustomRedisError;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ /// A `ScriptRunner` that never touches Redis: returns a canned reply, or an
+ /// error to drive the stage's fail-open path, and counts its invocations.
+ struct FakeScriptRunner {
+ result: Result<Vec<i64>, ()>,
+ calls: AtomicUsize,
+ }
+
+ impl FakeScriptRunner {
+ fn returning(reply: Vec<i64>) -> Self {
+ Self {
+ result: Ok(reply),
+ calls: AtomicUsize::new(0),
+ }
+ }
+
+ fn failing() -> Self {
+ Self {
+ result: Err(()),
+ calls: AtomicUsize::new(0),
+ }
+ }
+
+ fn call_count(&self) -> usize {
+ self.calls.load(Ordering::Relaxed)
+ }
+ }
+
+ #[async_trait]
+ impl ScriptRunner for FakeScriptRunner {
+ async fn eval_int_vec(
+ &self,
+ _script: &str,
+ _keys: Vec<String>,
+ _args: Vec<String>,
+ ) -> Result<Vec<i64>, CustomRedisError> {
+ self.calls.fetch_add(1, Ordering::Relaxed);
+ match &self.result {
+ Ok(reply) => Ok(reply.clone()),
+ Err(()) => Err(CustomRedisError::Timeout),
+ }
+ }
+ }
+
+ fn limiter_with(runner: Arc<FakeScriptRunner>) -> RedisRateLimiter {
+ RedisRateLimiter::new(runner, "test".to_string(), 3600)
+ }
+
+ fn settings(per_issue: Option<i32>, project: Option<i32>) -> RateLimitSettings {
+ RateLimitSettings {
+ per_issue_value: per_issue,
+ per_issue_bucket_minutes: Some(60),
+ project_value: project,
+ project_bucket_minutes: Some(60),
+ }
+ }
+
+ fn event(team_id: i32, issue_id: Option<Uuid>) -> ExceptionEventPipelineItem {
+ Ok(ExceptionProperties {
+ exception_list: ExceptionList(vec![]),
+ exception_sources: None,
+ exception_types: None,
+ exception_messages: None,
+ exception_functions: None,
+ exception_handled: None,
+ exception_releases: HashMap::new(),
+ fingerprint: None,
+ proposed_fingerprint: None,
+ fingerprint_record: None,
+ issue_id,
+ proposed_issue_name: None,
+ proposed_issue_description: None,
+ debug_images: vec![],
+ props: HashMap::new(),
+ uuid: Uuid::now_v7(),
+ timestamp: String::new(),
+ team_id,
+ issue: None,
+ })
+ }
+
+ #[tokio::test]
+ async fn fails_open_keeping_all_events_when_redis_errors() {
+ let runner = Arc::new(FakeScriptRunner::failing());
+ let limiter = limiter_with(runner.clone());
+ let issue = Uuid::now_v7();
+ let mut items: Vec<ExceptionEventPipelineItem> =
+ (0..5).map(|_| event(1, Some(issue))).collect();
+ let mut cfg = HashMap::new();
+ cfg.insert(1, settings(Some(1), Some(1)));
+
+ let outcomes = apply_rate_limits(&limiter, &cfg, None, &mut items).await;
+
+ // Redis errored, so the whole group is kept (fail open): nothing is
+ // flipped to Err, and no allowed/limited outcomes are tallied.
+ assert!(items.iter().all(|item| item.is_ok()));
+ assert_eq!(runner.call_count(), 1); // one group -> one (failed) redis call
+ assert!(outcomes.is_empty());
+ }
+
+ #[tokio::test]
+ async fn drops_over_limit_events_in_classify_order() {
+ // One issue group of 5; per-issue admits 3, project admits 1 of those.
+ let runner = Arc::new(FakeScriptRunner::returning(vec![3, 1]));
+ let limiter = limiter_with(runner);
+ let issue = Uuid::now_v7();
+ let mut items: Vec<ExceptionEventPipelineItem> =
+ (0..5).map(|_| event(7, Some(issue))).collect();
+ let mut cfg = HashMap::new();
+ cfg.insert(7, settings(Some(100), Some(100)));
+
+ apply_rate_limits(&limiter, &cfg, None, &mut items).await;
+
+ assert!(items[0].is_ok()); // kept
+ assert!(matches!(items[1], Err(EventError::RateLimitedProject(7))));
+ assert!(matches!(items[2], Err(EventError::RateLimitedProject(7))));
+ assert!(matches!(items[3], Err(EventError::RateLimitedPerIssue(_))));
+ assert!(matches!(items[4], Err(EventError::RateLimitedPerIssue(_))));
+ }
+
+ #[tokio::test]
+ async fn per_issue_metrics_key_by_issue_global_aggregates_per_team() {
+ // Every group: per-issue admits 3 of 5, project admits 1 of those 3.
+ let runner = Arc::new(FakeScriptRunner::returning(vec![3, 1]));
+ let limiter = limiter_with(runner);
+ let (issue_a, issue_b) = (Uuid::now_v7(), Uuid::now_v7());
+ let mut items: Vec<ExceptionEventPipelineItem> = (0..5)
+ .map(|_| event(7, Some(issue_a)))
+ .chain((0..5).map(|_| event(7, Some(issue_b))))
+ .collect();
+ let mut cfg = HashMap::new();
+ cfg.insert(7, settings(Some(100), Some(100)));
+
+ let outcomes = apply_rate_limits(&limiter, &cfg, None, &mut items).await;
+
+ // Per-issue tallies are keyed by the individual issue id — one bucket per
+ // issue — so each gets its own bare-UUID `app_source_id` like Node.js.
+ assert_eq!(
+ outcomes.get(&(7, LimitKind::PerIssue, Some(issue_a), Outcome::Allowed)),
+ Some(&3)
+ );
+ assert_eq!(
+ outcomes.get(&(7, LimitKind::PerIssue, Some(issue_b), Outcome::Allowed)),
+ Some(&3)
+ );
+ // The project tally carries no issue id, so both issues fold into one
+ // per-team row (`{team}:exceptions:global`): allowed 1+1, limited 2+2.
+ assert_eq!(
+ outcomes.get(&(7, LimitKind::Project, None, Outcome::Allowed)),
+ Some(&2)
+ );
+ assert_eq!(
+ outcomes.get(&(7, LimitKind::Project, None, Outcome::RateLimited)),
+ Some(&4)
+ );
+ }
+
+ #[tokio::test]
+ async fn skips_team_without_settings_without_touching_redis() {
+ let runner = Arc::new(FakeScriptRunner::returning(vec![0, 0]));
+ let limiter = limiter_with(runner.clone());
+ let mut items: Vec<ExceptionEventPipelineItem> =
+ (0..3).map(|_| event(42, Some(Uuid::now_v7()))).collect();
+ let cfg = HashMap::new(); // team 42 has no settings row
+
+ let outcomes = apply_rate_limits(&limiter, &cfg, None, &mut items).await;
+
+ assert!(items.iter().all(|item| item.is_ok())); // opted-out team untouched
+ assert_eq!(runner.call_count(), 0); // and we never hit redis for it
+ assert!(outcomes.is_empty());
+ }
+
+ #[tokio::test]
+ async fn only_rate_limits_allowlisted_teams() {
+ // Redis admits nothing, so any team that IS rate-limited loses its events.
+ let runner = Arc::new(FakeScriptRunner::returning(vec![0, 0]));
+ let limiter = limiter_with(runner.clone());
+ let issue = Uuid::now_v7();
+ let mut items: Vec<ExceptionEventPipelineItem> =
+ vec![event(1, Some(issue)), event(2, Some(issue))];
+ let mut cfg = HashMap::new();
+ cfg.insert(1, settings(Some(1), Some(1)));
+ cfg.insert(2, settings(Some(1), Some(1)));
+ let allowed: HashSet<i32> = [1].into_iter().collect();
+
+ apply_rate_limits(&limiter, &cfg, Some(&allowed), &mut items).await;
+
+ assert!(items[0].is_err()); // team 1 is allowlisted -> rate-limited
+ assert!(items[1].is_ok()); // team 2 is not -> untouched despite having settings
+ assert_eq!(runner.call_count(), 1); // only the allowlisted team hit redis
+ }
+
+ fn decision(issue: u32, team: u32) -> RateLimitDecision {
+ RateLimitDecision {
+ issue_admitted: issue,
+ team_admitted: team,
+ }
+ }
+
+ #[test]
+ fn fan_out_splits_keep_project_drop_per_issue_drop_in_order() {
+ let issue = Uuid::now_v7();
+ let indices = vec![10, 11, 12, 13, 14]; // n = 5
+ // 3 passed per-issue, 1 of those passed project.
+ let out = classify_group(7, Some(issue), &indices, decision(3, 1), true, true);
+
+ // keep idx 10; project-drop 11,12; per-issue-drop 13,14.
+ let mut by_idx: HashMap<usize, EventError> = out.drops.into_iter().collect();
+ assert!(by_idx.remove(&10).is_none());
+ assert_eq!(by_idx.remove(&11), Some(EventError::RateLimitedProject(7)));
+ assert_eq!(by_idx.remove(&12), Some(EventError::RateLimitedProject(7)));
+ assert_eq!(
+ by_idx.remove(&13),
+ Some(EventError::RateLimitedPerIssue(issue))
+ );
+ assert_eq!(
+ by_idx.remove(&14),
+ Some(EventError::RateLimitedPerIssue(issue))
+ );
+ assert!(by_idx.is_empty());
+
+ assert_eq!(out.per_issue, Some((3, 2))); // 3 allowed, 2 limited
+ assert_eq!(out.project, Some((1, 2))); // of the 3 survivors: 1 allowed, 2 limited
+ }
+
+ #[test]
+ fn per_issue_disabled_only_reports_project_limit() {
+ let indices = vec![0, 1, 2, 3];
+ // issue limit disabled => admits all 4; project keeps 2.
+ let out = classify_group(9, None, &indices, decision(4, 2), false, true);
+ assert_eq!(out.per_issue, None);
+ assert_eq!(out.project, Some((2, 2)));
+ // 2 project drops, no per-issue drops (issue_admitted == n).
+ assert_eq!(out.drops.len(), 2);
+ assert!(out
+ .drops
+ .iter()
+ .all(|(_, e)| matches!(e, EventError::RateLimitedProject(9))));
+ }
+
+ #[test]
+ fn all_admitted_no_drops() {
+ let indices = vec![0, 1];
+ let out = classify_group(
+ 1,
+ Some(Uuid::now_v7()),
+ &indices,
+ decision(2, 2),
+ true,
+ true,
+ );
+ assert!(out.drops.is_empty());
+ assert_eq!(out.per_issue, Some((2, 0)));
+ assert_eq!(out.project, Some((2, 0)));
+ }
+}
diff --git a/rust/cymbal/src/modes/processing/teams.rs b/rust/cymbal/src/modes/processing/teams.rs
index a1d80bbbb79e..584e807640fe 100644
--- a/rust/cymbal/src/modes/processing/teams.rs
+++ b/rust/cymbal/src/modes/processing/teams.rs
@@ -9,6 +9,7 @@ use crate::{
modes::processing::config::ProcessingConfig,
modes::processing::rules::assignment::AssignmentRule,
modes::processing::rules::grouping::GroupingRule,
+ modes::processing::rules::rate_limit::RateLimitSettings,
modes::processing::rules::spike::SpikeDetectionConfig,
modes::processing::rules::suppression::SuppressionRule,
};
@@ -21,6 +22,7 @@ pub struct TeamManager {
pub suppression_rules: Cache<TeamId, Vec<SuppressionRule>>,
pub group_type_indices: Cache<TeamId, Vec<GroupType>>,
pub spike_detection_configs: Cache<TeamId, Option<SpikeDetectionConfig>>,
+ pub rate_limit_settings: Cache<TeamId, Option<RateLimitSettings>>,
}
impl TeamManager {
@@ -64,6 +66,10 @@ impl TeamManager {
.time_to_live(Duration::from_secs(config.team_cache_ttl_secs))
.build();
+ let rate_limit_settings = CacheBuilder::new(config.max_team_cache_size)
+ .time_to_live(Duration::from_secs(config.team_cache_ttl_secs))
+ .build();
+
Self {
token_cache: cache,
assignment_rules,
@@ -71,6 +77,7 @@ impl TeamManager {
suppression_rules,
group_type_indices,
spike_detection_configs,
+ rate_limit_settings,
}
}
@@ -214,6 +221,65 @@ impl TeamManager {
result
}
+ pub async fn get_rate_limit_setting<'c, E>(
+ &self,
+ e: E,
+ team_id: TeamId,
+ ) -> Result<Option<RateLimitSettings>, UnhandledError>
+ where
+ E: sqlx::Executor<'c, Database = sqlx::Postgres>,
+ {
+ if let Some(cached) = self.rate_limit_settings.get(&team_id) {
+ metrics::counter!(ANCILLARY_CACHE, "type" => "rate_limit_settings", "outcome" => "hit")
+ .increment(1);
+ return Ok(cached);
+ }
+ metrics::counter!(ANCILLARY_CACHE, "type" => "rate_limit_settings", "outcome" => "miss")
+ .increment(1);
+ // We cache the "no settings row" result too (None), so opt-out teams don't re-query.
+ let settings = RateLimitSettings::load_for_team(e, team_id).await?;
+ self.rate_limit_settings.insert(team_id, settings.clone());
+ Ok(settings)
+ }
+
+ /// Batch-load rate-limit settings for the teams in a request. Teams with no
+ /// settings row (opted out) or a load error are omitted from the map, so the
+ /// rate-limiting stage simply skips them.
+ pub async fn get_rate_limit_settings(
+ &self,
+ pool: &sqlx::PgPool,
+ team_ids: impl IntoIterator<Item = i32>,
+ ) -> HashMap<TeamId, RateLimitSettings> {
+ let unique_ids: std::collections::HashSet<i32> = team_ids.into_iter().collect();
+
+ let tasks: Vec<(i32, _)> = unique_ids
+ .into_iter()
+ .map(|team_id| {
+ let manager = self.clone();
+ let pool = pool.clone();
+ let task =
+ tokio::spawn(
+ async move { manager.get_rate_limit_setting(&pool, team_id).await },
+ );
+ (team_id, task)
+ })
+ .collect();
+
+ let mut result = HashMap::new();
+ for (team_id, task) in tasks {
+ match task.await.expect("Task was not cancelled") {
+ Ok(Some(settings)) => {
+ result.insert(team_id, settings);
+ }
+ Ok(None) => {}
+ Err(e) => {
+ warn!("Failed to load rate limit settings for team {team_id}: {e}");
+ }
+ }
+ }
+ result
+ }
+
pub async fn get_group_types<'c, E>(
&self,
e: E,