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

推荐订阅源

博客园_首页
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Cyberwarzone
Cyberwarzone
C
CERT Recently Published Vulnerability Notes
Hacker News: Ask HN
Hacker News: Ask HN
AI
AI
T
The Exploit Database - CXSecurity.com
C
Cybersecurity and Infrastructure Security Agency CISA
Project Zero
Project Zero
Security Latest
Security Latest
Google Online Security Blog
Google Online Security Blog
Schneier on Security
Schneier on Security
P
Proofpoint News Feed
K
Kaspersky official blog
Security Archives - TechRepublic
Security Archives - TechRepublic
Help Net Security
Help Net Security
L
LINUX DO - 最新话题
Attack and Defense Labs
Attack and Defense Labs
T
Threatpost
P
Privacy International News Feed
P
Privacy & Cybersecurity Law Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
PCI Perspectives
PCI Perspectives
博客园 - Franky
C
Cisco Blogs
aimingoo的专栏
aimingoo的专栏
Stack Overflow Blog
Stack Overflow Blog
T
Tor Project blog
N
Netflix TechBlog - Medium
The Last Watchdog
The Last Watchdog
Know Your Adversary
Know Your Adversary
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The GitHub Blog
The GitHub Blog
Latest news
Latest news
Recorded Future
Recorded Future
M
MIT News - Artificial intelligence
博客园 - 叶小钗
H
Hacker News: Front Page
S
Secure Thoughts
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
阮一峰的网络日志
阮一峰的网络日志
S
Schneier on Security
Blog — PlanetScale
Blog — PlanetScale
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
腾讯CDC
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
量子位
L
LINUX DO - 热门话题

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
How I Slashed AI API Costs 60% as a Cloud Architect
swift · 2026-06-19 · via DEV Community

How I Slashed AI API Costs 60% as a Cloud Architect

I still remember the Slack message that started it all. Our CFO had pulled up a dashboard, and our monthly LLM bill had quietly crept past what we were paying for our entire Kubernetes cluster. Multiply that across three regions, add a comfortable redundancy multiplier, and you start having uncomfortable conversations with finance.

That was six months ago. Since then, I've rebuilt our inference layer from the ground up, swapped out a chunk of our OpenAI workloads, and managed to keep our p99 latency under 2 seconds while trimming 40-65% off our token spend. This isn't a theoretical exercise. These are notes from production — the kind you take when you're staring at a Datadog bill and a multi-region failover plan at 1 AM.

If you're running AI workloads at scale and sweating your monthly invoice, here's what I've learned.

The Multi-Region Math Problem Nobody Talks About

When you're shipping a product that serves users across North America, Europe, and APAC, you don't get to think about a single API call. You think about three: one near each user population, ideally routed through anycast or geo-DNS, with health checks firing every 15 seconds. You think about the cold path. You think about what happens when your primary provider has a bad Tuesday.

Most teams I talk to default to a single vendor — usually OpenAI — and then spend weeks building a thin wrapper that adds timeouts, retries, and a circuit breaker. That's not wrong, but it leaves money on the table. The unit economics of LLM calls get ugly fast when you multiply token cost by request volume by region by failover traffic by retries.

The shift I made was treating the model catalog as a tiered system:

  • Hot tier: Premium models (GPT-4o) for the 10% of requests that actually need them
  • Warm tier: Mid-range models (DeepSeek V4 Pro, Qwen3-32B) for the bulk of traffic
  • Cold tier: Cheap fast models (DeepSeek V4 Flash, GLM-4 Plus) for classification, routing, simple extraction

Routing between them based on query complexity dropped our blended cost per million tokens by more than half. The reliability story got better too — when your "expensive" path is only 10% of traffic, an outage there hurts a lot less.

The Price List That Made My CFO Smile

Here's the actual menu I work with today, all routed through Global API so I get a unified SDK, unified auth, and unified observability across 184 models. Prices are per million tokens.

Model Input Output Context Window
DeepSeek V4 Flash $0.27 $1.10 128K
DeepSeek V4 Pro $0.55 $2.20 200K
Qwen3-32B $0.30 $1.20 32K
GLM-4 Plus $0.20 $0.80 128K
GPT-4o $2.50 $10.00 128K

