Multi-Tenant LLM Gateway: Routing, Fallbacks, Budgets, PII Redaction and Cost Attribution

Build the LLM gateway a company's teams share: one OpenAI-compatible API in front of two hosted-provider formats and a self-hosted model, with cost, latency and data-policy routing, fallbacks and a circuit breaker shared by replicas, money budgets that concurrent requests cannot overrun, a cost ledger reconciled with provider billing, PII redaction restored inside streams, exact and semantic caches, and an evaluated router, all running locally.

AI Engineer. Advanced.

What you will build and explain

  • Serve an OpenAI-compatible API in front of providers with different wire formats, streaming included, and explain every translation it makes.
  • Route requests by cost, latency, capability and data policy, and show which deployment served each request and why.
  • Classify provider failures, fall back across providers within a deadline, and run a circuit breaker that every gateway replica agrees on.
  • Enforce per-key rate limits and per-team money budgets that hold under concurrent load, and prove it with a test.
  • Price every attempt, keep a cost ledger by team, project and feature, and reconcile it with provider billing.
  • Detect and redact personal data before it leaves the company, measure the detector, and restore placeholders in streamed answers.
  • Run exact and semantic caches safely and choose a similarity threshold from labelled data.
  • Train and evaluate a router that sends easy requests to a smaller model, and state its quality and cost trade-off.
  • Operate the gateway with dashboards, alerts, key revocation and failure drills.

Before you begin

  • Read and write Python, including async code, and call a chat-completion API.
  • Explain HTTP status codes and headers, read SQL with GROUP BY, and run containers with Docker Compose.
  • Gateways, circuit breakers, token buckets, Lua in Valkey, vector search, PII detection and model evaluation are taught.
  • A machine with Docker (Compose v2.24+), Git, a browser, 4 CPU cores, 8 GB of memory and 15 GB of free disk for Docker.

Who this is for

For engineers who write Python, use Docker Compose and call LLM APIs, and want to run one gateway for every team and provider: routing and fallbacks across providers, shared rate limits and money budgets, cost attribution, PII redaction, caches and an evaluated router.

Curriculum

Learning topics (13)
  1. Check what you need before you start

    This project builds and operates a gateway that sits between every application and every language model a company uses. You will run it on your own computer with Docker Compose: two gateway replicas, a control plane, two emulated hosted providers, a real self-hosted model runtime, Valkey, PostgreSQL, Prometheus and Grafana. Nothing needs a cloud account, a model provider's key or a payment method.

  2. One entrance, many models, shared state

    Tidewell's applications reach every model through one gateway. This page explains the components and how they connect, the path a request takes, where state lives and why, how the design handles failure, cost and security, and which alternatives were considered. The technology lessons go deeper into each part; this page is the map.

  3. Two wire formats and a stream

    Applications at Tidewell call the gateway with the OpenAI Chat Completions format. Behind it, Northwind and the self-hosted Ollama speak the same format, and Bluefin speaks the Anthropic Messages format. This lesson shows what each format sends and receives, how the gateway translates between them without losing stop reasons or token counts, and why it always streams from providers even when the caller asked for a complete answer.

  4. Virtual models and routing

    An application asks for tidewell/chat-fast, not for nw-mini. That one level of indirection is what lets the platform team change providers, add a fallback, move PII-bearing traffic to the self-hosted model or slow down spend without any application changing a line. This lesson explains virtual models, the filters that decide which deployments may serve a request, and the strategies that order the rest.

  5. Fallbacks, deadlines and circuit breakers

    Tidewell's main provider once failed for two hours and every feature failed with it, although a second provider was under contract. A gateway turns that outage into a fallback: the request goes to another deployment, a failing deployment is taken out of rotation for everyone, and a slow provider cannot hold a request forever. This lesson covers which failures may be retried elsewhere, how one deadline bounds all attempts, why a stream may only fall back before its first byte,

  6. Token buckets for requests and tokens

    Tidewell's Data Science team once ran a batch evaluation that used up a shared provider rate limit in the middle of the working day, and every other team's requests failed. A gateway prevents that twice over: each key gets its own request and token rate, so one caller cannot take everyone's allowance, and each deployment is paced below the provider's own limit, so the provider's 429s become rare. This lesson builds both from one primitive, the token bucket, implemented atomic

  7. Money budgets that hold under concurrency

    Every Tidewell team and project has a monthly budget in dollars. The obvious implementation, "check what was spent, call the provider, add the cost", fails as soon as requests run at the same time: fifty requests all read "spent $19.98 of $20", all pass, and together spend $25. This lesson builds budgets that cannot be overrun however many requests run at once, using worst-case reservations held atomically at three levels, and shows what that guarantee costs.

  8. Pricing, the ledger and reconciliation

    Before the gateway, nobody at Tidewell could say what each team spent on models, let alone each product feature. This lesson follows a request's cost from the provider's token counts to a chargeback report: how an attempt is priced, what is charged when the provider never reported usage, what the ledger records (and deliberately does not), and how the ledger is reconciled with a provider's own billing.

  9. Personal data: detect, replace, restore

    Last month a prompt with a customer's card number and e-mail address reached an external provider, and Tidewell's data-protection officer recorded an incident. This lesson builds the gateway's answer: recognisers that find structured personal data with high precision, team policies that decide what happens to it, reversible placeholders so the provider never sees the values while the caller still gets a useful answer, and restoration that works even when a stream splits a pla

  10. Exact and semantic caches

    Customer Care's assistant answers the same handful of questions all day: "how do I add a driver", "what is my excess". Paying a provider for the same answer a thousand times is waste, and a cache removes it. A cache that answers the wrong question, however, is worse than no cache. This lesson covers which requests may be cached at all, the exact cache, the semantic cache that also matches paraphrases, and how its similarity threshold was chosen from labelled data rather than

  11. An evaluated router for easy requests

    Many requests a company sends to a model are easy: add two numbers, classify a customer message as positive or negative. A smaller model answers those just as well, faster and cheaper. Others, such as multi-step arithmetic or counting letters, defeat small models. tidewell/auto chooses between the self-hosted qwen2.5:0.5b and qwen2.5:1.5b per request. This lesson builds that choice the way an AI engineer should: from measured outcomes on tasks with checkable answers, with a h

  12. Metrics, dashboards and alerts

    A gateway that every model call passes through is the best place to see how LLM features behave, and the worst place to be blind: when it is slow, every feature is slow. This lesson covers what the gateway measures and why its metric labels are deliberately few, the dashboard and alert rules, the ledger's queue and why it fails closed, and log lines that never contain a prompt.

  13. Keys, the control plane and running it

    A gateway concentrates risk: it holds every provider credential, sees every prompt and decides every team's spend. This lesson covers how Tidewell's gateway issues and revokes keys, why the control plane is a separate service, how each component gets only the database rights it needs, where secrets live, and the runbooks the platform team follows when something goes wrong.

