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

推荐订阅源

N
Netflix TechBlog - Medium
Recorded Future
Recorded Future
云风的 BLOG
云风的 BLOG
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Troy Hunt's Blog
Security Latest
Security Latest
Scott Helme
Scott Helme
Project Zero
Project Zero
C
Cybersecurity and Infrastructure Security Agency CISA
Google DeepMind News
Google DeepMind News
NISL@THU
NISL@THU
Latest news
Latest news
L
Lohrmann on Cybersecurity
P
Palo Alto Networks Blog
V
Vulnerabilities – Threatpost
Application and Cybersecurity Blog
Application and Cybersecurity Blog
AWS News Blog
AWS News Blog
S
Schneier on Security
TaoSecurity Blog
TaoSecurity Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
N
News and Events Feed by Topic
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
H
Hacker News: Front Page
D
DataBreaches.Net
大猫的无限游戏
大猫的无限游戏
W
WeLiveSecurity
Cyberwarzone
Cyberwarzone
T
Threat Research - Cisco Blogs
The Register - Security
The Register - Security
L
LINUX DO - 热门话题
阮一峰的网络日志
阮一峰的网络日志
T
Tailwind CSS Blog
B
Blog
D
Docker
Apple Machine Learning Research
Apple Machine Learning Research
P
Privacy & Cybersecurity Law Blog
Engineering at Meta
Engineering at Meta
A
About on SuperTechFans
Webroot Blog
Webroot Blog
Martin Fowler
Martin Fowler
The Cloudflare Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
SegmentFault 最新的问题
Vercel News
Vercel News
WordPress大学
WordPress大学
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Recent Announcements
Recent Announcements
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog

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
The Hidden Cost of AI Agents: Why Your LLM Pipeline Is Bleeding Money
Abdul Rehman · 2026-06-18 · via DEV Community

I've seen teams burn through their entire AI budget in weeks. Not because they built the wrong thing. Because they never looked at how each request flows through their pipeline.

That's the hidden cost of AI agents. It's not the API pricing page. It's the architecture decisions you make before you ship.

Here's what I've learned running production LLM pipelines that process 10,000+ jobs daily, and how to fix the leaks before they drain your budget.

The Three Cost Leaks Nobody Talks About

Most teams focus on the wrong thing. They obsess over per-token pricing when the real money bleeds from three structural problems.

Leak one: uniform model routing. Every request goes to the same expensive model because it's simpler to code. I've seen systems call GPT-4 to extract a date from a string. That's a regex job with an LLM-shaped price tag.

Leak two: synchronous everything. Each request opens a fresh connection, waits for a response, and holds resources idle. When you're processing thousands of jobs, the latency tax compounds into a cost tax.

Leak three: no caching. The same document gets re-embedded, the same prompt gets re-evaluated, the same extraction gets re-run. Every repeat call is pure waste.

After addressing these three leaks, the same workload can cost far less without changing any business logic.

Batch Everything That Doesn't Need Real-Time

The single most effective cost move I've made was adopting OpenAI's Batch API for non-urgent workloads.

Here's the tradeoff: batch jobs return in hours instead of seconds, but they cost 50% less. For any pipeline that processes data overnight, runs scheduled extractions, or handles background enrichment, this is free money.

// Before: individual API calls for each job
async function processJob(jobData: JobData) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4o-mini',
    messages: [{ role: 'user', content: buildPrompt(jobData) }]
  });
  return parseResponse(response);
}

// After: batch processing for non-urgent jobs
async function processBatch(jobs: JobData[]) {
  const batch = jobs.map(job => ({
    custom_id: job.id,
    method: 'POST',
    url: '/v1/chat/completions',
    body: {
      model: 'gpt-4o-mini',
      messages: [{ role: 'user', content: buildPrompt(job) }]
    }
  }));

  const batchFile = await openai.files.create({
    file: new File([JSON.stringify({ requests: batch })], 'batch.jsonl'),
    purpose: 'batch'
  });

  const batchJob = await openai.batches.create({
    input_file_id: batchFile.id,
    endpoint: '/v1/chat/completions',
    completion_window: '24h'
  });

  return batchJob.id; // Poll this later for results
}