Do the math with me. On our heaviest workload — a document summarization pipeline pushing maybe 8 million output tokens a day — running everything through GPT-4o was costing us around $80,000/month in output tokens alone. After I moved 70% of that traffic to DeepSeek V4 Pro, that same workload runs at about $31,000. The remaining 30% still uses GPT-4o for the cases where we've measured the quality gap matters.

If you do nothing else from this article, do that exercise with your own traffic. Multiply your monthly output tokens by $10.00. Then multiply them by $2.20. The number on the right is the one your CFO wants to see.

First Code Drop: The Boring Foundation

Before you do anything clever, you need a client that lets you swap models without rewriting your call sites. Here's the first thing I committed to our monorepo:

import openai
import os
from dataclasses import dataclass

@dataclass
class ModelTier:
    name: str
    model_id: str
    input_cost: float
    output_cost: float
    max_context: int

HOT = ModelTier("hot", "gpt-4o", 2.50, 10.00, 128_000)
WARM = ModelTier("warm", "deepseek-ai/DeepSeek-V4-Pro", 0.55, 2.20, 200_000)
COLD = ModelTier("cold", "deepseek-ai/DeepSeek-V4-Flash", 0.27, 1.10, 128_000)
ECONOMY = ModelTier("economy", "THUDM/glm-4-plus", 0.20, 0.80, 128_000)

client = openai.OpenAI(
    base_url="https://global-apis.com/v1",
    api_key=os.environ["GLOBAL_API_KEY"],
)

def chat(tier: ModelTier, prompt: str, max_tokens: int = 1024) -> str:
    response = client.chat.completions.create(
        model=tier.model_id,
        messages=[{"role": "user", "content": prompt}],
        max_tokens=max_tokens,
    )
    return response.choices[0].message.content

I like this because the chat() function doesn't know or care which model it's talking to. My routing layer decides that. If I want to test a new model next quarter, I add one line to the catalog and I haven't touched my call sites. This is the kind of small architectural decision that pays off for years.

Reliability and the p99 Conversation

Let's talk latency, because this is where the cost optimization crowd gets burned.

When I first routed traffic to DeepSeek V4 Flash, the average latency looked great. Like, suspiciously great. Then I pulled the p99 and p99.9 numbers, and they were not great. Burst traffic, cold connections, the occasional upstream hiccup — all of that lives in the tail, not the mean.

Here's what I ended up with as my SLOs:

  • p50 latency: under 800ms
  • p95 latency: under 1.5s
  • p99 latency: under 2.0s
  • p99.9 latency: under 4.0s
  • Availability target: 99.9% across all three regions

To hit those numbers, I run a few things in parallel:

  1. Connection pooling with keep-alive — never open a new TLS session per request
  2. Aggressive streaming for anything user-facing — perceived latency drops by 40-60%
  3. Regional fallback — if a region's p99 crosses 3s for 2 minutes, I drain traffic
  4. A caching layer in front of deterministic prompts — 40% hit rate is achievable on most workloads

That 40% cache hit rate is real money. If you're running the same system prompts, the same tool definitions, the same few hundred customer support questions, you're paying for the same tokens over and over. A simple semantic cache with Redis or even an in-process LRU can save you 30-50% on those workloads without changing a single model call.

The deeper point: the cheapest tokens are the ones you never request. Every optimization below that is a smaller win.

Second Code Drop: Streaming, Fallback, and Real Observability

Here's the version that actually lives in production. It's a bit longer, but every line is doing work:

import openai
import os
import time
import logging
from typing import Iterator

logger = logging.getLogger("inference")

client = openai.OpenAI(
    base_url="https://global-apis.com/v1",
    api_key=os.environ["GLOBAL_API_KEY"],
)

# Fallback chain: try warm first, then escalate
FALLBACK_CHAIN = [
    "deepseek-ai/DeepSeek-V4-Flash",  # cheap, fast
    "deepseek-ai/DeepSeek-V4-Pro",    # mid-range
    "gpt-4o",                          # premium
]

