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

推荐订阅源

L
LangChain Blog
The GitHub Blog
The GitHub Blog
Recent Announcements
Recent Announcements
MyScale Blog
MyScale Blog
P
Proofpoint News Feed
S
Security @ Cisco Blogs
N
News and Events Feed by Topic
H
Hacker News: Front Page
Attack and Defense Labs
Attack and Defense Labs
S
Secure Thoughts
Microsoft Security Blog
Microsoft Security Blog
N
Netflix TechBlog - Medium
U
Unit 42
Stack Overflow Blog
Stack Overflow Blog
T
Threat Research - Cisco Blogs
Google Online Security Blog
Google Online Security Blog
Spread Privacy
Spread Privacy
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
L
LINUX DO - 热门话题
T
Tenable Blog
博客园 - 叶小钗
D
DataBreaches.Net
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园_首页
人人都是产品经理
人人都是产品经理
aimingoo的专栏
aimingoo的专栏
C
Check Point Blog
博客园 - 三生石上(FineUI控件)
量子位
P
Proofpoint News Feed
H
Help Net Security
Blog — PlanetScale
Blog — PlanetScale
宝玉的分享
宝玉的分享
Recorded Future
Recorded Future
The Register - Security
The Register - Security
F
Fortinet All Blogs
Engineering at Meta
Engineering at Meta
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Last Week in AI
Last Week in AI
S
Schneier on Security
V
Vulnerabilities – Threatpost
雷峰网
雷峰网
Microsoft Azure Blog
Microsoft Azure Blog
G
GRAHAM CLULEY
G
Google Developers Blog
月光博客
月光博客
V
V2EX
T
Troy Hunt's 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
The 7 Postgres Indexes That Took My API From 400ms to 40ms
RAXXO Studio · 2026-04-25 · via DEV Community
  • I took one of my APIs from 400ms p95 to 40ms p95 by fixing 7 missing or wrong Postgres indexes.

  • Most of my slow queries were not slow because of bad SQL, they were slow because Postgres had to scan the whole table.

  • Partial indexes and covering indexes did more for me than plain B-tree indexes on primary columns.

  • EXPLAIN ANALYZE and pg_stat_statements are the only two tools you need to find the real bottlenecks.

The API in question powers my analytics dashboard. Nothing fancy. A few endpoints that read from a Postgres database with around 8 million rows spread across 14 tables. It had gotten slow. 400ms p95 on the hot endpoints, 900ms p99, timeouts on the reports page when I filtered by date range. I spent a Saturday looking at indexes instead of rewriting code, and that Saturday is the reason the dashboard now answers in 40ms. This post is what I changed, in order, with the numbers before and after. Postgres indexes are the lever I keep underestimating, and I want to stop doing that.

I am going to assume you know roughly what an index is. What I am not assuming is that you have seen the specific index shapes that saved me the most time. Partial indexes, covering indexes, and expression indexes do not get enough airtime in the tutorials I learned from. They should.

The 400ms Baseline: What My Queries Actually Looked Like

Before touching anything, I turned on pg_stat_statements and let it run for a full day. This is step zero. If you do not know which queries are slow, you will optimize the wrong things. I have done it. I have spent an hour tuning a query that accounts for 0.4% of total query time while the one eating 41% of the database kept running untouched.


CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

SELECT
  substring(query, 1, 80) AS query,
  calls,
  round(total_exec_time::numeric, 1) AS total_ms,
  round(mean_exec_time::numeric, 2) AS mean_ms,
  round((100 * total_exec_time / sum(total_exec_time) OVER ())::numeric, 1) AS pct
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;

Enter fullscreen mode Exit fullscreen mode

The results were humbling. Four queries were responsible for 78% of total execution time. Every one of them was doing a sequential scan on tables with millions of rows. I ran EXPLAIN (ANALYZE, BUFFERS) on each and confirmed it. Seq Scan, Seq Scan, Seq Scan, and a Nested Loop with a Seq Scan on the inner side.

This is the honest baseline I started from:

| Endpoint | p50 | p95 | p99 | Worst query |

|---|---|---|---|---|

| GET /events | 120ms | 410ms | 920ms | filter by user_id + created_at |

| GET /reports | 280ms | 890ms | 2100ms | aggregate by date range |

