TL;DR
- Concurrency limits bound simultaneous work. Rate limits bound how quickly new work arrives. Load shedding rejects work that cannot be served within a useful deadline.
- Start with fixed limits around the constrained dependency, bounded queues, request deadlines, and clear overload responses. Add an adaptive controller only when measurements and failure testing justify its complexity.
- Keep a per-process semaphore’s global effect in view: every FastAPI process and replica has a separate limit. Downstream quotas require fleet-wide coordination or provider-side controls.
- Use latency from successful work, resource pressure, queue age, and rejection rates together. Fast-fail latency can make the overall median look better while useful goodput gets worse.
- Retries can amplify overload. Return a clear retry policy, apply jitter and an overall deadline, and avoid retrying non-idempotent operations blindly.
Why FastAPI needs an overload boundary
Async endpoints can serve many clients while waiting on I/O, but that does not make the database, provider, CPU, or connection pools unlimited. If incoming work exceeds one of those boundaries, requests wait in sockets, application tasks, a thread pool, a database pool, or a remote service. More requests then increase latency and keep resources occupied for longer. Clients time out and retry, which can send still more work to the slowest dependency.
Load shedding rejects excess requests early so the service can finish useful work for requests it accepts. It is different from autoscaling, which adds capacity after a metric changes and a new instance becomes ready. Scaling has delay. A hard admission boundary can react immediately while capacity recovers.
Concurrency control, rate limiting, and load shedding solve related but different problems. A concurrency limit caps simultaneous requests or provider calls. A rate limit caps arrivals over a time window. A queue buffers short bursts but must be bounded by size and wait time. Load shedding stops accepting work that would otherwise wait past its deadline or threaten a more important operation.
Find the real bottleneck before choosing a controller
Trace a request through the application and identify where it queues. Measure in-flight requests, event-loop lag, thread-pool saturation, CPU, memory, database checkout wait, HTTP connection-pool wait, upstream latency, and queue age. Break results down by route and dependency. A slow SQL query and a saturated payment provider need different controls even if both produce a rising p99.
Use successful-request latency separately from rejected-request latency. A fast 503 should not be included as a successful response when calculating the service’s latency target. Track what fraction of work was admitted, completed before its deadline, shed, timed out, or retried. AWS’s overload guidance warns that rejection can make latency statistics look deceptively healthy unless accepted work and shedding decisions are visible. AWS Builders’ Library: using load shedding to avoid overload
Classify work by cost and importance. A small authenticated read may use a few milliseconds of database time; an export can hold a connection for much longer. Critical user actions, background refreshes, and speculative work should not compete without an explicit priority policy. Push low-priority or long-running work onto a durable queue where a user can observe progress.
Build fixed admission control as the first protection
For one expensive asynchronous operation, a process-local non-waiting limiter can provide a clear first boundary. It should fail fast when all slots are busy rather than build another unbounded queue inside the web server. This example is intentionally limited to one async event loop per process. Each process has its own counter, so the fleet-wide maximum is the per-process value multiplied by process and replica counts.
from fastapi import FastAPI, HTTPException
app = FastAPI()
class TryLimiter:
def __init__(self, maximum: int) -> None:
self.maximum = maximum
self.in_flight = 0
def try_acquire(self) -> bool:
# No await occurs between check and increment. This is for
# one asyncio event loop, not shared threads or processes.
if self.in_flight >= self.maximum:
return False
self.in_flight += 1
return True
def release(self) -> None:
self.in_flight -= 1
report_limiter = TryLimiter(maximum=24)
@app.get("/reports/{report_id}")
async def get_report(report_id: str):
if not report_limiter.try_acquire():
raise HTTPException(
status_code=503,
detail="Report service is temporarily at capacity",
headers={"Retry-After": "1"},
)
try:
return await render_report(report_id)
finally:
report_limiter.release()
The value 24 and one-second retry hint are examples, not a production prescription. Set a useful maximum from a load test. A request that is rejected should not hold a slot. Ensure every admitted path releases it, including exceptions and cancellation. If the endpoint streams a response, release after streaming finishes rather than when the response object is first returned.
This limiter protects only that process and only the wrapped work. With four replicas and two application processes per replica, a limit of 24 permits up to 192 concurrent operations across the fleet. Use a gateway or service-level mechanism when a downstream has a global quota. A distributed counter can become a hot dependency and should not be added without measuring its availability and latency impact.
Control the downstream dependency, not every endpoint uniformly
A route-level limiter protects the route’s own resources. If many routes call the same model API or database, they need a shared per-process limiter at that dependency boundary. Separate limits by provider and operation class. A request that calls both a search service and a payment provider should not consume one unrelated global semaphore for the whole request.
Set explicit timeouts on outbound calls. A concurrency limit without a deadline can allow a small number of stuck calls to occupy every slot forever. Reuse async HTTP clients and bound their connection pools. Set database statement and pool acquisition limits. Use a bulkhead so a stalled non-critical dependency cannot consume every worker or connection needed by critical operations.
At the tenant level, combine a per-tenant rate or concurrency quota with a global service limit. This prevents one customer from occupying all available capacity. Keep high-cardinality tenant identifiers out of metrics labels; use sampled traces or controlled logs when tenant-level diagnosis is needed. For shared background work, see per-tenant worker quotas and fair dispatch.
Adaptive concurrency is useful when a fixed cap becomes stale
A fixed limit is understandable and easy to test, but a workload or dependency can change. An adaptive concurrency controller adjusts the number of concurrent requests using measured latency or resource pressure. Envoy’s adaptive concurrency filter, for example, samples upstream latency, compares it with a periodically measured minimum round-trip time, and updates a concurrency limit. It also exposes metrics such as the current limit, blocked requests, and sampled latency. Envoy adaptive concurrency filter
That is a control loop, not a magic setting. It needs a representative baseline, enough samples, a safe minimum and maximum, and a place where it sees all relevant traffic. If some requests bypass the limiter, the controller can misjudge the actual concurrency. Envoy documents that its filter must control all requests destined for the cluster to behave as intended.
Latency is a lagging signal and includes more than saturation. A slow network, a large request mix, garbage collection, or a downstream outage may all raise response time. If the controller responds by increasing capacity during a downstream outage, it can make the failure worse. Protect each dependency with its own bound and use hard ceilings independent of the adaptive value.
Consider running the adaptive control at the gateway or service proxy when it owns routing and can observe the whole upstream pool. An application-level controller can make sense for a single dependency, but it adds shared mutable state and must be correct across async tasks, processes, and replicas. Start with fixed limits and an operationally safe manual control unless load tests show that fixed tuning is causing repeated underuse or overload.
Load shed by deadline and priority
Reject work before expensive parsing, database access, or provider calls when the request is already over its deadline or the service is at a known hard limit. Preserve lightweight health probes and control-plane operations so the load balancer can continue to observe the instance. Return a stable error format that clients can handle. Use 429 when a client exceeded its allocated quota; use 503 for temporary service capacity exhaustion. Keep the response small and avoid expensive logging on every rejected request.
Prioritize requests by product value only when the policy is consistent across the call path. If the API accepts critical work but a downstream queue places it behind bulk work, the priority decision disappears. A queue needs a bounded depth, maximum wait, and separate metrics. An old queued request may no longer be useful. Drop or expire work whose deadline passed rather than allowing it to consume capacity and fail later.
Make retries part of the control system. If every client retries a 503 immediately, the shed load returns as a synchronized burst. Provide retry guidance for safe operations, use exponential backoff with jitter, and respect an overall deadline. Avoid retrying payments with a new idempotency key. See payment retries and stable idempotency keys.
Measure whether the policy helps
Track admitted goodput, successful latency percentiles, rejection rate by reason and route, concurrency limit, upstream latency, pool wait, queue age, retries, and client-visible errors. Monitor false positives where requests are rejected while the dependency has spare capacity. If a limiter repeatedly blocks at low utilization, its placement or per-process math may be wrong.
Test overload by increasing offered load beyond the measured saturation point, then continue at a steady rate while removing some capacity or slowing a dependency. Verify that accepted requests still complete, rejection stays cheap, health probes work, and retries do not amplify the surge. Include heterogeneous request costs and a failure where CPU stays low while the database pool is exhausted.
Autoscaling and load shedding need coordinated signals. If shedding lowers CPU before a CPU-based autoscaler observes a need for capacity, scaling may not start. Measure rejected traffic alongside CPU and queue age. A useful policy rejects enough work to preserve service while leaving a signal that allows scaling or operator intervention.
Use bounded canaries for changes to the limit. Compare admitted throughput and successful latency with the previous policy. Keep a manual kill switch or fixed safe fallback. Do not roll out a controller that can silently change from protective to permissive without a bound.
Frequently asked questions
Is adaptive concurrency the same as rate limiting?
No. Rate limiting constrains how quickly a client can send requests over time. Concurrency limiting caps how many requests may be in flight simultaneously. An adaptive concurrency controller changes that cap based on observed conditions. A service may need all three controls for different risks.
Should a FastAPI concurrency limit be global across replicas?
A Python semaphore or counter inside a process only limits work in that process. Multiply it by application process and replica counts to estimate the fleet maximum. If a provider has a hard global quota, enforce that at a shared gateway, coordinated scheduler, or provider boundary and keep local limits as additional protection.
Should overloaded FastAPI endpoints return 429 or 503?
Use 429 when a client or tenant exceeded a defined rate or concurrency quota. Use 503 when the service temporarily cannot accept work because capacity is exhausted. Include a retry hint only when the client can safely retry, and require backoff with jitter to avoid a synchronized retry storm.
Can a queue replace load shedding?
A queue can absorb a short burst if it has a bounded size and wait time. It cannot create downstream capacity. When jobs wait past their usefulness deadline or the queue threatens memory and recovery objectives, reject, expire, or deprioritize work and expose its status clearly.
Use adaptive control after fixed boundaries are clear
FastAPI can handle concurrent I/O efficiently, but the database, provider, event loop, and worker pools still have finite capacity. Start with measured dependency limits, bounded queues, deadlines, and cheap overload responses. Add adaptive concurrency when a proven workload needs it and a controller can observe the complete path. Keep global ceilings, test overload deliberately, and monitor accepted goodput as carefully as rejected work. If cascading timeouts or load spikes are putting your API at risk, talk to our engineering team about service limits, dependency isolation, and overload testing.
