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

推荐订阅源

T
The Blog of Author Tim Ferriss
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
MongoDB | Blog
MongoDB | Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
AI
AI
NISL@THU
NISL@THU
AWS News Blog
AWS News Blog
V
Visual Studio Blog
博客园 - 三生石上(FineUI控件)
C
Cyber Attacks, Cyber Crime and Cyber Security
P
Privacy & Cybersecurity Law Blog
S
Schneier on Security
PCI Perspectives
PCI Perspectives
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Troy Hunt's Blog
云风的 BLOG
云风的 BLOG
N
News and Events Feed by Topic
Know Your Adversary
Know Your Adversary
F
Fortinet All Blogs
Spread Privacy
Spread Privacy
P
Proofpoint News Feed
Jina AI
Jina AI
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
WordPress大学
WordPress大学
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
V
Vulnerabilities – Threatpost
P
Privacy International News Feed
T
Tor Project blog
S
Security Affairs
S
Securelist
F
Full Disclosure
D
Docker
酷 壳 – CoolShell
酷 壳 – CoolShell
Martin Fowler
Martin Fowler
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
SecWiki News
SecWiki News
P
Palo Alto Networks Blog
Apple Machine Learning Research
Apple Machine Learning Research
N
News and Events Feed by Topic
Recorded Future
Recorded Future
The Hacker News
The Hacker News
Google Online Security Blog
Google Online Security Blog
Stack Overflow Blog
Stack Overflow Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
I
Intezer
Security Latest
Security Latest
Scott Helme
Scott Helme
U
Unit 42
Y
Y Combinator Blog
The GitHub Blog
The GitHub 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
Database Indexing Mistakes That Kill SaaS Performance at Scale
OutworkTech · 2026-06-02 · via DEV Community

Your API is fast. Your code is clean. Your architecture looks solid on paper.

Then you hit 500,000 records and everything slows down. Queries that ran in 12ms now take 4 seconds. Your dashboards lag. Users start filing support tickets. Your on-call engineer is staring at a query plan at midnight wondering what went wrong.

Nine times out of ten, the answer is indexing. Not missing indexes — wrong indexes. Indexes that exist but don't help. Indexes that actively hurt write performance without meaningfully improving reads.

This is a breakdown of the most damaging database indexing mistakes in production SaaS systems — and how to fix them before they become incidents.


Mistake 1: Indexing Everything "Just in Case"

The most common mistake isn't under-indexing. It's over-indexing out of anxiety.

New engineers especially fall into this pattern — add an index on every column that appears in a WHERE clause, just to be safe. Seems responsible. It isn't.

Every index you add is a write tax. On every INSERT, UPDATE, and DELETE, PostgreSQL (or MySQL) has to update every index on that table. On a table with 8 indexes, every write touches 8 data structures.

At low volume, this is invisible. At 10,000 writes per minute, it becomes your bottleneck.

The fix:

Audit your indexes regularly. In PostgreSQL:

SELECT
  schemaname,
  tablename,
  indexname,
  idx_scan,
  idx_tup_read,
  idx_tup_fetch
FROM pg_stat_user_indexes
ORDER BY idx_scan ASC;

Enter fullscreen mode Exit fullscreen mode

Any index with idx_scan = 0 or near zero hasn't been used since your last stats reset. That's a candidate for removal — not immediately, but after investigation.


Mistake 2: Not Understanding Index Selectivity

An index on a boolean column (is_active, is_deleted) is almost always useless.

Here's why: selectivity measures how many distinct values exist relative to total rows. A boolean column has two values. If 95% of your rows have is_active = true, an index on that column tells the query planner almost nothing useful. It will often skip the index entirely and do a full table scan — correctly.

-- This index is nearly useless on a table where 95% of rows are active
CREATE INDEX idx_users_is_active ON users(is_active);

-- This is what you probably need instead
CREATE INDEX idx_users_active_created ON users(created_at)
WHERE is_active = true;

Enter fullscreen mode Exit fullscreen mode

The second example is a partial index — it only indexes rows matching the condition. Smaller, faster, and actually selective.

Rule of thumb: If a column has fewer than 10-20 distinct values relative to table size, a plain index on it alone will underperform. Use partial indexes or composite indexes instead.


Mistake 3: Getting Composite Index Column Order Wrong

Composite indexes are powerful and widely misunderstood.

PostgreSQL can use a composite index (a, b, c) for queries filtering on a, or a and b, or a and b and c. It cannot efficiently use it for queries filtering on just b or just c.

-- Index created
CREATE INDEX idx_orders_user_status_date ON orders(user_id, status, created_at);

-- This query uses the index efficiently ✓
SELECT * FROM orders WHERE user_id = 123 AND status = 'pending';

-- This query does NOT efficiently use the index ✗
SELECT * FROM orders WHERE status = 'pending' AND created_at > '2025-01-01';

Enter fullscreen mode Exit fullscreen mode

The second query skips user_id — the leading column — so the index is effectively useless for it.

The fix:

Put the most selective column first, and design composite indexes around your actual query patterns — not your table schema. Run EXPLAIN ANALYZE on your real queries before creating indexes.

EXPLAIN ANALYZE
SELECT * FROM orders
WHERE user_id = 123
AND status = 'pending'
ORDER BY created_at DESC;

Enter fullscreen mode Exit fullscreen mode

If you see Seq Scan on a large table, you have an indexing problem. If you see Index Scan with high cost, you have a column order problem.


Mistake 4: Ignoring Index Bloat

Indexes degrade over time. This surprises most engineers who treat indexes as a set-and-forget solution.

In PostgreSQL, when rows are updated or deleted, the old index entries are not immediately removed. They become dead tuples — bloat that the index still has to scan through. On high-churn tables (orders, events, logs, sessions), this bloat accumulates fast.

