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(propdefs): keep the write pool off a demoted Aurora reader (#86792)

Eli Reisman2ec67446e62d
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 16fac2f583b1..571e7bd341ad 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -9221,6 +9221,7 @@ dependencies = [
"chrono",
"common-alloc",
"common-continuous-profiling",
+ "common-database",
"common-kafka",
"common-metrics",
"envconfig",
diff --git a/rust/common/database/src/lib.rs b/rust/common/database/src/lib.rs
index ac579eb14ffc..381f4339c31f 100644
--- a/rust/common/database/src/lib.rs
+++ b/rust/common/database/src/lib.rs
@@ -13,6 +13,13 @@ use sqlx::{
};
use thiserror::Error;
+pub mod writer_guard;
+
+pub use writer_guard::{
+ install_writer_guard, WriterGuard, WriterGuardConfig, DB_WRITER_GUARD_CAPPED_COUNTER,
+ DB_WRITER_PROBE_COUNTER,
+};
+
#[derive(Error, Debug)]
pub enum CustomDatabaseError {
#[error("Pg error: {0}")]
@@ -118,7 +125,9 @@ pub fn get_pool_with_config(url: &str, config: PoolConfig) -> Result<PgPool, sql
// Disable sqlx's default 30-min max_lifetime. Without this explicit None,
// connections created together (e.g. during pod scale-up) all expire at the
// same instant, causing a thundering herd of TLS reconnects that saturates
- // the database. Connection health is handled by test_before_acquire instead.
+ // the database. test_before_acquire covers a severed socket, but not a server
+ // that stopped accepting writes: a pool that must reach a writer needs
+ // `writer_guard` as well, since nothing here will ever recycle a demoted reader.
.max_lifetime(None);
if let Some(idle_timeout) = config.idle_timeout {
@@ -263,6 +272,49 @@ pub fn extract_timeout_type(error: &SqlxError) -> Option<&'static str> {
}
}
+/// Determines if a sqlx::Error is SQLSTATE 25006: the server refused a write because the
+/// session is read-only. On Aurora this is what a demoted writer returns, so retrying the same
+/// connection cannot help.
+pub fn is_read_only_error(error: &SqlxError) -> bool {
+ let SqlxError::Database(db) = error else {
+ return false;
+ };
+ db.code().as_deref() == Some("25006")
+}
+
+/// Coarse, bounded label for a failed query. Raw SQLSTATE has too many values to label a
+/// counter with.
+pub fn error_class(error: &SqlxError) -> &'static str {
+ // Pool-level cases first: `is_timeout_error` counts `PoolTimedOut`, but a saturated pool
+ // and a slow statement need different responses.
+ match error {
+ SqlxError::PoolTimedOut => return "pool_timeout",
+ SqlxError::PoolClosed => return "pool_closed",
+ _ => {}
+ }
+ if is_read_only_error(error) {
+ return "read_only";
+ }
+ if is_timeout_error(error) {
+ return "timeout";
+ }
+ if is_foreign_key_constraint_error(error) {
+ return "fk_violation";
+ }
+ match error {
+ SqlxError::Database(db) => match db.code().as_deref() {
+ Some("40P01") => "deadlock",
+ Some("40001") => "serialization",
+ Some("53300") => "too_many_connections",
+ Some("57P01" | "57P02" | "57P03") => "server_shutdown",
+ _ => "database",
+ },
+ SqlxError::Io(_) => "io",
+ SqlxError::Tls(_) => "tls",
+ _ => "other",
+ }
+}
+
/// Determines if a sqlx::Error represents a transient failure that should be retried
pub fn is_transient_error(error: &SqlxError) -> bool {
match error {
@@ -848,4 +900,25 @@ mod tests {
None
);
}
+
+ #[test]
+ fn error_class_separates_a_failover_from_ordinary_write_failures() {
+ assert_eq!(error_class(&SqlxError::PoolTimedOut), "pool_timeout");
+ assert_eq!(error_class(&SqlxError::PoolClosed), "pool_closed");
+ assert_eq!(
+ error_class(&SqlxError::Io(std::io::Error::other("x"))),
+ "io"
+ );
+ assert_eq!(error_class(&SqlxError::RowNotFound), "other");
+ }
+
+ #[test]
+ fn is_read_only_error_ignores_non_database_errors() {
+ assert!(!is_read_only_error(&SqlxError::PoolTimedOut));
+ // Only the SQLSTATE counts; matching message text would let any error impersonate a
+ // failover.
+ assert!(!is_read_only_error(&SqlxError::Protocol(
+ "cannot execute INSERT in a read-only transaction".to_string()
+ )));
+ }
}
diff --git a/rust/common/database/src/writer_guard.rs b/rust/common/database/src/writer_guard.rs
new file mode 100644
index 000000000000..ee0e1aff15a4
--- /dev/null
+++ b/rust/common/database/src/writer_guard.rs
@@ -0,0 +1,225 @@
+//! Keeps a write pool off a demoted Postgres reader after a failover.
+//!
+//! A connection that survives a failover is healthy at the protocol level, so sqlx's ping
+//! passes and writes keep failing with SQLSTATE 25006 until `max_lifetime` recycles it. sqlx
+//! cannot drain a live pool and does not implement libpq's `target_session_attrs=read-write`,
+//! so we run that check from `before_acquire` and discard any connection that fails it.
+
+use std::{
+ sync::{Arc, Mutex},
+ time::{Duration, Instant},
+};
+
+use sqlx::postgres::PgPoolOptions;
+
+/// Writability probes, labeled `result`: `clean`, `read_only` (connection discarded), or
+/// `unknown` (the GUC answered something other than `on`/`off`, treated as writable).
+/// A nonzero `read_only` rate means this pool reached a reader; there is no background rate.
+pub const DB_WRITER_PROBE_COUNTER: &str = "db_writer_probe_total";
+
+/// Times the guard stopped discarding connections because replacements were read-only too,
+/// which means the cluster is refusing writes and reconnecting cannot help.
+pub const DB_WRITER_GUARD_CAPPED_COUNTER: &str = "db_writer_guard_rejection_capped_total";
+
+/// Enough headroom to clear a pool's worth of poisoned connections several times over within
+/// one window, while still bounding churn when no replacement is writable either.
+const DEFAULT_MAX_REJECTIONS_PER_WINDOW: u32 = 32;
+
+/// Long enough for a failover's DNS transition to finish inside one window, short enough that
+/// the cap re-arms promptly once the cluster takes writes again.
+const DEFAULT_REJECTION_WINDOW: Duration = Duration::from_secs(60);
+
+#[derive(Debug, Clone)]
+pub struct WriterGuardConfig {
+ /// Most connections discarded per `rejection_window`. Past this the guard lets writes fail
+ /// rather than churn connections against a cluster that accepts none.
+ pub max_rejections_per_window: u32,
+ pub rejection_window: Duration,
+
+ /// Labels the guard's metrics. `Arc<str>` because it is cloned into a macro per probe.
+ pub pool_name: Option<Arc<str>>,
+}
+
+impl Default for WriterGuardConfig {
+ fn default() -> Self {
+ Self {
+ max_rejections_per_window: DEFAULT_MAX_REJECTIONS_PER_WINDOW,
+ rejection_window: DEFAULT_REJECTION_WINDOW,
+ pool_name: None,
+ }
+ }
+}
+
+/// Counts what probes find and bounds how many connections the guard will discard. Cheap to
+/// clone; clones share one state.
+#[derive(Clone)]
+pub struct WriterGuard {
+ config: Arc<WriterGuardConfig>,
+ state: Arc<Mutex<State>>,
+}
+
+#[derive(Default)]
+struct State {
+ window_started: Option<Instant>,
+ rejections_in_window: u32,
+}
+
+impl WriterGuard {
+ pub fn new(config: WriterGuardConfig) -> Self {
+ Self {
+ config: Arc::new(config),
+ state: Arc::new(Mutex::new(State::default())),
+ }
+ }
+
+ fn record_clean(&self) {
+ self.probe_counter("clean").increment(1);
+ }
+
+ fn record_unknown(&self) {
+ self.probe_counter("unknown").increment(1);
+ }
+
+ /// Records a probe that found a reader. Returns whether to discard the connection, which is
+ /// false once this window's rejection cap is spent.
+ fn record_read_only(&self, now: Instant) -> bool {
+ self.probe_counter("read_only").increment(1);
+ let mut state = self.lock();
+
+ let window_expired = state
+ .window_started
+ .is_none_or(|start| now.duration_since(start) >= self.config.rejection_window);
+ if window_expired {
+ state.window_started = Some(now);
+ state.rejections_in_window = 0;
+ }
+
+ if state.rejections_in_window >= self.config.max_rejections_per_window {
+ drop(state);
+ self.counter(DB_WRITER_GUARD_CAPPED_COUNTER).increment(1);
+ return false;
+ }
+
+ state.rejections_in_window += 1;
+ true
+ }
+
+ fn lock(&self) -> std::sync::MutexGuard<'_, State> {
+ self.state.lock().unwrap_or_else(|e| e.into_inner())
+ }
+
+ fn counter(&self, name: &'static str) -> metrics::Counter {
+ match &self.config.pool_name {
+ Some(pool) => metrics::counter!(name, "pool" => pool.clone()),
+ None => metrics::counter!(name),
+ }
+ }
+
+ fn probe_counter(&self, result: &'static str) -> metrics::Counter {
+ match &self.config.pool_name {
+ Some(pool) => {
+ metrics::counter!(DB_WRITER_PROBE_COUNTER, "pool" => pool.clone(), "result" => result)
+ }
+ None => metrics::counter!(DB_WRITER_PROBE_COUNTER, "result" => result),
+ }
+ }
+}
+
+/// Installs `guard` as a `before_acquire` hook so the pool stops handing out connections to a
+/// demoted reader.
+///
+/// The probe replaces sqlx's ping rather than adding to it: `test_before_acquire` already spends
+/// a round trip per acquire, and `SHOW transaction_read_only` answers the same liveness question
+/// plus whether the server still takes writes. Because it costs no extra round trip, the guard
+/// can probe every acquire, so a reader is caught on the next write.
+/// `PgPoolOptions::before_acquire` documents this pattern.
+///
+/// `before_acquire` only sees connections from the idle queue, so a freshly opened one reaches
+/// the caller unprobed and is caught on its next acquire. We deliberately do not also probe from
+/// `after_connect`: an error there sends sqlx into a reconnect-backoff loop until
+/// `acquire_timeout`, so a cluster-wide read-only state would surface as `PoolTimedOut` instead
+/// of a 25006 the caller can classify.
+pub fn install_writer_guard(options: PgPoolOptions, guard: &WriterGuard) -> PgPoolOptions {
+ let guard = guard.clone();
+ options
+ .test_before_acquire(false)
+ .before_acquire(move |conn, _meta| {
+ let guard = guard.clone();
+ Box::pin(async move {
+ // libpq's `target_session_attrs=read-write` check. Reads `on` on an Aurora reader
+ // and on a writer forced read-only, which are the same thing to this pool. An
+ // error propagates, which drops the connection exactly as a failed ping would.
+ let read_only: String = sqlx::query_scalar("SHOW transaction_read_only")
+ .fetch_one(&mut *conn)
+ .await?;
+
+ if read_only.eq_ignore_ascii_case("on") {
+ // `Ok(false)` closes this connection; the replacement re-resolves the endpoint.
+ return Ok(!guard.record_read_only(Instant::now()));
+ }
+
+ // Postgres reports only `on` or `off`, so a third value means an assumption
+ // broke. Keep the connection, because failing writes over a value we cannot
+ // parse is worse than serving a stale reader, but count it so it is not silent.
+ if !read_only.eq_ignore_ascii_case("off") {
+ guard.record_unknown();
+ return Ok(true);
+ }
+
+ guard.record_clean();
+ Ok(true)
+ })
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn guard() -> WriterGuard {
+ WriterGuard::new(WriterGuardConfig {
+ max_rejections_per_window: 2,
+ rejection_window: Duration::from_secs(60),
+ pool_name: None,
+ })
+ }
+
+ /// A clean probe must not consume rejection budget: if it did, ordinary healthy traffic
+ /// would exhaust the cap and the guard would stop discarding real readers.
+ #[test]
+ fn a_clean_probe_never_consumes_rejection_budget() {
+ let g = guard(); // cap of 2 per 60s
+ let t0 = Instant::now();
+
+ for _ in 0..100 {
+ g.record_clean();
+ }
+ {
+ let state = g.lock();
+ assert!(
+ state.window_started.is_none(),
+ "clean probes opened a window"
+ );
+ assert_eq!(state.rejections_in_window, 0);
+ }
+
+ assert!(g.record_read_only(t0));
+ assert!(g.record_read_only(t0));
+ assert!(!g.record_read_only(t0));
+ }
+
+ #[test]
+ fn stops_discarding_connections_once_the_cap_is_spent() {
+ let g = guard(); // cap of 2 per 60s
+ let t0 = Instant::now();
+
+ assert!(g.record_read_only(t0));
+ assert!(g.record_read_only(t0));
+ assert!(
+ !g.record_read_only(t0),
+ "replacements are readers too, so let writes fail instead of churning"
+ );
+
+ assert!(g.record_read_only(t0 + Duration::from_secs(60)));
+ }
+}
diff --git a/rust/common/database/tests/writer_guard_pg.rs b/rust/common/database/tests/writer_guard_pg.rs
new file mode 100644
index 000000000000..3a4160e6b0a2
--- /dev/null
+++ b/rust/common/database/tests/writer_guard_pg.rs
@@ -0,0 +1,252 @@
+//! Proves the guard gets a pool off a connection whose server stopped accepting writes,
+//! without restarting the process. `SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY`
+//! stands in for a demoted Aurora reader: the socket stays healthy, so a liveness check sees
+//! nothing, but every write is refused with SQLSTATE 25006.
+
+use common_database::{install_writer_guard, WriterGuard, WriterGuardConfig};
+use sqlx::{
+ postgres::{PgConnectOptions, PgPoolOptions},
+ PgPool, Row,
+};
+
+/// One connection, so the second acquire deterministically gets the poisoned one back.
+fn single_connection_pool(pool_opts: PgPoolOptions) -> PgPoolOptions {
+ pool_opts.min_connections(0).max_connections(1)
+}
+
+async fn backend_pid(pool: &PgPool) -> i32 {
+ sqlx::query("SELECT pg_backend_pid()")
+ .fetch_one(pool)
+ .await
+ .expect("pid query failed")
+ .get(0)
+}
+
+async fn transaction_read_only(pool: &PgPool) -> String {
+ sqlx::query_scalar("SHOW transaction_read_only")
+ .fetch_one(pool)
+ .await
+ .expect("read-only setting query failed")
+}
+
+/// Makes the pool's one connection read-only and returns its backend PID.
+async fn poison_the_pooled_connection(pool: &PgPool) -> i32 {
+ let mut conn = pool.acquire().await.expect("acquire failed");
+ let pid: i32 = sqlx::query("SELECT pg_backend_pid()")
+ .fetch_one(&mut *conn)
+ .await
+ .expect("pid query failed")
+ .get(0);
+ sqlx::query("SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY")
+ .execute(&mut *conn)
+ .await
+ .expect("failed to set the session read-only");
+ drop(conn);
+ pid
+}
+
+#[sqlx::test]
+async fn discards_a_read_only_connection_and_reopens_against_the_writer(
+ pool_opts: PgPoolOptions,
+ connect_opts: PgConnectOptions,
+) {
+ let guard = WriterGuard::new(WriterGuardConfig::default());
+ let pool = install_writer_guard(single_connection_pool(pool_opts), &guard)
+ .connect_with(connect_opts)
+ .await
+ .expect("connect failed");
+
+ let poisoned_pid = poison_the_pooled_connection(&pool).await;
+
+ // Capped at one connection, so this is either the poisoned one or its replacement.
+ assert_ne!(
+ backend_pid(&pool).await,
+ poisoned_pid,
+ "the guard should have discarded the read-only connection and opened a new one"
+ );
+ assert_eq!(
+ transaction_read_only(&pool).await,
+ "off",
+ "the replacement connection should accept writes"
+ );
+
+ pool.close().await;
+}
+
+#[sqlx::test]
+async fn writes_succeed_again_without_restarting_the_pool(
+ pool_opts: PgPoolOptions,
+ connect_opts: PgConnectOptions,
+) {
+ let guard = WriterGuard::new(WriterGuardConfig::default());
+ let pool = install_writer_guard(single_connection_pool(pool_opts), &guard)
+ .connect_with(connect_opts)
+ .await
+ .expect("connect failed");
+
+ sqlx::query("CREATE TABLE guard_probe (id int primary key)")
+ .execute(&pool)
+ .await
+ .expect("setup failed");
+
+ poison_the_pooled_connection(&pool).await;
+
+ // Without the guard this write fails with 25006 until the connection is recycled.
+ sqlx::query("INSERT INTO guard_probe (id) VALUES (1)")
+ .execute(&pool)
+ .await
+ .expect("write should succeed on the replacement connection");
+
+ let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM guard_probe")
+ .fetch_one(&pool)
+ .await
+ .expect("count failed");
+ assert_eq!(rows, 1);
+
+ pool.close().await;
+}
+
+/// The control: without the guard the poisoned connection survives, because its ping passes.
+/// Without this the tests above would only prove a healthy database accepts writes.
+#[sqlx::test]
+async fn without_the_guard_the_poisoned_connection_survives_and_writes_fail(
+ pool_opts: PgPoolOptions,
+ connect_opts: PgConnectOptions,
+) {
+ let pool = single_connection_pool(pool_opts)
+ .connect_with(connect_opts)
+ .await
+ .expect("connect failed");
+
+ sqlx::query("CREATE TABLE guard_probe (id int primary key)")
+ .execute(&pool)
+ .await
+ .expect("setup failed");
+
+ let poisoned_pid = poison_the_pooled_connection(&pool).await;
+
+ assert_eq!(
+ backend_pid(&pool).await,
+ poisoned_pid,
+ "sqlx has no reason to drop a connection that pings fine, so it hands the same one back"
+ );
+ assert_eq!(transaction_read_only(&pool).await, "on");
+
+ let err = sqlx::query("INSERT INTO guard_probe (id) VALUES (1)")
+ .execute(&pool)
+ .await
+ .expect_err("the write should be refused");
+ assert!(
+ common_database::is_read_only_error(&err),
+ "expected SQLSTATE 25006, got {err:?}"
+ );
+
+ pool.close().await;
+}
+
+/// The probe replaces sqlx's ping, so the probe is what has to notice a dead socket. Terminating
+/// the pooled backend proves the pool still recovers on its own: the probe fails, sqlx discards
+/// the connection, and the caller transparently gets a working replacement.
+#[sqlx::test]
+async fn recovers_when_the_pooled_backend_was_terminated(
+ pool_opts: PgPoolOptions,
+ connect_opts: PgConnectOptions,
+) {
+ let guard = WriterGuard::new(WriterGuardConfig::default());
+ let pool = install_writer_guard(single_connection_pool(pool_opts), &guard)
+ .connect_with(connect_opts.clone())
+ .await
+ .expect("connect failed");
+
+ let doomed_pid = backend_pid(&pool).await;
+
+ // A second pool, so killing the pooled backend does not kill the killer. The two-argument
+ // form waits for the backend to actually exit, which keeps the assertion below race-free.
+ let sidecar = PgPoolOptions::new()
+ .max_connections(1)
+ .connect_with(connect_opts)
+ .await
+ .expect("sidecar connect failed");
+ let terminated: bool = sqlx::query_scalar("SELECT pg_terminate_backend($1, 5000)")
+ .bind(doomed_pid)
+ .fetch_one(&sidecar)
+ .await
+ .expect("terminate failed");
+ assert!(terminated, "expected backend {doomed_pid} to exit");
+
+ assert_ne!(
+ backend_pid(&pool).await,
+ doomed_pid,
+ "the probe should have failed on the dead socket and opened a replacement"
+ );
+
+ sidecar.close().await;
+ pool.close().await;
+}
+
+/// The inverse of the poisoning tests, and the one they cannot catch: a probe that discards
+/// *every* connection still changes the backend PID and still lets writes succeed, so it passes
+/// all of them. In production that is a TCP and TLS handshake per acquire against the writer.
+#[sqlx::test]
+async fn a_healthy_pool_keeps_one_connection_across_many_acquires(
+ pool_opts: PgPoolOptions,
+ connect_opts: PgConnectOptions,
+) {
+ let guard = WriterGuard::new(WriterGuardConfig::default());
+ let pool = install_writer_guard(single_connection_pool(pool_opts), &guard)
+ .connect_with(connect_opts)
+ .await
+ .expect("connect failed");
+
+ let first = backend_pid(&pool).await;
+ for i in 0..8 {
+ assert_eq!(
+ backend_pid(&pool).await,
+ first,
+ "acquire {i} got a different backend; the guard is churning healthy connections"
+ );
+ }
+
+ pool.close().await;
+}
+
+/// Once the cap is spent the guard stops discarding, so the caller gets the reader and the write
+/// is refused. That is the documented behavior for a cluster that accepts no writes: fail fast
+/// with a classifiable error and let the alert fire, rather than churn connections.
+#[sqlx::test]
+async fn a_spent_cap_surfaces_25006_rather_than_churning(
+ pool_opts: PgPoolOptions,
+ connect_opts: PgConnectOptions,
+) {
+ let guard = WriterGuard::new(WriterGuardConfig {
+ max_rejections_per_window: 0,
+ ..Default::default()
+ });
+ let pool = install_writer_guard(single_connection_pool(pool_opts), &guard)
+ .connect_with(connect_opts)
+ .await
+ .expect("connect failed");
+
+ sqlx::query("CREATE TABLE guard_probe (id int primary key)")
+ .execute(&pool)
+ .await
+ .expect("setup failed");
+
+ let poisoned_pid = poison_the_pooled_connection(&pool).await;
+
+ let err = sqlx::query("INSERT INTO guard_probe (id) VALUES (1)")
+ .execute(&pool)
+ .await
+ .expect_err("the write should be refused, not silently retried");
+ assert!(
+ common_database::is_read_only_error(&err),
+ "expected SQLSTATE 25006, got {err:?}"
+ );
+ assert_eq!(
+ backend_pid(&pool).await,
+ poisoned_pid,
+ "a spent cap must keep the connection instead of churning it"
+ );
+
+ pool.close().await;
+}
diff --git a/rust/property-defs-rs/Cargo.toml b/rust/property-defs-rs/Cargo.toml
index 3767cdcf671c..530d604023b4 100644
--- a/rust/property-defs-rs/Cargo.toml
+++ b/rust/property-defs-rs/Cargo.toml
@@ -18,6 +18,7 @@ axum = { workspace = true }
metrics = { workspace = true }
chrono = { workspace = true }
quick_cache = { workspace = true }
+common-database = { path = "../common/database" }
common-metrics = { path = "../common/metrics" }
common-alloc = { path = "../common/alloc" }
common-continuous-profiling = { path = "../common/continuous_profiling" }
diff --git a/rust/property-defs-rs/src/app_context.rs b/rust/property-defs-rs/src/app_context.rs
index 6001cd0efe2c..9ba4e0aa5656 100644
--- a/rust/property-defs-rs/src/app_context.rs
+++ b/rust/property-defs-rs/src/app_context.rs
@@ -1,7 +1,12 @@
+use std::{sync::Arc, time::Duration};
+
+use common_database::{install_writer_guard, WriterGuard, WriterGuardConfig};
+use rand::Rng;
+use sqlx::{postgres::PgPoolOptions, PgPool};
+
use crate::{
api::v1::query::Manager, config::Config, group_type_resolver::GroupTypeResolver, types::Update,
};
-use sqlx::{postgres::PgPoolOptions, PgPool};
pub struct AppContext {
// this points to the original (shared) CLOUD DB instance in prod deployments
@@ -15,8 +20,7 @@ pub struct AppContext {
impl AppContext {
pub async fn new(config: &Config, qmgr: Manager) -> Result<Self, sqlx::Error> {
- let options = PgPoolOptions::new().max_connections(config.max_pg_connections);
- let pool = options.connect(&config.database_url).await?;
+ let pool = build_write_pool(config).await?;
let group_type_resolver = GroupTypeResolver::new(config);
@@ -38,3 +42,56 @@ impl AppContext {
self.group_type_resolver.resolve(updates).await
}
}
+
+/// Builds the definition-write pool. Every connection here writes, so the writer guard keeps
+/// the pool off a demoted Aurora reader, which a liveness ping cannot detect. The guard replaces
+/// that ping rather than adding to it.
+async fn build_write_pool(config: &Config) -> Result<PgPool, sqlx::Error> {
+ let guard = WriterGuard::new(WriterGuardConfig {
+ pool_name: Some(Arc::from("propdefs_write")),
+ ..Default::default()
+ });
+
+ let options = PgPoolOptions::new()
+ .max_connections(config.max_pg_connections)
+ .max_lifetime(jittered_max_lifetime(config.pg_max_lifetime_secs));
+
+ install_writer_guard(options, &guard)
+ .connect(&config.database_url)
+ .await
+}
+
+/// Spreads connection expiry across pods. sqlx compares age against `max_lifetime` exactly, so
+/// without jitter every pod reconnects in lockstep. Drawn once per process.
+fn jittered_max_lifetime(base_secs: u64) -> Duration {
+ let spread = base_secs / 5;
+ let jitter = if spread == 0 {
+ 0
+ } else {
+ rand::thread_rng().gen_range(0..=spread)
+ };
+ Duration::from_secs(base_secs + jitter)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn jitter_stays_within_a_fifth_above_the_base() {
+ for _ in 0..1000 {
+ let got = jittered_max_lifetime(300);
+ assert!(
+ got >= Duration::from_secs(300) && got <= Duration::from_secs(360),
+ "{got:?} outside 300..=360s"
+ );
+ }
+ }
+
+ #[test]
+ fn tiny_lifetimes_do_not_panic_on_an_empty_jitter_range() {
+ // spread == 0, which an exclusive range would panic on.
+ assert_eq!(jittered_max_lifetime(4), Duration::from_secs(4));
+ assert_eq!(jittered_max_lifetime(0), Duration::from_secs(0));
+ }
+}
diff --git a/rust/property-defs-rs/src/batch_ingestion.rs b/rust/property-defs-rs/src/batch_ingestion.rs
index 34827b254dcd..fe9e28672b1a 100644
--- a/rust/property-defs-rs/src/batch_ingestion.rs
+++ b/rust/property-defs-rs/src/batch_ingestion.rs
@@ -1,6 +1,7 @@
use std::{sync::Arc, time::Duration};
use chrono::{DateTime, Utc};
+use common_database::error_class;
use futures::stream::{FuturesUnordered, StreamExt};
use sqlx::PgPool;
use tokio::task::JoinHandle;
@@ -470,10 +471,16 @@ pub async fn process_batch(
match result {
Ok(batch_result) => match batch_result {
Ok(_) => continue,
- // fanned-out write attempts are instrumented locally w/more
- // detail, so we only publish global error metric here
- Err(_) => {
- metrics::counter!(ISSUE_FAILED, &[("reason", "failed")]).increment(1);
+ // fanned-out write attempts are instrumented locally w/more detail, so we
+ // only publish the global error metric here. `class` separates a failover
+ // (`read_only`) from routine deadlocks and timeouts; `reason` stays as-is
+ // because hand-managed Grafana panels select on `reason="failed"`.
+ Err(e) => {
+ metrics::counter!(
+ ISSUE_FAILED,
+ &[("reason", "failed"), ("class", error_class(&e))]
+ )
+ .increment(1);
}
},
Err(join_err) => {
diff --git a/rust/property-defs-rs/src/config.rs b/rust/property-defs-rs/src/config.rs
index 969b3a7b4e77..be1b35afdfea 100644
--- a/rust/property-defs-rs/src/config.rs
+++ b/rust/property-defs-rs/src/config.rs
@@ -16,6 +16,13 @@ pub struct Config {
#[envconfig(default = "10")]
pub max_pg_connections: u32,
+ // Backstop only; the writer guard is what detects a failover. Kept because the guard's
+ // `before_acquire` hook never sees a freshly opened connection, so recycling still bounds a
+ // connection the guard cannot reach. Overrides sqlx's 30 minute default. Jitter puts the
+ // effective lifetime in `base..=base + base/5`, so 300 here means 300-360s.
+ #[envconfig(default = "300")]
+ pub pg_max_lifetime_secs: u64,
+
#[envconfig(nested = true)]
pub kafka: KafkaConfig,