How does an LLM Gateway work?

Authors
How does an LLM Gateway work?

An LLM Gateway is a single middle layer that sits between our applications and all the LLM providers that we use. Every request goes through it, so it can route, secure, cache, limit, log, and track the cost of every LLM call in one place.

In this blog, we will learn about how an LLM Gateway works. We will also see the problem we face when many apps talk to many LLM providers directly, what happens to a request step by step inside the gateway, how routing, fallback, caching, rate limiting, and cost tracking work, a simple example with code, and when we need a gateway and when we do not.

We will cover the following:

  • The problem without an LLM Gateway
  • What is an LLM Gateway?
  • The journey of a request through the gateway
  • One API for all providers
  • Authentication and virtual keys
  • Routing and load balancing
  • Retries and fallback
  • Caching
  • Rate limiting and budgets
  • Guardrails
  • Logging, monitoring, and cost tracking
  • A simple example with code
  • Gateway vs calling the provider directly
  • When do we need an LLM Gateway?

I am Amit Shekhar, Founder @ Outcome School, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

I teach AI and Machine Learning at Outcome School.

Let's get started.

The problem without an LLM Gateway

Most of the time, we do not run LLMs on our own computers. They are run by companies like OpenAI, Anthropic, and Google. These companies are called LLM providers. We talk to them using their API, and each request needs an API key that tells the provider who we are, so that it can allow the request and send us the bill.

Let's say we work in a company. The company has three apps:

  • A customer support chatbot.
  • A tool that summarizes documents.
  • A code helper for developers.

Each app talks directly to the LLM providers, as below:

Support Bot  ---> OpenAI
Support Bot  ---> Anthropic
Summarizer   ---> OpenAI
Summarizer   ---> Google
Code Helper  ---> Anthropic
Code Helper  ---> OpenAI

Here, we can see that every app has its own direct connection to each provider that it uses. This looks fine at first, but the following issues arise:

  • Different APIs: Each provider has a slightly different way of sending a request. So, every app must write separate code for each provider.
  • Keys everywhere: The secret API keys are copied into every app. If one app leaks a key, we must change it in all apps.
  • No backup: If OpenAI goes down for 10 minutes, every app that uses it breaks.
  • No control on cost: One buggy app can send thousands of requests in a loop, and we only find out when the bill arrives.
  • No single view: Nobody knows how many requests each app sends, how slow they are, or how much each team spends.
  • Repeated work: Every team writes its own code for retries, logging, and safety checks. Most of the time, we do mistakes while writing the same thing again and again.

We needed a solution for that, and the LLM Gateway was introduced to solve this problem.

What is an LLM Gateway?

An LLM Gateway is a single middle layer between our apps and the LLM providers. Every LLM request from every app goes through it.

A gateway is a gate through which everything must pass. Think of the main gate of a big office building. Every visitor must pass through the reception. The receptionist checks the ID, writes the entry in a register, gives a visitor pass, and sends the visitor to the right floor.

An LLM Gateway is that reception desk for all our LLM calls.

Now, our picture looks like below:

  Support Bot     Summarizer      Code Helper
       ↓               ↓               ↓
+---------------------------------------------+
|                 LLM Gateway                 |
+---------------------------------------------+
       ↓               ↓               ↓
    OpenAI         Anthropic        Google

Here, we can see that apps no longer talk to providers directly. They only talk to the gateway. The gateway talks to the providers on their behalf.

So, all the shared work, like keys, retries, logging, limits, and cost tracking, now lives in one place. We write it once, and every app gets it for free.

Popular LLM Gateways include LiteLLM and Portkey.

Now, the question is, what exactly happens inside the gateway? Let's understand it step by step.

The journey of a request through the gateway

The best way to learn this is by taking an example.

Suppose the Support Bot sends this request: "Summarize this customer complaint." Inside the gateway, the request passes through a series of steps, like below:

+--------------------------------------------------+
| Request from app                                 |
+--------------------------------------------------+
                         ↓
+--------------------------------------------------+
| [1] Check identity (who is calling?)             |
+--------------------------------------------------+
                         ↓
+--------------------------------------------------+
| [2] Check limits and budget (are they allowed?)  |
+--------------------------------------------------+
                         ↓
+--------------------------------------------------+
| [3] Check input guardrails (is the prompt safe?) |
+--------------------------------------------------+
                         ↓
