Single-Node Performance Tuning and Indexing
15 min read
Welcome to the first module of our Database Sharding and Optimisation track!
Before you start splitting your tables across dozens of distributed nodes and losing sleep over two-phase commits, there is an unwritten law among staff database engineers:
"Premature sharding is the root of all cloud-bill existential dread."
If your query takes 12 seconds to run on a single machine, sharding that table across 10 machines doesn't make it 10 times faster—it just distributes your misery across 10 servers while introducing network latency, cross-node transactions, and distributed deadlocks.
In this guide, we will master single-node database internals. We will squeeze every microsecond out of the hardware before deciding whether distributed scaling is truly justified.
🎯 Scope and Boundaries: What Single-Node Tuning Can (and Cannot) Do
| What You Can Achieve | What You Cannot Do (The Hard Boundary) |
|---|---|
| Reduce a 5,000ms query to 2ms by eliminating random I/O and heap lookups. | Scale writes beyond the maximum physical IOPS of your storage drive. |
| Handle tens of thousands of concurrent reads using memory-efficient indexes. | Store more data than physical NVMe/SATA storage permits on one instance. |
| Prevent deadlocks and transaction lock-convoy stalls using MVCC tuning. | Survive a complete bare-metal hardware failure without failover replicas. |
Why does this boundary exist?
A single database node is bounded by hardware physics: CPU clock speed, RAM bandwidth, PCIe lane throughput, and disk IOPS. Single-node optimization maximizes the efficiency of these four components. When your write rate saturates the physical write-path bus of an enterprise NVMe SSD, or your working set outgrows standard system memory limits, you cross the boundary into sharding. Until then: optimize.
SubTopic 1: B-Tree vs. LSM-Tree Indexes and Storage Engine Mechanics
Definition & The Problem
When you run:
INSERT INTO logs (event_id, timestamp, payload) VALUES (101, NOW(), '{"status": 200}');The storage engine must decide: Where does this byte sequence live on disk, and how do we find it quickly later?
The fundamental problem is the physical nature of non-volatile storage: sequential I/O is orders of magnitude faster than random I/O. Even on modern NVMe drives, continuous sequential block writes can sustain several gigabytes per second, whereas scattered 4KB random writes quickly cause controller queue exhaustion and write-amplification stalls.
1. B-Tree Storage Engines (e.g., PostgreSQL, MySQL InnoDB)
A B-Tree (specifically a B+Tree in almost all production databases) organizes data into fixed-size blocks called Pages (typically 8KB in PostgreSQL, 16KB in MySQL InnoDB).
[ Root Page ]
/ \
[ Internal Page ] [ Internal Page ]
/ \ / \
[ Leaf: 1..10 ] [ Leaf: 11..20 ] [ Leaf: 21..30 ]- Leaf Nodes: Contain the actual keys and row pointers (or the clustered row data itself).
- Internal Nodes: Contain routing keys that guide traversals down to leaf nodes.
- Mechanism: When an insert or update occurs, the database identifies the exact leaf page that should contain the key. If the page is already full, it triggers a Page Split (the page is cut into two 50%-full pages, updating the parent page).
Trade-offs:
- 🟢 Reads: predictable, low-latency lookups. Reads touch very few pages. Range scans are fast because leaf nodes are doubly linked.
- 🔴 Writes (In-Place Updates): Writing data requires finding and updating specific pages on disk. This produces Random I/O. To survive crashes, the engine must write changes sequentially to a WAL (Write-Ahead Log in Postgres) or Redo Log (InnoDB) first, and then flush dirty pages to disk later (causing write amplification).
2. LSM-Tree Storage Engines (e.g., RocksDB, Cassandra, ScyllaDB, ClickHouse)
Log-Structured Merge-Trees eliminate in-place page modification entirely by treating writes as an append-only stream.
1. Write Request ──► [ Commit Log / WAL (Disk) ] (Crash Recovery)
│
▼
2. In-Memory Write ─► [ MemTable (Red-Black Tree or SkipList in RAM) ]
│ (When MemTable reaches 64MB)
▼
[ Flush to SSTable Level 0 (Immutable Disk Files) ]
│
▼ (Compaction Process)
[ Level 1 SSTables (Sorted, Non-overlapping) ]- MemTable: Writes are written sequentially to an in-memory sorted data structure (SkipList or Red-Black Tree) and appended to a disk-based write-ahead log for durability.
- SSTable (Sorted String Table): When the MemTable hits a threshold (e.g., 64MB), it freezes and flushes to disk as an immutable, sorted file.
- Compaction: Background threads continuously merge smaller sorted SSTables into larger sorted SSTables (similar to Merge Sort), removing deleted rows (tombstones) and obsolete versions.
Trade-offs:
- 🟢 Writes: Inserts are purely sequential memory writes followed by bulk sequential flushes. LSM-trees support extreme write throughput.
- 🔴 Reads (Read Amplification): Because data is split across multiple immutable SSTables, finding a key might require searching several disk files. LSM engines mitigate this using Bloom Filters (in-memory bit arrays that deterministically verify if a key is definitely not in an SSTable).
- 🔴 Compaction Stalls: During high write traffic, the background compaction process can saturate disk I/O, causing sudden query latency spikes.
When to Pick Which?
| Metric / Feature | B-Tree (InnoDB / Postgres B-Tree) | LSM-Tree (RocksDB / ScyllaDB) |
|---|---|---|
| Primary Workload | Read-heavy, complex OLTP, multi-row ACID | High-ingest writes, telemetry, time-series |
| Write Pattern | In-place updates (random writes to pages) | Append-only sequential writes |
| Space Overhead | Fragmented pages (often 30–40% dead space) | Compact storage; higher compression ratio |
| Latency Consistency | Highly predictable read/write latency | Occasional latency spikes during compactions |
SubTopic 2: Composite Indexes, Covering Indexes, and Index Cardinality
Definition & The Problem
A common database antipattern is adding an index for every column in a WHERE clause:
-- The "Desperate Developer" pattern:
CREATE INDEX idx_user_status ON orders(status);
CREATE INDEX idx_user_tenant ON orders(tenant_id);
CREATE INDEX idx_user_created ON orders(created_at);When this query runs:
SELECT id, total_amount FROM orders
WHERE tenant_id = 42 AND status = 'COMPLETED' AND created_at >= '2026-01-01';The query planner must choose one index, scan it, load matching records from disk, and then filter out the rest manually—or perform an expensive Bitmap Index Scan / Index Merge. Worse, every INSERT on this table now incurs the overhead of updating three separate B-Trees.
1. Index Cardinality & Selectivity
- Cardinality: The number of unique values in a column.
- Selectivity: The ratio of distinct values to total rows:
A column like uuid or email has high selectivity (), making it ideal for indexing. A column like is_deleted or gender has low selectivity, where an index often hurts performance because scanning the index plus fetching data from the table costs more than an outright Sequential Scan.
2. Composite Indexes & The Left-Prefix Rule
A composite index packs multiple columns into a single B-Tree:
CREATE INDEX idx_orders_tenant_status_created
ON orders (tenant_id, status, created_at);Think of this index like an old physical phonebook sorted by (LastName, FirstName):
- You can look up everyone named
"Smith"easily. - You can look up everyone named
"Smith, Alice"easily. - You cannot look up all people named
"Alice"without reading the entire book from front to back, because the index is ordered first byLastName.
Valid searches using idx_orders_tenant_status_created:
✓ WHERE tenant_id = 42
✓ WHERE tenant_id = 42 AND status = 'PAID'
✓ WHERE tenant_id = 42 AND status = 'PAID' AND created_at > '2026-01-01'
Invalid (cannot traverse the B-Tree directly, requires index scan/skip):
✗ WHERE status = 'PAID'
✗ WHERE created_at > '2026-01-01'Rule of Thumb for Composite Index Ordering:
- Equality columns first: Columns matched with
=(e.g.,tenant_id = 42). - Range/Inequality columns last: Columns matched with
>,<,BETWEEN, orIN(e.g.,created_at > ...). Once a range condition appears, the B-Tree can no longer use subsequent index columns for direct lookup!
3. Covering Indexes (INCLUDE Clause)
Normally, an index lookup requires two steps:
- Traverse the B-Tree index to find the index entry (contains the indexed columns + a physical Row ID/Tuple Pointer).
- Read the full table page from disk or cache to retrieve other requested columns. This is known as a Heap Fetch or Clustered Index Lookup.
If thousands of rows match, thousands of random heap fetches degrade performance.
A Covering Index satisfies the query entirely from the index tree itself, performing an Index Only Scan:
-- PostgreSQL syntax:
CREATE INDEX idx_orders_covering
ON orders (tenant_id, status)
INCLUDE (total_amount, customer_id);Index B-Tree Structure:
[ Keys used for sorting & search: (tenant_id, status) ]
│
└── Payload (not sorted, payload-only): (total_amount, customer_id)Why not just put all columns in the key?
Key columns increase tree depth, reduce the number of entries per page, and make index balancing expensive. Using INCLUDE keeps non-filter data stored only at the leaf nodes without cluttering the search tree.
SubTopic 3: Analyzing Query Execution Plans and Identifying Slow Queries
Definition & The Problem
When you run a SQL query, you write declaratively ("what data I want"). The database engine's Cost-Based Optimizer (CBO) calculates imperatively ("how to retrieve it").
If your database makes a bad plan choice, guessing won't fix it. You need to inspect the plan directly using execution plan tools.
1. Generating Execution Plans
In PostgreSQL:
EXPLAIN (ANALYZE, BUFFERS, SETTINGS, VERBOSE)
SELECT customer_id, SUM(total_amount)
FROM orders
WHERE tenant_id = 100 AND created_at >= '2026-01-01'
GROUP BY customer_id;ANALYZE: Executes the query. Warning: If you runEXPLAIN ANALYZE DELETE ..., it will actually delete the data!BUFFERS: Displays cache hits vs. disk reads.
2. Anatomy of an Execution Plan
Consider this example output:
HashAggregate (cost=1250.30..1270.30 rows=2000 width=16) (actual time=14.120..14.310 rows=150 loops=1)
Group Key: customer_id
Buffers: shared hit=412 read=85
-> Bitmap Heap Scan on orders (cost=42.10..1210.00 rows=8060 width=12) (actual time=1.210..9.410 rows=8200 loops=1)
Recheck Cond: (tenant_id = 100 AND created_at >= '2026-01-01'::date)
Buffers: shared hit=12 read=85
-> Bitmap Index Scan on idx_orders_tenant_created (cost=0.00..40.08 rows=8060 width=0) (actual time=0.980..0.980 rows=8200 loops=1)
Index Cond: ((tenant_id = 100) AND (created_at >= '2026-01-01'::date))
Buffers: shared hit=12
Planning Time: 0.231 ms
Execution Time: 14.512 msHow to read this tree:
Start from the most indented line (the innermost leaf) and read upward:
Bitmap Index Scan: Scannedidx_orders_tenant_created. Instead of immediately reading the table, it constructed an in-memory bit-array of candidate page locations (Buffers: shared hit=12).Bitmap Heap Scan: Visited table pages in physical disk order to fetch remaining fields. Notice:shared hit=12 read=85. It found 12 pages in memory cache, but had to read 85 pages from physical disk.HashAggregate: Grouped the retrieved records in memory bycustomer_idand computedSUM().
3. Red Flags in Query Plans
Seq Scanon massive tables:
The engine scanned every row in the table. If intentional (e.g., aggregating 80% of all data), this is fine. If it filters down to 3 rows, an index is missing.- Discrepancy between
rows=Xandactual rows=Y:
Look at:rows=10vsactual rows=500000. This means the optimizer's statistics are stale. Run:sqlANALYZE orders; -- Updates pg_statistic tables - Spilling to Disk (
external merge Disk: ...kBorSortMethod: external sort):
Occurs whenwork_mem(in Postgres) orsort_buffer_size(in MySQL) is smaller than the dataset being sorted or hashed. The engine writes temp data to disk, tanking throughput.
SubTopic 4: Locking Mechanisms, Concurrency Control, and MVCC
Definition & The Problem
If two transactions attempt to update the same account balance simultaneously:
- Tx 1: Reads balance ($100), adds $50.
- Tx 2: Reads balance ($100), subtracts $30.
- If they write back naively, one update overwrites the other (the Lost Update Problem).
Traditional databases solved this by locking rows during read and write operations. However, this creates a major bottleneck: readers block writers, and writers block readers.
1. Multi-Version Concurrency Control (MVCC)
Modern engines (PostgreSQL, MySQL InnoDB, Oracle) solve this via MVCC:
Readers never block writers, and writers never block readers.
Instead of mutating a row in place, an update creates a new version of that row.
How PostgreSQL Handles MVCC:
Every row (tuple) on disk has hidden system header columns:
xmin: The transaction ID () that inserted this row.xmax: The transaction ID that deleted or replaced this row (initially 0).
1. Tx 101 Inserts:
[Tuple 1] xmin: 101 | xmax: 0 | balance: 100
2. Tx 102 Updates balance to 150:
[Tuple 1] xmin: 101 | xmax: 102 | balance: 100 <-- Marked as expired
[Tuple 2] xmin: 102 | xmax: 0 | balance: 150 <-- New active versionWhen Tx 103 reads the table, the database checks Tx 103’s snapshot:
- If Tx 102 is still running, Tx 103 ignores
Tuple 2and readsTuple 1. - No shared locks on reading are necessary!
The MVCC Catch: Table Bloat & Vacuuming
Expired row versions remain on disk. In Postgres, the VACUUM background worker cleans up dead tuples and freezes old transaction IDs to prevent Transaction ID Wraparound (an emergency condition where the 32-bit transaction counter exhausts its values).
(Note: MySQL InnoDB uses a different mechanism: it writes the new version in place and appends older versions to an Undo Log segment in memory/disk space, avoiding Postgres-style table bloat at the cost of undo-chain traversal overhead.)
2. Pessimistic vs. Optimistic Locking
When updates conflict, we must choose our locking strategy:
A. Pessimistic Locking (SELECT ... FOR UPDATE)
Use this when data contention is frequent. We lock the row explicitly before updating:
BEGIN;
-- Row is locked; other transactions attempting FOR UPDATE will wait
SELECT balance FROM accounts
WHERE account_id = 9012
FOR UPDATE;
UPDATE accounts
SET balance = balance - 50
WHERE account_id = 9012;
COMMIT;B. Optimistic Locking (Application-Managed)
Use this when conflicts are rare. No database-level row lock is held during user think-time:
-- Step 1: Read data including a version field
SELECT balance, version FROM accounts WHERE account_id = 9012;
-- (Application processes the change...)
-- Step 2: Attempt conditional update
UPDATE accounts
SET balance = balance - 50, version = version + 1
WHERE account_id = 9012 AND version = 4;If ROW_COUNT() == 0, another client updated the record first. The application catches this and retries.
3. Understanding Deadlocks
A deadlock happens when two transactions wait for resources held by each other:
Tx 1: Locks Row A ───────────────► Tries to Lock Row B (Blocked!)
▲
│
Tx 2: Tries to Lock Row A (Blocked!) ◄── Locks Row BNeither transaction can proceed. Databases periodically run a Deadlock Detection Cycle (e.g., building a directed wait-for graph). When a cycle is detected, the engine aborts the cheaper transaction with an error:ERROR: deadlock detected.
Deadlock Prevention Best Practice:
Always update multiple resources in a consistent global order. If every transaction sorts IDs and updates them lowest-to-highest (WHERE id = 2 before WHERE id = 10), cyclic dependency becomes mathematically impossible.
💻 Hands-On Simulation: Optimizing a Crippled Query
Imagine an e-commerce platform processing 10,000,000 orders. Customer support runs this query to view high-priority tickets:
-- The Unoptimized Query
SELECT id, customer_id, order_date, total_amount
FROM orders
WHERE status = 'PROCESSING'
AND order_date >= '2026-01-01'
ORDER BY order_date DESC
LIMIT 50;The Problem:
statushas low cardinality ('PENDING','PROCESSING','COMPLETED','REFUNDED').- An index on
(status)forces the engine to read thousands of rows, sort them in memory, and discard all but 50. - Plan time:
Seq Scan on orders, cost=185200.00, Execution Time: 3420.12 ms.
The Solution:
Create a Composite Covering Partial Index:
CREATE INDEX idx_orders_processing_date_covering
ON orders (order_date DESC)
INCLUDE (customer_id, total_amount)
WHERE status = 'PROCESSING';Why this changes everything:
- Partial Index (
WHERE status = 'PROCESSING'): The index excludes all completed and refunded records (likely 95% of the table), keeping the index compact and resident in RAM. - Order-matched Key (
order_date DESC): The index matches theORDER BYclause exactly, removing the need for a sorting step. - Covering (
INCLUDE customer_id, total_amount): Prevents heap lookup fetches entirely.
Resulting Execution Plan:
Limit (cost=0.42..8.50 rows=50 width=24) (actual time=0.032..0.065 rows=50 loops=1)
-> Index Only Scan using idx_orders_processing_date_covering on orders
Execution Time: 0.082 msPerformance improvement: ~3,400ms down to 0.08ms (a 40,000x speedup).
📝 Practice Quiz
Take a moment to verify what you learned:
Why does an LSM-Tree achieve higher write throughput than a B-Tree on disk?
- Answer: LSM-trees transform random writes into sequential in-memory appends (MemTable) followed by sequential batch flushes to disk (SSTables), avoiding random I/O page modifications.
You have a composite index on
(department_id, employee_rank, hire_date). Will this index accelerate the query:SELECT * FROM staff WHERE employee_rank = 3;?- Answer: No. Under the Left-Prefix Rule, an index lookup requires the leading column (
department_id) to prune non-matching tree branches.
- Answer: No. Under the Left-Prefix Rule, an index lookup requires the leading column (
In PostgreSQL, what causes dead tuples to accumulate in a table?
- Answer: Updates and deletes under MVCC do not overwrite data in place; updates insert a new version and mark the old one expired. Dead tuples remain until cleaned up by the
VACUUMworker.
- Answer: Updates and deletes under MVCC do not overwrite data in place; updates insert a new version and mark the old one expired. Dead tuples remain until cleaned up by the
📚 References & Further Reading
Challenge
Scenario
You are tuning a read-heavy PostgreSQL OLTP orders table. The existing idx_orders_status index is on a low-cardinality column (status) and does not help much.
The slow query filters pending orders, sorts newest first, and returns only a few columns:
SELECT order_id, customer_id, order_date, total_cents
FROM orders
WHERE status = 'pending'
ORDER BY order_date DESC
LIMIT 50;Table shape
orders(
order_id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
order_date timestamptz NOT NULL,
total_cents integer NOT NULL,
shipping_address text,
notes text
)Task
Write PostgreSQL SQL that:
- Drops the existing single-column index
idx_orders_status. - Creates a partial covering composite index optimized for the query above.
- Adds an
EXPLAIN (ANALYZE, BUFFERS)verification statement for the target query.
Do not create a broad index covering every filter column. Focus on the equality filter, the ORDER BY, and the columns needed by the query.
Expected result
Success criteria: The editor should contain valid PostgreSQL SQL that:
- Drops
idx_orders_status. - Creates a partial covering B-tree index on
ordersforstatus = 'pending'. - Uses
statusas the equality key andorder_date DESCas the next key column. - Uses
INCLUDEfororder_id,customer_id, andtotal_centsso the target query can be index-only. - Includes a
WHERE status = 'pending'partial predicate to keep the index small. - Adds
EXPLAIN (ANALYZE, BUFFERS)before the target query.
The intent is to support the query without a sort and without heap fetches for the listed columns.