Practical build steps (12)
  1. Prepare and check the workstation

    Starting point: a computer with Docker. End point: Docker, Compose and Git checked, enough CPU, memory and disk for Docker, and the four lab ports free.

  2. Start the lab

    Starting point: the source folder and a working Docker. End point: .env with random secrets, the images built from hash-locked dependencies, and every service healthy.

  3. Pull the models and seed the tenants

    Starting point: every service healthy. End point: three models pulled and matched against their recorded digests, Tidewell's teams, projects, budgets and policies created, one key per team, and a first answer through the OpenAI SDK.

  4. Send requests and read how they were served

    Starting point: a seeded lab. End point: one answer from each virtual model, with the deployment, attempts and cost that served it, and a streamed answer with usage in its last chunk.

  5. Fall back, and open the shared breaker

    Starting point: a seeded lab. End point: a request served by Bluefin after Northwind answered 429, a circuit breaker opened by failures seen through one replica and respected by the other, and the breaker closed again by a probe.

  6. Limits and budgets under concurrency

    Starting point: a seeded lab. End point: thirty concurrent requests against the Sandbox team's small budget, some served and the rest refused with budget_exceeded, and the settled spend within the budget with nothing held.

  7. Personal data under three policies

    Starting point: a seeded lab. End point: the same claims note redacted for Claims, kept inside for Underwriting and refused for Data Science, and proof of what Northwind actually received.

  8. Exact and semantic caches

    Starting point: a seeded lab. End point: a miss, an exact hit and a semantic hit with the cost avoided, and the threshold table from 150 labelled question pairs.

  9. Train and adopt the router

    Starting point: a seeded lab with the models pulled. End point: the self-hosted models' throughput, labels for 210 tasks from both models, a trained router with its test report, and tidewell/auto choosing a model with it.

  10. Run a team workload and read the reports

    Starting point: a seeded lab. End point: two minutes of traffic from four teams with a provider failing for part of it, a chargeback report, a reconciliation with both providers' billing exports, and budget counters that match the ledger.

  11. Observe the gateway

    Starting point: a workload just run. End point: the Grafana dashboard showing spend, budgets, refusals, fallbacks and cache savings, the alerts Prometheus is evaluating, and log lines with no prompt text.

  12. Run every check, then clean up

    Starting point: the lab running. End point: scripts/lab-check.sh reporting lab check passed with its evidence in .lab/, then every container, volume, network and built image of the lab removed.

Access

Learning Access: INR 199 plus 18% GST. Source Pack: INR 399 plus 18% GST. 90 days of online access. No auto-renewal.

Cloud costs and boundaries

Runs entirely on your machine with Docker Compose: about 2.5 GB of container images and 1.5 GB of small open models, run on the CPU. The hosted providers are local emulators, so no cloud account, model-provider account, payment method or hosted lab is used or included. Connecting a real provider account is an optional extension you would pay that provider for. Running the optional CI workflow uses your own GitHub Actions minutes.

Licence and completion

Vectametric Project Source Licence (2026-09-27): lawfully obtained source may be copied, modified and deployed for personal learning and interview preparation, including personal portfolio demonstrations with attribution. These permissions continue after online access expires. Do not resell or redistribute the Source Pack or its original source files, unchanged or modified. Commercial or client production use requires separate written permission. Packages, container images and models downloaded when building or running, such as FastAPI, psycopg, Valkey, PostgreSQL with pgvector, Ollama, Grafana and the Qwen2.5 and MiniLM models, retain their own licences. See LICENSE.txt and the Project Source Licence section of the site Terms for the full rules.

Questions about projects

Do I need a cloud account?

You can read the project material without deploying it. Running a cloud build requires the accounts, permissions and tools listed in that project's prerequisites. Deployment runs in your environment, not in a hosted Vectametric lab.

Can I read the code with Learning Access?

Yes. Learning Access includes the online source-file browser and explanations. The Source Pack adds the downloadable reference repository where available. The project's licence governs use of the source.

Are cloud charges included?

No. Cloud and CI usage are separate. Read the project's cost notice, set a budget and stop deadline, and follow its destruction and leftover-resource checks.

Does the project include troubleshooting and interview preparation?

The project curriculum lists the available scenarios and interview topics. These focus on understanding the architecture and explaining decisions; they are not a promise of particular interview questions or a job.

How long can I use the project?

The project page and checkout show the online access period for your selected plan. Access does not auto-renew. Downloaded source remains subject to its licence; future releases are not automatically included.

Review the Terms and No-Refund Policy before confirming access. All sales are final; Vectametric does not offer refunds.

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy