Inference gateway
A private service that takes text from other systems, runs it through a language model reliably, and hands back structured results.
Built at MDN Labs, 2026
What it is
- An internal service that sits between BABIS and an external language model provider. BABIS submits news articles as jobs, then collects structured sentiment results when they are ready.
- It runs as one production deployment that BABIS reaches only over the private WireGuard mesh.
- I designed, built and deployed it from scratch, together with its infrastructure and release pipeline.
The problem
Model calls are slow, rate limited and sometimes fail. Calling a provider directly from each part of a product would mean every caller handling timeouts, retries and duplicate requests on its own.
The text also had to stay private: no provider that trains on the data, nothing sensitive in the logs, and no route in from the public internet.
How I built it
- Django 6 runs ASGI-only under Uvicorn, with async DRF views and one pooled httpx.AsyncClient for the provider.
- There is no message broker. Jobs are rows in PostgreSQL, drained by a separate async worker process that runs several provider calls at once, so the service needs nothing beyond the database it already has.
- Clients submit to POST /api/jobs with an Idempotency-Key. A new job gets 202 and a Location header, a repeat gets the original job back, and polling a job that has not finished returns a Retry-After hint.
- Each client has its own API key and can only see its own jobs. Keys are 256 random bits with a recognisable prefix so a secret scanner can spot a leak, and only their SHA-256 digest is stored.
- Calls go to OpenRouter with a strict JSON schema for the output, no fallback routing, and data collection denied, so providers that train on request data are excluded. Prompts are rows in the database, and a deploy never overwrites one that was edited by hand.
- Logs are structured JSON and redacted twice, by field name and by the shape of an API key. Article text is never logged, and the input text is cleared once a job reaches a final state.
- Request bodies are read by an ASGI layer outside Django that counts the bytes actually received rather than trusting Content-Length, stops at 1 MiB, and gives up on a body that dribbles in too slowly. A rejected request still gets a request ID and a metric.
The interesting parts
A job queue built on SKIP LOCKED
Each worker claims a batch of jobs with SELECT ... FOR UPDATE SKIP LOCKED. Rows another worker has already locked are skipped instead of waited on, so workers never block each other and never claim the same job. A claimed job gets a lease equal to the provider timeout plus a grace period. If a worker dies, its lease expires and the job goes back on the queue, and after the maximum number of attempts it fails as WORKER_LOST instead of retrying forever. A rate limit or provider outage puts the job back with a delay that grows with each attempt.
Completion guarded by the attempt number
A slow worker can come back after its lease has expired and the job has been handed to another worker. So finishing a job is a conditional update that only matches if the job is still RUNNING and its attempt count is the one this worker claimed. A stale worker’s write matches no row and changes nothing. If the completion write itself fails, nothing is lost: the lease expires and the job is picked up again.
Idempotency that catches mistakes
The pair of client and idempotency key is unique in the database, and each job stores a SHA-256 hash of a canonical form of the request. Submitting tries the insert first and only reads the existing job when the unique constraint fires, so two identical requests racing each other still produce one job. The same key with the same payload returns the original job. The same key with a different payload gets a 409, so a client bug that reuses a key is caught at once instead of silently returning the wrong answer.
Strict output that cannot quietly degrade
OpenRouter silently drops a parameter an endpoint does not support, so a model asked for JSON can answer in prose. The gateway sends require_parameters, which only routes to endpoints that honour the schema, and leaves fallbacks off, so an unsupported model fails loudly instead. The schema marks every field required and forbids extra ones at every level, because strict decoders reject anything else. Numeric ranges and span lengths are checked afterwards by a serializer, because decoders enforce those keywords inconsistently.
Timeouts that nest
Every timeout sits inside the next one. The provider call has a total deadline on top of its socket timeouts, because a read timeout resets with every chunk. That deadline is shorter than the proxy’s read timeout, which is shorter than the container’s stop grace period, and the settings refuse to start if the shutdown window is shorter than the provider deadline. On SIGTERM the worker stops claiming and drains the calls in flight. PostgreSQL gets server-side statement and lock timeouts, because a coroutine timeout cannot interrupt a blocked database driver call.
How it runs
- A three-stage Azure DevOps pipeline: Validate runs ruff, manage.py check, makemigrations --check and an OpenAPI schema build that fails on warnings; Build produces a multi-stage Alpine image and fails if it would run as root; Publish writes a release.env pinned to the pushed image digest.
- A standard-library Python deploy runner I wrote takes a host lock, checks every manifest field and asset checksum, and confirms that the runner executing is the one the manifest names. It runs migrations as a gate, waits for the API to be healthy and the worker to be running, and only then promotes the release, rolling back on failure.
- The runner records its current stage in a state file, so after a crash it refuses to start a new deploy until recovery has run. A deploy whose identity hash is already active is skipped, and that identity covers the infrastructure files as well as the image version.
- The Docker Compose stack uses two separate networks, one for ingress and one for the database, so the proxy can never reach PostgreSQL directly. Uvicorn binds no host ports in any environment.
- An OpenResty proxy has three listeners with their own exact-path allowlists: the API on the private mesh with /metrics refused, metrics and probes for the monitoring host only, and probes alone on localhost for the deploy gate. Every other path returns 404.
- Prometheus scrapes both the API and the worker, which serves its own metrics endpoint, and alerts on failure ratio, latency, scrape failures and the age of the oldest queued job.