惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Troy Hunt's Blog
Last Week in AI
Last Week in AI
D
DataBreaches.Net
大猫的无限游戏
大猫的无限游戏
Hugging Face - Blog
Hugging Face - Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Cyberwarzone
Cyberwarzone
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
WordPress大学
WordPress大学
Cisco Talos Blog
Cisco Talos Blog
Latest news
Latest news
月光博客
月光博客
博客园 - 司徒正美
C
CERT Recently Published Vulnerability Notes
L
LangChain Blog
Simon Willison's Weblog
Simon Willison's Weblog
The Register - Security
The Register - Security
T
The Blog of Author Tim Ferriss
V
V2EX
F
Fortinet All Blogs
AWS News Blog
AWS News Blog
T
Tor Project blog
V
Vulnerabilities – Threatpost
C
CXSECURITY Database RSS Feed - CXSecurity.com
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
小众软件
小众软件
L
Lohrmann on Cybersecurity
量子位
F
Full Disclosure
H
Hackread – Cybersecurity News, Data Breaches, AI and More
I
Intezer
NISL@THU
NISL@THU
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Jina AI
Jina AI
Scott Helme
Scott Helme
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Cybersecurity and Infrastructure Security Agency CISA
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园 - 三生石上(FineUI控件)
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Spread Privacy
Spread Privacy
N
Netflix TechBlog - Medium
P
Proofpoint News Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园_首页
P
Privacy & Cybersecurity Law Blog
T
Threat Research - Cisco Blogs
J
Java Code Geeks
S
Schneier on Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
What Is an AI Gateway? (And the Week We Realized We Desperately Needed One)
Sahajmeet Kaur · 2026-06-24 · via DEV Community

TL;DR

  • An AI gateway is a middleware layer between your application code and your LLM providers - it centralises routing, auth, rate limiting, cost tracking, and guardrails in one place
  • You probably don't think you need one until something specific breaks: a runaway cost spike, a failed model causing silent errors, a security audit you can't pass
  • We went from scattered SDKs and shared API keys to a gateway-first setup over about three months - this post covers what changed and what we'd do differently

Six months ago we had what I'd describe as a functional mess. We were running three LLM providers - OpenAI for our customer-facing chat, Anthropic for internal document summarisation, and a self-hosted Llama model for batch classification jobs. Each had its own SDK. Each had its own API key, living in .env files on whoever's machine had last run that service. Each had its own rate limiting logic, copy-pasted between services with slight variations.

It worked, in the way that things work when nobody has had a bad enough incident yet.

The incident arrived on a Tuesday. A background job that was supposed to run once a week got accidentally scheduled to run every minute. It was calling GPT-4o. We noticed when the Slack alert fired at 2am about an unusual credit card charge. By the time someone killed the job, we'd burned through $340 in about four hours. The API key had no spending limit. There was no alerting on token usage. The job had no rate limiting. All three of those gaps were things we knew about and hadn't prioritised.

That week, we started properly looking at AI gateways.


What an AI gateway actually is?

The simplest definition: an AI gateway is a middleware layer that sits between your application code and your LLM providers. All your LLM requests go through it, and it handles the cross-cutting concerns that you'd otherwise have to re-implement in every service: routing, authentication, rate limiting, cost tracking, caching, fallbacks, guardrails.

The analogy that clicked for me is an API gateway for the rest of your microservices stack. If you've ever set up Kong or AWS API Gateway to handle auth and rate limiting for your REST services, an AI gateway does the same thing but for LLM traffic specifically, which has different characteristics (token-based pricing, streaming responses, variable latency, context windows) that a generic API gateway doesn't handle cleanly.

Architecturally, it typically has:

  • A routing engine that directs requests to the right model based on rules you define (latency, cost, fallback chains)
  • A policy layer for rate limits, spending caps, and access control
  • An observability stack that logs requests, responses, token usage, and costs — ideally at per-user and per-team granularity
  • A caching layer that avoids redundant API calls for identical or semantically similar prompts

The important thing is that none of this lives in your application code. It's a separate layer with its own config, which means you can change routing rules or enforce a new spending limit without touching application code or doing a deployment.


The problems it actually solves

