Skip to main content

polars_io/cloud/
http_rate_limit.rs

1// Additive Increase / Multiplicative Decrease (AIMD) adaptive rate-limiter at
2// the HttpService with JIT-pricing.
3//
4// Components:
5// - Rate-limiter: responsible for config-based rate-limiting, including adapting
6//   to the observed success rate.
7// - Pacer (lock-free hot path): responsible for pacing the requests on `admit()`.
8//   The pacer will deny requests that have an estimated wait that is too far out.
9//   Holds an AtomicU64 f64 bits representation of the learned rate.
10// - PacerSignal (lock-free warm path): collects metrics from the pacer and holds
11//   time window boundaries to protect the cold path Mutex.
12// - AimdState (cold path): actuator, adapts the rate based on the observed
13//   HTTP success or failure rate. Authoritative for the atomic (learned) rate,
14//   shared real-time lock-free with the pacer and inflight concurrency controller.
15//
16// Integration points:
17// - The inflight concurrency controller adjusts its concurrency based on the
18//   learned rate. The `RateCell` contains the shared information.
19// - The object_store is responsible for retries, acting as a shock absorber
20//   for when the pipeline pushes above the rate-limit.
21// - The `InitPolicy` facilitates persistent learning when an object_store
22//   is rebuilt on error.
23//
24// TODO:
25// - Rate-limit is one per object_store per verb. AWS S3 scaled out its
26//   rate-limit per-prefix when hot. This can be used to refine the rate-limiter.
27// - The bridge between rate-limiter and inflight concurrency controller allows
28//   for a more reliable RTT_min signal than the clamped one currently in use,
29//   since it sits below the retry layer.
30
31use std::collections::VecDeque;
32use std::fmt;
33use std::str::FromStr;
34use std::sync::atomic::Ordering::Relaxed;
35use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64};
36use std::sync::{Arc, LazyLock, Mutex};
37use std::time::{Duration, Instant};
38
39use async_trait::async_trait;
40use chrono::Utc;
41use object_store::ClientOptions;
42use object_store::client::{
43    HttpClient, HttpConnector, HttpError, HttpErrorKind, HttpRequest, HttpResponse, HttpService,
44};
45use polars_core::runtime::ASYNC;
46use tokio::sync::oneshot;
47
48use super::stall_timer::{StallState, StallTimer};
49use super::token_bucket::TokenBucket;
50use crate::cloud::{CloudDirectionalRateLimitConfig, CloudRateLimitConfig};
51
52// For tracing purposes.
53static CONTROLLER_ID: AtomicU32 = AtomicU32::new(0);
54
55// Diagnostics; the format is unstable.
56static LOG_HTTP_RATE_LIMIT: LazyLock<bool> =
57    LazyLock::new(|| std::env::var("POLARS_LOG_HTTP_RATE_LIMIT").is_ok());
58
59// Request/s rate init and boundaries. Init is also the resting rate after idle. Init is a start:
60// reads raise the rate ahead of demand until the first throttle; the ceiling is the cap.
61// Documented baselines (rps):
62// AWS S3 per prefix 5500 GET/HEAD, 3500 PUT/POST/DELETE;
63// GCS per bucket 5000 reads, 1000 writes;
64// Azure per account 20_000.
65const DEFAULT_READ_INIT_RATE: f64 = 5000.0;
66const DEFAULT_WRITE_INIT_RATE: f64 = 1000.0;
67const DEFAULT_READ_FLOOR_RATE: f64 = 50.0;
68const DEFAULT_WRITE_FLOOR_RATE: f64 = 10.0;
69const DEFAULT_CEILING_RATE: f64 = 50_000.0;
70
71// Growth out of a cut is multiplicative, so a zero rate cannot recover.
72const MIN_RATE: f64 = 1.0;
73
74// Increase / decrease parameters.
75// Cold-start multiplicative increase, per tick.
76const FAST_RAMP_FACTOR: f64 = 2.0;
77// Track growth per `GROWTH_INTERVAL` that was busy and throttle-free: below the anchor
78// x `RECLAIM_STEP` (up to the anchor); above it x (1 + `PROBE_STEP`), and x (1 + `FAR_PROBE_STEP`)
79// from `FAR_FACTOR` x the anchor.
80const RECLAIM_STEP: f64 = 1.5;
81const PROBE_STEP: f64 = 0.125;
82const FAR_PROBE_STEP: f64 = 0.25;
83const FAR_FACTOR: f64 = 2.0;
84// Multiplicative decrease (on cut), with signal
85const BETA: f64 = 0.7;
86// Multiplicative decrease (on cut), no signal available (e.g. cold start)
87const BETA_NO_SIGNAL: f64 = 0.5;
88
89// Timing parameters.
90// Target queue depth as communicated to the concurrency controller.
91const DEFAULT_RATE_HORIZON_MS: u64 = 200;
92// Maximum queue depth, or admission denial ceiling: fail-fast rather than park
93// when the estimated wait exceeds this.
94// Note. Under nominal conditions the concurrency-driven population cap
95// sets depth below this value. Kicks in as buffer on rate collapse.
96// TODO: Dynamically size based on CloudRetryConfig and Init/Floor values.
97// Indicative sizing: to avoid object store erroring out, the rate-limiter must have
98// sufficient capacity to handle a drop-off from Init to Floor. This comes down
99// (MAX_WAIT * FLOOR) >= (INIT * HORIZON). In addition, the combined system
100// must be able to absorb a retry-storm, the size of which is unknown.
101const DEFAULT_RATE_MAX_WAIT_MS: u64 = 10_000;
102// Settle frequency, where AIMD updates its state based on the observed traffic.
103const TICK_INTERVAL: Duration = Duration::from_secs(1);
104// Period during which additional cuts will be suppressed.
105const REFRACTORY: Duration = Duration::from_secs(1);
106// Recover: period after a cut without growth.
107const PROBE_QUIET_PERIOD: Duration = Duration::from_secs(1);
108// Fast check: before the first throttle, reads follow demand every `FOLLOW_INTERVAL` (the rate is
109// kept at least `FOLLOW_FACTOR` x the measured demand); otherwise it runs every `GROWTH_INTERVAL`
110// and grows the rate in Track.
111const FOLLOW_INTERVAL: Duration = Duration::from_millis(100);
112const FOLLOW_FACTOR: f64 = 4.0;
113const GROWTH_INTERVAL: Duration = Duration::from_millis(500);
114// First cut without a success-rate EWMA: evidence needed to anchor on the goodput so far.
115const FIRST_CUT_MIN_ELAPSED: Duration = Duration::from_millis(100);
116const FIRST_CUT_MIN_SUCCESSES: u64 = 50;
117
118// Load and freshness parameters.
119// Utilization bound for growth.
120const SATURATION_THRESHOLD: f64 = 0.8;
121// EWMA weight of fresh goodput sample.
122const SUCCESS_SMOOTH: f64 = 0.8;
123// Decay multiplier towards init on idle, per tick.
124const IDLE_DECAY: f64 = 0.9;
125
126// Wake-latency tick. Bounds how long a parked waiter oversleeps past its
127// arithmetic due-time; does NOT affect pacing accuracy.
128pub(crate) const HTTP_RATE_LIMIT_WAKE_TICK: Duration = Duration::from_millis(1);
129
130// Used for sharing values between concurrency controller and rate-limiter.
131// Captures the f64 value in bits.
132pub type RateCell = Arc<AtomicU64>;
133
134/// What happens to the learned rate state when a store inits. Important
135/// when an object store rebuilds on error.
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137#[allow(unused)]
138pub(crate) enum InitPolicy {
139    /// Reset to init values: a rebuild is a deliberate clean slate.
140    SetToInit,
141    /// Reset to floor values: a rebuild falls back to a conservative start.
142    SetToFloor,
143    /// Leave the rate cells untouched: inherit the learned rate, if any.
144    Inherit,
145}
146
147impl InitPolicy {
148    fn target_rate(self, config: &DirectionalRateLimitConfig) -> Option<f64> {
149        match self {
150            Self::SetToInit => Some(config.init_rate),
151            Self::SetToFloor => Some(config.floor_rate),
152            Self::Inherit => None,
153        }
154    }
155}
156
157/// Rate-limit parameters.
158#[derive(Debug, Clone)]
159pub(crate) struct DirectionalRateLimitConfig {
160    // HTTP requests per second (rps).
161    pub(crate) init_rate: f64,
162    pub(crate) floor_rate: f64,
163    pub(crate) ceiling_rate: f64,
164    pub(crate) horizon: Duration,
165    pub(crate) max_wait: Duration,
166    pub(crate) init_policy: InitPolicy,
167    // Until the first throttle, keep the rate at least `FOLLOW_FACTOR` x the measured demand.
168    pub(crate) follows: bool,
169}
170
171/// Rate-limit parameters.
172#[derive(Debug, Clone)]
173pub(crate) struct RateLimitConfig {
174    pub(crate) read: DirectionalRateLimitConfig,
175    pub(crate) write: DirectionalRateLimitConfig,
176}
177
178impl From<CloudRateLimitConfig> for RateLimitConfig {
179    fn from(value: CloudRateLimitConfig) -> Self {
180        fn to_rate_limit_config(
181            config: &CloudDirectionalRateLimitConfig,
182            defaults: &DirectionalRateLimitConfig,
183        ) -> DirectionalRateLimitConfig {
184            let ceiling_rate = config
185                .ceiling_rate
186                .map_or(defaults.ceiling_rate, |r| r as f64)
187                .max(MIN_RATE);
188
189            let floor_rate = config
190                .floor_rate
191                .map_or(defaults.floor_rate, |r| r as f64)
192                .min(ceiling_rate)
193                .max(MIN_RATE);
194
195            let init_rate = config
196                .init_rate
197                .map_or(defaults.init_rate, |r| r as f64)
198                .clamp(floor_rate, ceiling_rate);
199
200            DirectionalRateLimitConfig {
201                init_rate,
202                floor_rate,
203                ceiling_rate,
204                horizon: defaults.horizon,
205                max_wait: defaults.max_wait,
206                init_policy: defaults.init_policy,
207                follows: defaults.follows,
208            }
209        }
210
211        let read_config = to_rate_limit_config(&value.read, &READ_DEFAULTS);
212        let write_config = to_rate_limit_config(&value.write, &WRITE_DEFAULTS);
213
214        return RateLimitConfig {
215            read: read_config,
216            write: write_config,
217        };
218
219        static READ_DEFAULTS: LazyLock<DirectionalRateLimitConfig> = LazyLock::new(|| {
220            directional_defaults(
221                DEFAULT_READ_INIT_RATE,
222                DEFAULT_READ_FLOOR_RATE,
223                "POLARS_CLOUD_READ_INIT_RATE",
224                "POLARS_CLOUD_READ_FLOOR_RATE",
225                "POLARS_CLOUD_READ_CEILING_RATE",
226                true,
227            )
228        });
229
230        static WRITE_DEFAULTS: LazyLock<DirectionalRateLimitConfig> = LazyLock::new(|| {
231            directional_defaults(
232                DEFAULT_WRITE_INIT_RATE,
233                DEFAULT_WRITE_FLOOR_RATE,
234                "POLARS_CLOUD_WRITE_INIT_RATE",
235                "POLARS_CLOUD_WRITE_FLOOR_RATE",
236                "POLARS_CLOUD_WRITE_CEILING_RATE",
237                false,
238            )
239        });
240
241        fn directional_defaults(
242            default_init_rate: f64,
243            default_floor_rate: f64,
244            init_rate_env: &'static str,
245            floor_rate_env: &'static str,
246            ceiling_rate_env: &'static str,
247            follows: bool,
248        ) -> DirectionalRateLimitConfig {
249            DirectionalRateLimitConfig {
250                init_rate: parse_env_var(default_init_rate, init_rate_env),
251                floor_rate: parse_env_var(default_floor_rate, floor_rate_env),
252                ceiling_rate: parse_env_var(DEFAULT_CEILING_RATE, ceiling_rate_env),
253                horizon: Duration::from_millis(parse_env_var(
254                    DEFAULT_RATE_HORIZON_MS,
255                    "POLARS_CLOUD_RATE_HORIZON_MS",
256                )),
257                max_wait: Duration::from_millis(parse_env_var(
258                    DEFAULT_RATE_MAX_WAIT_MS,
259                    "POLARS_CLOUD_RATE_MAX_WAIT_MS",
260                )),
261                init_policy: InitPolicy::Inherit,
262                follows,
263            }
264        }
265
266        fn parse_env_var<T: FromStr>(default: T, name: &'static str) -> T {
267            std::env::var(name).map_or(default, |x| {
268                x.parse::<T>()
269                    .ok()
270                    .unwrap_or_else(|| panic!("invalid value for {name}: {x}"))
271            })
272        }
273    }
274}
275
276/// Read-only view of the pacing budget including the learned rate-limit signal
277/// for internal consumers (e.g., ConcurrencyController).
278/// The cells contains learned rates (f64 bits in an AtomicU64), and are updated
279/// by the AIMD loop only.
280/// Valid for the process lifetime: object store rebuilds can rotate behind the
281/// cells rather than replacing them.
282#[derive(Debug, Clone)]
283pub struct PacingBudget {
284    rate_bits: RateCell,
285    admitted: Arc<AtomicU64>,
286    horizon: Duration,
287}
288
289impl PacingBudget {
290    pub fn rate(&self) -> f64 {
291        f64::from_bits(self.rate_bits.load(Relaxed))
292    }
293
294    /// Requests admitted by the pacer so far (monotonic).
295    pub fn admitted(&self) -> u64 {
296        self.admitted.load(Relaxed)
297    }
298
299    pub fn horizon(&self) -> Duration {
300        self.horizon
301    }
302
303    pub fn request_budget(&self, bdp: f64) -> f64 {
304        bdp.min(self.rate() * self.horizon().as_secs_f64())
305    }
306}
307// Persist rate-limit state when rebuilding an object_store with InitPolicy::Inherit.
308#[derive(Debug, Clone)]
309pub(crate) struct RateState {
310    pub rate_bits: RateCell,
311    pub max_bits: RateCell, // NaN represents None
312    // Requests admitted by the pacer, across rebuilds (monotonic).
313    pub admitted: Arc<AtomicU64>,
314    // A throttle response was seen.
315    pub throttled: Arc<AtomicBool>,
316    pub stall: Arc<StallState>,
317}
318
319impl RateState {
320    pub fn new(init_rate: f64) -> Self {
321        Self {
322            rate_bits: Arc::new(AtomicU64::new(init_rate.to_bits())),
323            max_bits: Arc::new(AtomicU64::new(f64::NAN.to_bits())),
324            admitted: Arc::new(AtomicU64::new(0)),
325            throttled: Arc::new(AtomicBool::new(false)),
326            stall: Arc::default(),
327        }
328    }
329
330    #[inline]
331    pub fn get_rate(&self) -> f64 {
332        f64::from_bits(self.rate_bits.load(Relaxed))
333    }
334
335    #[inline]
336    pub fn set_rate(&self, rate: f64) {
337        self.rate_bits.store(rate.to_bits(), Relaxed);
338    }
339
340    #[inline]
341    pub fn get_last_max(&self) -> Option<f64> {
342        // NaN means no value.
343        let value = f64::from_bits(self.max_bits.load(Relaxed));
344        (!value.is_nan()).then_some(value)
345    }
346
347    #[inline]
348    pub fn set_last_max(&self, max: Option<f64>) {
349        let bits = max.unwrap_or(f64::NAN).to_bits();
350        self.max_bits.store(bits, Relaxed);
351    }
352
353    pub fn reset(&self, init_rate: f64) {
354        self.set_rate(init_rate);
355        self.set_last_max(None);
356        self.throttled.store(false, Relaxed);
357    }
358}
359
360/// Builder-owned. State that may survive object store rebuilds.
361#[derive(Debug)]
362struct RateLimitState {
363    read_state: RateState,
364    write_state: RateState,
365}
366
367impl RateLimitState {
368    pub(crate) fn new(config: &RateLimitConfig) -> Self {
369        Self {
370            read_state: RateState::new(config.read.init_rate),
371            write_state: RateState::new(config.write.init_rate),
372        }
373    }
374
375    /// Initialize the cell values from prior state on object store rebuild.
376    pub(crate) fn apply_init_policy(&self, config: &RateLimitConfig) {
377        fn apply_one(state: &RateState, config: &DirectionalRateLimitConfig) {
378            if let Some(rate) = config.init_policy.target_rate(config) {
379                state.reset(rate);
380            }
381        }
382
383        apply_one(&self.read_state, &config.read);
384        apply_one(&self.write_state, &config.write);
385    }
386}
387
388#[derive(Debug)]
389pub(crate) struct RateLimiter {
390    pub(crate) config: RateLimitConfig,
391    state: RateLimitState,
392}
393
394impl RateLimiter {
395    pub(crate) fn new(config: RateLimitConfig) -> Self {
396        let state = RateLimitState::new(&config);
397        Self { config, state }
398    }
399
400    /// Initialize the cell values. Called at every store (re)build, before
401    /// constructing the new PacedHttpConnector.
402    pub(crate) fn apply_init_policy(&self) {
403        self.state.apply_init_policy(&self.config);
404    }
405
406    // Read-only view of pacing budget for 'read' based on learned rate.
407    // Targeted at upstream consumers.
408    pub(crate) fn read_budget(&self) -> PacingBudget {
409        PacingBudget {
410            rate_bits: Arc::clone(&self.state.read_state.rate_bits),
411            admitted: Arc::clone(&self.state.read_state.admitted),
412            horizon: self.config.read.horizon,
413        }
414    }
415
416    // Read-only view of pacing budget for 'write' based on learned rate.
417    // Targeted at upstream consumers.
418    #[allow(unused)]
419    pub(crate) fn write_budget(&self) -> PacingBudget {
420        PacingBudget {
421            rate_bits: Arc::clone(&self.state.write_state.rate_bits),
422            admitted: Arc::clone(&self.state.write_state.admitted),
423            horizon: self.config.write.horizon,
424        }
425    }
426}
427
428#[derive(Debug, Copy, Clone)]
429enum Regime {
430    // No knowledge about ceiling or cut. Fast-ramp.
431    Search,
432    // Recover from a congestion event.
433    Recover { until: Instant, anchor: f64 },
434    // Track towards a learned ceiling and probe above.
435    Track { anchor: f64 },
436}
437
438// Additive Increase Multiplicative Decrease (AIMD) state.
439// Note: the initial fast_ramp is multiplicative, not additive.
440// Cold path: state gets updated every tick interval.
441#[derive(Debug)]
442struct AimdState {
443    // How to drive the rate based on what has been observed.
444    regime: Regime,
445
446    // Source of truth for the learned request rates in requests per second (rps).
447    // Represented as f64 in bits and shared as Atomic cells.
448    shared: RateState,
449    // Exponentially weighted moving average (EWMA) of the success rate.
450    success_rate: Option<f64>,
451    // Start of window, where window is the interval between 2 ticks.
452    window_start: Option<Instant>,
453    // Last cut time.
454    last_cut_time: Option<Instant>,
455
456    // Pacer statistics at last tick.
457    prev_admitted: u64,
458    prev_denied: u64,
459    prev_resp_succeeded: u64,
460    prev_resp_throttled: u64,
461
462    // Fast check: pacer admissions, throttle responses and time at the previous check, the demand
463    // measured since then (requests/s), and rate raises since the last tick.
464    check_prev_admitted: u64,
465    check_prev_throttled: u64,
466    check_prev_ns: u64,
467    demand: Option<f64>,
468    raises: u32,
469}
470
471impl AimdState {
472    #[inline]
473    pub fn rate(&self) -> f64 {
474        self.shared.get_rate()
475    }
476
477    #[inline]
478    pub fn set_rate(&mut self, rate: f64) {
479        self.shared.set_rate(rate);
480    }
481
482    #[inline]
483    pub fn last_max(&self) -> Option<f64> {
484        self.shared.get_last_max()
485    }
486
487    #[inline]
488    pub fn set_last_max(&mut self, max: Option<f64>) {
489        self.shared.set_last_max(max);
490    }
491
492    /// The success_rate is the observed 'goodput' signal.
493    fn update_success_rate(&mut self, successes: u64, elapsed_s: f64) {
494        // Too short to be statistically meaningful (also guards div-by-zero).
495        if elapsed_s < 0.5 * TICK_INTERVAL.as_secs_f64() {
496            return;
497        }
498
499        if successes == 0 {
500            return;
501        }
502
503        let success_rate = successes as f64 / elapsed_s;
504        self.success_rate = Some(match self.success_rate {
505            None => success_rate,
506            Some(rate) => SUCCESS_SMOOTH * success_rate + (1.0 - SUCCESS_SMOOTH) * rate,
507        });
508    }
509}
510
511// Lock-free metrics and time window filter to guard the Mutex, warm path.
512#[derive(Debug)]
513pub(crate) struct PacerSignal {
514    // Fast-path view of window end.
515    window_end_ns: AtomicU64,
516    // Fast-path view of the next fast check (u64::MAX: before traffic).
517    check_end_ns: AtomicU64,
518    // Advisory refractory pre-check (0 = never).
519    last_cut_ns: AtomicU64,
520    // Cumulative HTTP response counters, since epoch.
521    resp_succeeded: AtomicU64,
522    resp_throttled: AtomicU64,
523    stall: Arc<StallState>,
524}
525
526#[derive(Debug)]
527pub(crate) struct AdaptiveRateController {
528    epoch: Instant,
529    // Hot path, lock-free atomics.
530    //  TBD - do we need an Arc?
531    pacer: Arc<Pacer>,
532    // Warm signal path, lock-free atomics.
533    signal: PacerSignal,
534    // Cold path, change state and rate.
535    state: Mutex<AimdState>,
536    // `RateState::throttled`, read and set without the lock.
537    throttled: Arc<AtomicBool>,
538    label: &'static str,
539    id: u32,
540    config: DirectionalRateLimitConfig,
541}
542
543impl AdaptiveRateController {
544    fn new(
545        label: &'static str,
546        id: u32,
547        shared: RateState,
548        config: DirectionalRateLimitConfig,
549    ) -> Self {
550        let epoch = Instant::now();
551
552        // A store rebuild tracks the learned ceiling, except for reads that were never throttled.
553        let throttled = shared.throttled.clone();
554        let regime = match shared.get_last_max() {
555            Some(anchor) if !config.follows || throttled.load(Relaxed) => Regime::Track { anchor },
556            _ => Regime::Search,
557        };
558
559        let token_bucket = Arc::new(TokenBucket::new(shared.rate_bits.clone()));
560        let pacer = Pacer::start(token_bucket, config.max_wait, shared.admitted.clone());
561
562        let signal = PacerSignal {
563            window_end_ns: AtomicU64::new(u64::MAX),
564            check_end_ns: AtomicU64::new(u64::MAX),
565            last_cut_ns: AtomicU64::new(0),
566            resp_succeeded: AtomicU64::new(0),
567            resp_throttled: AtomicU64::new(0),
568            stall: Arc::clone(&shared.stall),
569        };
570
571        let state = Mutex::new(AimdState {
572            regime,
573            shared,
574            success_rate: None,
575            window_start: None,
576            last_cut_time: None,
577            prev_admitted: 0,
578            prev_denied: 0,
579            prev_resp_succeeded: 0,
580            prev_resp_throttled: 0,
581            check_prev_admitted: 0,
582            check_prev_throttled: 0,
583            check_prev_ns: 0,
584            demand: None,
585            raises: 0,
586        });
587
588        Self {
589            epoch,
590            pacer,
591            signal,
592            state,
593            throttled,
594            label,
595            id,
596            config,
597        }
598    }
599
600    #[inline]
601    fn now_ns(&self) -> u64 {
602        self.epoch.elapsed().as_nanos() as u64
603    }
604
605    #[inline]
606    fn mark_first_traffic(&self) {
607        // The window origin is FIRST TRAFFIC, not construction: the pipeline
608        // takes an unknown time to spin up, and a window that spans the idle
609        // prologue measures emptiness (4 successes / 533ms at cold start).
610        if self.signal.window_end_ns.load(Relaxed) == u64::MAX {
611            let now_ns = self.now_ns();
612            self.signal
613                .window_end_ns
614                .store(now_ns + TICK_INTERVAL.as_nanos() as u64, Relaxed);
615            let mut state = self.state.lock().unwrap();
616            state.window_start = Some(Instant::now());
617            state.check_prev_admitted = self.pacer.admitted();
618            state.check_prev_throttled = self.signal.resp_throttled.load(Relaxed);
619            state.check_prev_ns = now_ns;
620            self.signal
621                .check_end_ns
622                .store(now_ns + self.check_interval().as_nanos() as u64, Relaxed);
623        }
624    }
625
626    /// Reads follow demand until the first throttle response.
627    fn follows(&self) -> bool {
628        self.config.follows && !self.throttled.load(Relaxed)
629    }
630
631    fn check_interval(&self) -> Duration {
632        if self.follows() {
633            FOLLOW_INTERVAL
634        } else {
635            GROWTH_INTERVAL
636        }
637    }
638
639    fn on_congestion(&self) {
640        self.signal.resp_throttled.fetch_add(1, Relaxed);
641        // Before `maybe_settle`: the follower stops at the first throttle response.
642        self.throttled.store(true, Relaxed);
643
644        self.mark_first_traffic();
645        self.maybe_settle();
646
647        // Lock-free fast-path (1): advisory refractory pre-check, avoid Mutex storm.
648        let now_ns = self.now_ns();
649        let last = self.signal.last_cut_ns.load(Relaxed);
650        if last != 0 && now_ns.saturating_sub(last) < REFRACTORY.as_nanos() as u64 {
651            return;
652        }
653
654        // Locking fast-path (2): check the authoritative `last_cut` in AimdState.
655        let now = Instant::now();
656        let mut state = self.state.lock().unwrap();
657        if state
658            .last_cut_time
659            .is_some_and(|t| now.duration_since(t) < REFRACTORY)
660        {
661            return;
662        }
663
664        // Calculate anchor rate, which is our (conservative) estimate for the unknown rate-limit enforced
665        // by the back-end.
666        let rate = state.rate();
667        let (anchor, beta) = match state.success_rate {
668            Some(success_rate) => (rate.min(success_rate.max(self.config.floor_rate)), BETA),
669            // Reads without an EWMA (e.g. before the first settled tick): the goodput so far if it
670            // reaches the initial rate, else the initial rate.
671            None if self.config.follows => match self.goodput_so_far(&state, now) {
672                Some(goodput) if goodput >= self.config.init_rate => (rate.min(goodput), BETA),
673                _ => (rate.min(self.config.init_rate), BETA_NO_SIGNAL),
674            },
675            None => (rate, BETA_NO_SIGNAL),
676        };
677
678        // Activate new rate and update state.
679        state.set_rate((anchor * beta).max(self.config.floor_rate));
680        state.last_cut_time = Some(now);
681        self.signal.last_cut_ns.store(now_ns, Relaxed);
682
683        // Unconditionally move into Recover on every cut.
684        state.regime = Regime::Recover {
685            until: now.checked_add(PROBE_QUIET_PERIOD).unwrap(),
686            anchor,
687        };
688
689        // Log.
690        if *LOG_HTTP_RATE_LIMIT {
691            eprintln!(
692                "[http rate_limit #{}_{} {}] ..cut (anchored): rate: {:.1}, success_rate: {:.1}, last_max: {:.1}",
693                self.id,
694                self.label,
695                Utc::now(),
696                state.rate(),
697                state.success_rate.unwrap_or_default(),
698                state.last_max().unwrap_or_default(),
699            );
700        }
701    }
702
703    fn on_success(&self) {
704        self.signal.resp_succeeded.fetch_add(1, Relaxed);
705
706        self.mark_first_traffic();
707        self.maybe_settle();
708    }
709
710    fn on_other(&self) {
711        self.mark_first_traffic();
712        self.maybe_settle();
713    }
714
715    #[inline]
716    fn maybe_settle(&self) {
717        // Lock-free fast path when neither is due.
718        let now_ns = self.now_ns();
719        if now_ns >= self.signal.check_end_ns.load(Relaxed) {
720            self.fast_check();
721        }
722        if now_ns >= self.signal.window_end_ns.load(Relaxed) {
723            self.settle_lazy_tick();
724        }
725    }
726
727    // Before the first throttle, reads raise the rate to at least `FOLLOW_FACTOR` x the demand since
728    // the previous check. In Track, a busy and throttle-free check grows the rate.
729    fn fast_check(&self) {
730        let mut state = self.state.lock().unwrap();
731        let now_ns = self.now_ns();
732
733        // Another response may have run the check while we waited on the lock.
734        if now_ns < self.signal.check_end_ns.load(Relaxed) {
735            return;
736        }
737
738        let admitted = self.pacer.admitted();
739        let win_admitted = admitted.saturating_sub(state.check_prev_admitted);
740        state.check_prev_admitted = admitted;
741        let throttled = self.signal.resp_throttled.load(Relaxed);
742        let win_throttled = throttled.saturating_sub(state.check_prev_throttled);
743        state.check_prev_throttled = throttled;
744        let elapsed_s = now_ns.saturating_sub(state.check_prev_ns) as f64 / 1e9;
745        state.check_prev_ns = now_ns;
746        let demand = win_admitted as f64 / elapsed_s.max(1e-3);
747        state.demand = Some(demand);
748
749        if let Regime::Recover { until, anchor } = state.regime
750            && Instant::now() > until
751        {
752            state.regime = Regime::Track { anchor };
753        }
754
755        let rate = state.rate();
756        let new_rate = match state.regime {
757            Regime::Search if self.follows() => FOLLOW_FACTOR * demand,
758            Regime::Track { anchor }
759                if win_throttled == 0 && demand >= SATURATION_THRESHOLD * rate =>
760            {
761                if rate < anchor {
762                    (rate * RECLAIM_STEP).min(anchor)
763                } else if rate < FAR_FACTOR * anchor {
764                    rate * (1.0 + PROBE_STEP)
765                } else {
766                    rate * (1.0 + FAR_PROBE_STEP)
767                }
768            },
769            _ => rate,
770        }
771        .min(self.config.ceiling_rate);
772        if new_rate > rate {
773            state.set_rate(new_rate);
774            state.raises += 1;
775        }
776
777        self.signal
778            .check_end_ns
779            .store(now_ns + self.check_interval().as_nanos() as u64, Relaxed);
780    }
781
782    /// Successes per second since the window started, given at least `FIRST_CUT_MIN_ELAPSED` and
783    /// `FIRST_CUT_MIN_SUCCESSES`.
784    fn goodput_so_far(&self, state: &AimdState, now: Instant) -> Option<f64> {
785        let elapsed = now.duration_since(state.window_start?);
786        let successes = self
787            .signal
788            .resp_succeeded
789            .load(Relaxed)
790            .saturating_sub(state.prev_resp_succeeded);
791        (elapsed >= FIRST_CUT_MIN_ELAPSED && successes >= FIRST_CUT_MIN_SUCCESSES)
792            .then(|| successes as f64 / elapsed.as_secs_f64())
793    }
794
795    // Settle the rate-limiter after every tick interval, on the first success response.
796    fn settle_lazy_tick(&self) {
797        let mut state = self.state.lock().unwrap();
798        let now = Instant::now();
799        let now_ns = self.now_ns();
800
801        // Another success event may have settled while we waited on the lock.
802        let elapsed = now.duration_since(state.window_start.unwrap());
803        let ticks = (elapsed.as_secs_f64() / TICK_INTERVAL.as_secs_f64()).floor();
804        if ticks < 1.0 {
805            return;
806        }
807
808        // Update AIMD stats.
809        let admitted = self.pacer.admitted();
810        let win_admitted = admitted.saturating_sub(state.prev_admitted);
811        state.prev_admitted = admitted;
812
813        let denied = self.pacer.denied.load(Relaxed);
814        let win_denied = denied.saturating_sub(state.prev_denied);
815        state.prev_denied = denied;
816
817        let succeeded = self.signal.resp_succeeded.load(Relaxed);
818        let win_succeeded = succeeded.saturating_sub(state.prev_resp_succeeded);
819        state.prev_resp_succeeded = succeeded;
820
821        let throttled = self.signal.resp_throttled.load(Relaxed);
822        let win_throttled = throttled.saturating_sub(state.prev_resp_throttled);
823        state.prev_resp_throttled = throttled;
824
825        // Growth conditions.
826        let elapsed_s = elapsed.as_secs_f64();
827        let util_bound = win_admitted as f64 >= SATURATION_THRESHOLD * state.rate() * elapsed_s;
828
829        // Update signal, if any. A window of two or more ticks spans a gap without responses, which
830        // would dilute the success rate.
831        if ticks < 2.0 {
832            state.update_success_rate(win_succeeded, elapsed_s);
833        }
834
835        // Goodput is always a lower bound on capacity, so an observation may always
836        // increase. It may only decrease when the system was pressure-tested (i.e., demand saturated).
837        if let Some(observed) = state.success_rate {
838            let pressure_tested =
839                win_admitted as f64 / elapsed_s >= state.last_max().unwrap_or(0.0);
840            let new_max = match state.last_max() {
841                Some(prev) if !pressure_tested => prev.max(observed),
842                _ => observed,
843            };
844            state.set_last_max(Some(new_max.max(self.config.floor_rate)));
845        }
846
847        // Evaluate and apply rate and regime changes.
848        let verdict = {
849            let rate = state.rate();
850            let init_rate = self.config.init_rate;
851            let floor_rate = self.config.floor_rate;
852            let ceiling_rate = self.config.ceiling_rate;
853
854            if win_admitted + win_denied == 0 {
855                // No demand - decay toward seed only if we are currently above it.
856                if rate > init_rate {
857                    let rate = init_rate + (state.rate() - init_rate) * IDLE_DECAY.powf(ticks);
858                    state.set_rate(rate.clamp(floor_rate, ceiling_rate));
859                }
860                // Note: we leave last_max as-is which is not always right.
861                "decay (idle)"
862            } else {
863                match state.regime {
864                    Regime::Search => {
865                        // Cold start -> aggressive exponential growth, if earned
866                        // Note. One may expect `.powf(ticks)`; this is deliberately omitted.
867                        if util_bound && win_throttled == 0 {
868                            state.set_rate((rate * FAST_RAMP_FACTOR).min(ceiling_rate));
869                            "increase (fast_ramp)"
870                        } else {
871                            "hold (app-limited)"
872                        }
873                    },
874                    Regime::Recover { .. } => {
875                        // No-op, rate changes were handled in `on_congestion`
876                        "hold (recover)"
877                    },
878                    // Grows in `fast_check`.
879                    Regime::Track { .. } => "track",
880                }
881            }
882        };
883
884        // Update state.
885        state.window_start = Some(now);
886        self.signal
887            .window_end_ns
888            .store(now_ns + TICK_INTERVAL.as_nanos() as u64, Relaxed);
889
890        // Logging.
891        let raises = std::mem::take(&mut state.raises);
892        if *LOG_HTTP_RATE_LIMIT {
893            let stall = self.signal.stall.take();
894            eprintln!(
895                "[http rate_limit #{}_{} {}] {}: rate: {:.1}, success_rate_ewma: {:.1}, last_max: {:.1}, \
896                    elapsed: {:.1}s, win_admit: {}, win_deny: {}, win_success: {}, win_throttle: {},  q_depth: {}, \
897                    demand: {:.1}, raises: {}, win_stall_hdr: {}, win_stall_body: {}, win_stall_refused: {}, \
898                    stall_t: {:.1}ms",
899                self.id,
900                self.label,
901                Utc::now(),
902                verdict,
903                state.rate(),
904                state.success_rate.unwrap_or_default(),
905                state.last_max().unwrap_or_default(),
906                elapsed_s,
907                win_admitted,
908                win_denied,
909                win_succeeded,
910                win_throttled,
911                self.pacer.queue_depth(),
912                state.demand.unwrap_or_default(),
913                raises,
914                stall.hdr_abandons,
915                stall.body_abandons,
916                stall.refused,
917                stall.t.as_secs_f64() * 1e3,
918            );
919        }
920    }
921}
922
923/// Grouped rate-limit controller as used by a logical object_store instance.
924#[derive(Debug)]
925pub(crate) struct RateController {
926    // GET, HEAD
927    pub read: AdaptiveRateController,
928    // PUT, POST, DELETE
929    pub write: AdaptiveRateController,
930}
931
932impl RateController {
933    pub(crate) fn new(rate_limiter: &RateLimiter) -> Arc<Self> {
934        // NOTE: A rebuilt object_store can share one rate state.
935        // Acceptable transient situation.
936        let id = CONTROLLER_ID.fetch_add(1, Relaxed);
937        Arc::new(Self {
938            read: AdaptiveRateController::new(
939                "read",
940                id,
941                rate_limiter.state.read_state.clone(),
942                rate_limiter.config.read.clone(),
943            ),
944            write: AdaptiveRateController::new(
945                "write",
946                id,
947                rate_limiter.state.write_state.clone(),
948                rate_limiter.config.write.clone(),
949            ),
950        })
951    }
952
953    fn class(&self, req: &HttpRequest) -> &AdaptiveRateController {
954        match req.method().as_str() {
955            "GET" | "HEAD" => &self.read,
956            _ => &self.write,
957        }
958    }
959}
960
961#[derive(Debug)]
962struct PacerBusy {
963    est_wait_ms: u64,
964}
965impl fmt::Display for PacerBusy {
966    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
967        write!(
968            f,
969            "internal pacer denied: estimated wait {}ms exceeds bound",
970            self.est_wait_ms
971        )
972    }
973}
974impl std::error::Error for PacerBusy {}
975
976// PACER INCL WAITER_QUEUE
977
978// The pacer is responsible for admission/denial into the `TokenBucket` annex
979// `WaiterQueue`. Once admitted, it paces the requests to the prescribed rate.
980
981#[derive(Debug, Default)]
982struct WaiterQueue {
983    parked: Mutex<VecDeque<oneshot::Sender<()>>>,
984    /// Lock-free mirror of parked.len(): read by the fast path (anti-barge),
985    /// the population coupling, and telemetry.
986    depth: AtomicU64,
987}
988
989impl WaiterQueue {
990    fn park(&self) -> oneshot::Receiver<()> {
991        let (tx, rx) = oneshot::channel();
992        let mut q = self.parked.lock().unwrap();
993        q.push_back(tx);
994        self.depth.store(q.len() as u64, Relaxed);
995        rx
996    }
997
998    /// Pop the head and deliver a grant. Returns false when the queue is
999    /// empty. A dead (cancelled) head consumes no grant: we skip it and keep
1000    /// the token for the next live waiter.
1001    fn grant_one(&self) -> bool {
1002        let mut q = self.parked.lock().unwrap();
1003        while let Some(tx) = q.pop_front() {
1004            self.depth.store(q.len() as u64, Relaxed);
1005            if tx.send(()).is_ok() {
1006                return true; // grant delivered
1007            }
1008            // Cancelled waiter: token still in hand, try the next.
1009        }
1010        false
1011    }
1012
1013    fn depth(&self) -> u64 {
1014        self.depth.load(Relaxed)
1015    }
1016}
1017
1018/// Lock-free hot path enforcing the rate-limit by pacing requests through the token bucket.
1019#[derive(Debug)]
1020pub struct Pacer {
1021    bucket: Arc<TokenBucket>,
1022    queue: Arc<WaiterQueue>,
1023    max_wait: Duration,
1024    // Decided to admit.
1025    admitted: AtomicU64,
1026    // Decided to admit, across rebuilds (`PacingBudget::admitted`).
1027    admitted_total: Arc<AtomicU64>,
1028    // Decided not to park.
1029    denied: AtomicU64,
1030}
1031
1032impl Pacer {
1033    /// Construct and spawn the wake tick. The tick is per-pacer.
1034    pub fn start(
1035        bucket: Arc<TokenBucket>,
1036        max_wait: Duration,
1037        admitted_total: Arc<AtomicU64>,
1038    ) -> Arc<Self> {
1039        let pacer = Arc::new(Self {
1040            bucket,
1041            queue: Arc::new(WaiterQueue::default()),
1042            max_wait,
1043            admitted: AtomicU64::new(0),
1044            admitted_total,
1045            denied: AtomicU64::new(0),
1046        });
1047        Self::spawn_wake_tick(Arc::downgrade(&pacer));
1048        pacer
1049    }
1050
1051    /// Admit a request to the pacer, which may get queued internally. Returns a
1052    /// PacerBusy Error when the estimated wait exceeds the wait bound.
1053    pub async fn admit(&self) -> Result<(), HttpError> {
1054        // Anti-barge plus fast path.
1055        if self.queue.depth() == 0 && self.bucket.try_acquire().is_ok() {
1056            self.admitted.fetch_add(1, Relaxed);
1057            self.admitted_total.fetch_add(1, Relaxed);
1058            return Ok(());
1059        }
1060
1061        // JIT rejection: price the line, before parking.
1062        let est_wait =
1063            Duration::from_secs_f64((self.queue.depth() + 1) as f64 / self.bucket.rate());
1064        if est_wait > self.max_wait {
1065            self.denied.fetch_add(1, Relaxed);
1066            return Err(HttpError::new(
1067                HttpErrorKind::Timeout, // retryable by object_store
1068                PacerBusy {
1069                    est_wait_ms: est_wait.as_millis() as u64,
1070                },
1071            ));
1072        }
1073
1074        // Park. Wake when granted.
1075        let rx = self.queue.park();
1076
1077        // Wait. On Err, allow through unpaced when WaiterQueue/Pacer is torn down.
1078        let _ = rx.await;
1079        self.admitted.fetch_add(1, Relaxed);
1080        self.admitted_total.fetch_add(1, Relaxed);
1081        Ok(())
1082    }
1083
1084    pub fn queue_depth(&self) -> u64 {
1085        self.queue.depth()
1086    }
1087
1088    pub fn admitted(&self) -> u64 {
1089        self.admitted.load(Relaxed)
1090    }
1091
1092    pub fn bucket(&self) -> &Arc<TokenBucket> {
1093        &self.bucket
1094    }
1095
1096    /// The single timer in the design. Each tick: while waiters exist AND the
1097    /// bucket yields a token, hand grants to the FIFO head. Weak handle so a
1098    /// dropped pacer (store rebuild) tears its tick down with it.
1099    fn spawn_wake_tick(gate: std::sync::Weak<Self>) {
1100        ASYNC.spawn(async move {
1101            let mut tick = tokio::time::interval(HTTP_RATE_LIMIT_WAKE_TICK);
1102            tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
1103            loop {
1104                tick.tick().await;
1105                let Some(g) = gate.upgrade() else { return };
1106
1107                while g.queue.depth() > 0 {
1108                    if g.bucket.try_acquire().is_err() {
1109                        break;
1110                    }
1111                    if !g.queue.grant_one() {
1112                        // Queue drained between the depth check and the grant
1113                        // (or all-cancelled): one token over-taken.
1114                        break;
1115                    }
1116                }
1117            }
1118        });
1119    }
1120}
1121
1122// OBJECT_STORE HTTP_SERVICE MIDDLEWARE
1123
1124#[derive(Debug)]
1125pub(crate) struct PacedHttpConnector {
1126    inner: Box<dyn HttpConnector>,
1127    controller: Arc<RateController>,
1128}
1129
1130impl PacedHttpConnector {
1131    pub(crate) fn new(inner: Box<dyn HttpConnector>, rate_limiter: &RateLimiter) -> Self {
1132        // The HTTP Connector may re-use its learned request rate.
1133        rate_limiter.apply_init_policy();
1134
1135        Self {
1136            inner,
1137            controller: RateController::new(rate_limiter),
1138        }
1139    }
1140}
1141
1142impl HttpConnector for PacedHttpConnector {
1143    fn connect(&self, options: &ClientOptions) -> object_store::Result<HttpClient> {
1144        let client = self.inner.connect(options)?;
1145        Ok(HttpClient::new(PacedHttpService {
1146            inner: client,
1147            controller: Arc::clone(&self.controller),
1148        }))
1149    }
1150}
1151
1152#[derive(Debug)]
1153pub(crate) struct PacedHttpService {
1154    inner: HttpClient,
1155    controller: Arc<RateController>,
1156}
1157
1158#[async_trait]
1159impl HttpService for PacedHttpService {
1160    async fn call(&self, req: HttpRequest) -> Result<HttpResponse, HttpError> {
1161        let verb_pacer = self.controller.class(&req);
1162
1163        // Enforce pacing: on admission, wait; on denied, raise an error.
1164        // Requests get denied when the estimated wait is too high (aka 'shed').
1165        // The object_store is responsible for retry.
1166        verb_pacer.pacer.admit().await?;
1167
1168        let stall_timer = StallTimer::start(&req, &verb_pacer.signal.stall);
1169        let response = match &stall_timer {
1170            Some(timer) => Box::pin(timer.headers(self.inner.execute(req))).await,
1171            None => self.inner.execute(req).await,
1172        };
1173        match &response {
1174            Ok(r) if r.status().as_u16() == 429 || r.status().as_u16() == 503 => {
1175                verb_pacer.on_congestion()
1176            },
1177            Ok(r) if r.status().is_success() => verb_pacer.on_success(),
1178            _ => verb_pacer.on_other(),
1179        }
1180
1181        match stall_timer {
1182            Some(timer) => timer.body(response),
1183            None => response,
1184        }
1185    }
1186}