+--------------------------------------------------+
| [4] Check cache (have we answered this before?)  |
| If found, return the saved answer                |
+--------------------------------------------------+
                         ↓
+--------------------------------------------------+
| [5] Pick a provider and model (routing)          |
+--------------------------------------------------+
                         ↓
+--------------------------------------------------+
| [6] Translate and send to the provider           |
| If it fails, retry or fall back                  |
+--------------------------------------------------+
                         ↓
+--------------------------------------------------+
| [7] Check output guardrails                      |
+--------------------------------------------------+
                         ↓
+--------------------------------------------------+
| [8] Log the request, count tokens, add the cost  |
+--------------------------------------------------+
                         ↓
+--------------------------------------------------+
| Response to app                                  |
+--------------------------------------------------+

Here, we can see that the request goes through a pipeline of checks before and after the provider call. Each step does one small job.

We will learn about each of them in detail.

One API for all providers

First, the gateway gives our apps one common API.

Each provider expects the request in its own shape. The field names are a little different, and the response comes back in a different shape too.

The gateway hides these differences. Our app always sends the request in one standard format. Many gateways use the OpenAI format because many tools already support it.

Then, the gateway translates the request into the format that the chosen provider expects. When the answer comes back, it translates the response back into the standard format.

Let's take an analogy. Think of a translator at an international meeting. We speak only English. The translator speaks to each guest in their own language and brings their reply back to us in English. We never learn any other language.

Advantage: If we want to switch from one provider to another, we change one setting in the gateway. The app code does not change at all.

Planning your move into AI?

No matter which tech domain you work in today, with your effort, you can transition to these roles:

  • AI Engineer
  • Forward Deployed Engineer
  • AI Agent Engineer
  • Harness Engineer
  • Voice AI Engineer
  • AI Architect
  • LLM Engineer
  • LLM Inference Engineer
  • Gen AI Engineer
  • MLOps Engineer
  • ML Engineer
  • Deep Learning Engineer

Our AI and Machine Learning Program at Outcome School takes you there.

Authentication and virtual keys

Now, let's understand how the gateway keeps the real keys safe.

The real provider API keys are stored only inside the gateway. Our apps never see them.

Instead, the gateway gives each app or team its own key, called a virtual key. A virtual key works only with the gateway, not directly with the provider.

+----------------------------------------------------+
| Support Bot (virtual key: vk-support-123)          |
+----------------------------------------------------+
                          ↓
+----------------------------------------------------+
| Gateway: "vk-support-123 belongs to Support team"  |
+----------------------------------------------------+
                          ↓
+----------------------------------------------------+
| Gateway uses the real OpenAI key stored inside     |
+----------------------------------------------------+

Here, we can see that the app shows its virtual key, the gateway checks who it belongs to, and then the gateway uses the real key on its behalf.

Advantages:

  • If a virtual key leaks, we cancel only that key. The real key stays safe.
  • We know exactly which team sent which request.
  • We can give different permissions to different keys, like "this key can use only cheap models".

Routing and load balancing

Now, it's time to learn how the gateway decides where to send the request.

Routing means deciding which provider and which model will answer the request.

The gateway can decide based on rules, for example:

  • Send simple questions to a small, cheap model.
  • Send hard coding questions to a big, powerful model.
  • Send requests from European users to a server in Europe.

We have a detailed blog on LLM Routing that explains how to send each query to the right LLM.

Load balancing means spreading requests across many copies so that no single one gets overloaded.

Let's say we have the same model available from two places: OpenAI directly and Azure OpenAI. The gateway can send 50% of requests to each.

                 Gateway
                    ↓
         +----------+----------+
         ↓                     ↓
        50%                   50%
  OpenAI (gpt-4o)        Azure (gpt-4o)

This way, if one place becomes slow or hits its limit, the other place takes more load.

A quick note for you

No matter which tech domain you work in, get familiar with these topics:

  • LLM
  • RAG
  • MCP
  • Agent
  • Fine-tuning
  • Quantization

We put it all together in one video:

AI Engineering Explained: LLM, RAG, MCP, Agent, Fine-Tuning, and Quantization

No need to stop reading - bookmark it and watch later when you get time. Future you will thank you.

Now, let's get back to the topic.

Retries and fallback

Now, the next big question is: what happens when a provider fails?