| GET /users/:id/summary | 60ms | 220ms | 480ms | join users to events |

| GET /search | 180ms | 520ms | 1400ms | ILIKE on title |

I want to be clear that this was not a case of Postgres being slow. Postgres was doing exactly what I told it to do. I had not told it how to find the rows I cared about without reading every row, so it read every row. That is on me.

The 7 Indexes That Actually Moved the Needle

These are the seven indexes I added, in the order I added them, with the before and after for the query that changed most.

1. Composite index on (user_id, created_at DESC)

The events table is ordered by write time. My queries are ordered by (user_id, created_at DESC) because I always want a user's newest events first. A single-column index on user_id is not enough. Postgres can find the user's rows but then has to sort them by created_at, which on a busy user is a lot of rows.


CREATE INDEX CONCURRENTLY idx_events_user_created
ON events (user_id, created_at DESC);

Enter fullscreen mode Exit fullscreen mode

Before: 410ms p95. After: 24ms p95. One index, 17x faster, and this was the single biggest win of the day. CONCURRENTLY matters. On a table I cannot take offline, a non-concurrent CREATE INDEX holds a lock that blocks writes. Always concurrent for production tables.

2. Partial index for unread events

A specific subset of events is "unread". That subset is less than 2% of total rows. A full index on the boolean read_at IS NULL column would touch every row. A partial index only stores the rows where the predicate is true, so it is smaller, faster to read, faster to maintain.


CREATE INDEX CONCURRENTLY idx_events_unread
ON events (user_id, created_at DESC)
WHERE read_at IS NULL;

Enter fullscreen mode Exit fullscreen mode

Before: the notification badge count query took 180ms. After: 3ms. The index is 94% smaller than the full equivalent, which also means it fits in cache and stays there.

3. Covering index for the hottest list query

This is the one I wish I had learned five years earlier. When Postgres uses an index to find rows, it still has to fetch the row data from the heap unless all the columns you need are inside the index itself. A covering index adds those columns via INCLUDE, so the heap fetch never happens. This is called an index-only scan, and it is as fast as Postgres gets.


CREATE INDEX CONCURRENTLY idx_events_list_covering
ON events (user_id, created_at DESC)
INCLUDE (title, type, read_at);

Enter fullscreen mode Exit fullscreen mode

EXPLAIN went from Index Scan + Heap Fetch to Index Only Scan. The list endpoint that renders the dashboard feed dropped from 96ms to 11ms. The trade-off is disk space. My covering index is 2.3x the size of the plain version. On an 8 million row table, that is about 240 MB. Worth it for a hot endpoint.

4. Expression index for case-insensitive search

My search endpoint was doing LOWER(title) ILIKE '%term%'. The ILIKE with a leading wildcard is a sequential scan no matter what. For the prefix case (ILIKE 'term%'), I can use an expression index on LOWER(title) with the right operator class.


CREATE INDEX CONCURRENTLY idx_events_title_lower
ON events (LOWER(title) text_pattern_ops);

Enter fullscreen mode Exit fullscreen mode

Searches that start from the beginning of the title dropped from 520ms to 14ms. For full substring search I eventually added pg_trgm and a GIN index, but that is another post. Start with the cheap win. Most of my search queries were prefix matches anyway.

5. GIN index on JSONB metadata

My events have a JSONB metadata column with things like device type, country, referrer. I was filtering on metadata ->> 'country' = 'DE' all over the place. Postgres supports GIN indexes on JSONB, and specifically on the jsonb_path_ops operator class, which is smaller and faster than the default for equality checks.


CREATE INDEX CONCURRENTLY idx_events_metadata_gin
ON events USING GIN (metadata jsonb_path_ops);

Enter fullscreen mode Exit fullscreen mode

Country filter queries dropped from 320ms to 18ms. The index is larger than a B-tree (28% of the table size in my case), but it covers any key inside the JSONB object. One index, many queries, all fast.

6. BRIN index for time-series scans

This one is niche but saved me on the reports endpoint. When your data is naturally ordered on disk by a column (in my case, created_at, because I never update old events), a BRIN index stores tiny summaries per block of pages instead of one entry per row. It is about 1000x smaller than an equivalent B-tree. For range scans across millions of rows, it is often fast enough and cheap enough to leave on every table.


