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

推荐订阅源

Engineering at Meta
Engineering at Meta
The GitHub Blog
The GitHub Blog
博客园_首页
T
The Blog of Author Tim Ferriss
H
Hackread – Cybersecurity News, Data Breaches, AI and More
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
腾讯CDC
I
InfoQ
量子位
J
Java Code Geeks
P
Proofpoint News Feed
有赞技术团队
有赞技术团队
Webroot Blog
Webroot Blog
Martin Fowler
Martin Fowler
D
Docker
F
Fortinet All Blogs
云风的 BLOG
云风的 BLOG
V
Vulnerabilities – Threatpost
罗磊的独立博客
P
Proofpoint News Feed
T
The Exploit Database - CXSecurity.com
Cyberwarzone
Cyberwarzone
P
Privacy & Cybersecurity Law Blog
Last Week in AI
Last Week in AI
爱范儿
爱范儿
The Hacker News
The Hacker News
S
SegmentFault 最新的问题
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 三生石上(FineUI控件)
V
V2EX
Simon Willison's Weblog
Simon Willison's Weblog
AI
AI
Y
Y Combinator Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
GbyAI
GbyAI
V
Visual Studio Blog
H
Heimdal Security Blog
S
Secure Thoughts
B
Blog RSS Feed
雷峰网
雷峰网
T
Tenable Blog
C
Check Point Blog
G
Google Developers Blog
大猫的无限游戏
大猫的无限游戏
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
About on SuperTechFans
Recent Commits to openclaw:main
Recent Commits to openclaw:main

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
RAG Series (22): Long Context vs RAG — Do We Even Need RAG?
WonderLab · 2026-05-19 · via DEV Community

A Question Worth Taking Seriously

Gemini 1.5 Pro supports 1 million token context. Claude 3.5 handles 200K tokens. GPT-4 Turbo handles 128K. A small novel fits in context. Some people ask: is RAG still necessary?

The question deserves a real answer, because it hides a genuine engineering decision: for a production system, should I use RAG or long context?


The Numbers

Large language model context windows (2024–2025):

Model Context Window Approximate text
Gemini 1.5 Pro 1,000,000 tokens ~750,000 words, ~1500 pages
Claude 3.5 Sonnet 200,000 tokens ~150,000 words, ~300 pages
GPT-4 Turbo 128,000 tokens ~96,000 words, ~190 pages
GPT-4o 128,000 tokens ~96,000 words, ~190 pages

This looks like a lot. But how much content does a real knowledge base have?

  • A mid-sized company's internal documentation: thousands of documents, millions of words
  • A large codebase: tens of thousands of files, billions of tokens
  • A news or research database: millions of articles

All of these exceed any model's context window. That is the hard ceiling on long context.


The Real Cost of Long Context

"Bigger window" doesn't mean "free." Every request processes every token, and the cost is real.

Cost 1: Money

Rough estimates at late 2024 pricing (input tokens):

Model Price per 1M tokens 1M token request
Gemini 1.5 Pro $1.25 $1.25
Claude 3.5 Sonnet $3.00 $3.00
GPT-4 Turbo $10.00 $10.00

Compare to RAG:

  • Retrieval phase: Embedding API only (< $0.001)
  • Generation phase: 2,000–5,000 tokens of retrieved context + question (< $0.05)

RAG can cost 20–200× less than long context for the same question.

At 1,000 user queries per day against an enterprise knowledge base:

  • Long context (1M tokens): ~$1,250/day
  • RAG (3K token context): ~$3–15/day

Cost 2: Latency

More tokens = slower response. Time to first token (TTFT) grows roughly linearly with input length:

100K token input → TTFT ~2–5 seconds
1M token input   → TTFT ~15–30 seconds (varies by model and infrastructure)

Enter fullscreen mode Exit fullscreen mode

A conversational application where the user waits 30 seconds before any output is largely unusable.

Cost 3: Lost in the Middle

A 2023 Stanford paper "Lost in the Middle" (Liu et al.) found that when relevant information appears in the middle of a long context, LLM recall drops significantly. Information at the beginning or end performs best; information in the middle performs worst.

Position vs. recall (approximate trend):
Beginning (0–10%)    ████████████████ high
Middle (40–60%)      ██████           low
End (90–100%)        ████████████     higher

Enter fullscreen mode Exit fullscreen mode

Stuffing 100 documents into context does not guarantee the model finds the one at position 50.


The Real Cost of RAG

RAG isn't free either.

Cost 1: Imperfect Retrieval

Vector search is approximate matching — it makes mistakes:

  • False negatives: relevant documents not retrieved. The user's question is semantically distant from the relevant passage; it falls outside the top-k.
  • False positives: irrelevant documents retrieved. The LLM receives noise, which can cause confusion or hallucination.

This is exactly the problem that earlier articles in this series addressed: hybrid retrieval, Rerank, HyDE — all of these are patches for retrieval imperfection.

Cost 2: Chunking Breaks Context

Chunking splits documents into fragments. Related information can end up in different chunks. A 10-page research report whose conclusion depends on an assumption from page 3 may be split such that only the conclusion chunk is retrieved — the LLM gets the conclusion without the premise.

Cost 3: System Complexity

RAG is an engineering system: vector store + embedding model + retrieval pipeline + update mechanism + evaluation framework. Compared to "send the document to the LLM," it has significantly higher maintenance cost.


Five-Dimension Comparison

