Skip to content
James Ross
articlePublished Updated 9 min read

Building an LLM gateway: an OpenAI-compatible API in front of tools that are not APIs

By James Ross

An LLM gateway is a translation layer: it accepts the request shape every chat client already speaks, does the work through a back end that speaks something else, and returns the response shape the client expects. When the back end is a command-line tool rather than an API, the gateway also has to own process lifetime, concurrency, session state and failure classification.

A universal adapter socket translating standard chat plugs to a back row of non-API tools, showing an LLM gateway.

This LLM gateway is one layer of the company AI workspace rollout, which needed a single HTTP face in front of a tool that ships only as a CLI.

The hard part is not the route. A chat completions call looks stateless and the thing behind it is not: a warm process is a conversation, a cold process costs seconds before it reads the prompt, and a timeout that kills the parent can leave the real worker running.

What the gateway actually translates

The public contract is small. One authenticated route takes a prompt, an optional JSON schema, an optional model alias and an optional timeout. A health route reports the process version, the authentication state and the queue depth. Everything else is a 404.

Inside, four things happen in order. The bearer token is checked. The request is validated, including the rule that a JSON schema must have type: "object" at the top level, because an array-rooted schema is rejected upstream and should never cost a process spawn. The request waits for a concurrency slot. Then a child process is spawned in its own working directory, its output envelope is parsed, and the structured result returns.

{
  "prompt": "Extract the line items from this invoice text...",
  "schema": {
    "type": "object",
    "properties": { "items": { "type": "array", "items": { "type": "string" } } },
    "required": ["items"]
  },
  "model": "fast-tier",
  "timeoutMs": 120000
}
{
  "status": "SUCCESS",
  "structured_output": { "items": ["A-1042", "B-2210"] },
  "usage": { "input_tokens": 9120, "output_tokens": 84 },
  "duration_seconds": 2.4
}

Callers use structured_output, never the response string. The string is what the model produced; the object is what the schema validated. Returning both and saying which is authoritative prevents the most common wrapper bug: a caller parsing prose because it happened to look like JSON.

Why spawn-per-request does not survive production

Spawning a fresh process per request is the obvious implementation and the wrong default. Every call pays the tool’s startup cost, dominated by loading the runtime and its own agent prompt rather than by the work. A cold call took about 5 seconds and a warm call in the same session about 2.7 seconds; four parallel calls finished in about 7 seconds (from the build notes).

Those numbers matter because of the queue, not the average. If each call costs five seconds of fixed overhead and the gateway allows four concurrent calls, throughput is four calls per five seconds no matter how fast the model is.

A pool changes the arithmetic twice. It pays startup before the request arrives, and it bounds the process count so a burst cannot fork the host to death. The pool here keeps spare warm processes, serves from a warm one, and starts a replacement in the background. A process retires after a fixed number of turns or when its context passes a ceiling, because a long conversation eventually costs more to carry than to rebuild.

That retirement policy is a real tuning decision. Retire too early and every request pays startup again. Retire too late and each call drags a huge conversation behind it, so latency and token cost climb together. The warm pool used elsewhere in this stack retires a process after 25 turns or when its context passes a 120k-token ceiling, with two spares kept warm and a hard cap of six.

Sessions: delta versus replay

A session is the difference between “remember this” and “here is everything again”. Callers are mostly stateless and resend the whole conversation on every call, because that is what the chat-completions shape implies. A warm process is the opposite: a continuing conversation that already holds the earlier turns.

The bridge reconciles the two by remembering what each warm process has seen. If an incoming request’s history starts with exactly those messages, only the new messages are sent, which is the delta path. If it does not match, a fresh process receives the conversation flattened into one prompt, which is the replay path. Delta is cheaper; replay is correct when the history changed.

Two details make this safe. The match is on the exact prefix, not a similarity score, because a near-match silently feeds the model a different conversation. And the tool runs in an empty directory with sandboxing on, so observed tool output, which can contain anything, has no project files to act on and cannot trigger commands.

The gateway does not attempt session affinity across replicas. A process is pinned to one container’s memory, and horizontal scaling means more containers, each with its own pool.

Quotas and backpressure

Quotas exist at two levels, and conflating them produces bad errors. The first is the gateway’s own capacity: a fixed number of slots and a bounded queue. The second is the upstream account’s quota, which the gateway can only observe.

Both should surface as 429, because both mean “not now, try later”, and both should carry Retry-After. RFC 6585 defines 429 for exactly this case. The difference belongs in the body: queue full clears in seconds; quota_exhausted may clear in hours.

The queue is bounded for a reason. An unbounded queue turns overload into latency: every request eventually succeeds, just late enough to be useless, and the client’s own timeout fires first. A queue of 16 with a fast 429 is a better product than a queue of 10,000 with a two-minute wait.

Three more limits belong at the edge: a 5 MiB body ceiling for text requests and a larger separate one for images, a per-call timeout clamped to the gateway maximum, and an authentication check before the body is read in full.

Timeouts and process groups

