Backend for AI
Choosing sync, streaming, jobs or webhooks, with idempotency keys; async fan-out with semaphores, backoff and Retry-After; Postgres + pgvector queries, indexes and isolation; and how to test code that calls a model.
Real vs simulated: Concurrency runs in virtual time against a simulated provider that enforces real limit rules; query plans and transaction interleavings are illustrative, not from a live database.
The provider
| Strategy | Done | Failed | 429s | Wall time |
|---|---|---|---|---|
| 60 | 0 | 0 | 93 s | |
| 10 | 50 | 50 | 2.0 s | |
| 40 | 20 | 20 | 8.3 s | |
| 60 | 0 | 28 | 65 s |
@retry(retry=retry_if_exception_type(RateLimited),
wait=wait_exponential_jitter(initial=0.25, max=16), stop=stop_after_attempt(8))
async def summarise(d): ... # and sleep at least Retry-After
sem = asyncio.Semaphore(LIMIT)Unbounded fan-out hits the provider’s limits at once and most calls fail. A semaphore protects the concurrency limit; only retries that respect Retry-After get everything through — and nothing beats the requests-per-minute ceiling (≈ 30 s here). In production put the limiter in front of everyone (a shared token bucket in Redis or the gateway), not in each worker.
Virtual time against a simulated provider with real limit rules; latencies are jittered ±40%.