def stream_with_fallback(
    prompt: str,
    primary_model: str = FALLBACK_CHAIN[0],
    max_tokens: int = 1024,
) -> Iterator[str]:
    """Stream tokens, falling back through the chain on failure."""
    models_to_try = [primary_model] + [m for m in FALLBACK_CHAIN if m != primary_model]

    for model in models_to_try:
        try:
            start = time.perf_counter()
            stream = client.chat.completions.create(
                model=model,
                messages=[{"role": "user", "content": prompt}],
                max_tokens=max_tokens,
                stream=True,
                timeout=30,
            )
            for chunk in stream:
                if chunk.choices[0].delta.content:
                    yield chunk.choices[0].delta.content

            elapsed = time.perf_counter() - start
            logger.info("inference_ok", extra={
                "model": model,
                "elapsed_ms": int(elapsed * 1000),
            })
            return
        except Exception as e:
            logger.warning("inference_fallback", extra={
                "model": model,
                "error": str(e),
            })
            continue

    raise RuntimeError("All models in fallback chain failed")

A few things worth pointing out:

  • Streaming is non-negotiable for anything user-facing. Even when the total latency is the same, the time-to-first-token is what your users actually feel. A 1.2s p95 looks instant if the first token arrives in 200ms.
  • The fallback chain isn't about price — it's about availability. If your cheap model is degraded for 10 minutes, do you really want to be returning 500s? Probably not. I let the chain escalate to GPT-4o only when the cheaper tiers fail.
  • Structured logging is what lets you compute p99 properly. The first version of this code logged nothing, and I had no way to tell whether latency was creeping up on a specific model until users complained.

The Five Things I Wish I'd Done Sooner

If you're starting this journey now, here's the order I'd recommend:

  1. Instrument first. Add latency, token count, and error rate metrics to every model call. You can't optimise what you can't see. Most teams skip this and end up flying blind.

  2. Cache aggressively. A 40% hit rate on your prompt cache is a 40% cost reduction on those requests. Redis, Memcached, an in-process dict — it doesn't matter. Cache the prompt and the response.

  3. Stream everything user-facing. Perceived latency is what users feel, and streaming cuts the time-to-first-token by 60-80% in most cases. Your p99 number doesn't change, but your support tickets do.

  4. Use economy tier for routing. I run a tiny, cheap model — GA-Economy in our setup, around half the cost of the warm tier — to classify incoming queries and route them to the right tier. The cost saving on the simple 80% of traffic easily pays for the extra hop.

  5. Monitor quality, not just cost. Cost optimization without quality monitoring is a slow-motion outage. Track user satisfaction, thumbs-up rates, escalation rates to human support. If those numbers move, you've over-optimised.

The Numbers After Six Months

Let me give you the scorecard from our actual production environment after running this architecture for a few months:

  • Cost reduction: 40-65% depending on workload, with the higher end on our classification and extraction pipelines
  • Average latency: 1.2s end-to-end for streaming responses
  • Throughput: 320 tokens/sec on sustained workloads
  • Quality: 84.6% average benchmark score across our internal eval suite
  • Setup time: under 10 minutes from a fresh pip install to a working client, because Global API gives you a single base URL and 184 models behind it

The setup time one matters more than people think. Every hour your team spends on auth, region routing, SDK mismatches, and provider-specific quirks is an hour not spent on the product. The unified interface through Global API collapsed what was previously a week of integration work into an afternoon.

What I Tell Other Architects

If I had to summarize the mindset shift, it's this: stop thinking of LLMs as a single API and start thinking of them as a tiered compute fabric. You wouldn't run every workload on the most expensive EC2 instance. You wouldn't put your batch jobs on the same tier as your latency-sensitive APIs. The same logic applies here, with even bigger cost differentials.

The other thing I'd say is: don't be afraid to mix providers. I was a GPT-4o loyalist for a long time, and the quality is genuinely good. But the gap between GPT-4o and the best open-weight models in 2026 is much smaller than it was 18 months ago, and the cost gap is enormous. For the 10-20% of workloads where the quality difference is measurable, keep GPT-4o. For everything else, route to the cheaper tiers and pocket the difference.

Try It Out

If you're working on something similar, Global API is worth a look. They expose 184 models through a single OpenAI-compatible endpoint, which means you can swap in their base URL (https://global-apis.com/v1) and start testing in minutes. The pricing spans $0.01 to $3.50 per million tokens, so there's a tier for basically every workload. I switched our entire inference layer to them in under a day, including the multi-region rollout, and I haven't looked back.

Run your own benchmarks. Pick your three or four hardest prompts. Measure cost, latency, and quality. Then decide for yourself. I think you'll be surprised how far the cheaper tiers have come — and how much that 60% saving can do for your runway.