CREATE INDEX CONCURRENTLY idx_events_created_brin
ON events USING BRIN (created_at) WITH (pages_per_range = 32);

Enter fullscreen mode Exit fullscreen mode

The report aggregate that scanned 90 days of data dropped from 890ms to 62ms. The index is 4 MB on an 8 million row table. Four megabytes.

7. Foreign key index on the join side

I had a foreign key from events.organization_id to organizations.id but no index on events.organization_id. Postgres does not create one for you when you add a foreign key. The join from organizations to events was a sequential scan on the events table every time.


CREATE INDEX CONCURRENTLY idx_events_org_id
ON events (organization_id);

Enter fullscreen mode Exit fullscreen mode

The organization summary endpoint dropped from 480ms to 9ms. I went back and audited every foreign key in my schema. I was missing three more. I added them all.

Where I Got Indexes Wrong

I also made mistakes. A few of the indexes I added first turned out to be useless or actively harmful, and I want to save you the debugging time.

Indexes I never used. My first instinct was to index every column that appeared in a WHERE clause. Postgres has pg_stat_user_indexes to tell you which indexes are actually being read. After a week of production traffic, I queried it and found three indexes with zero scans. I dropped them.


SELECT
  schemaname, relname, indexrelname,
  idx_scan, pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC;

Enter fullscreen mode Exit fullscreen mode

Every unused index is pure cost. It slows down writes, bloats backups, competes for cache. If it is not being scanned, drop it.

Indexes on low-cardinality columns. I indexed a status column with 4 distinct values. Postgres looked at the stats and chose a sequential scan anyway, because fetching 40% of the rows through an index is slower than just reading the table. The correct fix was a partial index, like the unread one above. Whenever a column has few distinct values but you mostly query one specific value, a partial index wins over a full index.

Indexing before migration finishes. I once added an index during a schema migration on a table that was being heavily written to. Without CONCURRENTLY, the migration held an ACCESS EXCLUSIVE lock for 90 seconds and blocked production writes the entire time. That incident is why every index I create now has CONCURRENTLY in the statement, no exceptions, even in development, because muscle memory is how you avoid incidents.

Over-covering indexes. My second attempt at the covering index on events had INCLUDE (title, type, read_at, metadata, raw_payload). Postgres refused to do an index-only scan anyway because raw_payload was too large. Covering indexes make sense when the included columns are small and hot. Large blobs belong in the heap.

Monitoring: How I Know an Index Is Earning Its Keep

After the dust settled, I set up three queries I now run weekly. Together they tell me whether my indexes are doing useful work.

Index hit ratio. The ratio of index reads coming from cache vs disk. Below 99% on a busy table is a sign the working set does not fit in memory or the indexes are too big.


SELECT
  relname,
  idx_blks_read,
  idx_blks_hit,
  round(100.0 * idx_blks_hit / nullif(idx_blks_hit + idx_blks_read, 0), 2) AS hit_pct
FROM pg_statio_user_indexes
WHERE idx_blks_read > 0
ORDER BY idx_blks_read DESC
LIMIT 20;

Enter fullscreen mode Exit fullscreen mode

Bloat. Indexes accumulate dead tuples over time, especially on tables with lots of updates. The pgstattuple extension gives you a real number. Above 30% bloat, I run REINDEX CONCURRENTLY (available in Postgres 12+). Before 12 I used pg_repack.

Unused indexes. The same pg_stat_user_indexes query from above, run on a fresh snapshot once a month. Anything at zero scans gets dropped.

None of this is exotic. All of it is built into Postgres. Most of it I learned by reading the docs after the fact, instead of before. If you do this before you go to production, you are ahead of where I was.

Bottom Line

Indexes are the highest leverage work I have ever done on a database and the one I keep putting off because it feels less fun than writing new features. That is a trap. A Saturday on indexes gave me a 10x speedup on the user-visible parts of my dashboard and retired three tickets about slowness that had been open for weeks. The tools to find the right indexes are already in your database. pg_stat_statements for the hottest queries. EXPLAIN ANALYZE for the execution plan. pg_stat_user_indexes for usage. If you have not opened any of those this month, open one today. Your p95 will thank you.