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

推荐订阅源

L
LINUX DO - 最新话题
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
PCI Perspectives
PCI Perspectives
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
H
Heimdal Security Blog
S
Security @ Cisco Blogs
N
News | PayPal Newsroom
J
Java Code Geeks
罗磊的独立博客
Security Archives - TechRepublic
Security Archives - TechRepublic
N
News and Events Feed by Topic
V
V2EX
WordPress大学
WordPress大学
Google Online Security Blog
Google Online Security Blog
N
News and Events Feed by Topic
www.infosecurity-magazine.com
www.infosecurity-magazine.com
月光博客
月光博客
AI
AI
小众软件
小众软件
The GitHub Blog
The GitHub Blog
MongoDB | Blog
MongoDB | Blog
A
Arctic Wolf
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
美团技术团队
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Hacker News - Newest:
Hacker News - Newest: "LLM"
T
Tailwind CSS Blog
S
Schneier on Security
博客园 - 三生石上(FineUI控件)
F
Full Disclosure
B
Blog RSS Feed
Forbes - Security
Forbes - Security
S
SegmentFault 最新的问题
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
人人都是产品经理
人人都是产品经理
云风的 BLOG
云风的 BLOG
Jina AI
Jina AI
Cisco Talos Blog
Cisco Talos Blog
U
Unit 42
Project Zero
Project Zero
H
Hacker News: Front Page
Y
Y Combinator Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
The Cloudflare Blog
大猫的无限游戏
大猫的无限游戏
S
Secure Thoughts
The Hacker News
The Hacker News
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 Fastest Query Is the One You Never Run: The Four Layers of Rails Caching
Dane Wu · 2026-06-27 · via DEV Community

Rails Performance: Lessons from Production — #4

The first three posts were about making queries cheaper — fewer N+1s, indexes, not dragging data back into Ruby. This one flips the angle: the fastest query is the one you never run. Compute a result once, store it, and hand it to everyone after. Same example throughout (a shipments table), walking through the four layers of Rails caching: compute, invalidate, render, transfer.


🔥 the same 800ms stat, recomputed for every visitor

The homepage shows a "courier shipment ranking." It's heavy — scanning a few million shipments and a GROUP BY takes 800ms.

The thing is: that number looks the same to every user, and it doesn't need to be real-time (a few minutes stale is fine). But our code makes every visitor recompute it from scratch — 800ms each. Under traffic, the DB gets ground down by the same calculation over and over.

That's the sweet spot for caching — expensive (worth saving) and hit repeatedly (the same result is reused). Let's start from the most basic tool.

Continuing the four layers from #1: the first three posts optimized "how data is fetched"; caching is "don't compute what you already computed." One idea runs through the whole post — use updated_at as a "version," reuse while the data hasn't changed.


📦 Layer 1 (compute): Rails.cache.fetch

Wrap that 800ms calculation:

Rails.cache.fetch("courier_ranking", expires_in: 5.minutes) do
  Shipment.group(:courier_id).count   # the heavy calculation
end

What fetch does, in one line: if it's there, take it; if not, compute it and store it.

  • First time: look up key → miss → run the block (800ms) → store it with a 5-minute expiry → return.
  • Next 5 minutes: look up key → hit → return the stored value, the block never runs (milliseconds).

So the first user pays 800ms, everyone else for the next 5 minutes gets it free.

Two key parameters:

  • key ("courier_ranking"): the cache's name. If the result varies by condition, the key must encode that, e.g. "courier_stats/#{courier.id}".
  • expires_in: how long until it expires, i.e. "how stale can you tolerate." Shorten it for fresher data.

When is something worth caching?Expensive — high recompute cost, worth saving. ② Hit repeatedly — the same result is used many times (across users, or the same query requested over and over).

As for "freshness" — that's not a precondition, it's a problem to solve: tolerate some staleness → use expires_in; need it current → use key-based invalidation so it updates the moment data changes (the next layer is exactly this).


🔑 Layer 2 (invalidate): key-based expiration

expires_in only handles "time's up," not "the data changed." You set 5 minutes, but a new shipment lands in between, and users see a stale number. How do you make the cache "update the moment data changes"?

❌ The dumb way: manually delete the cache when data changes

after_commit { Rails.cache.delete("courier_ranking") }

Problem: you have to remember "which operations affect which caches," and clear each one by hand. With many caches it becomes a nightmare — miss one and you've got a stale-data bug. This is the origin of the famous line "cache invalidation is one of the two hard problems."

✅ The smart way: put the "version" in the key, so the key changes when the data does

Rails generates a key for each record that changes with updated_at:

courier.cache_key_with_version
# → "couriers/1-20260626120000"   ← the trailing part is the updated_at timestamp

Use it as the cache key:

Rails.cache.fetch(courier.cache_key_with_version) do
  expensive_render(courier)
