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): map transient Postgres errors to retryable 503 (#72371)

posthog[bot]a956c5214a5e
diff --git a/rust/feature-flags/src/api/errors.rs b/rust/feature-flags/src/api/errors.rs
index 217a49b04afa..6c6adb485ec7 100644
--- a/rust/feature-flags/src/api/errors.rs
+++ b/rust/feature-flags/src/api/errors.rs
@@ -1,7 +1,9 @@
use axum::http::StatusCode;
use axum::response::{IntoResponse, Json, Response};
use common_cookieless::{CookielessManagerError, SaltCacheError};
-use common_database::{extract_timeout_type, is_timeout_error, CustomDatabaseError};
+use common_database::{
+ extract_timeout_type, is_timeout_error, is_transient_error, CustomDatabaseError,
+};
use common_hypercache::HyperCacheError;
use common_redis::CustomRedisError;
use serde::Serialize;
@@ -612,10 +614,25 @@ impl From<sqlx::Error> for FlagError {
match e {
sqlx::Error::RowNotFound => FlagError::RowNotFound,
_ => {
- // Check if it's a timeout-related SQL error
if is_timeout_error(&e) {
+ // Timeouts get their own retryable classification (503) with a type tag.
FlagError::TimeoutError(extract_timeout_type(&e).map(|s| s.to_string()))
+ } else if is_transient_error(&e) {
+ // Connection resets, serialization failures, and other transient
+ // connection-level Postgres faults are retryable, so surface them as a
+ // 503 rather than treating a DB blip as a hard 500 SDKs won't retry.
+ //
+ // DatabaseUnavailable carries no payload, so log the cause here or the
+ // SQLSTATE is lost — that detail is what distinguishes a connection
+ // blip (08***) from resource exhaustion (53***) during an incident.
+ tracing::warn!(
+ sqlstate = e.as_database_error().and_then(|db| db.code()).as_deref(),
+ "Transient database error, returning 503: {}",
+ e
+ );
+ FlagError::DatabaseUnavailable
} else {
+ // Genuine internal faults (data corruption, unknown SQLSTATEs) stay 500.
FlagError::DatabaseError(e, None)
}
}
@@ -786,6 +803,42 @@ mod tests {
assert!(matches!(sqlx_error, FlagError::RowNotFound));
}
+ #[test]
+ fn test_direct_sqlx_transient_conversion_is_503() {
+ // Transient/connection-level failures propagated via `?` must map to the retryable
+ // DatabaseUnavailable (503), not DatabaseError (500), so SDKs retry on a DB blip.
+ let pool_closed: FlagError = sqlx::Error::PoolClosed.into();
+ assert!(matches!(pool_closed, FlagError::DatabaseUnavailable));
+ assert_eq!(pool_closed.status_code(), 503);
+
+ let io_reset: FlagError = sqlx::Error::Io(std::io::Error::new(
+ std::io::ErrorKind::ConnectionReset,
+ "connection reset by peer",
+ ))
+ .into();
+ assert!(matches!(io_reset, FlagError::DatabaseUnavailable));
+ assert_eq!(io_reset.status_code(), 503);
+
+ let tls_error: FlagError =
+ sqlx::Error::Tls(Box::new(std::io::Error::other("TLS handshake failed"))).into();
+ assert!(matches!(tls_error, FlagError::DatabaseUnavailable));
+ assert_eq!(tls_error.status_code(), 503);
+ }
+
+ #[test]
+ fn test_direct_sqlx_internal_fault_stays_500() {
+ // Genuine internal faults (schema/config problems) are not transient and must
+ // remain DatabaseError (500) so they are not masked as retryable.
+ let column_error: FlagError = sqlx::Error::ColumnNotFound("missing".to_string()).into();
+ assert!(matches!(column_error, FlagError::DatabaseError(_, _)));
+ assert_eq!(column_error.status_code(), 500);
+
+ let config_error: FlagError =
+ sqlx::Error::Configuration("invalid connection string".into()).into();
+ assert!(matches!(config_error, FlagError::DatabaseError(_, _)));
+ assert_eq!(config_error.status_code(), 500);
+ }
+
#[test]
fn test_redis_timeout_conversion() {
// Test that Redis timeout errors are converted to FlagError::TimeoutError
diff --git a/rust/feature-flags/src/flags/flag_matching_utils.rs b/rust/feature-flags/src/flags/flag_matching_utils.rs
index fb05e6e06cb8..fb09b5ddec02 100644
--- a/rust/feature-flags/src/flags/flag_matching_utils.rs
+++ b/rust/feature-flags/src/flags/flag_matching_utils.rs
@@ -640,12 +640,21 @@ fn are_overrides_useful_for_flag(
})
}
-/// Determines if a FlagError should trigger a retry
+/// Classifies whether a FlagError is worth retrying.
+///
+/// NOTE: this does not gate retries. The call sites use `Retry::spawn`, which retries
+/// every `Err` unconditionally; this only labels metrics and logs. Switch to
+/// `RetryIf::spawn` with this as the predicate if retries should actually be gated.
fn should_retry_on_error(error: &FlagError) -> bool {
match error {
- // Retry on database errors that are likely transient
+ // Errors constructed with context (e.g. "Failed to fetch flags") bypass
+ // From<sqlx::Error> and still carry the raw error, so classify by transience here.
FlagError::DatabaseError(sqlx_error, _) => common_database::is_transient_error(sqlx_error),
+ // Transient DB faults propagated via `?` (From<sqlx::Error>) or connection
+ // acquisition failures arrive already classified as DatabaseUnavailable (503).
+ FlagError::DatabaseUnavailable => true,
+
// Other error types generally should not be retried
_ => false,
}
@@ -661,9 +670,11 @@ fn flag_error_is_foreign_key_constraint(error: &FlagError) -> bool {
}
}
-/// Classify and track database errors
-fn classify_and_track_error(error: &FlagError, operation: &str, will_retry: bool) {
- let (error_type, timeout_subtype) = match error {
+/// Maps a database-related FlagError to its `(error_type, timeout_subtype)` metric labels,
+/// or None for errors that aren't tracked. Split out from `classify_and_track_error` so the
+/// classification can be tested without observing the global counter.
+fn classify_db_error(error: &FlagError) -> Option<(&'static str, Option<&str>)> {
+ let labels = match error {
FlagError::DatabaseError(sqlx_error, _) => {
let err_type = if common_database::is_foreign_key_constraint_error(sqlx_error) {
"foreign_key"
@@ -672,18 +683,31 @@ fn classify_and_track_error(error: &FlagError, operation: &str, will_retry: bool
} else if common_database::is_timeout_error(sqlx_error) {
"timeout"
} else {
- // PoolTimedOut → intercepted by From<sqlx::Error>, arrives as TimeoutError
- // PoolClosed → caught by is_transient_error above
- // Everything else that reaches here is genuinely unknown
+ // Errors reaching this arm were built with context, bypassing
+ // From<sqlx::Error>; transient/timeout ones are caught above, so
+ // everything left here is genuinely unknown.
"unknown"
};
(err_type, None)
}
+ // Transient faults propagated via `?` and connection-acquisition failures arrive
+ // pre-classified with no raw error attached. Without this arm they fall through
+ // and vanish from FLAG_DATABASE_ERROR_COUNTER.
+ FlagError::DatabaseUnavailable => ("transient", None),
FlagError::TimeoutError(timeout_type) => {
let subtype = timeout_type.as_ref().map(|s| s.as_str());
("timeout", subtype)
}
- _ => return, // Only track database-related errors
+ _ => return None, // Only track database-related errors
+ };
+
+ Some(labels)
+}
+
+/// Classify and track database errors
+fn classify_and_track_error(error: &FlagError, operation: &str, will_retry: bool) {
+ let Some((error_type, timeout_subtype)) = classify_db_error(error) else {
+ return;
};
let mut labels = vec![
@@ -2453,6 +2477,50 @@ mod tests {
let row_not_found_error = FlagError::RowNotFound;
assert!(!should_retry_on_error(&row_not_found_error));
+
+ // Transient errors propagated via From<sqlx::Error> arrive as DatabaseUnavailable
+ // (a retryable 503); the retry loop must still retry them.
+ let pool_closed_via_conversion: FlagError = SqlxError::PoolClosed.into();
+ assert!(matches!(
+ pool_closed_via_conversion,
+ FlagError::DatabaseUnavailable
+ ));
+ assert!(should_retry_on_error(&pool_closed_via_conversion));
+ }
+
+ #[test]
+ fn test_classify_db_error_covers_pre_classified_errors() {
+ use sqlx::Error as SqlxError;
+
+ // Transient sqlx errors now arrive pre-classified as DatabaseUnavailable. They must
+ // still be tracked, or FLAG_DATABASE_ERROR_COUNTER loses the transient bucket during
+ // exactly the DB blips it exists to surface.
+ let transient_via_conversion: FlagError = SqlxError::PoolClosed.into();
+ assert_eq!(
+ classify_db_error(&transient_via_conversion),
+ Some(("transient", None))
+ );
+ assert_eq!(
+ classify_db_error(&FlagError::DatabaseUnavailable),
+ Some(("transient", None))
+ );
+
+ // Errors built with context bypass From<sqlx::Error> and are classified from the
+ // raw error they still carry.
+ let contextual = FlagError::DatabaseError(
+ SqlxError::ColumnNotFound("missing".to_string()),
+ Some("Failed to fetch flags".to_string()),
+ );
+ assert_eq!(classify_db_error(&contextual), Some(("unknown", None)));
+
+ let timeout = FlagError::TimeoutError(Some("pool_timeout".to_string()));
+ assert_eq!(
+ classify_db_error(&timeout),
+ Some(("timeout", Some("pool_timeout")))
+ );
+
+ // Non-database errors stay untracked.
+ assert_eq!(classify_db_error(&FlagError::MissingDistinctId), None);
}
#[test]