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

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
GbyAI
GbyAI
Jina AI
Jina AI
博客园_首页
Y
Y Combinator Blog
美团技术团队
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
M
MIT News - Artificial intelligence
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
MyScale Blog
MyScale Blog
MongoDB | Blog
MongoDB | Blog
雷峰网
雷峰网
罗磊的独立博客
博客园 - Franky
Last Week in AI
Last Week in AI
Vercel News
Vercel News
Martin Fowler
Martin Fowler
Stack Overflow Blog
Stack Overflow Blog
Microsoft Security Blog
Microsoft Security Blog
月光博客
月光博客
WordPress大学
WordPress大学
W
WeLiveSecurity
Apple Machine Learning Research
Apple Machine Learning Research
TaoSecurity Blog
TaoSecurity Blog
阮一峰的网络日志
阮一峰的网络日志
博客园 - 聂微东
Schneier on Security
Schneier on Security
Engineering at Meta
Engineering at Meta
Simon Willison's Weblog
Simon Willison's Weblog
博客园 - 【当耐特】
宝玉的分享
宝玉的分享
大猫的无限游戏
大猫的无限游戏
S
SegmentFault 最新的问题
P
Proofpoint News Feed
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园 - 叶小钗
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
L
LINUX DO - 最新话题
S
Security @ Cisco Blogs
B
Blog RSS Feed
B
Blog
爱范儿
爱范儿
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Tailwind CSS Blog
Attack and Defense Labs
Attack and Defense Labs
V
Visual Studio Blog
NISL@THU
NISL@THU
U
Unit 42
Hugging Face - Blog
Hugging Face - Blog
A
Arctic Wolf

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
A 1000x Speedup From One Index — and Why It Sometimes Does Nothing
Dane Wu · 2026-06-25 · via DEV Community

Rails Performance: Lessons from Production — #2

"Slow query? Add an index" is something everyone has heard. But I once hit a more embarrassing situation: I added the index, and the query didn't get any faster. Debugging that forced me to actually understand how indexes work — when they're lightning fast, and when they simply won't be used. This post walks through it with one example: a shipments table with a few million rows.


🐌 I added an index and the query was still slow

The shipments table has 3 million rows. The front end looks up one row by tracking number: Shipment.where(tracking_no: "ABC123") — 12 seconds slow. I added an index and it dropped to 8 milliseconds. One line of CREATE INDEX, a thousand times faster. Felt great.

Until another query, where I added an index the same way, and EXPLAIN still showed a full table scan — no faster at all. That's when it clicked: an index isn't magic that makes things fast just by existing. It has its own rules — and if you don't understand them, adding one does nothing.


📖 Why an index is fast: start from the full table scan

Without an index, the DB can only find a row by scanning from the first row to the last, comparing tracking_no one by one. With 3 million rows that's 1.5 million on average — like a book with no index, where finding a word means flipping through the whole thing.

SELECT * FROM shipments WHERE tracking_no = 'ABC123';
-- No index: Seq Scan, scans all 3 million rows

With an index, it's like the index page at the back of a book: it keeps tracking_no pre-sorted in a separate copy, each value noting "where this row lives in the main table." The DB doesn't flip through the whole book — it locates the value directly in the sorted index, then jumps to that row.

CREATE INDEX index_shipments_on_tracking_no ON shipments (tracking_no);

One sentence: an index is fast because it's pre-sorted, so the DB can use "fast lookup on sorted data" instead of "scan every row."


🌳 Under the hood it's a B-tree (not a binary tree)

Common confusion: an index's B-tree is not a binary tree. A binary tree has at most 2 branches per node; a B-tree has hundreds of branches per node — a wide, shallow tree.

Why wide and shallow? Because reading from disk is slow. Every level the DB descends is one more disk read.

  • Binary tree: 3 million rows is ~21 levels deep → 21 disk reads.
  • B-tree: each level fans out hundreds of times, so 3 million rows is only 3–4 levels → 3–4 disk reads.

So the whole point of a B-tree is to minimize the number of disk reads. That's the physical reason an index is fast.


💰 Indexes aren't free, so you can't index every column

An index is "an extra sorted copy of the data." Two costs:

Writes get slower — every INSERT / UPDATE / DELETE doesn't just change the main table, it has to maintain every index (inserting the new value into the right spot in each B-tree). With 5 indexes, each write touches 6 places. For a table like shipments that constantly takes new orders, that cost is very real.

Space — an index really does store an extra copy on disk.

So an index is fundamentally a trade-off: slower writes and more storage in exchange for faster reads. The rule of thumb: only index a column that's actually queried (where / order / join). Read-heavy, write-light columns pay off the most; on write-heavy tables, be sparing.


🎯 So when do you actually add one?

Indexes come from two places:

1. The ones you add by design (predictable)

  • Foreign keys: shipments.courier_id — you'll definitely where(courier_id:) and join on it.
  • Unique lookup columns: tracking_no, email, slug — the ones you use to pinpoint a single row.
  • Obviously high-frequency filter/sort columns: ones you know at design time will be queried constantly.

Rails note: in a migration, t.references / add_reference builds an index on the foreign-key column by default; foreign_key: true adds a data-integrity constraint, which is a separate thing from an index — don't conflate them.

2. The ones you add after launch, driven by data (the important part)

Don't speculatively add the rest — you can't guess which will be slow. The real workflow is "measure first, then index where needed":

  1. Find the slow query from APM or the DB's slow query log.
  2. Use EXPLAIN to confirm it's actually doing a full table scan (Seq Scan in Postgres, type: ALL in MySQL).
  3. Add an index on that column, then EXPLAIN again to confirm it became an Index Scan.
  4. Confirm it's actually faster.