end

  • courier unchanged → key unchanged → hit (old value) ✅
  • courier modified → updated_at changes → key changes → miss → recomputed automatically ✅

You never manually delete anything — when data changes, the old key is abandoned and the new key naturally computes the new value.

Mindset: don't "clear the old cache," let "a data change produce a new key." That notorious cache-invalidation problem mostly disappears.


🪆 Layer 3 (render): fragment + Russian Doll

So far we cached computed results. But sometimes computing the data is fast and the slow part is rendering it into HTML (lots of ERB, helpers). Here what you cache is the rendered HTML fragment.

Fragment caching: wrap a chunk with cache in the view:

<% @couriers.each do |courier| %>
  <% cache courier do %>          <%# automatically uses courier.cache_key_with_version as the key %>
    <div class="courier-card">
      <h3><%= courier.name %></h3>
      <p>Shipments: <%= courier.shipments_count %></p>
    </div>
  <% end %>
<% end %>

  • First time → miss → run ERB to produce HTML → store it.
  • After → hit → return the stored HTML directly, ERB doesn't run.
  • courier modified → key changes → only that chunk re-renders.

Russian Doll caching: nested — an outer cache wrapping inner caches, like a matryoshka:

<% cache courier do %>                  <%# outer: courier card %>
  <h3><%= courier.name %></h3>
  <% courier.shipments.each do |shipment| %>
    <% cache shipment do %>             <%# inner: each shipment %>
      <%= render shipment %>
    <% end %>
  <% end %>
<% end %>

The clever part is "change one, re-render only one." Change a shipment → only that inner card re-renders; the outer courier card also reassembles, but the unchanged shipments' inner cards come straight from cache, so reassembly is just stitching existing HTML — fast.

For "change a shipment → outer courier updates too" to work, the inner change must propagate up:

class Shipment < ApplicationRecord
  belongs_to :courier, touch: true   # a shipment change also touches the courier's updated_at
end

touch: true makes the inner change bump the outer key, which is what makes the whole Russian Doll work.

Why is touch needed? Because an outer cache hit returns the whole stored HTML wholesale — it never re-checks the inner caches. So if the outer key doesn't change, you'd serve stale inner content. touch forces the outer to miss and reassemble (pulling unchanged inners from cache).


🗄️ Where the cache lives (cache store)

Where Rails.cache stores things is decided by the cache store, and the production choice matters:

store where use
:file_store (the default when unset) local disk files single machine; not shared across machines
:memory_store a single process's memory lost on restart, not shared across workers — don't use in production
:redis_cache_store Redis ⭐ the production mainstream, shared across servers
:mem_cache_store Memcached pure-cache scenarios
:solid_cache_store the database (default in new Rails 8 apps) when you don't want to run a separate Redis

The key point: production usually has multiple servers / workers. With memory_store, the cache server A computed isn't visible to server B — effectively not shared. So use Redis / Memcached, a centralized store, so the whole system shares one cache.

# config/environments/production.rb
config.cache_store = :redis_cache_store, { url: ENV["REDIS_URL"] }


🌐 Layer 4 (transfer): HTTP caching (ETag)

The earlier layers save "recompute," but the server still assembles and sends the response. HTTP caching goes further — when data hasn't changed, don't even send it:

def show
  @courier = Courier.find(params[:id])
  fresh_when(@courier)   # computes an ETag (version fingerprint) from updated_at
end

  • On response, the server includes an ETag header; the browser remembers it.
  • On the next request, the browser automatically sends "I have this version."
  • The server compares: unchanged → returns 304 Not Modified with an empty body, the browser reuses its own copy; changed → normal 200 + new content.

What it saves is bandwidth and transfer — when nothing changed, just a tiny 304 instead of re-sending the whole page.


🏁 Wrap-up: the four layers of caching

layer tool what it saves
compute Rails.cache.fetch recomputing expensive work
invalidate key-based (cache_key_with_version) the pain of manual cache clearing
render fragment / Russian Doll re-rendering HTML
transfer HTTP caching (ETag) even the send (304)

All four share one underlying idea:

Use updated_at as a "version" — reuse while data is unchanged, auto-update when it changes.

The biggest trap in caching isn't "how to store," it's "how to keep it from going stale." Remember key-based — don't clear caches by hand, let the key follow the data's version — and that infamous cache-invalidation problem is mostly solved. But don't swing the other way and cache everything either: first confirm the thing is genuinely "expensive + reused," then cache it, or you've just added complexity and a "why am I seeing stale data" debugging nightmare.


📌 This post is about how caching works. But caching's real difficulty is in the failure modes you hit after it ships — hammering the DB the instant a key expires (stampede is just the appetizer), a whole code path breaking when the cache disappears, an unbounded key set blowing up memory, even faithfully storing an error. Those "you only learn it by getting burned" traps are in the follow-up: Caching, part 2 — the production landmines (link in comments).