NeuralGateway
Resilient LLM gateway prototype: provider failover, token-bucket budgets, circuit breakers
LLM gateway prototype in FastAPI with a Redis Lua token-bucket rate limiter, an embedding-similarity response cache, EWMA latency routing, circuit breakers and Kafka audit events. Providers are mocked by default.
LLM providers are simulated unless API keys are configured.
The problem
A gateway in front of several LLM providers has to enforce per-tenant quotas across replicas, avoid paying twice for equivalent prompts, and keep answering when a provider slows down or fails.
The approach
FastAPI with a Redis Lua token-bucket rate limiter, an embedding-similarity response cache, EWMA latency routing and circuit breakers; responses stream over SSE and audit events go to Kafka off the request path.
Architecture
- 01
Ingress and rate limit
FastAPI /v1/chat/completions checks a per-tenant token bucket executed atomically as a Redis Lua script and returns 429 with Retry-After and X-RateLimit headers; an in-memory bucket is used when Redis is unavailable.
- 02
Similarity cache
The prompt is embedded with all-MiniLM-L6-v2 when sentence-transformers is installed, otherwise with a deterministic hashed projection, and compared by dot product against the tenant's cached entries in Redis (default threshold 0.88).
- 03
EWMA routing
ProviderPool picks among providers whose breakers allow traffic with probability proportional to 1 / latency^1.5 over an EWMA of observed latency (alpha 0.25).
- 04
Circuit breakers
Each provider has a CLOSED, OPEN and HALF_OPEN breaker (4 failures to open, 15 s recovery, 2 half-open successes to close), with failover to the other provider if the first fails before emitting a token.
- 05
SSE streaming
Tokens are streamed as server-sent events, and generation stops when request.is_disconnected() reports the client has gone (recorded as status 499).
- 06
Audit and metrics
Audit events go through a bounded asyncio queue to an aiokafka producer (acks=all), or to a local log when Kafka is offline; Prometheus metrics cover requests, time to first token, tokens per second and estimated cost.
Key decisions
- Runs the token-bucket refill and decrement as one Redis Lua script, so quota checks are atomic in a single round trip and shared across replicas; the in-memory fallback is per process and not shared.
- Routes by weighted random choice over inverse EWMA latency instead of always picking the fastest provider, so faster providers get more traffic while slower ones still receive some.
- Pushes audit events onto a bounded queue drained by a background producer and drops the oldest event when the queue is full, putting request latency ahead of audit completeness.
- Fails over to the secondary provider only if the primary fails before the first token, so a response is never stitched together from two providers; failures after streaming starts are not retried.
- Stores normalized vectors per tenant in Redis hashes and scans all of a tenant's entries on lookup; this is simple and exact, but lookup cost grows linearly with cache size.
- Falls back to a hashed token projection when sentence-transformers is missing (it is not in requirements.txt), keeping the image small at the cost of matching surface tokens rather than meaning.
Results
- The gateway runs end to end in standalone mode with mock providers and in-memory rate limiting and cache, which is how the public demo is deployed.
- Docker Compose starts the gateway with Redis, ZooKeeper-based Kafka (Confluent images) and Prometheus for the distributed mode.
- A fault-injection header or dashboard control trips a provider's breaker, and traffic moves to the other provider.
How it is tested
- 3 pytest unit tests: in-memory rate limiter allow and deny with retry-after, circuit breaker transitions from CLOSED to OPEN to HALF_OPEN to CLOSED, and cache hit and miss around the similarity threshold.
- test_gateway.py holds 5 more tests that call a live server at 127.0.0.1:8000 (health, streaming, cache hit, rate limit, metrics).
- verify_suite.py drives the app in-process through FastAPI's TestClient: dashboard, health, non-streaming completion, cache hit, cache clear, circuit reset, stats and an SSE stream.
- CI runs ruff, pytest and verify_suite.py on Python 3.11; locustfile.py exists for load tests, but no load-test results are committed.
Limits, stated plainly
- Providers are mocks by default; real OpenAI or Anthropic calls happen only when DEMO_MODE is off and API keys are set, and the public demo runs in simulated mode.
- No performance numbers: every row of the README benchmark table is TBD.
- Without sentence-transformers the cache matches on hashed tokens rather than meaning, and the Redis cache clear() uses a different key prefix from the one entries are written under.
- In-memory fallbacks are per process, Redis is a single dependency, and the gateway's limits are not synchronised with provider-side quotas.
- Test coverage is thin, and CI installs pytest without pytest-asyncio although the unit tests are async.