seiva_http/backpressure.rs
1//! Per-route load control: a request **timeout** (→ `504 Gateway Timeout`) and a
2//! **concurrency limit with immediate shedding** (→ `503 Service Unavailable`),
3//! applied per route so one slow or heavy endpoint cannot pin every worker while
4//! the rest of the service stays responsive.
5//!
6//! # Why this exists (OWASP API4)
7//!
8//! The framework already bounds *one* request's body size ([`router`](crate::router))
9//! and the *rate* of requests from one client ([`rate_limit`](mod@crate::rate_limit),
10//! `429`). Neither bounds the **work in flight** for a single route: a reporting
11//! endpoint that takes seconds, or a write that stalls on a slow dependency, can
12//! accumulate requests until the whole pool is blocked and healthy routes start
13//! failing too. OWASP API Security **API4 (Unrestricted Resource Consumption)**
14//! asks the service to bound that. This primitive does, per route:
15//!
16//! - **Timeout.** A request to a controlled route that outlives its configured
17//! budget is cut off with `504` — distinct from the framework's global
18//! `408 Request Timeout` (a slowloris guard on the whole service). The `504`
19//! says "this route's own deadline was exceeded", the operator-facing meaning
20//! of a gateway deadline.
21//! - **Backpressure.** Each in-flight request to a controlled route holds one
22//! permit of a fixed-size [`Semaphore`]. At capacity the next request is shed
23//! **immediately** (`try_acquire`, never queued) with `503` — fail fast rather
24//! than let work pile up unbounded. A `503` is the load balancer's cue to
25//! retry elsewhere or back off, and it keeps the route's latency bounded for
26//! the requests already admitted.
27//!
28//! # Per route, composed at the root
29//!
30//! A [`RouteControls`] maps path prefixes to [`RouteLimit`]s (longest prefix
31//! wins), and [`with_route_controls`] wraps a router in the middleware that
32//! enforces them. The composition root applies it to the **module** sub-router
33//! before the framework layers wrap it, so control runs *after* the caller is
34//! authenticated (an admitted caller) but *around* each route's own work. A route
35//! with no matching rule is untouched — the control is opt-in per endpoint, the
36//! tower-level counterpart to the opt-in [`DistributedRateLimit`](crate::DistributedRateLimit).
37//!
38//! ```no_run
39//! use std::time::Duration;
40//! use seiva_http::{with_route_controls, RouteControls, RouteLimit};
41//!
42//! # let modules = axum::Router::new();
43//! // Writes under `/v1/projects` must answer within 2 s and run at most 64 at a
44//! // time; past either bound the caller gets a `504`/`503` instead of a stuck worker.
45//! let controls = RouteControls::new().route(
46//! "/v1/projects",
47//! RouteLimit::new().timeout(Duration::from_secs(2)).max_in_flight(64),
48//! );
49//! let modules = with_route_controls(modules, controls);
50//! ```
51
52use std::sync::Arc;
53use std::time::Duration;
54
55use axum::extract::{Request, State};
56use axum::http::{HeaderValue, StatusCode};
57use axum::middleware::{from_fn_with_state, Next};
58use axum::response::{IntoResponse, Response};
59use axum::Router;
60use tokio::sync::Semaphore;
61
62use crate::problem::{Problem, ProblemResponse};
63use crate::request_id::RequestIdExt;
64
65/// The `Retry-After` (seconds) a shed `503` suggests before retrying. Small on
66/// purpose: a concurrency breach is transient — the permit frees the moment an
67/// in-flight request finishes.
68const BACKPRESSURE_RETRY_AFTER: HeaderValue = HeaderValue::from_static("1");
69
70/// The load-control limits for one route: an optional per-request `timeout`
71/// (breach → `504`) and an optional `max_in_flight` concurrency cap (breach →
72/// `503`). Either, both, or neither; an empty `RouteLimit` is a no-op.
73#[derive(Debug, Clone, Default)]
74pub struct RouteLimit {
75 timeout: Option<Duration>,
76 max_in_flight: Option<usize>,
77}
78
79impl RouteLimit {
80 /// An empty limit (no timeout, no concurrency cap). Build it up with
81 /// [`RouteLimit::timeout`] / [`RouteLimit::max_in_flight`].
82 #[must_use]
83 pub fn new() -> Self {
84 Self::default()
85 }
86
87 /// Cut a request off with `504` if it outlives `budget`.
88 #[must_use]
89 pub fn timeout(mut self, budget: Duration) -> Self {
90 self.timeout = Some(budget);
91 self
92 }
93
94 /// Admit at most `max` concurrent requests to this route; shed the rest with
95 /// `503` (fail fast, never queue). `0` is clamped to `1` so a route is never
96 /// wedged shut by a typo.
97 #[must_use]
98 pub fn max_in_flight(mut self, max: usize) -> Self {
99 self.max_in_flight = Some(max.max(1));
100 self
101 }
102}
103
104/// One compiled rule: a path prefix, its timeout, and — if a concurrency cap was
105/// set — the shared semaphore that enforces it across every request to the route.
106#[derive(Clone)]
107struct Rule {
108 prefix: String,
109 timeout: Option<Duration>,
110 semaphore: Option<Arc<Semaphore>>,
111}
112
113/// A set of per-route load-control rules. Each [`route`](RouteControls::route)
114/// adds a prefix → [`RouteLimit`] mapping; at request time the **longest**
115/// matching prefix wins, so a specific `/v1/projects/export` rule overrides a
116/// broad `/v1` one. Cheap to clone (the semaphores are shared behind `Arc`).
117#[derive(Clone, Default)]
118pub struct RouteControls {
119 rules: Vec<Rule>,
120}
121
122impl RouteControls {
123 /// An empty rule set — [`with_route_controls`] with this is a no-op.
124 #[must_use]
125 pub fn new() -> Self {
126 Self::default()
127 }
128
129 /// Apply `limit` to every request whose path starts with `prefix`. The
130 /// concurrency cap (if any) is materialised into one shared semaphore here,
131 /// so all requests to the route draw from the SAME budget.
132 #[must_use]
133 pub fn route(mut self, prefix: impl Into<String>, limit: RouteLimit) -> Self {
134 self.rules.push(Rule {
135 prefix: prefix.into(),
136 timeout: limit.timeout,
137 semaphore: limit.max_in_flight.map(|n| Arc::new(Semaphore::new(n))),
138 });
139 // Longest prefix first, so `match_rule` returns the most specific rule.
140 self.rules
141 .sort_by_key(|r| std::cmp::Reverse(r.prefix.len()));
142 self
143 }
144
145 /// Whether any rule is configured (an empty set means no control at all).
146 #[must_use]
147 pub fn is_empty(&self) -> bool {
148 self.rules.is_empty()
149 }
150
151 /// The most specific rule whose prefix the `path` starts with, if any.
152 fn match_rule(&self, path: &str) -> Option<&Rule> {
153 self.rules.iter().find(|r| path.starts_with(&r.prefix))
154 }
155}
156
157/// Wrap `router` in the per-route load control described by `controls`. An empty
158/// `controls` returns `router` untouched (no layer, no cost). Apply it to the
159/// module sub-router in the composition root, before [`router_with_modules`](crate::router_with_modules)
160/// wraps the framework layers around it.
161pub fn with_route_controls(router: Router, controls: RouteControls) -> Router {
162 if controls.is_empty() {
163 return router;
164 }
165 router.layer(from_fn_with_state(Arc::new(controls), route_controls))
166}
167
168/// The middleware: match the request path to a rule, hold a concurrency permit
169/// (shedding with `503` when the route is saturated), and bound the handler with
170/// the route's timeout (`504` on breach). A path with no rule passes straight
171/// through.
172async fn route_controls(
173 State(controls): State<Arc<RouteControls>>,
174 request: Request,
175 next: Next,
176) -> Response {
177 let path = request.uri().path().to_owned();
178 let Some(rule) = controls.match_rule(&path) else {
179 return next.run(request).await;
180 };
181 let request_id = request.extensions().request_id();
182
183 // Backpressure: one permit per in-flight request. `try_acquire` never
184 // queues, so a saturated route sheds the overflow immediately with `503`
185 // rather than letting latency grow unbounded. The permit is held for the
186 // whole handling (including the timeout wait) and released on drop.
187 let _permit = match &rule.semaphore {
188 Some(semaphore) => match Arc::clone(semaphore).try_acquire_owned() {
189 Ok(permit) => Some(permit),
190 Err(_) => return overloaded_response(&path, request_id),
191 },
192 None => None,
193 };
194
195 match rule.timeout {
196 Some(budget) => match tokio::time::timeout(budget, next.run(request)).await {
197 Ok(response) => response,
198 Err(_) => gateway_timeout_response(&path, request_id),
199 },
200 None => next.run(request).await,
201 }
202}
203
204/// The `503` a shed request gets when its route is at capacity, carrying a short
205/// `Retry-After` (the breach is transient).
206fn overloaded_response(path: &str, request_id: Option<String>) -> Response {
207 let mut response = ProblemResponse(
208 Problem::new(StatusCode::SERVICE_UNAVAILABLE, "service overloaded")
209 .with_detail("the route is at its concurrency limit; retry shortly")
210 .with_instance(path.to_owned())
211 .with_request_id_opt(request_id),
212 )
213 .into_response();
214 response
215 .headers_mut()
216 .insert("retry-after", BACKPRESSURE_RETRY_AFTER);
217 response
218}
219
220/// The `504` a request gets when it outlives its route's timeout budget.
221fn gateway_timeout_response(path: &str, request_id: Option<String>) -> Response {
222 ProblemResponse(
223 Problem::new(StatusCode::GATEWAY_TIMEOUT, "route timed out")
224 .with_detail("the route did not complete within its configured timeout")
225 .with_instance(path.to_owned())
226 .with_request_id_opt(request_id),
227 )
228 .into_response()
229}
230
231#[cfg(test)]
232mod tests {
233 use super::*;
234 use std::sync::Arc;
235 use std::time::Duration;
236
237 use axum::body::Body;
238 use axum::http::Request as HttpRequest;
239 use axum::routing::get;
240 use axum::Router;
241 use tokio::sync::Notify;
242 use tower::ServiceExt; // for `oneshot`
243
244 #[tokio::test]
245 async fn request_over_the_budget_returns_504() {
246 let app = with_route_controls(
247 Router::new().route(
248 "/slow",
249 get(|| async {
250 tokio::time::sleep(Duration::from_millis(200)).await;
251 "done"
252 }),
253 ),
254 RouteControls::new()
255 .route("/slow", RouteLimit::new().timeout(Duration::from_millis(5))),
256 );
257 let res = app
258 .oneshot(HttpRequest::get("/slow").body(Body::empty()).unwrap())
259 .await
260 .unwrap();
261 assert_eq!(res.status(), StatusCode::GATEWAY_TIMEOUT);
262 }
263
264 #[tokio::test]
265 async fn request_within_the_budget_passes() {
266 let app = with_route_controls(
267 Router::new().route("/fast", get(|| async { "done" })),
268 RouteControls::new().route("/fast", RouteLimit::new().timeout(Duration::from_secs(5))),
269 );
270 let res = app
271 .oneshot(HttpRequest::get("/fast").body(Body::empty()).unwrap())
272 .await
273 .unwrap();
274 assert_eq!(res.status(), StatusCode::OK);
275 }
276
277 #[tokio::test]
278 async fn unmatched_path_is_not_controlled() {
279 let app = with_route_controls(
280 Router::new().route(
281 "/other",
282 get(|| async {
283 tokio::time::sleep(Duration::from_millis(50)).await;
284 "done"
285 }),
286 ),
287 // A rule only for `/slow`; `/other` must be untouched despite being slow.
288 RouteControls::new()
289 .route("/slow", RouteLimit::new().timeout(Duration::from_millis(1))),
290 );
291 let res = app
292 .oneshot(HttpRequest::get("/other").body(Body::empty()).unwrap())
293 .await
294 .unwrap();
295 assert_eq!(res.status(), StatusCode::OK);
296 }
297
298 #[tokio::test]
299 async fn concurrency_limit_sheds_overflow_with_503() {
300 // `/held` parks on a Notify until the test releases it, so the first
301 // request deterministically holds the only permit while the second tries.
302 let gate = Arc::new(Notify::new());
303 let entered = Arc::new(Notify::new());
304 let app = {
305 let gate = Arc::clone(&gate);
306 let entered = Arc::clone(&entered);
307 with_route_controls(
308 Router::new().route(
309 "/held",
310 get(move || {
311 let gate = Arc::clone(&gate);
312 let entered = Arc::clone(&entered);
313 async move {
314 entered.notify_one();
315 gate.notified().await;
316 "done"
317 }
318 }),
319 ),
320 RouteControls::new().route("/held", RouteLimit::new().max_in_flight(1)),
321 )
322 };
323
324 // Request 1 enters and holds the permit, parked on the gate.
325 let first = {
326 let app = app.clone();
327 tokio::spawn(async move {
328 app.oneshot(HttpRequest::get("/held").body(Body::empty()).unwrap())
329 .await
330 .unwrap()
331 })
332 };
333 entered.notified().await; // the handler is in → permit is taken
334
335 // Request 2 finds no permit and is shed with 503.
336 let second = app
337 .clone()
338 .oneshot(HttpRequest::get("/held").body(Body::empty()).unwrap())
339 .await
340 .unwrap();
341 assert_eq!(second.status(), StatusCode::SERVICE_UNAVAILABLE);
342 assert_eq!(
343 second
344 .headers()
345 .get("retry-after")
346 .map(|v| v.to_str().unwrap()),
347 Some("1")
348 );
349
350 // Release request 1; it completes 200 and frees the permit.
351 gate.notify_one();
352 let first = first.await.unwrap();
353 assert_eq!(first.status(), StatusCode::OK);
354 }
355}