saluki_core/accounting/limiter.rs
1use std::{
2 sync::{
3 atomic::{AtomicU64, Ordering::Relaxed},
4 Arc, OnceLock,
5 },
6 time::Duration,
7};
8
9use metrics::{counter, gauge, Counter};
10use process_memory::Querier;
11use tracing::{debug, info, warn};
12
13use super::MemoryGrant;
14
15/// How often the checker thread samples the process's memory usage.
16const CHECK_INTERVAL: Duration = Duration::from_millis(250);
17
18/// A process-wide memory limiter.
19///
20/// In many cases, it can be useful to know when the process has exceeded a certain memory usage threshold in order to
21/// be able to react that: clearing caches, temporarily blocking requests, and so on.
22///
23/// `MemoryLimiter` watches the process's physical memory usage (Resident Set Size/Working Set) and keeps track of when
24/// the usage approaches the configured limit. Cooperating tasks call `wait_for_capacity` to participate in accepting
25/// backpressure that can be used to throttle work that's responsible for allocating memory.
26///
27/// The backpressure is scaled based on how close the memory usage is to the configured limit, with a minimum and
28/// maximum backoff duration that's applied. Until usage crosses a starting threshold, no backpressure is applied. Past
29/// that threshold, backpressure grows proportionally until it reaches its maximum at a second, higher threshold. Once
30/// throttling has started, it continues at the minimum backoff until usage falls below a lower clearing threshold, so
31/// that usage hovering around the starting threshold doesn't flap between throttling and not throttling. Callers are
32/// never fully blocked, even if the limit is reached.
33///
34/// Throttling is logged when it starts and when it clears, and is reported through internal metrics: the current
35/// backoff, the number of throttled calls, and the total time callers were throttled.
36#[derive(Clone)]
37pub struct MemoryLimiter {
38 active_backoff_nanos: Arc<AtomicU64>,
39 throttle_counters: Arc<OnceLock<ThrottleCounters>>,
40}
41
42/// Counters for the calls that the memory limiter throttles.
43///
44/// The handles are held for the limiter's lifetime. A counter whose handles are all dropped is evicted from internal
45/// metrics once it stops changing, which would reset the throttling totals shortly after throttling stops.
46struct ThrottleCounters {
47 calls: Counter,
48 nanoseconds: Counter,
49}
50
51impl ThrottleCounters {
52 fn new() -> Self {
53 Self {
54 calls: counter!("memory_limiter.throttled_calls_total"),
55 nanoseconds: counter!("memory_limiter.throttled_nanoseconds_total"),
56 }
57 }
58}
59
60impl MemoryLimiter {
61 /// Creates a new `MemoryLimiter` based on the given `MemoryGrant`.
62 ///
63 /// A background task is spawned that frequently checks the used memory for the entire process, and callers of
64 /// `wait_for_capacity` will observe waiting once the memory usage approaches the grant's initial limit. The waiting
65 /// time will scale progressively the closer the memory usage is to the limit.
66 ///
67 /// The thresholds are measured against the grant's initial limit rather than its effective limit: the slop factor
68 /// is headroom for memory bounds verification, and applying it here as well would start throttling well before the
69 /// process is actually close to its limit. Throttling starts above 85% of the limit, reaches its maximum at 95%, and
70 /// clears once usage falls to 75% or below. The backoff ranges from 1 ms to 25 ms.
71 pub fn new(grant: MemoryGrant) -> Option<Self> {
72 // Smoke test to see if we can even collect memory stats on this system.
73 Querier::default().resident_set_size()?;
74
75 let policy = BackoffPolicy {
76 rss_limit: grant.initial_limit_bytes(),
77 start_ratio: 0.85,
78 full_ratio: 0.95,
79 clear_ratio: 0.75,
80 backoff_min: Duration::from_millis(1),
81 backoff_max: Duration::from_millis(25),
82 };
83
84 let active_backoff_nanos = Arc::new(AtomicU64::new(0));
85 let active_backoff_nanos2 = Arc::clone(&active_backoff_nanos);
86
87 std::thread::Builder::new()
88 .name("memory-limiter-checker".to_string())
89 .spawn(move || check_memory_usage(active_backoff_nanos2, policy))
90 .unwrap();
91
92 Some(Self {
93 active_backoff_nanos,
94 throttle_counters: Arc::new(OnceLock::new()),
95 })
96 }
97
98 /// Creates a no-op `MemoryLimiter` that doesn't perform any limiting.
99 ///
100 /// All calls to `wait_for_capacity` will return immediately.
101 pub fn noop() -> Self {
102 Self {
103 active_backoff_nanos: Arc::new(AtomicU64::new(0)),
104 throttle_counters: Arc::new(OnceLock::new()),
105 }
106 }
107
108 /// Waits a short period of time based on the available memory.
109 ///
110 /// If the used memory isn't within the threshold of the configured limit, no waiting will occur. Otherwise, the
111 /// call will wait a variable amount of time depending on how close to the configured limit the process is.
112 pub async fn wait_for_capacity(&self) {
113 let active_backoff_nanos = self.active_backoff_nanos.load(Relaxed);
114 if active_backoff_nanos > 0 {
115 // The counters are registered on the first throttled call rather than at construction, so that they're
116 // registered with the metrics recorder even if the limiter was created before the recorder was installed.
117 let counters = self.throttle_counters.get_or_init(ThrottleCounters::new);
118 counters.calls.increment(1);
119 counters.nanoseconds.increment(active_backoff_nanos);
120
121 tokio::time::sleep(Duration::from_nanos(active_backoff_nanos)).await;
122 }
123 }
124}
125
126/// When, and how hard, the memory limiter throttles callers.
127#[derive(Clone, Copy, Debug)]
128struct BackoffPolicy {
129 /// Memory limit, in bytes, that the ratios are measured against.
130 rss_limit: usize,
131
132 /// Fraction of the limit above which throttling starts, at the minimum backoff.
133 start_ratio: f64,
134
135 /// Fraction of the limit at which the backoff reaches its maximum.
136 full_ratio: f64,
137
138 /// Fraction of the limit at or below which active throttling clears.
139 clear_ratio: f64,
140
141 /// Backoff applied just above the starting threshold, and while throttling hasn't yet cleared.
142 backoff_min: Duration,
143
144 /// Backoff applied at or above the full threshold.
145 backoff_max: Duration,
146}
147
148impl BackoffPolicy {
149 /// Calculates the backoff to apply for the given memory usage.
150 ///
151 /// `throttling` is whether a backoff was applied for the previous sample. While usage sits between the clearing and
152 /// starting thresholds, it keeps throttling active at the minimum backoff.
153 fn calculate_backoff(&self, actual_rss: usize, throttling: bool) -> Option<Duration> {
154 let limit = self.rss_limit as f64;
155 let actual = actual_rss as f64;
156 let start = limit * self.start_ratio;
157
158 if actual > start {
159 // Spread the backoff range across the band between the starting and full thresholds.
160 //
161 // For example, with minimum/maximum backoff durations of 100ms/1000ms, a 100MB limit, and a band of 85% to
162 // 95%, we back off by just over 100ms past 85MB, and by 1000ms at 95MB or above. At 90MB, halfway through
163 // the band, we back off by 100ms + (0.5 * 900ms) => 550ms.
164 let band = limit * (self.full_ratio - self.start_ratio);
165 let position = ((actual - start) / band).min(1.0);
166 let backoff_range = self.backoff_max - self.backoff_min;
167 Some(self.backoff_min + backoff_range.mul_f64(position))
168 } else if throttling && actual > limit * self.clear_ratio {
169 Some(self.backoff_min)
170 } else {
171 None
172 }
173 }
174}
175
176fn check_memory_usage(active_backoff_nanos: Arc<AtomicU64>, policy: BackoffPolicy) {
177 debug!("Memory limiter checker started.");
178
179 let mut querier = Querier::default();
180 let mut throttling = false;
181
182 loop {
183 let actual_rss = querier
184 .resident_set_size()
185 .expect("memory statistics should be available");
186
187 let maybe_backoff = policy.calculate_backoff(actual_rss, throttling);
188 log_transition(&policy, actual_rss, throttling, maybe_backoff);
189 throttling = maybe_backoff.is_some();
190
191 let backoff = maybe_backoff.unwrap_or_default();
192 active_backoff_nanos.store(backoff.as_nanos() as u64, Relaxed);
193 gauge!("memory_limiter.current_backoff_secs").set(backoff.as_secs_f64());
194
195 if throttling {
196 debug!(rss_limit = policy.rss_limit, actual_rss, current_backoff = ?backoff, "Enforcing backoff due to memory pressure.");
197 }
198
199 std::thread::sleep(CHECK_INTERVAL);
200 }
201}
202
203/// Logs when throttling starts or clears.
204///
205/// Logging only on transitions keeps sustained memory pressure from flooding the logs while still surfacing it at the
206/// default log level. The clearing threshold keeps usage that hovers around the starting threshold from logging on
207/// every check.
208fn log_transition(policy: &BackoffPolicy, actual_rss: usize, was_throttling: bool, backoff: Option<Duration>) {
209 let usage_pct = actual_rss as f64 / policy.rss_limit as f64 * 100.0;
210 match (was_throttling, backoff) {
211 (false, Some(backoff)) => warn!(
212 rss_limit = policy.rss_limit,
213 actual_rss,
214 current_backoff = ?backoff,
215 "Memory usage is at {:.1}% of the memory limit. Throttling ingestion until it falls to {:.0}%.",
216 usage_pct,
217 policy.clear_ratio * 100.0,
218 ),
219 (true, None) => info!(
220 rss_limit = policy.rss_limit,
221 actual_rss, "Memory usage is at {:.1}% of the memory limit. No longer throttling ingestion.", usage_pct,
222 ),
223 _ => {}
224 }
225}
226
227#[cfg(test)]
228mod tests {
229 use std::sync::atomic::Ordering::Relaxed;
230 use std::time::Duration;
231
232 use super::{BackoffPolicy, MemoryLimiter};
233
234 // These cases reproduce the worked example from `calculate_backoff`'s own comment: minimum/maximum backoff durations
235 // of 100ms/1000ms, a 100MB limit, and a band of 85% to 95%, clearing at 75%. The comment promises specific values at
236 // specific fractions of the limit, so we assert those exact durations rather than merely that a backoff was
237 // produced.
238 const MIN: Duration = Duration::from_millis(100);
239 const MAX: Duration = Duration::from_millis(1000);
240 const POLICY: BackoffPolicy = BackoffPolicy {
241 rss_limit: 100_000_000,
242 start_ratio: 0.85,
243 full_ratio: 0.95,
244 clear_ratio: 0.75,
245 backoff_min: MIN,
246 backoff_max: MAX,
247 };
248
249 fn backoff_at(actual_rss: usize) -> Option<Duration> {
250 POLICY.calculate_backoff(actual_rss, false)
251 }
252
253 fn backoff_while_throttling_at(actual_rss: usize) -> Option<Duration> {
254 POLICY.calculate_backoff(actual_rss, true)
255 }
256
257 #[test]
258 fn no_backoff_below_or_at_starting_threshold() {
259 // Well below the threshold: no backpressure at all.
260 assert_eq!(backoff_at(70_000_000), None);
261
262 // Between the clearing and starting thresholds, throttling doesn't start.
263 assert_eq!(backoff_at(83_000_000), None);
264
265 // Exactly at the 85% threshold: the comparison is strictly greater-than, so still no backoff.
266 assert_eq!(backoff_at(85_000_000), None);
267 }
268
269 #[test]
270 fn backoff_scales_linearly_across_the_band() {
271 // Halfway through the 85%..95% band, the backoff is the minimum (100ms) plus half of the 900ms range (450ms).
272 assert_eq!(backoff_at(90_000_000), Some(Duration::from_millis(550)));
273 }
274
275 #[test]
276 fn backoff_saturates_at_the_full_threshold() {
277 // At exactly 95% of the limit we reach the far end of the band, which is the maximum backoff.
278 assert_eq!(backoff_at(95_000_000), Some(MAX));
279
280 // Beyond the full threshold, and beyond the limit itself, the backoff is clamped to the maximum.
281 assert_eq!(backoff_at(99_000_000), Some(MAX));
282 assert_eq!(backoff_at(120_000_000), Some(MAX));
283 }
284
285 #[test]
286 fn active_throttling_holds_the_minimum_until_usage_clears() {
287 // Once throttling, falling back below the starting threshold keeps the minimum backoff, so that usage hovering
288 // around the starting threshold doesn't toggle throttling on every check.
289 assert_eq!(backoff_while_throttling_at(85_000_000), Some(MIN));
290 assert_eq!(backoff_while_throttling_at(76_000_000), Some(MIN));
291
292 // At or below the clearing threshold, throttling stops.
293 assert_eq!(backoff_while_throttling_at(75_000_000), None);
294 assert_eq!(backoff_while_throttling_at(50_000_000), None);
295
296 // Above the starting threshold, the backoff follows the band regardless of the previous state.
297 assert_eq!(
298 backoff_while_throttling_at(90_000_000),
299 Some(Duration::from_millis(550))
300 );
301 }
302
303 #[tokio::test]
304 async fn throttle_counter_handles_outlive_the_throttled_call() {
305 // Internal metrics evict a counter once none of its handles are alive and it stops changing, so the limiter
306 // must keep its throttling counters alive after a throttled call. Otherwise the totals reported on the status
307 // page would reset to zero shortly after throttling stops.
308 let limiter = MemoryLimiter::noop();
309 let clone = limiter.clone();
310
311 limiter.wait_for_capacity().await;
312 assert!(
313 limiter.throttle_counters.get().is_none(),
314 "an unthrottled call shouldn't register the counters"
315 );
316
317 limiter.active_backoff_nanos.store(1, Relaxed);
318 limiter.wait_for_capacity().await;
319
320 assert!(limiter.throttle_counters.get().is_some());
321 assert!(
322 clone.throttle_counters.get().is_some(),
323 "clones of a limiter share its counters"
324 );
325 }
326}