Before I get into specific features, it helps to be concrete about the problems. The ones we hit:

1. Unmanaged API keys

We had four API keys in four .env files. When an engineer left the team, we invalidated their personal keys but not the shared service keys, because we weren't entirely sure which services were using them. A gateway solves this by being the only thing that holds the real provider keys. Application services authenticate to the gateway with scoped virtual keys. If you need to revoke access, you revoke the virtual key — the underlying provider key stays intact and doesn't need to change.

2. Zero cost visibility

We knew our monthly spend from the Anthropic and OpenAI dashboards. We had no idea which team or service was responsible for which portion of that spend. When costs went up, we couldn't attribute it. A gateway with per-team and per-service cost tracking meant that the next month, we had a breakdown: classification job (42%), customer chat (31%), internal summarisation (19%), miscellaneous (8%). Suddenly we knew where to optimise.

3. No spending limits

The Tuesday incident. Enough said. A gateway lets you set hard token or spend limits per API key, per team, per service. When the limit hits, the request gets a rate-limit error instead of a bill at the end of the month.

4. Silent failures on model outages

When OpenAI had a partial outage last March, our customer chat just... failed quietly. Requests returned errors, the frontend showed a generic message, and we found out from a user report rather than an alert. A gateway with fallback routing would have automatically switched to Anthropic or our self-hosted model and kept the service up. We were just making direct SDK calls with no fallback logic.

5. The security audit

This one came from outside the team. Our security team did a review and had two questions we couldn't fully answer: "Can you show me an audit log of which users triggered which model calls in the last 90 days?" and "How do you ensure that production credentials aren't accessible to developers locally?" We couldn't answer either cleanly. A gateway with request-level logging and centralised key management is the infrastructure answer to both.


What "routing" means in practice

One feature that sounds vague but turned out to be genuinely useful: routing.

Not just "send this request to OpenAI" — but intelligent routing. There are a few modes worth understanding:

Latency-based routing: The gateway continuously monitors response times across your configured providers. When one provider's latency spikes, it automatically routes to whichever is fastest. This is particularly useful when you're using multiple deployments of the same model across regions.

Weighted load balancing: You can split traffic across providers by percentage. We used this when testing a new model — routing 10% of requests to the new model, watching the metrics, and gradually shifting the split as confidence grew. No code changes, just a config update.

Fallback chains: Define a priority order. If the primary model is unavailable or rate-limited, try the secondary, then the tertiary. The request succeeds from the application's perspective — it never sees the fallback happen.

Cost-based routing: Route to cheaper models for lower-stakes tasks. We ended up routing classification jobs to a smaller, cheaper model and only using GPT-4o for the tasks that genuinely needed it. The gateway enforces this policy centrally rather than relying on individual engineers to make cost-conscious choices in every service.


Caching: the feature we underestimated

We expected to use caching for exact-match deduplication — if two users send the identical prompt, return the cached response. Useful, but not that common in practice.

What we didn't expect was how useful semantic caching turned out to be. Semantically similar prompts — not identical, but asking for the same thing slightly differently — return the cached response if the similarity score is above a threshold you configure. For our summarisation workload, we found that a significant portion of requests were semantically similar enough to return cached results. That's real cost reduction without any change in output quality.

The key configuration decisions: cache expiry (how long is a cached response valid?), and the similarity threshold (how similar is "similar enough"?). These are worth tuning — the defaults are conservative and you can usually go more aggressive once you understand your workload.


Guardrails: the part most teams skip until they shouldn't

Guardrails are the part of AI gateway setup that gets deferred because it feels like a "compliance problem" rather than an engineering problem. It's both.

A guardrail is a policy that runs on requests before they're sent to the model (input guardrails) and on responses before they're returned to the application (output guardrails). Common uses:

  • PII detection: Strip or redact personally identifiable information before it leaves your environment or appears in a response. Crucial if you're handling customer data.
  • Content moderation: Filter inputs or outputs that violate safety policies.
  • Prompt injection detection: Flag or block requests that appear to be attempting to manipulate the model's behaviour via injected instructions. Particularly important if any user-generated content makes it into your prompts.

