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

推荐订阅源

爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
罗磊的独立博客
大猫的无限游戏
大猫的无限游戏
人人都是产品经理
人人都是产品经理
博客园 - 司徒正美
Apple Machine Learning Research
Apple Machine Learning Research
Microsoft Security Blog
Microsoft Security Blog
IT之家
IT之家
M
MIT News - Artificial intelligence
S
SegmentFault 最新的问题
H
Hackread – Cybersecurity News, Data Breaches, AI and More
AI
AI
I
InfoQ
博客园_首页
T
Threatpost
Know Your Adversary
Know Your Adversary
T
Tenable Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
NISL@THU
NISL@THU
V
Vulnerabilities – Threatpost
The Hacker News
The Hacker News
N
News and Events Feed by Topic
O
OpenAI News
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
TaoSecurity Blog
TaoSecurity Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Spread Privacy
Spread Privacy
W
WeLiveSecurity
Hacker News - Newest:
Hacker News - Newest: "LLM"
K
Kaspersky official blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
Troy Hunt's Blog
Help Net Security
Help Net Security
Hacker News: Ask HN
Hacker News: Ask HN
C
CERT Recently Published Vulnerability Notes
H
Heimdal Security Blog
A
About on SuperTechFans
The Last Watchdog
The Last Watchdog
腾讯CDC
Jina AI
Jina AI
Schneier on Security
Schneier on Security
T
Threat Research - Cisco Blogs
Security Latest
Security Latest
Recorded Future
Recorded Future
量子位
有赞技术团队
有赞技术团队
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org

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
Productionizing Ollama: Rate Limits, Cloud Fallback, and Cost Guardrails
NeuroLink AI · 2026-05-16 · via DEV Community

Productionizing Ollama: Rate Limits, Cloud Fallback, and Cost Guardrails

Running Ollama locally is easy. Running it in a production service that handles concurrent users without melting your box — that's a different problem.

I wrote up the basic Ollama + NeuroLink setup in Running Local LLMs with NeuroLink and Ollama: Complete Guide. This article is the follow-up: what happens after you ship it and it gets real traffic.

Three things break first: request queues pile up under concurrency, latency spikes on heavier models, and you have no budget guardrails because "it's free" turns out not to mean "it can't cause you problems." Here's how to solve all three.


The Problem: Ollama Has No Native Rate Limiting

OpenAI returns a 429 when you hit its rate limit. Ollama doesn't have a rate limit — it queues requests and processes them serially on whatever GPU you have. Five concurrent requests to llama3.1:70b on a single machine means the fifth request waits for the first four to finish.

In practice, your p99 latency goes from 4 seconds to 20 seconds and your users give up.

You need to impose your own rate limiting at the SDK layer before requests reach the Ollama process.


Pattern 1: Request Throttling via Middleware

NeuroLink's middleware system runs as a pipeline on every generate() call. A throttling middleware can reject or queue requests before they're dispatched to the provider:

import { NeuroLink } from "@juspay/neurolink";

// Simple token-bucket rate limiter
class TokenBucket {
  private tokens: number;
  private lastRefill = Date.now();

  constructor(
    private readonly capacity: number,
    private readonly refillRatePerSecond: number
  ) {
    this.tokens = capacity;
  }

  consume(): boolean {
    const now = Date.now();
    const elapsed = (now - this.lastRefill) / 1000;
    this.tokens = Math.min(
      this.capacity,
      this.tokens + elapsed * this.refillRatePerSecond
    );
    this.lastRefill = now;

    if (this.tokens >= 1) {
      this.tokens -= 1;
      return true;
    }
    return false;
  }
}

const bucket = new TokenBucket(10, 2); // 10 burst, 2 req/sec sustained

const throttleMiddleware = {
  name: "ollama-throttle",
  priority: 120, // Runs before everything else
  transformParams: async (params: any) => {
    if (!bucket.consume()) {
      throw new Error("LOCAL_RATE_LIMIT: Ollama request queue full");
    }
    return params;
  },
};

const ai = new NeuroLink({
  provider: "ollama",
  model: "llama3.1",
  middleware: [throttleMiddleware],
});

Enter fullscreen mode Exit fullscreen mode

The middleware throws a LOCAL_RATE_LIMIT error before the request reaches Ollama. Your calling code catches this and routes elsewhere — which brings us to the next pattern.


Pattern 2: Falling Back to Cloud When Local is Overloaded

This is the multi-provider fallback pattern from Building Resilient AI: Multi-Provider Fallback Patterns in TypeScript applied specifically to the Ollama overload scenario.