For a job platform I work on, description extraction runs through the Batch API. Jobs submitted during the day get results by morning. The cost difference is substantial.

Model Selection Per Task

Not every task needs a frontier model. I run a multi-tier routing system that assigns requests based on complexity.

Rules I apply in production:

  • GPT-4o-mini handles most traffic: extraction, classification, simple generation. It's fast and cheap.
  • DeepSeek V4 Flash handles structured output tasks where I need JSON reliability without paying GPT-4 prices. It costs roughly 23x less than GPT-4.1 for equivalent quality on well-defined schemas.
  • GPT-4o only enters for tasks requiring nuanced reasoning, multi-step analysis, or when smaller models fail quality gates.

Here's the router pattern I use:

type TaskComplexity = 'simple' | 'medium' | 'complex';

function selectModel(task: TaskComplexity): string {
  switch(task) {
    case 'simple':
      return 'gpt-4o-mini'; // $0.15/1M input tokens
    case 'medium':
      return 'deepseek-chat'; // ~$0.14/1M input, 23x cheaper than GPT-4.1
    case 'complex':
      return 'gpt-4o'; // Only when smaller models fail
  }
}

The trick is having a quality gate that demotes failed outputs. If GPT-4o-mini returns a malformed JSON or misses a required field, the system escalates to the next tier. That way you're not guessing which model to use. The data decides.

Fallback Chains Prevent Costly Retries

When an LLM call fails, most teams retry the same model. That's expensive and pointless. The failure is often model-specific.

I build fallback chains that route through progressively cheaper models first, then escalate to expensive ones only when necessary.

async function callWithFallback(prompt: string, models: string[]) {
  for (const model of models) {
    try {
      const response = await openai.chat.completions.create({
        model,
        messages: [{ role: 'user', content: prompt }],
        temperature: 0.1 // Lower temperature for deterministic fallback behavior
      });
      return response.choices[0].message.content;
    } catch (error) {
      console.warn(`Model ${model} failed, trying next in chain`);
      continue;
    }
  }
  throw new Error('All models in fallback chain failed');
}

// Usage: try cheap models first
const result = await callWithFallback(prompt, [
  'gpt-4o-mini',
  'deepseek-chat',
  'gpt-4o'
]);

This pattern keeps costs predictable. The cheap models succeed the vast majority of the time. The expensive ones only trigger for the edge cases.

Caching at Every Layer

Most teams cache at the database level. They miss the bigger wins.

Prompt result caching. If two jobs produce the same prompt (same input data, same task), the second call should return cached output. I use a simple key-value store with the prompt hash as the key.

Embedding caching. For RAG pipelines, the same documents get embedded repeatedly. Cache the embedding vectors by document hash. The first call pays the full cost. Every subsequent call costs a cache lookup.

Model selection caching. If a specific input pattern consistently fails on GPT-4o-mini and succeeds on DeepSeek, cache that mapping. The system learns which model works for which input signature without re-testing every time.

Monitoring That Tells You What's Broken

You can't fix what you don't measure. I track three metrics per pipeline:

  • Cost per job. Not per token. Per job. This is the number that matters to the business.
  • Model distribution. What percentage of requests hit each tier. If GPT-4o is handling a large share of traffic, that's a red flag.
  • Fallback rate. How often does the cheap model fail and escalate? A high fallback rate means your routing rules need tuning.

Sentry catches errors. LogRocket shows user impact. But a simple dashboard tracking these three numbers catches the cost leaks before they become emergencies.

When to Spend More

Here's the counterintuitive part. Sometimes you should spend more, not less.

If a cheap model produces output that requires human review or rework, the cost of fixing bad output often exceeds the savings from the cheap call. I've seen teams save pennies on an API call and lose dollars in human labor fixing the result.

The rule: measure output quality alongside cost. If your fallback rate to expensive models stays low, the cheap tier is working. If it climbs, your routing needs adjustment, not just cost cutting.

If your team is building AI agents that need to handle production volume without surprise bills, that's the kind of thing I help with. Happy to compare notes on what's working in your pipeline.


Written by Abdul Rehman, full-stack AI engineer building production SaaS, MVPs, and AI automation. More at PrimeStrides.