Providers fail sometimes. They return errors when they are busy, they hit their rate limits, or they go down for some time.

Without a gateway, our app breaks unless every team writes its own retry and backup logic. So, here comes the gateway to the rescue.

First, the gateway retries, which means it tries the same request again after a short wait. Many errors are temporary, so a second try often works.

If the retries also fail, the gateway uses fallback. Fallback means moving to a backup model from another provider.

+------------------------------+
| Try OpenAI gpt-4o            |
| Result: error (server busy)  |
+------------------------------+
               ↓
+------------------------------+
| Retry OpenAI gpt-4o          |
| Result: error again          |
+------------------------------+
               ↓
+------------------------------+
| Fall back to Claude          |
| Result: success              |
+------------------------------+
               ↓
+------------------------------+
| Return answer to the app     |
+------------------------------+

Here, we can see that the app gets an answer, and it does not need to know that OpenAI failed.

Let me write a small version of this logic just for the sake of understanding:

def call_with_fallback(prompt, models):
    for model in models:              # try models in order
        for attempt in range(2):      # try each one twice
            try:
                return call_provider(model, prompt)
            except ProviderError:
                wait_a_little()       # short pause before trying again
    raise Exception("All models failed")

Here, we have a list of models in order of preference. For each model, we try two times. If a call works, we return the answer right away. If it fails, we wait a little and try again. If both tries fail, we move to the next model in the list. Only when every model fails, we raise an error.

A real gateway does the same thing with more care, like waiting longer after each failure and stopping the use of a provider for some time if it keeps failing.

Caching

Now, it's time to learn how the gateway saves money with caching.

Caching means saving an answer so that we can reuse it later without doing the work again.

Suppose 500 users ask the support bot, "What are your office hours?". Without a cache, we pay the provider 500 times for the same answer.

With a cache, the gateway saves the answer after the first call. For the next 499 requests, it returns the saved answer instantly, without a provider call and without any cost.

There are two types of caching:

  • Exact cache: The answer is reused only if the new prompt is exactly the same as an old one, letter by letter.
  • Semantic cache: The answer is reused if the new prompt has the same meaning. "What are your office hours?" and "When is your office open?" have the same meaning. The gateway turns both prompts into embeddings, which are lists of numbers that capture meaning, and checks how close they are.

Note: Caching works well for common, repeated questions. It must be used carefully for personal or time-sensitive questions, because an old answer can become wrong.

We have a detailed blog on how Semantic Caching works that covers this step by step.

Rate limiting and budgets

Now, let's understand how the gateway protects our budget.

Rate limiting means putting a cap on how many requests or how many tokens a key can use in a fixed time.

A token is a small piece of text, like a word or part of a word. Providers charge us based on the number of tokens.

For example, the gateway can have rules like:

  • The Summarizer team can send at most 100 requests per minute.
  • The Code Helper team can use at most 1 million tokens per day.
  • The Support team has a budget of 500 dollars per month.

When a key crosses its limit, the gateway stops the request and returns an error, instead of sending it to the provider.

So, one buggy app running in a loop can no longer use up the full company budget overnight.

Guardrails

Now, let's move to safety.

Guardrails are safety checks on what goes in and what comes out.

On the way in, the gateway can:

On the way out, the gateway can:

  • Block harmful or unsafe content in the answer.
  • Check that the answer follows the expected format.

Because these checks live in the gateway, every app gets the same safety rules. No team can forget to add them.

To master AI Security and Prompt Injection, check out our AI and Machine Learning Program at Outcome School.

Logging, monitoring, and cost tracking

Finally, after the response comes back, the gateway writes down everything about the request:

  • Which app and which team sent it.
  • Which model answered it.
  • How many tokens went in and how many came out.
  • How long it took.
  • Whether it was successful or failed.
  • How much it cost.

The gateway knows the price of every model, so it can multiply the tokens by the price and calculate the cost of each request.

With all this data, we can make dashboards and answer questions like "Which team spends the most?", "Which model is the slowest?", or "Why did our cost double yesterday?".

This is how the gateway gives us one single view of all our LLM usage.

Stay updated: Subscribe to our newsletter to get our latest AI and Machine Learning blogs straight to your inbox.

A simple example with code

Now, let's see a real example using LiteLLM, which is an open-source LLM Gateway.

First, we write a config file for the gateway as below:

model_list:
  - model_name: smart-model
    litellm_params:
      model: openai/gpt-4o
      api_key: os.environ/OPENAI_API_KEY

  - model_name: backup-model
    litellm_params:
      model: anthropic/claude-sonnet-4-5
      api_key: os.environ/ANTHROPIC_API_KEY

litellm_settings:
  num_retries: 2
  fallbacks: [{ 'smart-model': ['backup-model'] }]

Here, we have:

  • Created a name smart-model that points to gpt-4o from OpenAI.
  • Created a name backup-model that points to a Claude model from Anthropic.
  • Kept the real API keys in environment variables, so they stay inside the gateway machine.
  • Set num_retries to 2, so a failed call is tried again.
  • Set fallbacks, so if smart-model keeps failing, the gateway moves to backup-model.

Then, we start the gateway using the command below:

litellm --config config.yaml

Here, the gateway starts as a server on our machine, by default on port 4000.

After that, our app talks to the gateway instead of the provider. We can write the code as below:

from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:4000",   # the gateway, not the provider
    api_key="sk-my-virtual-key"          # virtual key given by the gateway
)

response = client.chat.completions.create(
    model="smart-model",
    messages=[{"role": "user", "content": "Summarize this complaint."}]
)

print(response.choices[0].message.content)

Here, we can notice a few things:

  • We are using the normal OpenAI client library, but the base_url points to our gateway.
  • We are passing a virtual key, not the real OpenAI key.
  • We ask for smart-model, a name that we defined in the gateway. The app does not care which provider is behind it.

If OpenAI fails, the gateway retries and then falls back to Claude. Our app code stays the same.

Note: The exact model names and settings change over time. We must check the documentation of the gateway that we use.

Gateway vs calling the provider directly

Let me tabulate the differences between calling providers directly and using an LLM Gateway for your better understanding so that you can decide which one to use based on your use case.

PointCalling providers directlyUsing an LLM Gateway
APIDifferent code for each providerOne common API
API keysCopied into every appStored only in the gateway
Provider failureApp breaksRetry and fallback
Repeated questionsPaid every timeServed from cache
Cost controlSeen only in the monthly billLimits and budgets per team
Safety checksEach team writes its ownSame guardrails for all
VisibilityScatteredOne dashboard for everything
Extra stepNoneAdds a small delay and one more system to run

Note: A gateway is one more system that we must run and keep healthy. If the gateway goes down, all LLM calls stop. So, in production, we run more than one copy of the gateway.

If we want to go deep into Model Deployment and Serving, Monitoring and Logging, and Infrastructure and Platform, we have a complete program on this - check out our AI and Machine Learning Program at Outcome School that covers these end to end.

When do we need an LLM Gateway?

We need an LLM Gateway when:

  • Many apps or teams use LLMs in the same company.
  • We use more than one provider or want the freedom to switch.
  • We need backup when a provider fails.
  • We must control and track the cost per team.
  • We must apply the same safety and privacy rules everywhere.

We do not need it when we have one small app, one provider, and very less traffic. In that case, calling the provider directly is simple and enough.

Now we must have understood how an LLM Gateway works.

Frequently Asked Questions

What happens if the LLM Gateway itself goes down?

If the LLM Gateway goes down, all LLM calls stop, because every request from every app passes through it. A gateway is one more system that we must run and keep healthy. So, in production, we run more than one copy of the gateway to keep our LLM calls working.

Does an LLM Gateway add latency?

Yes, an LLM Gateway adds a small delay, because every request takes one extra step through it. But it can also save time. When a request is served from the cache, the gateway returns the saved answer instantly, without any provider call and without any cost.

Do we need to change our app code to use an LLM Gateway?

Only a little. Many gateways use the OpenAI format, so our app can keep using the normal OpenAI client library. We point the base_url to the gateway and pass a virtual key instead of the real provider key. After that, switching providers is one setting in the gateway, and the app code does not change.

What is the difference between an exact cache and a semantic cache?

An exact cache reuses an answer only when the new prompt is exactly the same as an old one, letter by letter. A semantic cache reuses an answer when the new prompt has the same meaning. It turns the prompts into embeddings and checks how close they are, so "When is your office open?" can reuse the answer to "What are your office hours?".

That's it for now.

Thanks

Amit Shekhar
Founder @ Outcome School

You can connect with me on:

Follow Outcome School on:

Read all of our high-quality blogs here.