One thing often overlooked: small tables don't need indexes. A few thousand rows scans in milliseconds anyway; an index just adds write cost. The value of an index only shows up once the table is big enough.

In short: add the few predictable ones by design; for the rest, index against actual slow queries and verify with EXPLAIN; leave small tables alone.


🔑 Composite indexes and the leftmost prefix

Real queries are often multi-condition: where(courier_id: 1, status: "delivered"). For that, a single composite index can cover multiple columns:

CREATE INDEX idx ON shipments (courier_id, status, created_at);

The key is how it's sorted: first by courier_id, then by status within the same courier_id, then by created_at within the same status. Just like a phone book — sorted by last name, then first name within a last name.

The leftmost-prefix rule: because it sorts starting from the left column, you can only use it contiguously from the left.

Query Uses the index?
where(courier_id: 1)
where(courier_id: 1, status: "x")
where(status: "delivered") ❌ skips the leftmost courier_id

Why doesn't where(status:) use it? The phone book is sorted by last name first. If you only know the first name "John" but not the last name, the Johns are scattered across every last name — not grouped by first name — so you still flip through the whole book. status is scattered in the index the same way.

So column order matters. Two principles:

  1. Put the column most often queried alone on the left (so it works both alone and combined).
  2. Equality (=) before range (>, <). A range "truncates" the index — created_at > x spans a big stretch across many different created_at values, and within that stretch the later columns are out of order, so the index can't continue.

⚠️ Why an index sometimes doesn't kick in (back to the opening trap)

EXPLAIN still shows a full table scan even though you added the index — usually one of these, all sharing one cause: they defeat the index's sort order.

1. Applying a function or operation to the column

where("DATE(created_at) = ?", "2026-06-25")          # ❌ DB must compute DATE() per row to compare
where(created_at: Date.parse("2026-06-25").all_day)  # ✅ use a range instead — touch the value, not the column

The index sorts by the column's raw value; the moment you compute on the column, that sort order is useless.

2. LIKE '%xxx' with a leading wildcard

where("tracking_no LIKE ?", "ABC%")   # ✅ knows the prefix, can locate
where("tracking_no LIKE ?", "%123")   # ❌ no prefix, scans everything

3. Type mismatchtracking_no is a string column but you pass a number:

where(tracking_no: 123)    # ❌ DB casts every row's column to a number to compare = operating on the column → index defeated
where(tracking_no: "123")  # ✅ types match, uses the index directly

4. The condition matches too large a fraction — if a condition hits a big chunk of the table, the DB deliberately skips the index, because "locate + repeatedly jump back to the main table" ends up slower than just scanning once:

where(status: "active")    # ❌ if 90% of shipments are active → DB prefers a full scan
where(status: "returned")  # ✅ only 1%, a small slice → the index pays off

Indexes are for grabbing a small slice, not a big chunk. So a column like status with only a few, unevenly distributed values often can't use an index.

5. OR across different columnscourier_id and tracking_no each have an index, but a single OR query struggles to use both at once and often degrades to a full scan. Splitting into two queries, each using its own index, then merging, is faster:

# ❌ one OR, hard to use both indexes
Shipment.where("courier_id = ? OR tracking_no = ?", 1, "ABC123")

# ✅ split into two, each uses its own index, then merge + dedupe
a = Shipment.where(courier_id: 1)
b = Shipment.where(tracking_no: "ABC123")
(a + b).uniq

-- the SQL equivalent: UNION two queries that each use their index
SELECT * FROM shipments WHERE courier_id = 1
UNION
SELECT * FROM shipments WHERE tracking_no = 'ABC123';

The shared principle: an index works off the sort order of the column's raw value. Anything that makes the DB "compute/cast the column per row" or "lose the ability to locate by prefix" defeats it. So — don't touch the column, touch the value side instead.


🏁 Wrap-up

An index isn't a switch that makes things fast just by flipping it. It's fast because it's pre-sorted and the B-tree minimizes disk reads; it has a cost, so you only index columns that get queried; and it has rules — a composite index is used contiguously from the left, and operating on a column defeats it.

That opening query that "had an index but wasn't faster" turned out to have a function wrapped around the column. The question was never "should I add an index" — it's whether you understand how it sorts and when it gets used. Next time a query is slow, don't rush to CREATE INDEX — run EXPLAIN first and see what it's actually doing. The answer is usually right there.


🧩 Appendix: (a + b).uniq and UNION / DISTINCT

About that (a + b).uniq from the OR-split above, in three parts:

a = Shipment.where(courier_id: 1)          # query 1
b = Shipment.where(tracking_no: "ABC123")  # query 2
(a + b).uniq

① What a + b does — runs both queries, fetches each, and concatenates them into one array (not one combined SQL statement).

② What .uniq does — dedupes. A shipment might satisfy both conditions and appear on both sides, so concatenating creates duplicates; .uniq folds them into one.

③ Why + hits the DB — because a and b aren't arrays yet; they're "not-yet-executed queries" (ActiveRecord::Relation), lazy. (Back to the four layers from #1: .where only accumulates conditions, it hasn't touched the DB.) + is an Array method — it needs arrays, not relations — so it forces both to execute and become arrays before adding:

a + b
#  → a.to_a fires SELECT ... WHERE courier_id = 1
#  → b.to_a fires SELECT ... WHERE tracking_no = 'ABC123'
#  → then concatenates the two arrays

So hitting the DB isn't done by + — it's a side effect of + forcing the relations to execute so it can build the array.

The whole (a + b).uniq is just simulating SQL's UNION in Ruby: two separate queries, merged, deduped.

Aside: UNION vs DISTINCT — both dedupe; the difference is "whose duplicates":

What it does
DISTINCT dedupes within one result set (one query)
UNION merges two queries + dedupes
UNION ALL merges two queries but does not dedupe (faster)