Size and scale an AI backend
Size API and worker concurrency, pools and token budgets together, load-test them and write the runbook.
By Invicly Tech, , in FastAPI with Python for AI Backends. About 13 minutes to read.
In short
API processes, worker concurrency, database pool sizes and model rate limits are linked: raising one without the others just moves the queue somewhere else. Sizing them together, enforcing token budgets per tenant and load-testing against a local fake model shows where the real limit is. Gradual rollouts and a written runbook keep changes and incidents under control.
Think of it like this: Scaling one part alone is like adding checkout lanes when the bottleneck is the car park exit.
Explained simply
Scaling means handling more users without the service falling over or the bill exploding. In an AI backend, most of a request's time is spent waiting for the model, often several seconds. That changes the maths: you need many requests in flight at once, but each one uses very little CPU while it waits.
Several limits stack up. Each API process can hold a certain number of database connections. PostgreSQL accepts a limited number in total. The model provider allows a certain number of requests and tokens per minute. If you raise one limit without checking the others, the waiting just moves to a different place.
Money is a limit too. Each tenant should have a token budget, checked before the model is called, so one busy customer cannot use up the shared provider quota or run up a surprise bill. When a tenant hits its budget, the API returns a clear 429 error.
You find real limits with a load test. A tool such as Locust pretends to be many users. Point it at your local stack with a fake model that waits about as long as the real one, and watch latency, errors and pool usage as users increase. Then write down what to do when limits are hit in production: a runbook.
Press Play on a diagram to walk through it one step at a time.
- 1API processes
Uvicorn workers x concurrent requests each
- 2DB pool
pool_size + max_overflow per process
- 3Model semaphore
Max in-flight provider calls per process
- 4Provider limits
Requests and tokens per minute
- 5Tenant budget
Daily token cap checked before the call
- 1Set limits together
Pools, semaphores, budgets
- 2Load-test locally
Fake model, stepped users
- 3Find the first saturated part
Pool, slots, CPU or provider
- 4Change one setting
Then retest
- 5Roll out gradually
Canary and watch p95
- Back to step 1
In depth
Matching pools to concurrency
Start from the database. PostgreSQL's max_connections defaults to 100, and a few are reserved for administrators. Every process with a SQLAlchemy engine has its own pool: pool_size connections kept open (default 5) plus up to max_overflow extra (default 10). So 4 Uvicorn workers with defaults can open 60, and adding 4 worker containers with the same settings brings it to 120, over the limit. Add every process, including migrations and admin tools, and keep headroom. If you need more, put PgBouncer in front of PostgreSQL.
The most important rule for AI routes: do not hold a database connection while waiting for the model. Load what you need, release the session, call the model, then open a new short session to save the answer. Otherwise a 10-second model call pins a connection for 10 seconds and a small pool runs dry at low traffic.
- Total = processes x (pool_size + max_overflow)
- Stay well under max_connections
- Set pool_timeout so waiting fails fast with a clear error
- Release the session before the model call
Little's law and model concurrency
Little's law says the average number of requests in flight equals the arrival rate multiplied by the average time each spends in the system. At 10 chat requests per second and 6 seconds each, you have about 60 in flight. Async FastAPI handles that easily in one process because waiting costs little, but the provider might not: check its requests-per-minute and tokens-per-minute limits.
Put an asyncio.Semaphore around provider calls in each process, sized so that processes multiplied by slots stays inside the provider limit. When all slots are busy, new requests wait briefly and then fail with 429 or 503 and a Retry-After header, which is better than letting them pile up until everything times out. Size the ingestion worker the same way: its embedding calls share the provider quota, so give it a separate, smaller budget so a big upload cannot starve live chat.
- Many short-lived requests
- Latency matters most
- Semaphore for chat calls
- Small DB pool, short sessions
- Few long jobs
- Throughput matters most
- Separate embedding budget
- Concurrency set by jobs per worker
Token budgets and cost caps per tenant
Rate limits protect the service per second; budgets protect money per day or month. Keep a counter per tenant in Redis, such as tokens:contoso:2026-12-01, with an expiry a little longer than the period. Before a model call, estimate input tokens plus the maximum output tokens you allow and reserve them with an atomic INCRBY; if the new total exceeds the tenant's limit, undo the reservation and return 429 with a code like token_budget_exceeded. After the call, adjust by the difference between the estimate and the actual usage the provider reported.
Also set max output tokens on every model call, so one answer cannot be unexpectedly long. Keep a global daily cap as a last line of defence, and alert at 80 percent of any budget so you can talk to the customer before they hit the wall. Record final usage in your own database for billing.
Load-testing a local fixture
Prerequisites: the Compose stack, a fake model that sleeps for a realistic, random time such as 1 to 4 seconds and streams fixed tokens, and Locust installed with pip install locust. Write a locustfile with a user class that asks questions from your eval fixtures for the two demo tenants. Run it headless, for example locust -f locustfile.py --headless -u 100 -r 10 -t 5m --host http://localhost:8000, where -u is the number of users, -r how many start per second and -t the run time.
Raise users in steps and watch p95 latency, error rate, DB pool usage and in-flight model calls. The knee, where latency starts climbing steeply, is your current limit; the metric that saturates first tells you which setting to change. Expected evidence: a short table of users against p95 and errors for each step. Cleanup: stop Locust and run docker compose down.
Gradual rollout and the incident runbook
Change pools, semaphores and models gradually. A canary sends a small share of traffic, say 5 percent, to the new version and compares its error rate and p95 with the old one before going further. Blue-green keeps two full environments and switches all traffic at once with a fast switch back. Feature flags let you turn on a new model per tenant. Most managed container platforms support traffic splitting between revisions.
A runbook turns a bad night into a checklist. For each alert, write: what it means, the first three things to check with exact dashboards or queries, the safe actions in order (shed load, lower concurrency, switch to a fallback model, pause ingestion) and how to roll back. Add who to tell and where to record the timeline. Practise it during the failure drills, so the steps are known to work.
- Canary: small share first, compare, then widen
- Blue-green: two environments, instant switch
- Feature flags: per-tenant model changes
- Runbook: meaning, checks, actions, rollback, comms
Learn it in 5 short steps
About 40m each. Track them with a timer in your plan.
- 1Match pools to concurrency~40m
- 2Budget tokens and cost per tenant~40m
- 3Load-test a local fixture~40m
- 4Roll out changes gradually~40m
- 5Write an incident runbook~40m
Key points
- Total database connections = processes x (pool_size + max_overflow); keep it under PostgreSQL's max_connections with headroom.
- Little's law: requests in flight = arrival rate x time per request, so slow model calls need many concurrent slots.
- Cap in-flight model calls with a semaphore and check a per-tenant token budget before every call.
- Load-test with a fake model that has realistic delays, so you find your own limits without paying a provider.
- Roll out changes to a small share of traffic first, and keep a runbook with the checks and the rollback.
Key terms
Tap a card to flip it. 0/6 known
Examples
import asyncio
from sqlalchemy.ext.asyncio import create_async_engine
# 4 processes x (5 + 5) = 40 connections, under max_connections=100
engine = create_async_engine(DB_URL, pool_size=5, max_overflow=5, pool_timeout=5)
MODEL_SLOTS = asyncio.Semaphore(16) # per process
async def call_model(provider, prompt: str, tenant_id: str):
await budgets.reserve(tenant_id, estimate_tokens(prompt)) # raises if over budget
async with MODEL_SLOTS:
return await provider.complete(prompt)Pool, model concurrency and the tenant budget set in one place.
Sizing the connection budget
The stack runs 3 API containers with 2 Uvicorn workers each, and 2 ingestion workers. PostgreSQL allows 100 connections and you keep 15 free for admin, migrations and monitoring, leaving 85. Step 1: count processes: 3 x 2 + 2 = 8. Step 2: divide: 85 / 8 is about 10 connections per process. Step 3: set pool_size=6 and max_overflow=4. Step 4: if autoscaling may double API containers, either lower the pool or add PgBouncer. Step 5: confirm under load with SELECT count(*) FROM pg_stat_activity.
A Locust user for the chat route
Step 1: save the file as locustfile.py. Step 2: run locust headless at 20, 50 and 100 users for five minutes each against the local stack with the fake model. Step 3: record p95 and failures from Locust's summary, and pool usage from your metrics. Expected evidence: at 100 users p95 jumps from 4 to 12 seconds while in-flight model calls sit at the semaphore limit, so the semaphore, not the database, is the first limit.
import random
from locust import HttpUser, task, between
QUESTIONS = ["What is the refund window?", "Who approves travel?", "How long is data kept?"]
TOKENS = {"contoso": "Bearer <test-token-contoso>", "fabrikam": "Bearer <test-token-fabrikam>"}
class ChatUser(HttpUser):
wait_time = between(1, 3)
def on_start(self):
self.auth = TOKENS[random.choice(list(TOKENS))]
@task
def ask(self):
self.client.post("/chat", json={"question": random.choice(QUESTIONS)}, headers={"Authorization": self.auth}, name="/chat")Quick reference
- DB connections = processes x (pool_size + max_overflow); PostgreSQL default max_connections is 100.
- SQLAlchemy defaults: pool_size=5, max_overflow=10.
- Little's law: in flight = arrival rate x time in system.
- Release the DB session before awaiting the model.
- asyncio.Semaphore(n) per process caps in-flight provider calls.
- Reserve tokens with Redis INCRBY before the call; adjust after with real usage.
- locust -f locustfile.py --headless -u 100 -r 10 -t 5m --host http://localhost:8000
- Canary first; every alert links to a runbook with checks, actions and rollback.
Common mistakes
- Doubling API processes without lowering the per-process pool, then hitting too many clients errors in PostgreSQL.
- Load-testing against the real provider, which costs money and measures their limits instead of yours.
- Holding a database connection open while waiting for a 20-second model call.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
You run 3 API processes and 2 workers and want at most 70 total connections. Choose pool_size and max_overflow for every process.
- Exercise 2medium
Write reserve_tokens(redis, tenant_id, n, limit) that atomically adds n to today's counter, sets a 2-day expiry, and raises BudgetExceeded (after undoing) if the total passes limit.
- Exercise 3hard
Write a short runbook entry for the alert "p95 chat latency above 8 s for 10 minutes".
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How many Uvicorn workers should I run?
- A common start is one process per CPU core, then adjust from load tests. On container platforms that scale replicas for you, many teams run one process per container and let the platform add containers.
- Should I scale the API or the worker first?
- Look at the metrics. Rising chat latency with free worker capacity points at the API, model slots or database. Growing queue lag points at the workers or their provider budget.
- What is PgBouncer and when do I need it?
- PgBouncer is a lightweight connection pooler that sits in front of PostgreSQL and shares a small number of server connections among many clients. Add it when the sum of your pools approaches max_connections.
- Is Locust the only option for load testing?
- No. k6, JMeter and Vegeta are common too. Locust fits this course because tests are plain Python.