Database Index for an AI App: Read the Query Plan, Pick the Column Order, Name the Write Cost
The chat history page of a support assistant goes from 80 ms to 900 ms once the messages table passes 40 million rows (synthetic). Read the plan, add one composite index on tenant, conversation and time in that order, cover the hot query, and remember the index for deleting a document.
What you will learn
- Diagnose a slow query by comparing rows scanned with rows returned in the query plan
- Build a composite index with equality columns first and the sort column last
- Explain a covering index and an index-only scan
- Name the write cost of every index and the forgotten index for deleting a document
Before you start
- SQL Essentials: SELECT, WHERE, JOIN, GROUP BY
- Latency Math: p50, p95, p99
A database index is a sorted guide to a table. It lets the database jump to the rows it needs instead of reading all of them. In an interview, "add an index" is never the full answer. The interviewer wants to hear which index, in what column order, and what it costs you.
The chat history page gets slow
Our support assistant answers tickets for 500 small businesses and three banks on one platform. Each business is a tenant. Every time an agent opens a conversation, the app loads the last 50 messages of that chat, and all the messages of all the tenants sit in one table.
That table keeps growing. When it passes 40 million rows, the page that took 80 milliseconds now takes 900. These numbers are synthetic, but the shape is very common. Nobody changed the code. Only the data grew.
Loading the last 50 messages of a chat takes 900 ms at 40 million rows. Diagnose it and fix it.
The short answer has four parts:
- Diagnose. Look at the query plan and compare rows scanned with rows returned.
- Fix. Add one composite index on tenant, conversation and created time, in that order.
- Cost. Every insert now updates the index too, so writes get a little slower.
- The forgotten one. Mention the index for deleting a document.
One line to remember: index the question you actually ask, in the order you ask it.
The index at the back of a book
You have a thick book and you want the page about refunds. You can read every page from the start until you find it. That's a full scan. Or you turn to the index at the back. It's sorted, so you find R, then "refunds", and it says page 212. You go straight there.
The book didn't change at all. You only added a small sorted list that points into it. That is exactly what a database index is.
Scan versus search
The lecture's small lab builds the same tables in SQLite with 200,000 synthetic messages and asks for the plan of one query. Here is the query:
SELECT created_at, role, body FROM messages
WHERE tenant_id=? AND conversation_id=?
ORDER BY created_at DESC LIMIT 50
And the two indexes it tries, the wrong order and the right one:
CREATE INDEX ix_wrong ON messages (created_at, tenant_id, conversation_id);
CREATE INDEX ix_chat ON messages (tenant_id, conversation_id, created_at);
Here are the plans that index_lab.py prints. Its timings change from machine to machine, so we leave them out. The plans stay the same:
no index : SCAN messages | USE TEMP B-TREE FOR ORDER BY
wrong order : SCAN messages USING INDEX ix_wrong
right order : SEARCH messages USING INDEX ix_chat (tenant_id=? AND conversation_id=?)
rows back : 50
With no index, the plan says SCAN. The database reads every row, keeps the ones for this chat, then builds a temporary B-tree to sort them by time. At 40 million rows that is 40 million read to return 50, or 800,000 rows read for every row you show.
With the right index, the plan says SEARCH ... USING INDEX with tenant and conversation as the keys. It jumps to this one conversation, reads the newest 50 entries in order and stops. There is no sort step. Rows scanned against rows returned is the number that tells you an index is missing.
Column order matters
Here's the trap weak candidates fall into: the right columns in the wrong order. Our index is sorted by tenant, then by conversation inside the tenant, then by time inside the conversation. So one chat sits together, already in time order.
Put created time first and the newest messages of every chat on the platform are mixed together. The plan above shows it: SCAN messages USING INDEX ix_wrong. The database walks the whole index, checking each entry.
The rule is simple. Columns you compare with equals go first. The column you sort by, or filter with a range, goes last. And an index only helps a query that uses its first column. A phone book sorted by surname can't find everyone called Anna.
Covering index and index-only scan
Normally the index finds the 50 entries, then the database goes back to the table to fetch each row. That's 50 extra lookups. If the index also holds every column the query needs, it's a covering index. Say the list view only needs the time and the role:
CREATE INDEX ix_cover ON messages (tenant_id, conversation_id, created_at, role);
SELECT created_at, role FROM messages
WHERE tenant_id=? AND conversation_id=?
ORDER BY created_at DESC LIMIT 50;
narrow query : SEARCH messages USING COVERING INDEX ix_cover (tenant_id=? AND conversation_id=?)
The table lookups disappear. The index-only scan is the plan step that uses it. In Postgres there is one catch: it still checks a visibility map to know whether each row is visible to your transaction, and if that map is out of date (vacuum keeps it current), it goes back to the table anyway.
Don't copy the message body into the index, though. That makes it huge. Cover a small, hot query, not everything.
What the index costs
Without indexes, one new message is one write, into the table. With the chat index, the same message also goes into the sorted list in the right place: two writes. If someone has added four indexes, every message is five writes. Insert latency goes up, and the indexes take disk and memory.
So the trap is indexing every column just in case. Every index is paid for on every write, forever. The good news: the chat index is cheap to keep, because new messages always land at the end of their conversation.
The index you forget: deleting a document
The assistant answers from the tenants' documents, split into chunks. A bank says: delete this document, everywhere, today. Maybe it was uploaded by mistake, maybe it's a right-to-erasure request. With no index on the document id, the delete scans every chunk of every tenant.
The catch is that an index on tenant then document doesn't help a delete that only names the document:
delete doc : SCAN chunks
+ (tenant, doc) : SCAN chunks
scoped delete : SEARCH chunks USING INDEX ix_doc (tenant_id=? AND doc_id=?)
+ (doc_id) : SEARCH chunks USING INDEX ix_doc2 (doc_id=?)
The delete must match the index. Either delete by tenant and document together, or add an index that starts with the document id. This is a normal table index on the chunk metadata, not the vector index that finds similar text (that one is in Vector Index). Different job.
Prove it, then the follow-ups
Read the plan and watch rows scanned against rows returned, ideally close to 50 for 50. Track p95 of the history page and p95 of inserts, so you see what the index costs, and watch the index size. For the failure test, load the table to 40 million synthetic rows and replay real traffic. It passes if the history page stays near its old time, inserts stay within budget, and deleting a document doesn't scan the chunks table. A fix you didn't measure is just a guess.
- Why not put created time first? Then one chat is scattered across the whole index. Equality columns first, sort column last.
- What happens to insert latency? It rises a little with every index, so keep only the indexes your real queries use and drop the rest.
- Covering index or index-only scan? The covering index is what you build. The index-only scan is the plan step that uses it.
Recap
| Step | What to say |
|---|---|
| Diagnose | Query plan: SCAN plus a temp B-tree sort, 800,000 rows read per row shown |
| Fix | (tenant_id, conversation_id, created_at): equality first, sort last |
| Cover | Add the few columns a hot query needs, never the body |
| Cost | One extra write per index on every insert, plus disk and memory |
| Forgotten | Deleting a document needs an index that starts with doc_id, or a scoped delete |
When one table outgrows one machine even with good indexes, the next steps are replication for reads and sharding for size.
Try it yourself
The assistant also has a page that lists one tenant's open tickets, newest first, filtered by status. Write the composite index you would build, in order, and say which column goes last and why.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
When the main model goes down, the backup has to be allowed to take the data, able to read the whole request and tested before the bad day. A simulated four-model chain for an EU customer: a 6,000-token request lands on mid-eu, flagged degraded; a 10,000-token request is served by nobody, on purpose.
Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
A bulk upload buries the chat. In a small simulation, one shared queue grows to 199 waiting and the middle chat answer takes 80.2 s. A bound plus a chat lane brings it to 0.35 s while 178 bulk jobs are told to retry in 10 s, and cancelling abandoned calls saves 21,000 wasted tokens.
Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
Six GPU replicas, two at 95% and four at 30%: round robin counts requests, and requests aren't equal. In a small simulation, least outstanding requests cuts p95 from 6.52 s to 3.05 s, prefix affinity lifts cache hits to 95% but pushes p95 to 11.45 s, a real health check takes errors from 48 to 2, and draining cuts 0 answers instead of 4.
A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
A queue doesn't lose a document, but it can hand one out twice. In a small simulation, a worker crash makes document two go from 3 to 6 chunks and the index holds 11 when the documents hold 8. An idempotent consumer brings it back to 8 with the same two deliveries, and a limit of three tries moves a poison file to a dead letter queue.
