AI Engineering

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

StrategyDoneFailed429sWall time
600093 s
1050502.0 s
4020208.3 s
6002865 s
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%.