A timeout that kills the process you spawned is not a timeout. The wrapper here spawns its own child, and that child inherits the stdout pipe. Killing only the wrapper leaves the child alive and the pipe open, so the close event never fires and the request hangs past its deadline. In one measured case, a 500 ms timeout took 60 seconds to return.

The fix is to spawn the child in its own process group and kill the group. In Node that means detached: true and process.kill(-pid). A negative PID signals the whole process group on POSIX systems, which is the only way to reach a grandchild you never spawned.

The same rule applies to cleanup. Each request gets a temporary directory, removed in a finally block on success, upstream error, spawn failure and timeout. A timeout path that returns before cleanup leaks a directory per failure, which is invisible until the disk fills.

The hardened container

The gateway is the one process holding a credential that can spend money, so it gets the least privilege that still works. It runs as a non-root user, drops every Linux capability, and mounts one named volume for the upstream authentication material so a refreshed token survives a restart. cap_drop: ALL removes every capability from the container’s default set, the correct starting point for a service that only makes outbound HTTPS calls and writes its own volume (Docker Compose reference).

Three operational details are easy to miss:

  1. No CA bundle, no TLS. A slim base image may ship without certificate authorities. The version check still passes, so the health check stays green while every outbound call fails with an unknown authority error.
  2. Health must report auth separately. Returning ok: true while the upstream is signed out keeps the container from restarting in a loop during a device login, but it also means “healthy” is not “usable”. Report the auth state as its own field.
  3. Never log the prompt or the token. Log the request id, model, prompt size, wall time, status and token counts. A gateway that logs bodies becomes a second copy of every customer document.

Migrating every consumer in one change

Callers should never know a model id. They ask for an alias; the gateway resolves it in one configuration file. That indirection makes a migration one change instead of a coordinated deploy across systems with different release cadences.

Two things keep the alias layer honest. The model list route must return the aliases the gateway actually serves, not the upstream catalogue, or clients ask for names that resolve to nothing. And the response should report the alias plus the model that answered, because “which model produced this output” gets asked months later.

The sequence is short: add the new model behind a new alias, run the contract test against both, repoint the existing alias, watch error rates and token counts for a day, remove the old entry. The contract test checks request shape, response shape and error codes. It does not check prose quality, because that is not the gateway’s job.

Spawn-per-request vs warm pool vs hosted API

Approach Time to first token Concurrency control Session state Failure isolation When it fits
Spawn per request Seconds of fixed startup per call Whatever the host allows None, or rebuilt every call One bad request can fork unbounded processes Prototypes, one-off scripts
Warm pool behind a gateway Startup paid ahead of the request Slots plus a bounded queue Delta or replay per request Bad calls queue, time out and die by group Sustained traffic on a CLI-only back end
Hosted model API Network round trip Provider-side rate limits Server-side where offered Provider handles it You can buy the capability directly

Which should you choose? If the back end is a real HTTP API, call it directly; a wrapper adds a hop and a failure mode. If the back end is a CLI with occasional traffic, spawn per request and keep the code simple. A warm pool earns its complexity when startup is a meaningful share of each call and traffic is sustained, which is the case for an internal workspace answering dozens of requests an hour.

What broke and what we changed

The timeout killed the wrapper and nothing else. A 504 took 60 seconds instead of 500 ms because the child held the stdout pipe. Spawning detached and killing the group fixed it, and the regression test now asserts the child is gone, not just that a response arrived.

The slim image had no CA bundle. Every outbound call failed certificate validation while the container passed its own health check. Installing ca-certificates and changing the probe to make one real request fixed both the bug and the blind spot.

The system prompt never reached the back end. The caller sent only the day’s activity text, because the system prompt had always been assembled on the caller’s side. On the new path it was silently dropped, so the model answered without the rules that shaped its output: structurally valid and semantically wrong. The fix was to make the system prompt part of the gateway request, and to reject a request without one.

Validation ran after the spawn. A top-level array schema reached the upstream tool, which rejected it after paying startup. Moving schema validation before the slot wait turned a slow 502 into an instant 400.

Frequently asked questions

What does an OpenAI-compatible gateway do?

It accepts the chat-completions request shape existing clients already implement, translates it to what the back end speaks, and returns a response in the same shape. When the back end is a command-line tool, the gateway also manages process lifetime, concurrency and session state.

Why pool processes instead of starting one per request?

Because startup cost dominates. If each call pays several seconds before it reads the prompt, throughput is capped by startup rather than by the model. A pool pays that cost ahead of time, bounds the process count, and keeps a conversation warm across calls.

How should a gateway handle rate limits?

Return HTTP 429 with Retry-After, and distinguish the gateway's queue from the upstream account's quota in the body. Both are "try later", but one clears in seconds and the other may clear in hours, and the caller's retry policy should differ.

Why kill a process group instead of a process?

Because the process you spawned may have spawned its own child, and that child can hold the stdout pipe open. Killing only the parent leaves the pipe open, so the close event never fires and the request hangs. A negative PID signals the whole group on POSIX systems.

How do you avoid breaking callers when the model changes?

Expose a stable alias and resolve it in one place. Callers ask for the alias, the gateway reports both the alias and the model that answered, and the migration is one configuration change with a contract test on either side.