Skip to content

Lesson 9 of 9 · 28m

Production Capacity, Load Shedding, and Resilience Patterns

Design async services with bounded concurrency, admission control, retries with budgets, and explicit degradation behavior.

Async Rust can handle impressive concurrency, but that does not mean unbounded concurrency is safe. Every in-flight task consumes memory and usually holds a socket, permit, buffer, database connection, or downstream dependency budget. Production design means choosing limits before the incident chooses them for you.

Bound concurrency at the work boundary

A semaphore is the simplest explicit limiter:

static PERMITS: std::sync::LazyLock<tokio::sync::Semaphore> = std::sync::LazyLock::new(|| tokio::sync::Semaphore::new(64));

async fn run_job(job: Job) -> Result<()> {
    let _permit = PERMITS.acquire().await?;
    process(job).await
}

The permit is dropped when the task finishes, releasing capacity. Choose the number from resource budgets: downstream connections, memory per job, CPU cores, or external rate limits. Do not choose it because 64 feels round.

Admission control beats heroic queueing

When the system is full, decide what the caller sees:

match semaphore.try_acquire() {
    Ok(permit) => process_with_permit(job, permit).await,
    Err(_) => Err(AppError::Overloaded),
}

For interactive traffic, fast rejection with 503 or a domain-specific overload response is often better than queueing until every client times out. For asynchronous ingestion, queueing may be correct if persistence and memory bounds are explicit. The bad design is invisible queueing with no deadline.

Retry without a budget is a distributed denial of service

Retries amplify partial failure. Use capped exponential backoff, jitter, and a total deadline:

let mut delay = Duration::from_millis(50);
for attempt in 1..=4 {
    match call().await {
        Ok(value) => return Ok(value),
        Err(err) if attempt == 4 => return Err(err),
        Err(_) => tokio::time::sleep(delay).await,
    }
    delay = (delay * 2).min(Duration::from_secs(2));
}

In real services, jitter should be random rather than synchronized. More importantly, retries must fit inside the caller's deadline. A three-second request that internally retries for twelve seconds is not resilient; it is lying.

Bulkheads isolate failure

Separate dependency capacity by function or tenant class. A reporting workload should not consume every database connection needed by login. A batch importer should not consume all outbound upstream permits needed by synchronous requests. Bulkheads can be separate semaphores, pools, runtimes, worker pools, or processes. The goal is not elegance; it is preventing one workload's failure mode from becoming everyone's failure mode.

Test overload as a first-class scenario

Most teams test correctness and maybe throughput. Few test the shape of degradation. Use a small load harness or integration test that blocks a downstream dependency, fills the queue, and verifies admission behavior: requests fail fast, queue depth stays bounded, shutdown completes, metrics rise, and recovery drains cleanly. The behavior you do not test is the behavior production will invent.

Field notes

  • A semaphore limits concurrent execution, not queue length; pair it with admission policy.
  • Fairness matters: one hot tenant can consume all permits unless you partition or weight capacity.

Was this lesson helpful?

Sign in to rate