Core Concepts
Database Indexes
Follow an alias lookup into a B-tree and see how an index can enforce a concurrent claim.
A database index organizes selected values so a query can find matching rows without scanning the whole table. Each index takes up space and adds work when its entries change. Start with the lookup or sort that benefits from that extra structure.
Find one link by its code
When the short-link cache misses on /notes, the service needs the database row whose short_code is notes. A B-tree keeps keys in order across a tree of pages, the blocks the database reads and writes. Starting at the top, the database follows the branch whose range contains the search key until it reaches the matching entry. PostgreSQL index introduction
In a normal PostgreSQL index scan, the entry tells the database where the row lives. Suppose the entry for notes points to page 9, slot 3. The database follows that pointer, checks whether this query is allowed to see that version of the row, and reads its destination URL. PostgreSQL calls the table's row storage the heap. PostgreSQL index and heap reads
The path fits a selective query, one that matches a small share of the rows. A report reading almost every link can instead use a sequential scan, which reads through the table in storage order. Following an index to many scattered rows can cost more than scanning the table once. That choice comes from the query planner, the part of the database that estimates how much work each possible plan requires. PostgreSQL query plans
Keep one conversation together
A chat history screen asks for the latest two turns in conversation C7 before sequence 104. It needs 103 and 102, in that order. An index on seq can keep the numbers sorted, but many conversations can have a turn numbered 103. The database would have to check which of those entries belong to C7.
The ChatGPT walkthrough uses a composite index, with more than one key column, on (conversation_id, seq). The B-tree sorts first by conversation and then by sequence, so turns for C7 sit together. The query finds the boundary at 104 within that range, reads backward through 103 and 102, and stops. With the right order available in the index, the planner can return the requested rows without sorting the whole conversation. The walkthrough uses a page of 20 turns. Two turns make the scan easy to trace here. PostgreSQL multicolumn indexes · PostgreSQL indexes and sort order
Choose index columns from the query's filter and order. Here an equality filter on the leading key, conversation_id, restricts the search to one conversation. A range on the next key, seq, gives the starting point within it. A query for a sequence across all conversations would use a different access pattern. If values can tie at a page boundary, put a stable tie-breaking key in the order and cursor as well so the next page can pick up at a precise position.
Let the database decide who owns an alias
Two people try to claim notes. Both requests read the table before either has written, and both see an empty result. That read tells each request what was visible at the time. It leaves the alias free for another request to claim.
A unique constraint on short_code lets only one mapping own each code. PostgreSQL uses a unique index to enforce the rule when inserting the row. If one insert is still waiting to commit, a conflicting insert can wait for its outcome. If the first commits, the second hits the conflict. If the first rolls back, the second can win. PostgreSQL unique constraints · PostgreSQL concurrent uniqueness checks
The URL Shortener uses INSERT ... ON CONFLICT (short_code) DO NOTHING RETURNING short_code. A row returned by a successful claim means that request inserted the mapping. The API reports success after commit. An empty insert result means the conflict already has an owner, so the API returns 409 Conflict. Generated and custom codes share the same uniqueness rule. PostgreSQL INSERT conflict handling
A partial index includes only rows that satisfy a condition. In the ChatGPT design, a unique index on conversation_id applies to turns whose status is pending or running. It enforces one active turn per conversation and allows any number of completed turns. A separate unique index on (account_id, client_turn_id) answers a different question. It limits each account to one stored turn per retry key. The client supplies the same key when it retries. PostgreSQL partial indexes
Check which work the index saves
If redirects often need only the long URL, we can store destination_url in the alias index as an included column. In PostgreSQL, INCLUDE adds the value without making it part of the uniqueness key. That makes it a covering index for this lookup because it contains all the needed fields. In PostgreSQL, this makes an index-only scan possible, but it may still need the table. PostgreSQL can skip visiting a table page when its visibility map confirms that the page's rows are all visible to current transactions. Recent writes can clear that mark. PostgreSQL index-only scans
Every additional index takes space. PostgreSQL has to maintain index entries as rows are inserted and when relevant updates need new entries. A wider index also takes more space per key. Test on data that resembles production. Use EXPLAIN to see the chosen plan and estimated row counts. Run EXPLAIN (ANALYZE, BUFFERS) on a test read to see actual rows, hits in PostgreSQL's buffer cache, and reads that had to bring pages into the cache. A read can still be served by the operating system's cache. ANALYZE executes the statement. Compare those counts before and after adding the index. PostgreSQL index maintenance · PostgreSQL EXPLAIN
See also
- PostgreSQL explains how its heap, visibility map, and B-tree work together.
- B-Trees vs LSM-Trees follows what happens when a leaf fills and compares how sorted files handle updates.
- SQL vs NoSQL starts storage selection with the reads and writes the application needs.
- Database Sharding covers the next decision when one database cannot handle the work.
- Isolation Levels and MVCC explains which row version a query can read.
Used in
- URL Shortener looks up uncached codes and enforces uniqueness across generated codes and aliases.
- ChatGPT reads history in sequence and uses independent uniqueness rules for retries and active turns.
Done reading? Mark it so it sticks in your dashboard.