The way TrueFoundry handles this is through pre-built integrations that need no external credentials for the basics, with options to plug in Azure Content Safety, AWS Bedrock Guardrails, OpenAI Moderations, or Google Model Armor for more specific requirements. You can run guardrails in validate mode (inspect, flag, optionally block) or mutate mode (inspect and modify — useful for PII scrubbing where you want to replace rather than reject).

The thing that shifted my thinking on this: guardrails aren't just for compliance. Prompt injection via third-party content is a real engineering risk once you're building agents that retrieve external content and put it into context. A guardrail that runs on retrieved content before it reaches the model is the right architectural answer — not trying to sanitise inputs at the application layer.


How we ended up on TrueFoundry

We evaluated a few options. LiteLLM was the first thing we tried — it's the obvious starting point because it's open source, MIT licensed, and gets you a unified endpoint across providers in an afternoon. We ran it for about six weeks. What broke for us: no SSO integration (we needed Okta for compliance), and the per-team budget enforcement we needed was behind the enterprise license. The YAML config also got unwieldy as we added more models and routing rules.

We ended up on TrueFoundry's AI Gateway. A few specifics that mattered to our evaluation:

Architecture: The gateway runs entirely in-memory for auth, rate limiting, and routing decisions — no external DB lookups on the hot path. Config syncs from the control plane via NATS. This means gateway latency doesn't degrade as you add governance rules. The benchmarks show 350+ RPS on 1 vCPU with under 10ms added latency at full load, which matched what we saw in our own testing.

Key management: Developers get virtual keys that map to gateway-managed provider credentials. The actual OpenAI and Anthropic keys never leave the secrets manager. Onboarding a new developer means issuing a new virtual key. Offboarding means revoking it — one action, immediate effect.

Per-team budgets: Enforced on the request path, not as a post-spend alert. When the limit hits, requests return rate-limit errors. We haven't had another 2am Slack alert.

Self-hosted model support: We route to our on-prem Llama deployment through the same gateway as our OpenAI and Anthropic traffic. Same observability, same cost attribution, same rate limiting. This was the biggest gap with Portkey, which has no visibility into self-hosted model infrastructure.

Deployment: We run it inside our VPC. The whole control plane stays in our infrastructure, which is what our security team needed to answer the data residency question cleanly.

What I'd flag as the honest tradeoff: TrueFoundry is more to set up than LiteLLM. It's Kubernetes-native, so if you don't have a K8s environment, there's more upfront work. And Portkey's prompt management UI is genuinely better for non-engineers who want to iterate on prompts without touching config files. Those are real differences worth knowing before you evaluate.


The one-line config change that changed everything

The moment everything clicked was adding this to our service configs:

export ANTHROPIC_BASE_URL=https://<gateway-url>/api/inference/
export OPENAI_BASE_URL=https://<gateway-url>/api/inference/

That's it. Every existing SDK call — LangChain, the OpenAI Python client, direct requests — started going through the gateway without any code changes. Suddenly we had cost attribution, rate limiting, and request logging across all our services. The application code didn't know anything had changed.

This is also, incidentally, the right way to think about what a gateway does to your architecture: it's a configuration change at the infrastructure layer, not a code change at the application layer. That's why the governance it provides actually holds — it's enforced at the network level, not dependent on individual engineers remembering to implement it.


When you probably don't need one yet

I don't want to make it sound like everyone needs an AI gateway immediately. If you're at an early stage, the overhead isn't worth it.

You probably don't need a gateway yet if:

  • You're one developer building a prototype or demo
  • You use a single model from a single provider
  • You have no cost visibility requirements and no compliance obligations
  • You don't have multiple teams sharing AI infrastructure

You're ready for a gateway when:

  • More than one team is hitting LLMs and you can't answer "what is each team spending?"
  • An engineer leaving means you need to hunt down and rotate credentials across multiple places
  • A model outage has caused a user-facing incident and you had no fallback
  • Someone has asked for an audit log and you didn't have one

The Tuesday incident was our sign. Hopefully yours is less expensive.


What's the specific thing that pushed your team toward a gateway — or convinced you to hold off? Curious whether cost incidents are as common a forcing function as they were for us, or whether it's usually the security audit that does it. Drop it in the comments.