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

推荐订阅源

爱范儿
爱范儿
T
The Blog of Author Tim Ferriss
G
Google Developers Blog
博客园_首页
博客园 - 【当耐特】
量子位
S
SegmentFault 最新的问题
B
Blog RSS Feed
酷 壳 – CoolShell
酷 壳 – CoolShell
V
Visual Studio Blog
T
Tailwind CSS Blog
阮一峰的网络日志
阮一峰的网络日志
V
V2EX
Y
Y Combinator Blog
博客园 - 聂微东
The Cloudflare Blog
小众软件
小众软件
J
Java Code Geeks
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
月光博客
月光博客
H
Help Net Security
Jina AI
Jina AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
宝玉的分享
宝玉的分享

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
The Hidden Cost of AI: Moving from Tutorial Code to Produ...
Anubhav Gupta · 2026-06-23 · via DEV Community

If you've watched a web development tutorial in the last year, chances are you've seen someone build an "AI-powered" app. The instructor pastes their OpenAI API key into an environment file, writes a simple fetch request, and within 10 minutes, the app is magically generating text.

It looks incredibly easy. So, you build your own version. It works perfectly on localhost:3000. You're ready to deploy and share it with the world.

Then, the panic sets in.

What happens if someone shares your link on Reddit? What if a user absentmindedly clicks the "Generate" button 50 times? What if a malicious bot finds your open endpoint?

Because AI APIs charge by the "token" (the amount of text processed), an unprotected endpoint isn't just a bug—it's a financial liability.

Here is what tutorials don't tell you, and how I had to adapt my backend architecture to safely deploy AI features.

The Problem: The Unprotected Wrapper
The standard tutorial implementation is essentially an unprotected wrapper. Your frontend talks to your Next.js/Node.js backend, and your backend blindly forwards the request to the LLM.

// ❌ The Tutorial Way (Dangerous in Production)
export async function POST(req) {
  const { prompt } = await req.json();

  // Blindly forwarding the request and paying for it
  const response = await openai.chat.completions.create({
    model: "gpt-4",
    messages: [{ role: "user", content: prompt }],
  });

  return Response.json(response.choices[0].message);
}

The Solution: Building a Defense Layer
To move this to production, I had to stop treating the AI API like a standard database query and start treating it like a precious resource. Here are the three pillars of production AI architecture I implemented.

1. Strict Rate Limiting
Before a request even touches the logic of my application, it has to pass a rate limiter. Using a tool like Redis (or Upstash), you can track how many requests a specific IP address or User ID has made in a given window.

If a user tries to generate 10 responses in 10 seconds, the server throws a 429 Too Many Requests error and refuses to talk to the AI. This instantly stops bots and button-mashers.

2. Token Tracking and Quotas
Rate limiting protects against bursts, but what about a user who slowly drains your API credits over a month?

To solve this, I had to update my database schema to include a tokens_used column for every user. Every time a successful AI request completes, the API returns a usage object. I extract the total_tokens from that object and add it to the user's profile in my database.

If their usage exceeds their tier (e.g., free tier vs. premium), they are locked out until they upgrade or the month resets.

3. Caching (Don't Pay for the Same Answer Twice)
This was the biggest "Aha!" moment. Why should I pay the AI to answer "How do I reverse a string in Python?" if another user asked the exact same question yesterday?

By implementing a caching layer (saving the Prompt and the AI's Response to my own database), I can check the database first. If the answer exists, I serve it instantly for free. If it doesn't, only then do I query the AI.

Your 5-line tutorial endpoint suddenly turns into this:

// ✅ The Production Way (Pseudocode)
export async function POST(req) {
  const user = await authenticateUser(req);
  const { prompt } = await req.json();

  // 1. Rate Limiting Check
  if (await isRateLimited(user.id)) return Error("Too many requests");

  // 2. Quota Check
  if (user.tokens_used > MAX_LIMIT) return Error("Upgrade your plan");

  // 3. Cache Check
  const cachedResponse = await checkDatabaseCache(prompt);
  if (cachedResponse) return Response.json(cachedResponse);

  // 4. The actual AI call
  const response = await openai.chat.completions.create({...});

  // 5. Save usage and cache the response
  await saveToCache(prompt, response);
  await updateUserTokens(user.id, response.usage.total_tokens);

  return Response.json(response);
}

The Takeaway
Integrating an AI API is the easiest part of building an AI application. The real engineering challenge lies in building the infrastructure around it—protecting your endpoints, managing costs, and optimizing performance.

Are you building an AI-powered app? What strategies are you using to manage API costs and prevent abuse? Let me know in the comments!