Skip to content

Commit b9cccf8

Browse files
jemiahwclaudeJemiah9000
authored
perf(db): jitter pool connection retirement; configurable reader floor and lifetime (#10047)
## Why sqlx 0.9 retires a pool connection once it outlives one fixed `max_lifetime`, which is 300 s here, hard-coded for the writer and reader pools. A load burst makes every relay pod open many connections within the same few seconds. With a fixed lifetime, those connections then all close within the same few seconds. If load comes back after that, the pod re-dials the whole cohort on the request path (TCP + TLS + SCRAM for each connection). Pool metrics show this as a sawtooth in database connections: a burst, a plateau lasting exactly `max_lifetime`, then a cliff. **Scope.** Jitter spreads retirement at release time while traffic is running, so a burst's cohort doesn't close in one cliff at `max_lifetime`. It does **not** keep capacity warm. After a lull long enough for the surplus above the floor to retire, the next burst dials that surplus again, as it would without jitter. A pool with no traffic is still closed by sqlx's reaper in one pass. Keeping burst capacity warm is a floor-sizing decision (`BUZZ_DB_READ_POOL_MIN`), outside this PR. The reader pool's warm floor is also fixed at one fifth of its ceiling, with no way to raise it short of growing the whole pool. ## What - **Lifetime jitter (writer and reader).** Each connection gets its own retirement point in `[max_lifetime - jitter, max_lifetime]` and closes the first time it is released after that point (`after_release`), once its request is done. On the reader, the check runs before the existing release check and skips that check's round trip. Jitter spreads when connections close, not when they are dialed again. Below the pool floor, sqlx's floor maintenance dials the replacement in the background. Above the floor, a retired connection is dialed again only when a later checkout finds the idle queue empty, so the timing of that dial depends on demand, not on the jitter window. The writer floor is 2 (the `DbConfig` default, not overridden by the relay); the reader floor is a fifth of the reader ceiling, or `BUZZ_DB_READ_POOL_MIN`. sqlx's `max_lifetime` still applies as before. sqlx checks it on release and in its reaper pass, not on idle checkout, so a connection past it is recycled on release or at the next reaper pass. - **Per-connection point:** a hash of the connection's creation instant at 10 µs resolution. sqlx 0.9 keeps no per-connection state that a hook can attach to. Because sqlx and this code read the clock less than a microsecond apart, the recomputed instant falls in the true bucket or the next one. So a connection's point is approximately fixed: almost always one of two candidates, both inside the window. A thread preempted between sqlx's age read and the hook's clock read gets a fresh draw, still inside the window. Connections dialed in parallel get independent points. - **Scope: jitter on release.** The point is checked only when a connection is released, so the spread depends on how often the pool hands out connections. sqlx's idle queue is FIFO, so each checkout takes the longest-idle connection, and a pool serving steady traffic cycles all its idle connections through the check well inside the window. A quiet pool does not: with 50 idle connections and one checkout every 10–30 s, only a few pass through the check during the 60 s window. sqlx's reaper closes the rest together, as it does today, and the next burst re-dials them. The reaper runs every min(`max_lifetime`, `idle_timeout`) = 300 s, so an untouched cohort closes at the first pass after 300 s, at an age of up to about 600 s. With the defaults `idle_timeout` (600 s) never fires, because the reaper re-queues each kept connection with a fresh `idle_since`; this is existing sqlx behavior. `BUZZ_DB_READ_POOL_MIN` is the lever for keeping a warm reader floor through quiet periods. Closing the gap fully needs a per-connection deadline in sqlx's own idle maintenance, which isn't possible without changing sqlx, so that is left as a possible follow-up if metrics still show a cliff. An earlier revision added a separate idle sweep, but review found it reset sqlx's idle timestamps, could hold a one-connection reader pool during a request's acquire budget, and outlived dropped pools, so it was removed. - **Metrics:** a new counter, `buzz_db_pool_lifetime_retired_total{pool_role}`, counts retirements; it is registered in `describe_db_pool_metrics()` and documented in `deploy/charts/buzz/README.md`. The audit pool reports as `audit`, separate from the serving `writer`, through a new `DbConfig::writer_pool_role`. - **`BUZZ_DB_MAX_LIFETIME_JITTER_SECS`** (default `60`, `0` disables) sets the window width. It is clamped to the lifetime, and a warning is logged when it exceeds half the lifetime. - **`BUZZ_DB_MAX_LIFETIME_SECS`** (default `300`) makes the lifetime ceiling configurable. - **`BUZZ_DB_READ_POOL_MIN`** (default: a fifth of the reader ceiling) overrides the reader warm floor, capped at the reader ceiling. ## Compatibility and rollback - With no env changes, the only behavior change is jitter: connections now retire somewhere in 240–300 s instead of at exactly 300 s. The mean lifetime drops from 300 s to about 270 s, which is roughly 11% more reconnects per connection. In exchange, while traffic continues, a burst's connections stop closing all at once. Jitter spreads closes only; it does not spread re-dials, because a closed connection above the floor is dialed again only when demand needs it, and it does not stop a burst from re-dialing surplus capacity after a lull. - The 60 s jitter default applies to every `Db::new` / `connect_writer_pool` user: buzz-admin, the deletion workers and workflow, not just the relay. Only buzz-relay reads `BUZZ_DB_MAX_LIFETIME_JITTER_SECS`, so the kill switch is relay-only. Elsewhere, disabling jitter means reverting the commit. - To restore the previous behavior exactly in the relay, set `BUZZ_DB_MAX_LIFETIME_JITTER_SECS=0`. Reverting the commit also restores it. - The test-only `Db::read_pool_options(max)` keeps its 1-arg signature; the configurable builder is `Db::read_pool_options_with(max, min, lifetime)`. #9431's `span_route_tests` compile whichever PR merges first. - The audit pool reuses the writer config, so it gets the same jitter, but it is labeled `audit`. The fence-probe and push-enqueue side pools are unchanged. ## Rollout plan 1. **Staging first**, with the defaults (60 s jitter, 300 s lifetime, reader floor = ceiling/5). After a burst, check: - While traffic continues, `buzz_db_pool_connections{pool_role}` loses its 300 s plateau-then-cliff and shows a spread over the 240-300 s window instead. After traffic stops, the remaining surplus can still close in one reaper pass; that is expected. - `buzz_db_pool_lifetime_retired_total` runs at about pool size / 270 s per pod under steady load. It counts retirements at release only, not reaper closes, so a quiet pool's reaper cliff does not show up in it. - Writer and reader `buzz_db_pool_acquire_duration_seconds` don't rise. 2. **Then production**, watching the same three signals. 3. **Kill switch:** `BUZZ_DB_MAX_LIFETIME_JITTER_SECS=0` (relay only). It needs a values change plus a pod roll, so it isn't instant. Otherwise, revert. 4. **Before raising `BUZZ_DB_READ_POOL_MIN`:** floor x relay pods, including old and new pods overlapping during a rolling deploy, must fit under the replica's `max_connections`. 5. **Mixed versions:** config and behavior only, with no schema or wire change, so it is safe during a rolling deploy. ## Testing - `cargo test -p buzz-db --lib` and `cargo test -p buzz-relay --lib config::` pass. New unit tests check that: - retirement points stay inside the window; - points spread across the window for dials 10 ms apart and for a 10 ms burst of 500 dials 20 µs apart, with every connection in that burst getting its own point; - a connection on a bucket boundary gets points inside the window; - jitter is clamped, and zero jitter leaves retirement to sqlx; - the reader-floor override is applied and capped; - the production `connect_read_pool` applies the configured floor and lifetime; - env parsing works and falls back on bad values. - New Postgres test `trickle_cycles_idle_cohort_through_jittered_retirement` (writer): a writer pool warms 12 connections in one burst (4 s lifetime, 3 s jitter, floor 3), then serves one query every 20 ms. It asserts that retirements land in several separate releases spread over at least 0.5 s, and that the floor of 3 holds. With the release check disabled, it fails: all nine surplus connections close within 0.18 s of each other at about 4 s. - New Postgres test `retiring_reader_release_skips_the_release_check` (reader, local Postgres 17, passes): connections released inside an open transaction past their retirement point are counted as `lifetime_retired_total` retirements, never as `open_transaction` closes. A jitter-off control pool shows the release check does catch the same session. The test records each cohort backend's pid and waits for all 8 cohort backends to exit before asserting exact totals from the final snapshot; each backend closes only after its release hook counted it. Mutation (check-first): running the release check before the retirement decision makes it fail with 8 `open_transaction` and 0 retired. Mutation (both): a variant that runs both the check and the retirement fails with 8 `open_transaction` plus 7 retired, which the old sum-threshold exit could have missed. The existing trickle test still passes under the check-first mutation, which is why this test was needed. - New Postgres test `reader_trickle_cycles_idle_cohort_through_jittered_retirement`, built through `Db::connect_read_pool` (4 s lifetime, 3 s jitter, floor 3). It asserts that at least 3 retirements span at least 500 ms, the floor settles at 3, `buzz_db_pool_lifetime_retired_total{pool_role="reader"}` is at least 3, and `buzz_db_reader_release_closed_total` stays 0 because a retiring release closes before the release check. Removing the reader hook's `if retire { return Ok(false) }` makes it fail: all 9 retirements land in one reaper pass at 4.02-4.19 s. - Local runs (2026-12-01), before the latest follow-up: `cargo clippy -p buzz-db -p buzz-relay --all-targets -- -D warnings` and `cargo fmt` clean; `buzz-db` lib 234/234; the two pool Postgres suites (`pool_release_postgres_tests`, `reader_pool_postgres_tests`, 16 tests) against local Postgres 17 passed 16/16 in each of 3 runs. - Local runs on Postgres 17 (2026-12-01), after the latest follow-up: `cargo clippy -p buzz-db -p buzz-relay --all-targets -- -D warnings` clean; the pool suites (`pool_release_postgres_tests` and `reader_pool_postgres_tests`) 17/17; `buzz-db` lib 234/234. - After merging `origin/main` at 59a51c2: fmt and clippy clean, `buzz-db` lib 234/234, and `buzz-relay` `config::tests::` + `metrics::` 79/79. - The chart README now states the same scope: jitter spreads release-time retirement while traffic runs; it does not keep capacity warm through a lull; raise the floor to keep burst capacity warm. - Not yet done: a local relay run. ## Follow-up commits - `docs(db): drop staggered-redial claims; wait for every cohort close in the ordering test`: the chart README, `.env.example` and buzz-db docs no longer say jitter spreads replacement dials (it spreads closes; a closed connection above the floor is dialed again only when demand needs it), and the ordering test waits for every cohort close before asserting exact totals. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Jemiah Westerman <jemiah@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Jemiah9000 <9424fd1a46ba04715d24ac3967d4a66d3cfcddd5fbe56a229c8386b4159810bf@buzz.block.builderlab.xyz>
1 parent a12a999 commit b9cccf8

11 files changed

Lines changed: 854 additions & 21 deletions

File tree

‎.env.example‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,23 @@ REDIS_URL=redis://localhost:6379
3434
# Max connections in each of the relay's Postgres pools — writer and, when
3535
# READ_DATABASE_URL is set, reader (default 50).
3636
# BUZZ_DB_POOL_SIZE=50
37+
# Max connections in the reader pool (default BUZZ_DB_POOL_SIZE).
38+
# BUZZ_DB_READ_POOL_SIZE=50
39+
# Connections the reader pool keeps open even when idle, capped at its size
40+
# (default: a fifth of BUZZ_DB_READ_POOL_SIZE).
41+
# BUZZ_DB_READ_POOL_MIN=10
42+
# Writer and reader connections close once they are this old (default 300).
43+
# BUZZ_DB_MAX_LIFETIME_SECS=300
44+
# Each connection closes at its own point in this many seconds before the
45+
# lifetime, so connections opened in one burst do not all close together.
46+
# Jitter does not schedule replacements: a closed connection above the floor
47+
# is dialed again only when a request needs it. 0 closes every connection at
48+
# exactly the lifetime (default 60).
49+
# The point is checked when a connection is returned to the pool, so the
50+
# spread depends on traffic: a quiet pool can still close its idle
51+
# connections together at the lifetime. BUZZ_DB_READ_POOL_MIN keeps a warm
52+
# reader floor through quiet periods.
53+
# BUZZ_DB_MAX_LIFETIME_JITTER_SECS=60
3754
# Read-only partition catalog audit interval, clamped to 60s..24h (default 900s).
3855
# BUZZ_PARTITION_AUDIT_INTERVAL_SECS=900
3956
# Emergency kill switch for all automatic partition DDL, including catch-all
Lines changed: 240 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,240 @@
1+
//! Spread connection retirement across a window before `max_lifetime`.
2+
//!
3+
//! sqlx 0.9 retires a connection once it outlives one fixed `max_lifetime`.
4+
//! A load burst opens many connections in the same few seconds, so with a
5+
//! fixed lifetime they all close in the same few seconds too.
6+
//! [`ConnectionLifetime`] gives each connection its own
7+
//! retirement point in `[max_lifetime - jitter, max_lifetime]`, checked in
8+
//! the pools' `after_release` hooks: retiring on release closes a connection
9+
//! after its request is done. Below the pool's `min_connections` floor,
10+
//! sqlx's floor maintenance dials the replacement in the background. Above
11+
//! the floor nothing replaces it until a later checkout finds the idle queue
12+
//! empty and dials on the request path; when that happens depends on demand,
13+
//! not on the retirement point, so jitter spreads closes, not dials. sqlx's
14+
//! `max_lifetime` still applies, but
15+
//! sqlx checks it only on release and in its reaper pass, not on idle
16+
//! checkout, so a connection past it is recycled on release or at the next
17+
//! reaper pass.
18+
//!
19+
//! The check runs whenever a connection is released, which covers idle
20+
//! connections too while the pool serves any traffic: sqlx's idle queue is
21+
//! FIFO, so each checkout takes the connection that has been idle longest,
22+
//! and a trickle of queries cycles every idle connection through release.
23+
//! A pool with no traffic at all is left to sqlx's reaper, which runs every
24+
//! `min(max_lifetime, idle_timeout)` and closes idle connections past
25+
//! `max_lifetime` in one pass, so an untouched cohort closes at an age of up
26+
//! to about twice `max_lifetime`. (The reaper re-queues each connection it
27+
//! keeps with a fresh idle timestamp, so with `idle_timeout` above
28+
//! `max_lifetime` it never closes one for idleness.) That costs nothing
29+
//! until traffic returns, and a connection past
30+
//! its point is closed by then whether or not points were spread. Spreading
31+
//! retirement inside the reaper itself would need a per-connection deadline
32+
//! in sqlx's own maintenance, which sqlx 0.9 does not offer.
33+
34+
use std::sync::OnceLock;
35+
use std::time::{Duration, Instant};
36+
37+
use super::DbPoolRole;
38+
39+
/// Retirement policy for one pool (see the module docs).
40+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41+
pub(crate) struct ConnectionLifetime {
42+
max: Duration,
43+
jitter: Duration,
44+
}
45+
46+
/// Resolution at which a connection's creation time is read back from
47+
/// sqlx's `age`, in nanoseconds.
48+
///
49+
/// sqlx 0.9 keeps no per-connection state a hook can attach to, so a
50+
/// connection's retirement point is a hash of its creation instant, which
51+
/// sqlx records when the connection is established. Each check recomputes
52+
/// that instant as `now - age`. The two clock reads are a synchronous call
53+
/// apart, almost always well under this resolution, so the recomputed
54+
/// instant almost always lands in one of two adjacent buckets. A thread
55+
/// preempted between the reads gets a fresh draw instead, still inside the
56+
/// window, so a connection's point can move but never leaves it. Two
57+
/// connections share
58+
/// a point only if they were established within the same 10 µs.
59+
const CREATION_RESOLUTION_NS: u128 = 10_000;
60+
61+
impl ConnectionLifetime {
62+
/// Policy for `max_lifetime_secs` with a retirement window of
63+
/// `jitter_secs`, clamped to the lifetime. A window wider than half the
64+
/// lifetime is allowed but logged: it lets some connections retire soon
65+
/// after they open, which costs reconnects without spreading them more.
66+
pub(crate) fn new(max_lifetime_secs: u64, jitter_secs: u64) -> Self {
67+
if jitter_secs > max_lifetime_secs / 2 {
68+
tracing::warn!(
69+
max_lifetime_secs,
70+
jitter_secs,
71+
"connection lifetime jitter exceeds half the lifetime; some connections will retire soon after opening"
72+
);
73+
}
74+
// Pin the clock anchor before the pool dials its first connection,
75+
// so every connection is created after it (see `retire_on_release`).
76+
anchor();
77+
Self {
78+
max: Duration::from_secs(max_lifetime_secs),
79+
jitter: Duration::from_secs(jitter_secs.min(max_lifetime_secs)),
80+
}
81+
}
82+
83+
/// The lifetime to hand sqlx as `max_lifetime`: connections older than
84+
/// this are recycled on release or at the next reaper pass.
85+
pub(crate) fn max(&self) -> Duration {
86+
self.max
87+
}
88+
89+
/// Whether a connection of `age` should close instead of returning to
90+
/// the pool. Counts each retirement in
91+
/// `buzz_db_pool_lifetime_retired_total` by `pool_role`.
92+
pub(crate) fn retire_on_release(&self, age: Duration, pool_role: DbPoolRole) -> bool {
93+
if self.jitter.is_zero() {
94+
// sqlx's fixed `max_lifetime` check already covers this case.
95+
return false;
96+
}
97+
let created = Instant::now()
98+
.checked_sub(age)
99+
.map_or(Duration::ZERO, |created| {
100+
created.saturating_duration_since(anchor())
101+
});
102+
let retire = age >= self.retire_at(created);
103+
if retire {
104+
metrics::counter!("buzz_db_pool_lifetime_retired_total", "pool_role" => pool_role.as_str())
105+
.increment(1);
106+
}
107+
retire
108+
}
109+
110+
/// The age at which a connection created `created` after the process
111+
/// anchor retires: a point in `[max - jitter, max]` derived from its
112+
/// creation time. Because the creation time is recomputed on each check,
113+
/// a connection's point is approximately fixed: almost always one of two
114+
/// candidates, and always in the window (see [`CREATION_RESOLUTION_NS`]).
115+
/// Connections created together get different points.
116+
fn retire_at(&self, created: Duration) -> Duration {
117+
let bucket = (created.as_nanos() / CREATION_RESOLUTION_NS) as u64;
118+
let fraction = (splitmix64(bucket) >> 11) as f64 / (1u64 << 53) as f64;
119+
self.max - self.jitter + self.jitter.mul_f64(fraction)
120+
}
121+
}
122+
123+
/// Process-wide clock origin for connection creation times.
124+
fn anchor() -> Instant {
125+
static ANCHOR: OnceLock<Instant> = OnceLock::new();
126+
*ANCHOR.get_or_init(Instant::now)
127+
}
128+
129+
/// SplitMix64 finalizer: spreads adjacent creation buckets uniformly over
130+
/// `u64`, so connections dialed milliseconds apart get unrelated retirement
131+
/// points.
132+
fn splitmix64(mut x: u64) -> u64 {
133+
x = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
134+
x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
135+
x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
136+
x ^ (x >> 31)
137+
}
138+
139+
#[cfg(test)]
140+
mod tests {
141+
use super::*;
142+
143+
#[test]
144+
fn jitter_is_clamped_to_the_lifetime() {
145+
let lifetime = ConnectionLifetime::new(30, 120);
146+
assert_eq!(lifetime.max(), Duration::from_secs(30));
147+
assert_eq!(lifetime.jitter, Duration::from_secs(30));
148+
}
149+
150+
#[test]
151+
fn retirement_points_stay_inside_the_window_and_spread_across_it() {
152+
let lifetime = ConnectionLifetime::new(300, 60);
153+
let start = Duration::from_secs(240);
154+
let end = Duration::from_secs(300);
155+
// A burst: 200 connections dialed 10ms apart over two seconds.
156+
let points: Vec<Duration> = (0..200)
157+
.map(|i| lifetime.retire_at(Duration::from_millis(5_000 + i * 10)))
158+
.collect();
159+
assert!(points.iter().all(|p| (start..=end).contains(p)));
160+
let earliest = points.iter().min().copied().unwrap_or(end);
161+
let latest = points.iter().max().copied().unwrap_or(start);
162+
assert!(
163+
earliest < start + Duration::from_secs(6) && latest > end - Duration::from_secs(6),
164+
"a burst must spread over the window, got {earliest:?}..{latest:?}"
165+
);
166+
}
167+
168+
#[test]
169+
fn a_sub_millisecond_burst_spreads_across_the_window() {
170+
let lifetime = ConnectionLifetime::new(300, 60);
171+
let start = Duration::from_secs(240);
172+
let end = Duration::from_secs(300);
173+
// Parallel dials: 500 connections established 20µs apart, 10ms total.
174+
let mut points: Vec<Duration> = (0..500)
175+
.map(|i| lifetime.retire_at(Duration::from_micros(7_000_000 + i * 20)))
176+
.collect();
177+
assert!(points.iter().all(|p| (start..=end).contains(p)));
178+
points.sort();
179+
points.dedup();
180+
assert_eq!(points.len(), 500, "every connection gets its own point");
181+
// Each sixth of the window holds a share of the burst.
182+
for sixth in 0..6u32 {
183+
let from = start + Duration::from_secs(10) * sixth;
184+
let to = from + Duration::from_secs(10);
185+
let n = points.iter().filter(|p| (from..to).contains(p)).count();
186+
assert!((40..=130).contains(&n), "{n} points in sixth {sixth}");
187+
}
188+
}
189+
190+
#[test]
191+
fn a_connection_keeps_its_retirement_point_across_releases() {
192+
let lifetime = ConnectionLifetime::new(300, 60);
193+
let created = Duration::from_millis(12_340);
194+
let point = lifetime.retire_at(created);
195+
// The two clock reads differ by far less than the resolution.
196+
for wobble_ns in [0, 1, 100, 999] {
197+
assert_eq!(
198+
lifetime.retire_at(created + Duration::from_nanos(wobble_ns)),
199+
point
200+
);
201+
}
202+
}
203+
204+
#[test]
205+
fn a_connection_on_a_bucket_boundary_has_at_most_two_points_both_in_the_window() {
206+
// sqlx reads `age` a synchronous call before this module reads the
207+
// clock, so the recomputed creation instant is late by well under
208+
// the resolution: it lands in the true bucket or the next one.
209+
let lifetime = ConnectionLifetime::new(300, 60);
210+
let window = Duration::from_secs(240)..=Duration::from_secs(300);
211+
let boundary = Duration::from_millis(12_340);
212+
let mut points: Vec<Duration> = [0, 50, 100, 500]
213+
.into_iter()
214+
.flat_map(|ns| {
215+
[
216+
boundary - Duration::from_nanos(1) + Duration::from_nanos(ns),
217+
boundary + Duration::from_nanos(ns),
218+
]
219+
})
220+
.map(|created| lifetime.retire_at(created))
221+
.collect();
222+
points.sort();
223+
points.dedup();
224+
assert!(points.len() <= 2, "{points:?}");
225+
assert!(points.iter().all(|p| window.contains(p)), "{points:?}");
226+
}
227+
228+
#[test]
229+
fn retires_only_inside_the_window() {
230+
let lifetime = ConnectionLifetime::new(300, 60);
231+
assert!(!lifetime.retire_on_release(Duration::from_secs(239), DbPoolRole::Writer));
232+
assert!(lifetime.retire_on_release(Duration::from_secs(300), DbPoolRole::Writer));
233+
}
234+
235+
#[test]
236+
fn zero_jitter_leaves_retirement_to_sqlx() {
237+
let lifetime = ConnectionLifetime::new(300, 0);
238+
assert!(!lifetime.retire_on_release(Duration::from_secs(10_000), DbPoolRole::Writer));
239+
}
240+
}

0 commit comments

Comments
 (0)