:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(error-tracking): reconnect cymbal redis clients after connection loss (#84941)
Cataline72499cecede
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 66aeb5aa9c18..53ed562bec3d 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -3380,6 +3380,7 @@ dependencies = ["proguard","rand 0.8.5","rdkafka",+ "redis","regex","reqwest 0.12.28","rustls 0.23.37",diff --git a/rust/common/redis/src/client.rs b/rust/common/redis/src/client.rsindex 6f7e4d5d74a5..75b283a52e69 100644--- a/rust/common/redis/src/client.rs+++ b/rust/common/redis/src/client.rs@@ -1179,7 +1179,7 @@ mod integration_tests {use crate::{ClientPipelineExt, PipelineResult};use testcontainers::core::{IntoContainerPort, WaitFor};use testcontainers::runners::AsyncRunner;- use testcontainers::GenericImage;+ use testcontainers::{GenericImage, ImageExt};async fn create_test_client() -> (RedisClient, testcontainers::ContainerAsync<GenericImage>) {let container = GenericImage::new("redis", "7-alpine")@@ -1206,6 +1206,106 @@ mod integration_tests {(client, container)}+ // Kill the Redis container and bring it back on the same port: a client+ // stays broken (MultiplexedConnection never reconnects) until heal() swaps+ // in a rebuilt connection.+ #[tokio::test]+ #[ignore] // Requires Docker; run with: cargo test integration_tests -- --ignored+ async fn test_heal_recovers_connection_after_redis_restart() {+ // A fixed host port: docker assigns a NEW random host port when a+ // killed container restarts, which would leave the client dialing a+ // dead port and turn this test into a false failure.+ let host_port = 30000 + (std::process::id() % 10000) as u16;+ let container = GenericImage::new("redis", "7-alpine")+ .with_wait_for(WaitFor::message_on_stdout("Ready to accept connections"))+ .with_mapped_port(host_port, 6379.tcp())+ .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}");++ let connect = || async {+ RedisClient::with_config(+ url.clone(),+ CompressionConfig::disabled(),+ RedisValueFormat::Utf8,+ Some(Duration::from_millis(1000)),+ Some(Duration::from_millis(2000)),+ )+ .await+ };++ // The readiness banner can land a hair before the socket accepts, so+ // probe with a real command until Redis answers.+ let mut healed_client = None;+ for _ in 0..20 {+ if let Ok(c) = connect().await {+ if c.set("probe".to_string(), "1".to_string()).await.is_ok() {+ healed_client = Some(c);+ break;+ }+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ let healed_client = healed_client.expect("redis container never became ready");+ let broken_client = connect().await.unwrap();+ broken_client+ .set("k".to_string(), "v".to_string())+ .await+ .unwrap();++ // Kill/start via the docker CLI: an abrupt kill matches the+ // node-replacement failure heal() exists for.+ let docker = |args: Vec<String>| {+ let status = std::process::Command::new("docker")+ .args(&args)+ .status()+ .unwrap();+ assert!(status.success(), "docker {args:?} failed");+ };+ docker(vec!["kill".to_string(), container.id().to_string()]);++ assert!(healed_client+ .set("k".to_string(), "v".to_string())+ .await+ .is_err());+ assert!(broken_client+ .set("k".to_string(), "v".to_string())+ .await+ .is_err());++ docker(vec!["start".to_string(), container.id().to_string()]);+ // Wait until the restarted Redis answers (checked via a fresh client)+ // so the single heal attempt below cannot race the restart and burn+ // its cooldown.+ let mut ready = false;+ for _ in 0..50 {+ if let Ok(c) = connect().await {+ if c.set("probe".to_string(), "1".to_string()).await.is_ok() {+ ready = true;+ break;+ }+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ assert!(ready, "redis container never came back");++ healed_client.heal().await;+ assert!(healed_client+ .set("k".to_string(), "v".to_string())+ .await+ .is_ok());++ // Without heal() the connection stays dead - the failure mode heal+ // exists to fix.+ assert!(broken_client+ .set("k".to_string(), "v".to_string())+ .await+ .is_err());+ }+#[tokio::test]#[ignore] // Requires Docker; run with: cargo test integration_tests -- --ignoredasync fn test_pipeline_set_and_get() {diff --git a/rust/cymbal/Cargo.toml b/rust/cymbal/Cargo.tomlindex 01e9f8e47093..98f3ecf29d9c 100644--- a/rust/cymbal/Cargo.toml+++ b/rust/cymbal/Cargo.toml@@ -60,6 +60,8 @@ common-temporal = { path = "../common/temporal" }[dev-dependencies]common-compression = { path = "../common/compression" }+# For constructing IO-flavored RedisErrors in redis_heal classifier tests+redis = { workspace = true }httpmock = { workspace = true }mockall = { workspace = true }insta = { version = "1.46.0", features = ["json", "redactions"] }diff --git a/rust/cymbal/src/modes/processing/app_context.rs b/rust/cymbal/src/modes/processing/app_context.rsindex 2caa87c82676..1175647f3dd9 100644--- a/rust/cymbal/src/modes/processing/app_context.rs+++ b/rust/cymbal/src/modes/processing/app_context.rs@@ -9,6 +9,7 @@ use tokio::{sync::Semaphore, task::JoinHandle};use tracing::info;use uuid::Uuid;+use crate::modes::processing::redis_heal::HealGate;use crate::{core::config::build_pg_pool,error::UnhandledError,@@ -43,6 +44,8 @@ pub struct AppContext {pub team_manager: TeamManager,pub issue_buckets_redis_client: Arc<dyn RedisClientTrait + Send + Sync>,+ // Debounces heal-task spawns for the issue-buckets client (see redis_heal).+ pub issue_buckets_heal_gate: HealGate,// 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>>,@@ -188,6 +191,7 @@ impl AppContext {process_request_limiter,team_manager,issue_buckets_redis_client,+ issue_buckets_heal_gate: HealGate::new(),rate_limiter,rate_limiter_enabled_team_ids,issue_cache,diff --git a/rust/cymbal/src/modes/processing/mod.rs b/rust/cymbal/src/modes/processing/mod.rsindex c3f64e281a0c..c654ef78b4ba 100644--- a/rust/cymbal/src/modes/processing/mod.rs+++ b/rust/cymbal/src/modes/processing/mod.rs@@ -14,6 +14,7 @@ pub mod config;pub mod fingerprinting;pub mod issue_resolution;pub mod normalization;+pub mod redis_heal;pub mod router;pub mod rules;pub mod server;diff --git a/rust/cymbal/src/modes/processing/redis_heal.rs b/rust/cymbal/src/modes/processing/redis_heal.rsnew file mode 100644index 000000000000..b5938f36bf14--- /dev/null+++ b/rust/cymbal/src/modes/processing/redis_heal.rs@@ -0,0 +1,145 @@+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++use common_redis::{Client, CustomRedisError, RedisErrorKind};++/// Minimum time between heal-task spawns per gate. This only bounds task+/// creation — the client's own cooldown governs how often a dial actually+/// happens.+const HEAL_SPAWN_DEBOUNCE: Duration = Duration::from_secs(1);++/// Bounds heal-task spawns for one Redis client to a single in-flight task,+/// plus a debounce between spawns. Spawned tasks park on the client's heal+/// mutex while a dial is in flight, so without this an outage's failure storm+/// (hundreds of failing commands per batch) would pile up detached tasks+/// without bound — and a dial slower than the debounce would still queue them.+#[derive(Clone, Default)]+pub struct HealGate(Arc<Mutex<GateState>>);++#[derive(Default)]+struct GateState {+ last_spawn: Option<Instant>,+ in_flight: bool,+}++impl HealGate {+ pub fn new() -> Self {+ Self::default()+ }++ /// Run `heal` in a background task, unless one is already in flight or a+ /// spawn happened within the debounce window.+ pub(crate) fn spawn_heal<F>(&self, heal: F)+ where+ F: std::future::Future<Output = ()> + Send + 'static,+ {+ if !self.try_claim(Instant::now()) {+ return;+ }+ let gate = self.clone();+ tokio::spawn(async move {+ heal.await;+ gate.release();+ });+ }++ fn try_claim(&self, now: Instant) -> bool {+ let mut state = self.0.lock().unwrap();+ if state.in_flight+ || state+ .last_spawn+ .is_some_and(|t| now.duration_since(t) < HEAL_SPAWN_DEBOUNCE)+ {+ return false;+ }+ state.last_spawn = Some(now);+ state.in_flight = true;+ true+ }++ fn release(&self) {+ self.0.lock().unwrap().in_flight = false;+ }+}++/// True when the error means the shared Redis connection is broken (or points+/// at the wrong node) and rebuilding it can help. Timeouts deliberately don't+/// count: they are ambiguous with a slow-but-healthy Redis, and healing on+/// them would churn connections exactly when Redis is under load. The cost is+/// that a connection failing only with timeouts (a blackholed socket that+/// never resets) stays until a hard error surfaces — the same trade-off+/// capture's heal wiring makes.+pub fn is_connection_error(err: &CustomRedisError) -> bool {+ match err {+ // ReadOnly: after a failover the old primary can stay alive as a+ // replica, and only a redial (re-resolving the primary endpoint)+ // heals the writes. redis-rs maps it to `RetryMethod::NoRetry`, so+ // `is_unrecoverable_error()` alone would miss it.+ CustomRedisError::Redis(e) => {+ e.is_unrecoverable_error() || e.kind() == RedisErrorKind::ReadOnly+ }+ _ => false,+ }+}++/// Kick [`Client::heal`] in a background task when `err` is connection-class,+/// so the fail-open caller never waits on the redial. The gate bounds task+/// creation; heal attempts themselves are serialized and cooldown-bounded by+/// the client.+///+/// The underlying connection is shared by every user of the client, so one+/// healed call site repairs them all — only a hot path per client needs+/// wiring, not every error branch.+pub fn heal_on_connection_error(+ gate: &HealGate,+ redis: &Arc<dyn Client + Send + Sync>,+ err: &CustomRedisError,+) {+ if !is_connection_error(err) {+ return;+ }+ let redis = redis.clone();+ gate.spawn_heal(async move { redis.heal().await });+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn only_connection_class_errors_heal() {+ let readonly = CustomRedisError::from_redis_kind(RedisErrorKind::ReadOnly, "READONLY");+ assert!(is_connection_error(&readonly));++ let dropped = CustomRedisError::from(redis_error(std::io::ErrorKind::BrokenPipe));+ assert!(is_connection_error(&dropped));++ // From<RedisError> maps IO timeouts to CustomRedisError::Timeout.+ let timeout = CustomRedisError::from(redis_error(std::io::ErrorKind::TimedOut));+ assert!(matches!(timeout, CustomRedisError::Timeout));+ assert!(!is_connection_error(&timeout));++ let app_error = CustomRedisError::from_redis_kind(RedisErrorKind::TypeError, "WRONGTYPE");+ assert!(!is_connection_error(&app_error));+ assert!(!is_connection_error(&CustomRedisError::NotFound));+ }++ fn redis_error(kind: std::io::ErrorKind) -> redis::RedisError {+ redis::RedisError::from(std::io::Error::new(kind, "test"))+ }++ // A failure storm must not spawn a heal task per failing command, and a+ // dial outlasting the debounce window must not queue further tasks.+ #[test]+ fn gate_allows_one_in_flight_heal_per_debounce_window() {+ let now = Instant::now();+ let gate = HealGate::new();+ assert!(gate.try_claim(now));+ for i in 0..10 {+ assert!(!gate.try_claim(now + i * HEAL_SPAWN_DEBOUNCE));+ }+ gate.release();+ assert!(!gate.try_claim(now));+ assert!(gate.try_claim(now + HEAL_SPAWN_DEBOUNCE));+ }+}diff --git a/rust/cymbal/src/modes/processing/stages/alerting/spike_detection.rs b/rust/cymbal/src/modes/processing/stages/alerting/spike_detection.rsindex 927859c9ed32..8ea8ac234016 100644--- a/rust/cymbal/src/modes/processing/stages/alerting/spike_detection.rs+++ b/rust/cymbal/src/modes/processing/stages/alerting/spike_detection.rs@@ -14,6 +14,7 @@ use crate::metric_consts::{SPIKE_INCREMENT_TEAM_BUCKETS_TIME, SPIKE_ISSUES_BLOCKED_BY_COOLDOWN, SPIKE_ISSUES_CHECKED,SPIKE_ISSUES_SPIKING,};+use crate::modes::processing::redis_heal::{heal_on_connection_error, HealGate};use crate::modes::processing::rules::spike::SpikeDetectionConfig;use crate::types::ProcessedExceptionProperties;@@ -89,7 +90,8 @@ fn get_now_rounded_to_minutes(minutes: i64) -> String {}async fn try_increment_issue_buckets(- redis: &(dyn Client + Send + Sync),+ heal_gate: &HealGate,+ redis: &Arc<dyn Client + Send + Sync>,issue_counts: &HashMap<Uuid, u32>,) {if issue_counts.is_empty() {@@ -112,11 +114,13 @@ async fn try_increment_issue_buckets(.await{warn!("Failed to increment issue buckets batch: {err}");+ heal_on_connection_error(heal_gate, redis, &err);}}async fn try_increment_team_buckets(- redis: &(dyn Client + Send + Sync),+ heal_gate: &HealGate,+ redis: &Arc<dyn Client + Send + Sync>,issues_by_id: &HashMap<Uuid, Issue>,issue_counts: &HashMap<Uuid, u32>,) {@@ -152,6 +156,7 @@ async fn try_increment_team_buckets(.await{warn!("Failed to increment team buckets batch: {err}");+ heal_on_connection_error(heal_gate, redis, &err);}// Track unique issues per team bucket using sets@@ -171,6 +176,7 @@ async fn try_increment_team_buckets(.await{warn!("Failed to add issues to team sets: {err}");+ heal_on_connection_error(heal_gate, redis, &err);}}@@ -209,12 +215,18 @@ pub async fn do_spike_detection(.await;let issue_buckets_timer = common_metrics::timing_guard(SPIKE_INCREMENT_ISSUE_BUCKETS_TIME, &[]);- try_increment_issue_buckets(&*context.issue_buckets_redis_client, &issue_counts).await;+ try_increment_issue_buckets(+ &context.issue_buckets_heal_gate,+ &context.issue_buckets_redis_client,+ &issue_counts,+ )+ .await;issue_buckets_timer.fin();let team_buckets_timer = common_metrics::timing_guard(SPIKE_INCREMENT_TEAM_BUCKETS_TIME, &[]);try_increment_team_buckets(- &*context.issue_buckets_redis_client,+ &context.issue_buckets_heal_gate,+ &context.issue_buckets_redis_client,&issues_by_id,&issue_counts,)diff --git a/rust/cymbal/src/modes/processing/stages/rate_limiting/limiter.rs b/rust/cymbal/src/modes/processing/stages/rate_limiting/limiter.rsindex c42b5c8fba1c..d7e3b9a22338 100644--- a/rust/cymbal/src/modes/processing/stages/rate_limiting/limiter.rs+++ b/rust/cymbal/src/modes/processing/stages/rate_limiting/limiter.rs@@ -5,6 +5,7 @@ use chrono::Utc;use common_redis::{CustomRedisError, RedisClient};use uuid::Uuid;+use crate::modes::processing::redis_heal::HealGate;use crate::modes::processing::rules::rate_limit::BucketParams;/// Outcome of one fused rate-limit call for a single issue group of `n` events.@@ -82,6 +83,11 @@ pub trait ScriptRunner: Send + Sync {keys: Vec<String>,args: Vec<String>,) -> Result<Vec<i64>, CustomRedisError>;++ /// Rebuild the underlying connection after a connection-class failure;+ /// see `common_redis::Client::heal`. Default no-op keeps test fakes+ /// trivial.+ async fn heal(&self) {}}#[async_trait]@@ -94,12 +100,17 @@ impl ScriptRunner for RedisClient {) -> Result<Vec<i64>, CustomRedisError> {RedisClient::eval_int_vec(self, script, keys, args).await}++ async fn heal(&self) {+ self.heal_connection().await;+ }}pub struct RedisRateLimiter {redis: Arc<dyn ScriptRunner>,key_prefix: String,bucket_ttl_seconds: u64,+ heal_gate: HealGate,}impl RedisRateLimiter {@@ -108,6 +119,7 @@ impl RedisRateLimiter {redis,key_prefix,bucket_ttl_seconds,+ heal_gate: HealGate::new(),}}@@ -121,6 +133,15 @@ impl RedisRateLimiter {fn team_key(&self, team_id: i32) -> String {format!("{}/{{{team_id}}}/project", self.key_prefix)}++ /// Kick a background heal of the limiter's Redis connection; called when+ /// an admit fails with a connection-class error. Never blocks the+ /// fail-open path; heal attempts are serialized and cooldown-bounded by+ /// the client.+ pub fn spawn_heal(&self) {+ let redis = self.redis.clone();+ self.heal_gate.spawn_heal(async move { redis.heal().await });+ }}impl RedisRateLimiter {diff --git a/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs b/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rsindex c367f17e2993..bf631428806a 100644--- a/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs+++ b/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs@@ -222,6 +222,9 @@ async fn apply_rate_limits(// 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(indices.len() as u64);+ if crate::modes::processing::redis_heal::is_connection_error(&e) {+ limiter.spawn_heal();+ }continue;}};