Targeted Fixes and Overload Guards
Apply targeted query optimization with database indexes, prove fixes under identical load conditions, and implement concurrency limits and load-shedding guards.
Contentsand lesson path
On this page
- Why it matters
- Targeted fixes: query plans and a fair before-and-after test
- Overload protection: concurrency caps and load shedding
- Check your understanding
- Apply it
- Review prompt
Lessons of API Performance & Profiling
- Percentiles, Throughput and Little's Law Concept · 20 min
- Lab: A Reproducible Load Test Lab · 30 min
- Profiling a Slow Endpoint Worked example · 25 min
- Targeted Fixes and Overload Guards Concept · 25 min
- Lab: Prove the Fix, Then Push Past Capacity Lab · 30 min
- Check: Diagnose from the Numbers Knowledge check · 8 questions
What you will learn
- Apply one targeted fix (query or index change, pool or worker sizing, payload reduction, caching or moving work to a job) and record before-and-after results.
- Protect a service from overload with per-client rate limits that answer 429 with Retry-After, caps on concurrent in-flight work, and load shedding that keeps health checks and critical routes responsive, and demonstrate it with a load test past capacity.
01. Why it matters
Suppose profiling showed that GET /orders spends most of its time in one query, and a sale next week may bring three times the usual traffic. Two jobs follow. First, fix the slow query and prove that the fix, not a quieter day, made the endpoint faster. Second, make sure that when traffic goes beyond what even the fixed service can handle, it turns the excess away quickly instead of becoming slow for everyone. This lesson covers both: reading query plans and testing fairly, then concurrency caps and load shedding.
02. Targeted fixes: query plans and a fair before-and-after test
When profiling shows that a slow endpoint spends its time in the database, read the query plan instead of guessing. In PostgreSQL, EXPLAIN (ANALYZE, BUFFERS) runs the query and shows the plan the optimizer chose, with the real row counts, timings and buffer use of each step:
- Sequential scan or index scan: without a usable index, a
WHEREclause on a large table becomes aSeq Scan, which reads every 8 KB page of the table, so its cost grows with the table (O(N)). A B-tree index finds the matching entries by walking a few tree levels (O(log N)), so its cost grows with the result instead. On a small table, or when most rows match, a sequential scan can still be the cheaper plan. - Planning time and execution time:
EXPLAIN ANALYZEreports how long the optimizer took to choose a plan and how long the query ran. WithBUFFERSit also showsBuffers: shared hit=... read=...:hitpages came from PostgreSQL's shared buffers,readpages had to be fetched from the operating system, possibly from disk. Manyreadpages on a repeated query suggest the working set does not fit in memory. - A composite index that matches the filter: for a query that filters on equality and then a range (e.g.
WHERE tenant_id = 10 AND created_at >= '2026-01-01'), a composite index on(tenant_id, created_at)lets PostgreSQL jump to that tenant's entries and read only the matching date range, skipping the rows of every other tenant. - Covering indexes and index-only scans: to avoid reading the table at all, you can add a covering index using the
INCLUDEclause (e.g.CREATE INDEX idx_orders_covering ON orders (tenant_id, created_at) INCLUDE (total_amount)). When the query selects only indexed and included attributes, PostgreSQL can use anIndex-Only Scan, which skips heap pages that the visibility map marks as all-visible. CheckHeap FetchesinEXPLAIN ANALYZE: on a busy table that has not been vacuumed recently it can stay high, and regular (auto)vacuum keeps it low.
Then prove the fix with a controlled comparison. If you add an index or a cache and the production dashboard shows "p95 down 40%" the next day, that is not good evidence that your change was the cause.
Production traffic changes from day to day in volume, user mix, query parameters and background batch jobs. A fair comparison keeps everything but the change fixed: run the same open-model load test, against the same seeded data, on the same machines, before and after, and change one thing at a time.
03. Overload protection: concurrency caps and load shedding
What happens when a surge of traffic exceeds what your system can serve, for example 5,000 requests per second for a cluster that handles 1,000?
A service without protection tries to process every request it accepts. That can push it into a metastable failure, a bad state that keeps itself going:
- Queues grow. Requests wait in socket backlogs, proxy queues and worker backlogs, so latency rises from milliseconds to many seconds, and memory fills with waiting requests.
- Clients time out and retry. Browsers, apps and other services give up and send the request again. The load rises further, while the server still spends CPU on requests whose clients have already gone.
- The overload outlives its trigger. When the original surge ends, the retries and the backlog can keep the system overloaded, and throughput stays low until load drops well below normal, for example because operators shed traffic or restart instances.
Two guards break that loop: concurrency caps and load shedding:
- Bound the work in flight: cap the number of requests a process works on at once (e.g. 50 in flight per process). Size the cap with Little's law (in flight = rate × time per request) from the rate and latency you measured at a healthy load, so admitted requests keep roughly that latency.
- Reject quickly and cheaply: when the concurrency limit is reached, reject excess requests immediately with HTTP 429 Too Many Requests (including a
Retry-After: 30header for client rate limits) or HTTP 503 Service Unavailable (for server capacity limits). - Keep health checks out of the guard: do not shed or queue the liveness endpoint (
/healthz). If it waits behind user traffic, Kubernetes concludes that a busy pod is dead and restarts it, removing capacity when it is most needed. Readiness (/ready) is exempted here too; some teams instead let it fail on purpose under sustained overload so the load balancer sends traffic elsewhere.
With a well-sized cap, admitted requests keep close to their normal latency, while the excess is rejected before it takes a database connection or much memory. The rejections are not free: past some rate the process spends its CPU just saying no, which is why heavy shedding also belongs at a proxy or load balancer in front.
import asyncio
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
app = FastAPI()
# Concurrency guard: at most 50 requests in flight in this process
MAX_CONCURRENT_REQUESTS = 50
concurrency_semaphore = asyncio.Semaphore(MAX_CONCURRENT_REQUESTS)
@app.middleware("http")
async def load_shedding_middleware(request: Request, call_next):
# Probes skip the guard, so a busy process still answers them
if request.url.path in ("/healthz", "/ready"):
return await call_next(request)
# No free slot: reject fast instead of queuing. Safe without a lock,
# because nothing awaits between this check and the acquire below.
if concurrency_semaphore.locked():
return JSONResponse(
{"title": "Server at capacity", "status": 503,
"detail": "Too many requests in progress. Retry later."},
status_code=503,
headers={"Retry-After": "5"},
media_type="application/problem+json",
)
async with concurrency_semaphore:
# No blanket try/except: route errors still reach your handlers
return await call_next(request)04. Check your understanding
05. Apply it
Apply this to the slow endpoint of your skill project:
- Read query plans: Run
EXPLAIN (ANALYZE, BUFFERS)on slow queries in staging. Create indexes whose leading columns match the query's equality filters, then its range orORDER BYcolumns. Checkpg_stat_user_indexeslater to see whether each index is actually used. - Add concurrency limits and backpressure: Use semaphores in the app or connection limits at a reverse proxy (e.g. Nginx
limit_connandlimit_req) to cap in-flight requests. Keep any request queue short; a long queue only adds waiting time and memory. - Protect health and monitoring endpoints: Exempt
/healthzand/metricsfrom load shedding, so the orchestrator does not restart busy pods and Prometheus keeps scraping. - Send Retry-After and ask clients for jitter: When returning 429 or 503, include
Retry-After. Ask client SDKs to use capped exponential backoff with random jitter, so they do not all retry in the same second when the service recovers.
In the next lesson, you will run a hands-on lab proving a performance fix under baseline load, then pushing the service past capacity to verify overload protection.
06. Review prompt
Without looking back, explain how EXPLAIN ANALYZE shows a sequential scan and how a composite or covering index can replace it. Describe why a production dashboard cannot prove that an optimisation worked, when an index-only scan still visits the heap, and how a concurrency cap with fast rejection keeps a traffic spike from turning into a metastable failure.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.