NeuroLink's fallbackChain handles provider-level failures automatically, but the throttle middleware above throws before the provider is even called. You need to catch that specific error and escalate.

Here's the full pattern:

import { NeuroLink } from "@juspay/neurolink";

// Primary: local Ollama with throttle
const localAI = new NeuroLink({
  provider: "ollama",
  model: "llama3.1",
  middleware: [throttleMiddleware],
});

// Fallback: cloud providers in priority order
const cloudAI = new NeuroLink({
  providers: [
    { name: "anthropic", model: "claude-3-5-haiku-20241022", priority: 1 },
    { name: "openai", model: "gpt-4o-mini", priority: 2 },
  ],
  fallbackChain: ["anthropic", "openai"],
});

async function generate(prompt: string) {
  try {
    return await localAI.generate({ input: { text: prompt } });
  } catch (err: any) {
    if (err.message?.startsWith("LOCAL_RATE_LIMIT")) {
      // Ollama queue full — route to cloud
      console.warn("Ollama saturated, routing to cloud");
      return await cloudAI.generate({ input: { text: prompt } });
    }
    throw err; // Re-throw unexpected errors
  }
}

const result = await generate("Summarize this support ticket...");
console.log(`Provider used: ${result.provider}`);

Enter fullscreen mode Exit fullscreen mode

The critical thing here: you want Haiku or GPT-4o-mini as your cloud fallback, not Claude Sonnet or GPT-4o. The fallback scenario is "Ollama is busy" — you're handling overflow, not upgrading quality. Match the capability tier, not the price tier.


Pattern 3: Latency Budgets — Switching on Timeout

Queue saturation isn't the only signal that Ollama is struggling. A 70B model under thermal throttling might accept the request but take 30 seconds to answer. You need a latency budget.

NeuroLink's generate() accepts a timeout option (number ms or string like "8s") plus an abortSignal, and the FallbackConfig chain triggers on errors — including timeout errors. Combine both for a clean latency-budget pattern:

import { NeuroLink } from "@juspay/neurolink";

const ai = new NeuroLink({
  providers: [
    {
      name: "ollama",
      model: "llama3.1",
      priority: 1,
    },
    {
      name: "anthropic",
      model: "claude-3-5-haiku-20241022",
      priority: 2,
      apiKey: process.env.ANTHROPIC_API_KEY,
    },
  ],
  fallbackConfig: {
    enabled: true,
    maxAttempts: 2, // ollama, then anthropic
    circuitBreaker: true,
  },
});

const result = await ai.generate({
  input: { text: prompt },
  timeout: 8000, // 8s budget for the call; throws → fallback chain takes over
});

// Log which provider actually served this request
if (result.provider !== "ollama") {
  console.warn(`Latency budget exceeded, fell back to ${result.provider}`);
  metrics.increment("ollama.latency_fallback");
}

Enter fullscreen mode Exit fullscreen mode

Set your timeout conservatively. An 8-second budget for an interactive request is already too slow for chat. If you're building a real-time interface, consider 3-4 seconds and accepting that heavy models will frequently fall back. Batch processing can afford 15-30 seconds.

The timeout option applies to the whole generate() call. For a strict per-provider deadline (e.g., "give Ollama exactly 3 seconds before racing Claude"), wrap each provider's call in a Promise.race with your own AbortController — the SDK doesn't expose a per-provider timeout field directly.


Pattern 4: Cost Guardrails with the onFinish Hook

"Ollama is free" is true for the LLM calls themselves. It's not true for:

  • Cloud fallback calls (every Anthropic/OpenAI request costs money)
  • Your compute bill if you're running Ollama on cloud GPU instances
  • The engineering time debugging a service that's silently spending money

The onFinish lifecycle hook fires after every successful generation with usage data and provider info. Use it to track where your spend is going:

import { NeuroLink } from "@juspay/neurolink";

// Per-1K token pricing (cloud fallback providers)
const CLOUD_PRICING: Record<string, { input: number; output: number }> = {
  "claude-3-5-haiku-20241022": { input: 0.0008, output: 0.004 },
  "gpt-4o-mini": { input: 0.00015, output: 0.0006 },
};

let sessionCost = 0;
const BUDGET_ALERT_USD = 5.0; // Alert when session spend hits $5