A table with 1 million live rows can have an index sized for 8 million rows due to bloat. Every query through that index is doing 8x the work it should.

Check your index bloat:

SELECT
  tablename,
  indexname,
  pg_size_pretty(pg_relation_size(indexrelid)) AS index_size,
  idx_scan
FROM pg_stat_user_indexes
JOIN pg_index USING (indexrelid)
ORDER BY pg_relation_size(indexrelid) DESC;

Enter fullscreen mode Exit fullscreen mode

The fix:

Schedule regular REINDEX CONCURRENTLY on high-churn tables during low-traffic windows:

REINDEX INDEX CONCURRENTLY idx_orders_user_status_date;

Enter fullscreen mode Exit fullscreen mode

CONCURRENTLY is critical — a standard REINDEX locks the table. On a production SaaS, that lock will cause an incident.

Also make sure autovacuum is properly tuned. The default settings are conservative and often insufficient for high-write SaaS workloads.


Mistake 5: Using Indexes on Low-Cardinality Columns in Multi-Tenant Systems

This one is specific to SaaS and almost always overlooked.

In a multi-tenant system, most queries include a tenant_id filter. The natural instinct is to index tenant_id. But if you have 50 large tenants sharing a table with 10 million rows, tenant_id alone is low-cardinality for those tenants — each one owns 200,000 rows.

An index scan on tenant_id = 'large-tenant-uuid' returns 200,000 rows. PostgreSQL may decide a sequential scan is faster. Your "indexed" query is still slow.

-- Insufficient for large tenants
CREATE INDEX idx_events_tenant ON events(tenant_id);

-- Much better — tenant + time range covers real query patterns
CREATE INDEX idx_events_tenant_created ON events(tenant_id, created_at DESC);

-- Even better for specific query patterns
CREATE INDEX idx_events_tenant_type_created ON events(tenant_id, event_type, created_at DESC)
WHERE event_type IN ('purchase', 'refund', 'signup');

Enter fullscreen mode Exit fullscreen mode

The real fix for multi-tenant systems at serious scale is table partitioning by tenant_id — but that's a separate architectural decision. Composite indexes with time-range columns are the practical first step.


Mistake 6: Not Indexing Foreign Keys

This one causes slow deletes and JOINs that no one can explain.

In PostgreSQL, foreign key columns are not automatically indexed. When you delete a parent row, PostgreSQL has to check all child tables for referencing rows — and without an index on the foreign key column, it does a sequential scan on every child table for every delete.

-- You have this
ALTER TABLE orders ADD CONSTRAINT fk_orders_user
  FOREIGN KEY (user_id) REFERENCES users(id);

-- PostgreSQL does NOT automatically create this
CREATE INDEX idx_orders_user_id ON orders(user_id);

-- You have to create it manually

Enter fullscreen mode Exit fullscreen mode

On small tables this is invisible. On a user_id column in an orders table with 50 million rows, deleting or updating a user triggers a full table scan. That 4-second delete? This is often why.

The fix:

After every foreign key constraint, immediately create an index on the referencing column. Make it a team convention — part of your migration checklist.


Mistake 7: Not Using EXPLAIN ANALYZE Before Deploying Index Changes

Most indexing decisions are made by intuition. Intuition is wrong often enough to matter.

EXPLAIN ANALYZE shows you exactly what the query planner is doing — which indexes it uses, which it ignores, how many rows it actually scanned versus estimated, and where the time is actually being spent.

EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT o.id, o.total, u.email
FROM orders o
JOIN users u ON u.id = o.user_id
WHERE o.tenant_id = 'abc-123'
  AND o.status = 'pending'
  AND o.created_at > NOW() - INTERVAL '7 days'
ORDER BY o.created_at DESC
LIMIT 50;

Enter fullscreen mode Exit fullscreen mode

What to look for:

  • Seq Scan on large tables → missing index
  • Rows Removed by Filter: 89420 → index exists but wrong columns, low selectivity
  • Buffers: shared hit=0 read=45000 → index is there but cold, or bloated
  • High actual time on a node despite index use → index bloat or statistics out of date

Run ANALYZE tablename to refresh planner statistics if query plans look wrong.


The Indexing Checklist for SaaS Systems

Before your next migration goes to production:

  • [ ] Does every foreign key column have an index?
  • [ ] Are composite index columns ordered by selectivity, not convenience?
  • [ ] Are boolean or low-cardinality filters using partial indexes instead of full indexes?
  • [ ] Have you run EXPLAIN ANALYZE on the top 10 slowest queries this week?
  • [ ] Do you have a process for identifying and removing unused indexes?
  • [ ] Are high-churn tables scheduled for regular REINDEX CONCURRENTLY?
  • [ ] Is autovacuum tuned for your actual write volume, not PostgreSQL defaults?
  • [ ] In multi-tenant tables, do indexes include tenant_id as the leading column?

The Bigger Point

Indexes are not a performance feature you add when things get slow. They are a design decision you make alongside your schema — and revisit as your query patterns evolve.

The teams that handle scale well aren't the ones with the most indexes. They're the ones who understand what each index costs, what it buys, and when to remove the ones that are no longer earning their keep.

A database that's fast at 10,000 rows and fast at 50 million rows doesn't happen by accident. It happens because someone treated query planning as a first-class engineering concern — not an afterthought.


This post is part of OutworkTech's backend engineering series. If you missed the previous posts — How to Version APIs Without Breaking Production and REST vs GraphQL vs gRPC — they cover the API layer that sits on top of the database decisions discussed here.

OutworkTech builds and scales backend systems, APIs, and SaaS infrastructure for companies that need engineering depth without the overhead. If your database is becoming a bottleneck — let's talk.