Skip to main content

matier_pool/
scale.rs

1//! HTTP/2 connection autoscaling policy: thresholds and the pure decision functions (unit tested).
2//!
3//! Zero-config: nobody tells the pool how many connections to open. It starts with
4//! `h2_min_conns_per_origin` (1), watches the load signals each connection actor publishes
5//! (`matier_transport::h2::LoadSnapshot`) and
6//!
7//! * **scales up** by one background dial when the connection a request just picked is saturated, at most
8//!   once per [`SCALE_UP_COOLDOWN`], never above `h2_max_conns_per_origin` (default: the number of CPUs) or the runtime's worker count;
9//!   the triggering request is not delayed;
10//! * **scales down** by closing connections that carried no stream for `idle_timeout`, and by draining
11//!   the newest connection when the whole origin has been under-used for [`DRAIN_AFTER_LOW`]
12//!   (with the hysteresis rules below), always keeping `h2_min_conns_per_origin`.
13
14use std::time::Duration;
15
16use matier_transport::h2::LoadSnapshot;
17
18/// A connection actor busy more than this fraction (permille) of wall time (EWMA over 10 ms windows) is
19/// saturated. This is deliberately far below 100 %: the actor is one link of a request/response pipeline
20/// (callers -> actor -> socket -> server -> socket -> actor -> callers), so at ~50 % busy it already spends
21/// the rest of its time waiting for work it could have overlapped with a second connection. Measured on
22/// the bench at c=64 / 1 KiB: one connection is 57 % busy and carries 113k req/s; two connections are 43 %
23/// busy each and carry 213k req/s.
24pub const BUSY_SATURATED_PERMILLE: u32 = 500;
25/// A connection whose requests wait longer than this (EWMA of enqueue -> HEADERS handed to the socket) is
26/// saturated even if the actor is not 100% busy (it is blocked on the socket or lagging behind its inbox).
27pub const DISPATCH_SATURATED: Duration = Duration::from_micros(100);
28/// A command queue longer than this at a tick means the actor cannot keep up with its callers.
29pub const INBOX_SATURATED: usize = 256;
30/// The load signals only count as saturation with at least this many streams in flight on the connection:
31/// a connection carrying one or two requests cannot be helped by a second one (nothing to split), however
32/// slow its actor or its peer is.
33pub const SCALE_MIN_IN_FLIGHT: usize = 4;
34/// A connection this deep is saturated at a much lower busy fraction: with this many streams multiplexed on one
35/// actor, a second connection splits the per-request actor work even though the actor is not close to
36/// saturation (it alternates between small bursts and waiting on the peer). Measured at c=64 / 1 KiB after the
37/// receive-path work: one connection sits at 45-50 % busy (just under [`BUSY_SATURATED_PERMILLE`]) and carries
38/// 114k req/s, two ~195k, three ~233k, four or five ~245k (5 runtime workers). At 40 (the old value) c=32 stayed
39/// on one connection (115k vs 176k) and c=64 sometimes stalled at two for seconds. Overshoot is bounded by the
40/// ceiling ([`h2_ceiling`]: never more connections than runtime workers), and an actor with little to do stays
41/// under [`SCALE_DEEP_BUSY_PERMILLE`] however many slow requests it carries.
42pub const SCALE_DEEP_IN_FLIGHT: usize = 16;
43/// Busy fraction (permille) above which a connection with [`SCALE_DEEP_IN_FLIGHT`] streams is saturated.
44pub const SCALE_DEEP_BUSY_PERMILLE: u32 = 250;
45/// Minimum spacing between scale-up dials for one origin. Roughly the time the busy EWMA needs to reflect the
46/// new connection (a few 10 ms windows), so a burst does not overshoot to the maximum.
47pub const SCALE_UP_COOLDOWN: Duration = Duration::from_millis(50);
48/// "Under-used" means every selectable connection is below this busy fraction (permille) ...
49pub const BUSY_LOW_PERMILLE: u32 = 200;
50/// ... and the remaining connections would carry the load at no more than this busy fraction (permille) after
51/// one is drained. The gap between this (300) and [`BUSY_SATURATED_PERMILLE`] (500) is the hysteresis band that
52/// stops drain/scale-up flapping.
53pub const DRAIN_PROJECTED_MAX_PERMILLE: u32 = 300;
54/// The origin must be under-used continuously for this long before a connection is drained; the timer restarts
55/// after every drain, so connections go one at a time.
56pub const DRAIN_AFTER_LOW: Duration = Duration::from_secs(1);
57/// No drain within this long after a scale-up.
58pub const DRAIN_HOLDOFF_AFTER_SCALE_UP: Duration = Duration::from_secs(5);
59/// Bounds of the maintenance tick (idle / drain bookkeeping); the tick is `idle_timeout / 4` within them.
60pub const REAP_TICK_MIN: Duration = Duration::from_millis(5);
61/// See [`REAP_TICK_MIN`].
62pub const REAP_TICK_MAX: Duration = Duration::from_millis(250);
63
64/// Default upper bound of HTTP/2 connections per origin: the number of CPUs (a connection actor is one task,
65/// so more connections than cores cannot add parallelism).
66#[must_use]
67pub fn default_h2_max_conns() -> usize {
68    std::thread::available_parallelism().map_or(4, std::num::NonZero::get)
69}
70
71/// The ceiling autoscaling actually uses: `max_conns`, further capped at the current tokio runtime's worker
72/// count (more actors than workers cannot run in parallel; they only split each connection's write batches,
73/// which costs syscalls on both ends), but never below `min_conns`, so an explicit pin is honoured.
74#[must_use]
75pub fn h2_ceiling(min_conns: usize, max_conns: usize) -> usize {
76    let workers =
77        tokio::runtime::Handle::try_current().map_or(usize::MAX, |h| h.metrics().num_workers());
78    max_conns.min(workers).max(min_conns).max(1)
79}
80
81/// Scale-up thresholds. The defaults are the named constants above; override them only for tests or for
82/// workloads whose connections you know to be unusual.
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub struct ScaleThresholds {
85    /// See [`BUSY_SATURATED_PERMILLE`].
86    pub busy_permille: u32,
87    /// See [`DISPATCH_SATURATED`].
88    pub dispatch_delay: Duration,
89    /// See [`INBOX_SATURATED`].
90    pub inbox: usize,
91    /// See [`SCALE_UP_COOLDOWN`].
92    pub cooldown: Duration,
93}
94
95impl Default for ScaleThresholds {
96    fn default() -> Self {
97        Self {
98            busy_permille: BUSY_SATURATED_PERMILLE,
99            dispatch_delay: DISPATCH_SATURATED,
100            inbox: INBOX_SATURATED,
101            cooldown: SCALE_UP_COOLDOWN,
102        }
103    }
104}
105
106impl ScaleThresholds {
107    /// Is a connection with these signals (and `in_flight` of `limit` streams) saturated?
108    #[must_use]
109    pub fn is_saturated(&self, load: LoadSnapshot, in_flight: usize, limit: usize) -> bool {
110        in_flight >= limit
111            || (in_flight >= SCALE_DEEP_IN_FLIGHT && load.busy_permille > SCALE_DEEP_BUSY_PERMILLE)
112            || (in_flight >= SCALE_MIN_IN_FLIGHT
113                && (load.busy_permille > self.busy_permille
114                    || load.dispatch_delay > self.dispatch_delay
115                    || load.inbox > self.inbox))
116    }
117}
118
119/// [`ScaleThresholds::is_saturated`] with the default thresholds.
120#[must_use]
121pub fn is_saturated(load: LoadSnapshot, in_flight: usize, limit: usize) -> bool {
122    ScaleThresholds::default().is_saturated(load, in_flight, limit)
123}
124
125/// May one connection be drained, given the busy fraction (permille) of every selectable connection?
126/// (The caller checks `len > h2_min_conns_per_origin`.)
127#[must_use]
128pub fn can_drain(busy_permille: &[u32]) -> bool {
129    let n = busy_permille.len();
130    if n < 2 {
131        return false;
132    }
133    let sum: u32 = busy_permille.iter().sum();
134    busy_permille.iter().all(|&b| b < BUSY_LOW_PERMILLE)
135        && sum / (n as u32 - 1) < DRAIN_PROJECTED_MAX_PERMILLE
136}
137
138/// Maintenance tick for an origin with this `idle_timeout`.
139#[must_use]
140pub fn reap_tick(idle_timeout: Duration) -> Duration {
141    (idle_timeout / 4).clamp(REAP_TICK_MIN, REAP_TICK_MAX)
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    fn load(busy: u32, disp_us: u64, inbox: usize) -> LoadSnapshot {
149        LoadSnapshot {
150            busy_permille: busy,
151            dispatch_delay: Duration::from_micros(disp_us),
152            inbox,
153        }
154    }
155
156    #[test]
157    fn saturation_signals() {
158        assert!(!is_saturated(load(0, 0, 0), 3, 128));
159        assert!(!is_saturated(load(250, 100, 256), 39, 128)); // boundaries are exclusive
160        assert!(!is_saturated(
161            load(500, 100, 256),
162            SCALE_DEEP_IN_FLIGHT - 1,
163            128
164        ));
165        assert!(is_saturated(load(501, 0, 0), 8, 128));
166        assert!(is_saturated(load(10, 101, 0), 8, 128));
167        assert!(is_saturated(load(10, 0, 257), 8, 128));
168        // Nothing to split: a lone request never justifies another connection.
169        assert!(!is_saturated(load(1000, 5000, 1000), 1, 128));
170        assert!(!is_saturated(
171            load(1000, 5000, 1000),
172            SCALE_MIN_IN_FLIGHT - 1,
173            128
174        ));
175        assert!(is_saturated(load(1000, 0, 0), SCALE_MIN_IN_FLIGHT, 128));
176        assert!(is_saturated(load(0, 0, 0), 128, 128));
177        assert!(is_saturated(load(0, 0, 0), 5, 4));
178    }
179
180    #[test]
181    fn deep_connections_saturate_at_a_lower_busy_fraction() {
182        // c=64 on one connection at ~47 % busy: a second connection helps.
183        assert!(is_saturated(load(470, 20, 6), 64, 128));
184        assert!(is_saturated(load(251, 0, 0), SCALE_DEEP_IN_FLIGHT, 128));
185        // Light or balanced load never dials extra connections.
186        assert!(!is_saturated(load(250, 0, 0), 64, 128));
187        assert!(!is_saturated(
188            load(470, 20, 6),
189            SCALE_DEEP_IN_FLIGHT - 1,
190            128
191        ));
192        assert!(!is_saturated(load(470, 20, 6), 1, 128));
193        // Two balanced c=64 connections (32 each) still help with a third.
194        assert!(is_saturated(load(430, 20, 6), 32, 128));
195    }
196
197    #[test]
198    fn drain_needs_everyone_low_and_projection_ok() {
199        assert!(!can_drain(&[]));
200        assert!(!can_drain(&[10]));
201        assert!(can_drain(&[10, 10]));
202        assert!(can_drain(&[140, 140, 140])); // 420/2 = 210 < 300
203        assert!(!can_drain(&[190, 190])); // projected 380 would be too close to saturation
204        assert!(!can_drain(&[10, 200])); // one connection not low
205        assert!(can_drain(&[199, 199, 199, 199, 199, 199, 199, 199, 100])); // 1491/8 = 186
206        // Hysteresis: the projected load after a drain never reaches the scale-up threshold.
207        for n in 2..=64u32 {
208            let busy = vec![BUSY_LOW_PERMILLE - 1; n as usize];
209            if can_drain(&busy) {
210                let projected = (BUSY_LOW_PERMILLE - 1) * n / (n - 1);
211                assert!(projected < BUSY_SATURATED_PERMILLE);
212            }
213        }
214    }
215
216    #[test]
217    fn ceiling_follows_runtime_workers_but_honours_a_pin() {
218        assert_eq!(h2_ceiling(1, 8), 8); // no runtime: config only
219        let rt = tokio::runtime::Builder::new_multi_thread()
220            .worker_threads(3)
221            .build()
222            .unwrap();
223        rt.block_on(async {
224            assert_eq!(h2_ceiling(1, 8), 3);
225            assert_eq!(h2_ceiling(1, 2), 2);
226            assert_eq!(h2_ceiling(6, 6), 6);
227        });
228    }
229
230    #[test]
231    fn tick_is_bounded() {
232        assert_eq!(reap_tick(Duration::from_millis(1)), REAP_TICK_MIN);
233        assert_eq!(reap_tick(Duration::from_secs(90)), REAP_TICK_MAX);
234        assert_eq!(
235            reap_tick(Duration::from_millis(200)),
236            Duration::from_millis(50)
237        );
238    }
239
240    #[test]
241    fn default_max_is_positive() {
242        assert!(default_h2_max_conns() >= 1);
243    }
244}