const ai = new NeuroLink({
  providers: [
    { name: "ollama", model: "llama3.1", priority: 1 },
    {
      name: "anthropic",
      model: "claude-3-5-haiku-20241022",
      priority: 2,
      apiKey: process.env.ANTHROPIC_API_KEY,
    },
  ],
  fallback: true,
  fallbackConfig: { timeoutMs: 8000, retryAttempts: 1 },
  middleware: [
    {
      name: "cost-guard",
      onFinish: (result, metadata) => {
        // Ollama cost is effectively zero, but the hook still fires
        const pricing = CLOUD_PRICING[metadata.model] ?? { input: 0, output: 0 };
        const callCost =
          ((result.usage?.promptTokens ?? 0) / 1000) * pricing.input +
          ((result.usage?.completionTokens ?? 0) / 1000) * pricing.output;

        sessionCost += callCost;

        // Always log provider — visibility into fallback frequency is useful
        console.log(
          `[cost-guard] provider=${metadata.provider} ` +
          `model=${metadata.model} ` +
          `tokens=${result.usage?.totalTokens ?? 0} ` +
          `cost=$${callCost.toFixed(6)} ` +
          `session_total=$${sessionCost.toFixed(4)}`
        );

        if (metadata.provider !== "ollama") {
          metrics.increment("ollama.fallback_call", {
            provider: metadata.provider,
          });
        }

        if (sessionCost > BUDGET_ALERT_USD) {
          notifyOps(`Cloud fallback cost alert: $${sessionCost.toFixed(2)} this session`);
        }
      },
    },
  ],
});

Enter fullscreen mode Exit fullscreen mode

Even when Ollama handles the request, this log line tells you your fallback rate. If 30% of requests are hitting cloud fallback, your Ollama instance is undersized for your traffic.


Putting It Together: A Production-Ready Ollama Service

Here's the complete pattern for a service that handles realistic traffic:

import { NeuroLink } from "@juspay/neurolink";

const CLOUD_PRICING = {
  "claude-3-5-haiku-20241022": { input: 0.0008, output: 0.004 },
  "gpt-4o-mini": { input: 0.00015, output: 0.0006 },
};

const bucket = new TokenBucket(10, 2);

export const ai = new NeuroLink({
  providers: [
    { name: "ollama", model: "llama3.1", priority: 1 },
    {
      name: "anthropic",
      model: "claude-3-5-haiku-20241022",
      priority: 2,
      apiKey: process.env.ANTHROPIC_API_KEY,
    },
  ],
  fallback: true,
  fallbackConfig: {
    timeoutMs: 8000,
    retryAttempts: 1,
  },
  middleware: [
    {
      name: "throttle",
      priority: 120,
      transformParams: async (params: any) => {
        if (!bucket.consume()) {
          throw new Error("LOCAL_RATE_LIMIT");
        }
        return params;
      },
    },
    {
      name: "cost-guard",
      onFinish: (result, metadata) => {
        const pricing = (CLOUD_PRICING as any)[metadata.model] ?? { input: 0, output: 0 };
        const cost =
          ((result.usage?.promptTokens ?? 0) / 1000) * pricing.input +
          ((result.usage?.completionTokens ?? 0) / 1000) * pricing.output;

        recordMetrics({
          provider: metadata.provider,
          model: metadata.model,
          tokens: result.usage?.totalTokens ?? 0,
          cost,
          duration: metadata.duration,
          wasLocal: metadata.provider === "ollama",
        });
      },
      onError: (error, metadata) => {
        logger.error("generation_failed", {
          provider: metadata.provider,
          error: error.message,
          recoverable: metadata.recoverable,
        });
      },
    },
  ],
});

export async function generateWithFallback(prompt: string) {
  try {
    return await ai.generate({ input: { text: prompt } });
  } catch (err: any) {
    if (err.message?.startsWith("LOCAL_RATE_LIMIT")) {
      // Explicit queue-full path: skip Ollama entirely, go straight to cloud
      return await new NeuroLink({
        providers: [
          {
            name: "anthropic",
            model: "claude-3-5-haiku-20241022",
            apiKey: process.env.ANTHROPIC_API_KEY,
          },
        ],
      }).generate({ input: { text: prompt } });
    }
    throw err;
  }
}

Enter fullscreen mode Exit fullscreen mode


What to Watch in Production

A few metrics worth tracking:

  • ollama.fallback_rate: What percentage of requests don't complete on Ollama. Over 10% means your instance is undersized.
  • ollama.p95_latency: If your 70B model's p95 goes above your timeout threshold, you need a smaller model or more hardware.
  • cloud_fallback.cost_per_hour: Your actual cloud spend from overflow requests. This is your real Ollama infrastructure cost.
  • token_bucket.rejection_rate: How often you're hitting the local rate limit before even trying Ollama. A spike here usually means a burst of traffic, not a hardware problem.

The Ollama guide covers what to run. This setup covers what to watch after you run it.


Get started with NeuroLink: