expression
REST: model a bounded token bucket
A token bucket admits requests while tokens remain and replenishes over time, up to a fixed capacity. This integer model refills one token per synthetic second. Real implementations need a monotonic clock, atomic updates and bounded state. Standalone synthetic example. Expected stdout (not executed): 0: true 0: true 0: false 1: true 1: false 9: true Common mistake: Allowing idle time to create unlimited tokens.
Formal Syntax & Structure
rust syntaxrust
tokens = min(capacity, tokens + refill)Working Example
Example Snippetrust
use axum::{Router, Json, body::{Body, to_bytes}, http::{Request, StatusCode}};use serde::{Deserialize, Serialize};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() { let (mut tokens, mut last) = (2_u64, 0_u64); for now in [0_u64, 0, 0, 1, 1, 9] { tokens = 2.min(tokens.saturating_add(now.saturating_sub(last))); last = now; let allowed = tokens > 0; if allowed { tokens -= 1; } println!("{now}: {allowed}"); }}