Dimension Long Context RAG
Document volume ceiling ~10–100 docs (limited by window and cost) Unlimited (vector store scales)
Cost High (all tokens billed every request) Low (only relevant fragments)
Latency High (large inputs are slow) Low (small inputs are fast)
Recall completeness Perfect (everything is present) Incomplete (depends on retrieval quality)
Knowledge updates Requires resending all content Only update changed documents
Engineering complexity Low (direct API call) High (retrieval pipeline to maintain)
Single-document understanding Strong (cross-document reasoning) Weaker (affected by chunking)

Neither approach wins on all dimensions.


Decision Framework: Which One?

Four dimensions to locate your scenario:

Dimension 1: Document Volume

< 50 docs, total < 100K tokens     → consider long context
50–1000 docs                       → evaluate cost, decide
> 1000 docs, or total > 1M tokens  → RAG

Enter fullscreen mode Exit fullscreen mode

Dimension 2: Update Frequency

Static content (monthly updates or less)   → long context acceptable
Dynamic content (daily/hourly updates)     → RAG (incremental indexing is cheap)
Real-time data                             → RAG (or direct API integration)

Enter fullscreen mode Exit fullscreen mode

Dimension 3: Query Volume

One-time analysis (research, report generation)   → long context
Low-frequency queries (< 100/day)                 → either works
High-frequency queries (> 1000/day)               → RAG (cost differences compound)

Enter fullscreen mode Exit fullscreen mode

Dimension 4: Latency Requirements

Interactive Q&A (< 3 second response)   → RAG
Report generation, offline analysis     → long context acceptable

Enter fullscreen mode Exit fullscreen mode

Summary Decision Table

Use case                       Docs    Updates   Queries   Recommendation
──────────────────────────────────────────────────────────────────────────
Legal contract review (single) small   none      once      Long context
Enterprise knowledge base Q&A  large   frequent  high      RAG
PDF financial report analysis  medium  none      once      Long context
Product documentation chatbot  large   moderate  high      RAG
Codebase understanding         huge    frequent  high      RAG
Meeting notes summary (single) small   none      once      Long context

Enter fullscreen mode Exit fullscreen mode


Hybrid Strategy: Use Both

Long context and RAG are not mutually exclusive. Sometimes the best choice is a combination.

Strategy 1: RAG selects documents, long context reads in full

# Step 1: use RAG to find the 3 most relevant documents
relevant_docs = retriever.invoke(query)  # top-3 documents

# Step 2: send full documents (not chunks) to the LLM
full_docs = [load_full_doc(doc.metadata["source"]) for doc in relevant_docs]
full_context = "\n\n".join([doc.page_content for doc in full_docs])

# Step 3: LLM answers based on complete documents
answer = llm.invoke(f"Answer based on the following documents:\n{full_context}\n\nQuestion: {query}")

Enter fullscreen mode Exit fullscreen mode

Good fit for: large document sets (can't send all), but each document requires complex cross-passage reasoning.

Strategy 2: Coarse-grained RAG with large chunks

Traditional RAG uses 512–1024 token chunks. With larger windows, you can use 3,000–10,000 token chunks — preserving much more context while still doing retrieval filtering.

# Split with larger chunks (preserve more context)
splitter = RecursiveCharacterTextSplitter(
    chunk_size=4000,    # traditional 512 → now 4000 is reasonable
    chunk_overlap=400,
)

# Retrieve fewer chunks since each is larger
retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
# 3 × 4000 = 12,000 tokens: precise and context-rich

Enter fullscreen mode Exit fullscreen mode

Strategy 3: Summary cache + precise retrieval

For large document libraries, use the LLM to generate a structured summary for each document; retrieve summaries; load the original passage on demand.

# Pre-processing: generate summaries (one-time)
for doc in all_documents:
    summary = llm.invoke(f"Summarize this document's key points in 3 sentences:\n{doc.page_content}")
    summary_doc = Document(page_content=summary, metadata={
        "source": doc.metadata["source"],
        "original": doc.page_content,
    })
    summary_vectorstore.add_documents([summary_doc])

# Query time: retrieve summaries, load original passages
def query_with_summary(question):
    summaries = summary_vectorstore.similarity_search(question, k=5)
    relevant_chunks = [
        extract_relevant_passage(s.metadata["original"], question)
        for s in summaries
    ]
    return llm.invoke(build_prompt(question, relevant_chunks))

Enter fullscreen mode Exit fullscreen mode


What Actually Changed

The rise of large context windows genuinely shifted some decisions:

Scenarios where RAG was once necessary but now may not be:

  • Understanding documents under 50 pages (just stuff it in — simpler)
  • One-time document analysis tasks (not worth building a RAG system)
  • Prototype validation (fast idea testing, no need for production-grade RAG)

Scenarios where RAG is still necessary (most production systems):

  • Knowledge bases with > 1,000 documents
  • Frequently updated content
  • High concurrency, cost-sensitive deployments
  • Attribution requirements (RAG natively knows which document an answer came from)

Large context windows made "skip RAG for simple cases" a reasonable choice. They didn't make RAG obsolete — they made RAG's use case clearer: when document volume, update frequency, or cost makes "full context" impractical, RAG is irreplaceable.


Summary

Long Context RAG
Core strength Complete context, cross-document reasoning Scalable, low cost, real-time updates
Core limitation High cost, high latency, hard document ceiling Imperfect retrieval, engineering complexity
Best for Small-scale, one-time deep analysis Large-scale production systems
Trend Windows keep growing, costs keep falling Retrieval quality keeps improving

These are not competitors — they're complementary tools. Understanding the true cost of each, and choosing the right one, is engineering judgment.


References