Indexing Strategy and Design Questions
Choosing and designing indexes: B-tree, hash, composite, covering, partial, and full-text/inverted indexes, and the trade-offs between read acceleration and write/storage overhead. Covers selecting index columns from query patterns, cardinality and selectivity reasoning, diagnosing why an index is or is not used, and index maintenance: rebuilding or reorganizing a fragmented index, finding and dropping redundant or unused indexes, and rolling out a new index to production safely. Also covers indexing in analytical (bitmap, columnar), partitioned, and distributed/NoSQL systems. Central to database performance interviews.
You have a JSONB column profile in users storing nested fields. Example query: SELECT id FROM users WHERE profile->'address'->>'city' = 'Seattle'. Write two different Postgres index strategies (functional b-tree and GIN) to accelerate this query and explain pros/cons of each.
Sample Answer
Direct answer
For WHERE profile->'address'->>'city' = 'Seattle', where profile is a JSONB (Postgres's binary-encoded JSON, JavaScript Object Notation, column type that supports indexing and efficient key lookups, unlike plain text JSON) column, the fastest, cheapest option is a functional (expression) B-tree index built on exactly that expression: CREATE INDEX ON users ((profile->'address'->>'city')). A GIN (Generalized Inverted iNdex, Postgres's index type for indexing every element inside a composite value like a JSONB document or an array) index on the whole profile column is more flexible (it can answer many different key-path queries, not just this one) but it only accelerates containment-style queries (profile @> '{"address":{"city":"Seattle"}}'), not the ->>'city' = form as literally written, and it costs more to write and more to store. If you only ever query this one path, the functional B-tree wins outright; if the application queries many different keys inside profile unpredictably, GIN is the one index that covers all of them, at a real cost.
Structured elaboration
Functional (expression) B-tree. Postgres lets you index the RESULT of an expression, not just a raw column. CREATE INDEX idx_users_city ON users ((profile->'address'->>'city')) builds a plain B-tree over the extracted city string. It only matches queries whose WHERE clause contains that EXACT expression (same operators, same path), it is small (roughly proportional to the number of rows, like any B-tree on a single scalar), and it supports equality and range/sort on that one derived value.
GIN. CREATE INDEX idx_users_profile_gin ON users USING GIN (profile) decomposes the whole JSONB document into its component keys and values and indexes each one, so it can accelerate @> containment queries against ANY path inside the document, including paths you didn't anticipate when you built the index, and multiple keys in one query. The cost is a bigger index (it stores an entry per key/value pair, not per row) and slower writes (every insert or update has to update potentially many index entries per document, not one).
| Functional B-tree on one path | GIN on the whole column | |
|---|---|---|
| Matches | that exact expression, as written | any @> containment path inside the document |
| Write cost | one index entry per row | many entries per row (per key/value) |
| Storage | small, proportional to rows | larger, proportional to document contents |
| Query form required | profile->'address'->>'city' = 'Seattle' | profile @> '{"address":{"city":"Seattle"}}' |
Worked example
Seeded on Postgres 16: users(id, profile jsonb), 500,000 rows, with profile->'address'->>'city' = 'Seattle' matching 2,000 rows (0.4 percent selectivity).
No index at all:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM users WHERE profile->'address'->>'city' = 'Seattle';
-- Gather (actual time=20.704..23.055, rows=2000)
-- Parallel Seq Scan on users (Rows Removed by Filter: 166000)
-- Execution Time: 23.123 ms
Functional B-tree:
CREATE INDEX idx_users_city ON users ((profile->'address'->>'city'));
EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM users WHERE profile->'address'->>'city' = 'Seattle';
-- Bitmap Heap Scan (actual time=0.047..0.136, rows=2000)
-- -> Bitmap Index Scan on idx_users_city
-- Execution Time: 0.197 ms
23.1 ms down to 0.2 ms, about 115x faster, for a small single-purpose index.
GIN on the whole column, queried with the matching containment form:
DROP INDEX idx_users_city;
CREATE INDEX idx_users_profile_gin ON users USING GIN (profile);
EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM users WHERE profile @> '{"address":{"city":"Seattle"}}';
-- Bitmap Heap Scan (actual time=0.216..0.444, rows=2000)
-- -> Bitmap Index Scan on idx_users_profile_gin
-- Execution Time: 0.507 ms
Fast too (about 45x faster than no index), but notice what happens if the query is left in its ORIGINAL form with only the GIN index present:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM users WHERE profile->'address'->>'city' = 'Seattle';
-- Gather -> Parallel Seq Scan (Rows Removed by Filter: 166000)
-- Execution Time: 17.752 ms
Still a full scan. The GIN index was built and is healthy, but the ->>'city' = expression does not map to the @> operator GIN accelerates, so it is never even considered. That gap between "an index exists on this column" and "an index accelerates this exact query form" is the single most common JSONB indexing mistake.
Trade-offs & pitfalls
Before indexing the JSONB path at all, weigh normalizing it into its own column (or a separate table, for a repeating structure like tags or line items). If city is queried, filtered and joined on constantly, an ordinary typed column with an ordinary B-tree is simpler to reason about, cheaper to index, and lets the query planner use accurate per-column statistics instead of the coarser statistics Postgres keeps for JSONB paths. Reach for indexing inside the JSONB when the schema is genuinely variable (different documents have different shapes) or the paths queried are too numerous or too unpredictable to normalize one by one.
Once an application is already carrying an expensive, broad GIN index over a whole JSONB column, and most queries turn out to hit only two or three hot paths, migrating those hot paths to small functional B-tree indexes (and, once traffic confirms nobody queries the old paths, dropping the broad GIN) is a real, incremental way to cut both write amplification and storage without a big-bang schema rewrite.
If indexing alone stops being enough, for example a dashboard needs city, plan and a derived metric together and touches most of the table anyway, a materialized view or a denormalized reporting table refreshed on a schedule is the next escape hatch: it turns a JSONB path-extraction query into an ordinary, cheaply-indexed columnar query, at the cost of some staleness.
A GIN index also supports jsonb_path_ops, a narrower operator class that indexes only @> containment (not key-existence operators like ?), which produces a smaller, faster-to-maintain index when containment is the only query shape you need; the default jsonb_ops class is more flexible but larger.
Define index selectivity and cardinality. Given a customers table with 1,000,000 rows and a column 'country' with 5 unique values and a column 'customer_id' with 1,000,000 unique values, explain which column is a better candidate for an index and why. Also explain how selectivity affects optimizer choice.
Sample Answer
Direct answer
Cardinality is the number of distinct values a column has. Selectivity is that cardinality expressed as a fraction of the table: how much a single value narrows the result down. For a customers table with 1,000,000 rows, customer_id has 1,000,000 distinct values (cardinality 1,000,000, selectivity 1.0, meaning each value matches exactly one row), while country has 5 distinct values (cardinality 5, selectivity roughly 0.0000005 per exact-match lookup on customer_id, versus roughly 0.2, or 20%, per value on country, since values aren't evenly split here). customer_id is the far better index candidate: an index on it eliminates all but one row per lookup, while an index on country still leaves a large fraction of the table to sift through.
Structured elaboration
selectivity of a value v in column c=total rowsrows where c=v
Lower selectivity (a smaller fraction) is better for point lookups: it means a single value matches fewer rows, so an index eliminates more of the table. customer_id, being unique per row, has the best possible selectivity for equality lookups: exactly 1,000,0001 per value. country, with only 5 distinct values, has selectivity around 51=0.2 per value if the values were evenly distributed, meaning a typical WHERE country = ? still returns roughly a fifth of the entire table.
Why the optimizer cares. Every query plan is a bet on which access method reads the least data. An index lookup has a fixed per-row cost (walk the tree, then fetch the row), so it beats a sequential scan only when it fetches meaningfully fewer rows than the sequential scan would have to read anyway. At high selectivity (few matching rows), the index wins by a wide margin. At low selectivity (a large fraction of rows matching), the index degenerates toward reading almost the whole table anyway, PLUS the overhead of the index traversal itself, so the optimizer correctly prefers a sequential scan past some crossover point, which depends on the table's physical layout and the storage engine's cost model, not a single fixed percentage.
Worked example
Real distinct-value counts from the customers table used here, exactly matching the setup described above:
SELECT count(DISTINCT country) AS distinct_countries,
count(DISTINCT customer_id) AS distinct_customer_ids,
count(*) AS total_rows
FROM customers;
distinct_countries | distinct_customer_ids | total_rows
---------------------+------------------------+------------
5 | 1000000 | 1000000
Querying on the high-cardinality column, customer_id (already indexed as the primary key):
EXPLAIN (ANALYZE, BUFFERS) SELECT customer_id FROM customers WHERE customer_id = 777777;
Index Only Scan using customers_pkey on customers (cost=0.42..4.44 rows=1 width=4) (actual time=0.055..0.055 rows=1 loops=1)
Index Cond: (customer_id = 777777)
Heap Fetches: 0
Buffers: shared hit=1 read=3
Execution Time: 0.062 ms
Querying on the low-cardinality column, country, after building a matching index:
EXPLAIN (ANALYZE, BUFFERS) SELECT customer_id FROM customers WHERE country = 'US';
Bitmap Heap Scan on customers (cost=2253.67..16761.26 rows=201967 width=4) (actual time=3.275..34.310 rows=200301 loops=1)
Recheck Cond: (country = 'US'::text)
Heap Blocks: exact=11983
-> Bitmap Index Scan on idx_customers_country (actual time=2.442..2.442 rows=200301 loops=1)
Index Cond: (country = 'US'::text)
Execution Time: 37.387 ms
The customer_id lookup returned 1 row using 4 buffer reads and finished in a fraction of a millisecond, with Heap Fetches: 0 confirming it never touched the table storage at all. The country lookup, despite having its own index, matched 200,301 rows (roughly 20% of the table, since 'US' is one of the more common of the 5 values here) and took over 500x longer in this run, because at that selectivity the index still has to identify, and then fetch, a large fraction of the table's pages: the database chose a Bitmap Heap Scan (build a bitmap of matching pages from the index, then visit each page once) specifically because it's cheaper than either a naive row-by-row index scan or a full sequential scan at this selectivity, not because the index made the query fast in any absolute sense.
Trade-offs & pitfalls
Don't judge an index candidate purely by "does it have a reasonable number of distinct values": 5 distinct values across 1,000,000 rows sounds like it should help, and it does help somewhat (this query would be even slower with no index, and did cost less by the optimizer's own estimate than a plain sequential scan), but "helps somewhat" is a very different outcome from the near-instant, sub-millisecond result the high-cardinality column gets. In an OLTP (online transaction processing) system, where a filter like country = 'US' typically appears alongside a more selective predicate (a specific customer's transactions, say), it's the COMBINED selectivity of all the predicates in a composite index that matters, not any single column's cardinality in isolation. In an OLAP (online analytical processing) system, where a query is expected to summarize a large fraction of the table anyway, a low-selectivity column being "worse for point lookups" is often irrelevant, since the query was never going to touch a small slice of the table to begin with.
Discuss when you would use a clustered columnstore index versus a nonclustered columnstore index in SQL Server for a large analytical fact table that receives frequent micro-batch loads. Explain how the delta store and tuple-mover affect query and load performance, and how you would structure data loads to minimize fragmentation.
Sample Answer
Direct answer: For a large analytical fact table (a big, append-heavy table of business events or transactions, as opposed to a small reference "dimension" table like a customer or product list) that receives frequent micro-batch loads, use a CLUSTERED columnstore index (CCI) if this table's primary storage should just BE stored column-by-column, which is the normal choice for a warehouse fact table, since that's the natural fit for the scan-heavy queries fact tables usually see; use a NONCLUSTERED columnstore index (NCCI) only when you need to keep the table's primary storage in its traditional row-by-row layout, for fast single-row lookups and updates, and add a second, columnar copy alongside it purely to accelerate analytics run concurrently against the same data. Either way, micro-batch loads interact with the same underlying mechanism, the delta store, and the load pattern you choose has a direct, controllable effect on fragmentation.
Row-store vs. columnstore, and what "heap," "B-tree," and "clustered index" mean here
Two physical-storage concepts sit underneath this whole comparison, so it's worth naming them plainly before going further.
A row-store is the traditional table layout: every column belonging to one row is stored together on disk, one row after another. That's efficient for reading or changing ONE specific row (an OLTP query, short for online transaction processing: live application traffic doing many small reads and writes to individual rows, like one order being created or updated), since everything about that row sits in one place. It's inefficient for a query that scans millions of rows but only needs a handful of the table's columns, because the engine still has to read every row's full width off disk just to get those few columns.
A columnstore (columnar storage) flips that layout: it stores each COLUMN's values together instead, e.g. every order_date value in one place, every amount value in another. A large analytical scan that only touches a few columns now reads just those columns, not the full row width, and because values within one column tend to repeat or trend together, they also compress far better sitting next to each other than interleaved with unrelated columns. The cost shows up on the write side: touching one row now means touching several separate per-column structures instead of one row location, which is why a table under constant single-row transactional writes suits a row-store better than a columnstore.
Within a row-store, SQL Server organizes a table's rows one of two ways. A heap has no defined row order at all, a new row just goes wherever there's free space. A clustered index is not a separate structure sitting beside the table, it IS the table: the table's rows are physically stored on disk sorted in that index's key order, which is why a table can have at most one clustered index (or, if it defines none, it's stored as a heap instead). Once you add any index to speed up lookups, that index is typically implemented as a B-tree (specifically a B+ tree in SQL Server, a balanced, sorted tree structure that finds one row in a small, predictable number of steps instead of scanning every row).
CCI and NCCI, below, are both just ways of getting the columnar layout: either as the table's ONLY physical storage (CCI, replacing the heap/B-tree row-store entirely) or as a second, columnar copy layered next to a row-store original that keeps serving OLTP traffic (NCCI).
Clustered vs. nonclustered columnstore
- A clustered columnstore index (CCI) IS the table: it's the only, primary physical storage for every row and column, replacing what would otherwise be a heap or a B-tree clustered index. You create it directly (
CREATE TABLE ... WITH (INDEX ... CLUSTERED COLUMNSTORE)) or convert an existing rowstore table to one. - A nonclustered columnstore index (NCCI) is a secondary structure layered on top of a table whose primary storage stays row-based (a heap or a B-tree). It holds a compressed columnar copy of some or all columns, letting transactional (OLTP) queries keep using the row-store B-tree while analytical queries run against the columnstore copy concurrently, an SQL Server feature Microsoft calls real-time operational analytics. Since 2016, an NCCI is updatable and stays in sync automatically as the underlying rowstore table changes.
The delta store and the tuple-mover
- Rowgroup. A columnstore index physically slices the table into rowgroups, each holding up to 1,048,576 rows, compressed column-by-column. Bigger rowgroups compress better; too many small ones hurt query performance, so SQL Server also enforces a practical MINIMUM before it will compress a rowgroup: 102,400 rows.
- Delta store (a.k.a. the delta rowgroup(s)). Writing directly into compressed columnar format is expensive for a handful of rows at a time, so SQL Server stages small or incremental writes in the delta store instead: one or more ordinary, uncompressed, B-tree-indexed rowgroups (the docs are explicit that this is a real B+ tree, the same structure a normal clustered index uses, layered specifically for staging). Rows accumulate here until a rowgroup fills to the 1,048,576-row maximum, at which point it flips from OPEN to CLOSED.
- Tuple-mover. A background process that watches for CLOSED delta rowgroups and compresses them into the columnstore as new, permanent COMPRESSED rowgroups. Because it runs asynchronously in the background, a query issued right after a small load may still have to read from BOTH the compressed columnstore and the (uncompressed, B-tree) delta store and merge the results, which is measurably slower than reading from compressed columnstore alone. In SQL Server 2019 and later (and in Azure SQL Database/Managed Instance), the tuple-mover gets help from an additional background merge task that also compresses smaller long-lived OPEN delta rowgroups and merges COMPRESSED rowgroups that have had many rows deleted from them, improving index quality over time without manual intervention.
Structuring micro-batch loads to minimize fragmentation
The single highest-leverage lever is batch SIZE relative to the 102,400-row minimum:
- Batches at or above ~102,400 rows (and ideally close to a full 1,048,576-row rowgroup) can go DIRECTLY into compressed columnar rowgroups during a bulk load, bypassing the delta store entirely. This is the "big enough batch" regime and it produces the least fragmentation.
- Batches below that threshold always land in the delta store, because SQL Server won't compress a group that small on its own; frequent tiny micro-batches therefore generate many small delta rowgroups, all waiting on the tuple-mover, which is exactly the "too many small rowgroups" fragmentation state the docs warn degrades columnstore index quality.
- Practical structuring choices: batch application-level writes up to (or just above) 102,400 rows before committing them to the table when the source system allows it; use bulk-load paths with table-lock hints (
TABLOCK) where possible, since large parallel bulk loads write directly to compressed rowgroups more aggressively than row-by-row inserts; and scheduleALTER INDEX ... REORGANIZE(which forces the tuple-mover's work and merges small COMPRESSED rowgroups, always runs online, at lower resource cost than a full rebuild) during low-traffic windows if micro-batches can't be sized up at the source. ReserveALTER INDEX ... REBUILDfor periodic full defragmentation, since it's more resource-intensive though it can produce a cleaner result. - Tracing one load pattern through the two thresholds. Say a source system delivers a micro-batch of 40,000 rows every 10 minutes, well under the 102,400-row minimum, so every batch lands in the delta store instead of going straight to compressed columnar storage:
- Load 1 (40,000 rows): a new delta rowgroup opens, holding 40,000 rows, OPEN and uncompressed.
- Load 2 (another 40,000 rows, 10 minutes later): appended into the same OPEN delta rowgroup, now 80,000 rows, still OPEN; any query touching this data reads it from the slower, B-tree-indexed delta store, not compressed columnar storage.
- Load 3 (another 40,000 rows, 120,000 total): the rowgroup is now past the 102,400-row minimum, but that minimum only controls whether a bulk-load batch can skip the delta store entirely; it does NOT make an already-open delta rowgroup close. The rowgroup stays OPEN and keeps accepting rows.
- This keeps accumulating, roughly one delta rowgroup per 26 loads (26 x 40,000 = 1,040,000, just under the 1,048,576-row cap), until a load finally pushes it to the 1,048,576-row maximum. Only then does the rowgroup flip from OPEN to CLOSED, at which point the background tuple-mover picks it up, compresses it into a permanent COMPRESSED columnar rowgroup, and a fresh empty delta rowgroup opens for the next load.
- Contrast that with sizing the same source batches up to 102,400+ rows before committing (say, buffering three 40,000-row loads into one 120,000-row batch): each such batch can go straight into a compressed columnar rowgroup during a bulk load, never touching the delta store at all, so there is no lingering OPEN delta rowgroup for a query to fall back to between loads.
- On SQL Server 2019+, Azure SQL Database, Azure SQL Managed Instance (Microsoft's fully-managed, near-100%-compatible SQL Server instance running in Azure), and Synapse dedicated SQL pools (Azure Synapse Analytics' provisioned, large-scale data-warehouse compute tier), the automatic background merge task reduces (but doesn't eliminate) how much manual
REORGANIZE/REBUILDscheduling this needs.
Trade-offs and pitfalls
- Reading from the delta store is slower than reading from compressed columnstore alone, so a table under constant micro-batch load always has SOME fraction of recent data being served at row-store speed rather than columnstore speed; that's expected behavior, not a misconfiguration, but it means "how fresh is recent data" and "how fast are the most recent rows to query" are in tension.
- Batch mode execution, SQL Server's vectorized (multiple-rows-at-once) query processing mode used for columnstore scans, typically improves analytical query performance by roughly 2 to 4x over row-by-row execution; it only engages properly once data has left the delta store and lives in compressed rowgroups, another reason small, lingering delta rowgroups cost you more than their storage footprint suggests.
- Deleting from a compressed columnstore row only marks it logically deleted (physical space isn't reclaimed until a rebuild), while deleting from the delta store removes it immediately; a workload with heavy deletes against old, already-compressed data accumulates dead space that only
REBUILD(or, since 2019, the automatic merge task) reclaims. - A rowgroup that's had all its rows deleted transitions to TOMBSTONE and is cleaned up by the tuple-mover, so a table with a lot of delete churn benefits from the same background processes that manage delta-store compression, not a separate mechanism.
Discuss the trade-offs of adding covering indexes vs allowing index-only scans vs creating wide composite indexes. Consider index size, cache locality, write penalty, and cache eviction. Provide heuristics for when to choose each approach in a high-throughput OLTP environment.
Sample Answer
Direct answer
No, a bigger covering index is not always better, and the honest heuristic is: cover only the small number of queries that are both frequent and latency-critical, keep the included-column list short, and validate the index actually gets used after deployment rather than assuming it will. A covering index trades write cost and cache footprint for eliminating a heap fetch on read; a wide composite trades some of the same things for serving several different filter shapes from one structure. Neither is free, and I have real size numbers, not estimates, to put behind the cost side.
The three options and what they cost
- Covering index (base key columns plus
INCLUDEpayload columns): enables an index-only scan (the query is answered entirely from the index, no heap access) for a specific, known query shape. Every included column is pure overhead for every other query that doesn't need it. - Index-only scans generally: only possible when the visibility map (Postgres's per-page record of which pages have no uncommitted or dead row versions) says the relevant pages are all-visible, which requires
VACUUMto have run recently enough. An index-only scan design that ignores autovacuum cadence will quietly degrade back into ordinary index scans with heap fetches. - Wide composite index (many key columns, no INCLUDE): serves any query whose filters form a leftmost prefix of the key, at the cost of a larger, deeper B-tree and a maintenance write on every column in the key whenever any of them changes.
Worked example: measuring the size cost directly
-- orders table, 2,000,000 rows, columns: order_id, customer_id, order_date, status, amount
CREATE INDEX idx_narrow ON orders (customer_id);
CREATE INDEX idx_wide_covering ON orders (customer_id) INCLUDE (order_date, status, amount);
SELECT pg_size_pretty(pg_relation_size('idx_narrow')) narrow_size,
pg_size_pretty(pg_relation_size('idx_wide_covering')) wide_size;
Real result on Postgres 16: idx_narrow is 22 MB; idx_wide_covering, same 2,000,000 rows, same leading key, three extra INCLUDE columns, is 82 MB: roughly 3.7x larger for one index on one table. shared_buffers (Postgres's in-memory page cache) and the operating system's page cache are both finite and shared across every table and index in the database; an index that is several times larger competes for that same finite cache space against everything else the database is doing. A covering index that makes one dashboard query fast can make an unrelated hot query slower by evicting its working set from cache, and that failure mode does not show up in EXPLAIN on the query you just optimized. It shows up as a regression somewhere else, which is why "is a bigger covering index always better" is a trap question: the cost is real but it is not visible in the plan you're looking at.
There's a write-side cost too, and it's not confined to key columns. An UPDATE that changes a column carried only in a covering index's INCLUDE list, not its key, still requires a new index entry, because the index has to store and maintain that column's current value regardless of whether it's part of the search key. That disqualifies Postgres's Heap-Only Tuple optimization (an in-place update path that skips writing new index entries when no indexed column changed) for that row, the same as changing a key column would. Adding INCLUDE columns "just in case" is not a free way to widen coverage; it widens the set of updates that pay the full index-maintenance cost.
Heuristics for a high-throughput OLTP (online transaction processing) system
- Cover a query only when it is both hot (high call volume) and latency-sensitive enough that eliminating a heap fetch materially matters; do not cover a report that runs once an hour.
- Keep the INCLUDE list to the columns the query's SELECT list actually needs, not every column that might someday be useful; each one adds size and update cost with no read benefit for other queries.
- Prefer several narrower composite indexes, each matched to a real WHERE-clause shape from production query logs, over one all-purpose wide index, unless you can show the wide index is actually reused across those shapes via the leftmost-prefix rule.
- After deploying a covering index, check
pg_stat_user_indexes.idx_scanto confirm it is actually being chosen; an unused covering index is pure cost with none of the intended benefit. - Track total index size against
shared_buffers; if your indexes collectively no longer fit in cache, adding another wide one is a direct trade against every other query's cache hit rate, not just a local decision about one query.
Trade-offs and pitfalls
The most common wrong turn is reasoning about a covering index purely from the query it was built for and never checking what it costs everywhere else: on writes to that table, in cache pressure, and in pg_relation_size. A close second is assuming that adding columns to an existing index's INCLUDE list is safe because "it's not in the key," when in fact any column in the index, key or included, blocks Heap-Only Tuple updates and adds an entry that has to be maintained. Validate index size and idx_scan after every covering-index change, on a schedule, not just at design time.
Discuss how secondary indexes are implemented in distributed NewSQL systems like CockroachDB or Spanner. Explain transaction implications, read/write amplification, how index-maintenance is coordinated across nodes, and the effect on latency for multi-region writes.
Sample Answer
Direct answer: In any horizontally-partitioned database, a secondary index is a second, independently-keyed data structure: its rows are ordered by the indexed column, so they almost always land on different partitions than the base row they point back to. Every write to an indexed column therefore has to touch at least two partitions instead of one, and if you want that index to return transactionally correct results, the database has to pay for cross-node coordination on every single write, not just occasionally. CockroachDB and Spanner both choose to pay this cost synchronously (the index write is part of the same distributed transaction as the base-row write), which is exactly what buys you a secondary index whose reads you can trust; systems that instead update indexes asynchronously trade that trust for lower write latency and more availability under partition.
The general cost, before any vendor specifics
This is true of secondary indexes in ANY distributed database, not just CockroachDB or Spanner: maintaining one is expensive because it is a second write path that has to stay correct relative to the first. That cost shows up as three concrete things:
- Write amplification. One logical write to the base row becomes N physical writes: one to the base table, one per secondary index that covers a changed column.
- Cross-node coordination. If the index entry and the base row live in different partitions (the normal case), keeping them consistent needs a distributed transaction, a locking/intent protocol, or an eventual-consistency compromise.
- Read amplification when the index isn't covering. A non-covering index gives you a matching key, not the full row, so a query often pays for an index lookup AND a follow-up fetch of the base row by primary key.
When you'd avoid a secondary index on a distributed table entirely
Given that cost, the honest "don't" cases are: (a) a column that's written far more often than it's queried by, where the write amplification dwarfs the read benefit, particularly under high write throughput per node; (b) a query pattern that can be served by denormalizing the needed columns directly onto the base row or into a separate purpose-built table instead (an async projection, a change-feed into a search system like Elasticsearch/OpenSearch, or a materialized summary table), decoupling the write-hot path from the index-maintenance cost entirely; and (c) a column whose selectivity is so low (e.g., a boolean status flag) that an index barely narrows the scan, so a full or partial scan is cheap enough not to be worth the write cost. In all three cases the fix is the same shape: stop trying to make the base table serve every access pattern, and let a second, purpose-built and separately-scaled structure absorb the query instead of a tightly-coupled secondary index.
CockroachDB and Spanner specifics
Physical layout. In both systems a secondary index is not a pointer structure bolted onto the table; it is itself a distinct, independently-partitioned keyspace, sharded and distributed across nodes exactly like a table is. An index row's key is built from the indexed column(s) (plus, if not unique, the primary key to disambiguate), and its value holds either nothing (a bare index, requiring a lookup back to the primary key for other columns) or the extra columns you name in a STORING clause (CockroachDB) / STORING(GoogleSQL)-INCLUDE(PostgreSQL-dialect) clause (Spanner). A STORING clause turns the index into a covering index for queries that only need the stored columns: the read is satisfied from the index alone, with no extra round trip to fetch the base row, which is the main lever you have for cutting the read-amplification cost above.
Transaction implications. Both systems fold index writes into the SAME distributed transaction as the base-row write. CockroachDB calls its partition unit a "range" and Spanner calls its "split"; both are just the vendor-specific name for the same idea this answer has been calling a partition, the physical chunk of sorted data that gets replicated and moved as one piece. In CockroachDB, each table and each index lives in one or more Raft-replicated ranges (Raft is a consensus protocol: a way for multiple replicas holding the same data to agree on the order of writes and elect a leader, even when some replicas are slow or unreachable), and a multi-range write goes through the transaction coordinator, which writes provisional "intents" across every affected range and only resolves them atomically at commit; the underlying per-range consensus is Raft. In Spanner, commits across the ranges (splits) touched by a transaction use two-phase commit (2PC: the coordinator first asks every participant "can you commit this?" and only tells them to actually commit once every participant has said yes, so a transaction spanning multiple partitions either commits everywhere or nowhere) coordinated with TrueTime, Google's globally-synchronized clock service, which lets Spanner assign a commit timestamp that every replica can agree on without extra communication just to establish ordering. Either way, correctness costs coordination: you cannot get a transactionally-consistent secondary index in a distributed table for free.
Coordination across nodes and write amplification. Because base row and index row are usually on different ranges/splits (unless deliberately colocated), a single-row UPDATE on an indexed column becomes at minimum two range writes, more if multiple indexes cover the changed column, each requiring intent-write-then-resolve (CockroachDB) or inclusion in the same 2PC commit (Spanner). Spanner has a specific mitigation for this: INTERLEAVE IN on the index lets you colocate the index's rows with an ancestor table's rows in the same split, so that when the index is interleaved in an ancestor of the base table, the index write becomes a LOCAL operation instead of a cross-split one, avoiding the two-phase commit overhead entirely for that write.
Multi-region write latency, and the eventual-consistency trade-off. When the ranges or splits touched by a transaction (base row plus every indexed column's index entry) span regions, the commit has to wait on cross-region round trips and quorum acknowledgment from replicas in those regions, regardless of how fast any single node is. Spanner's TrueTime bounds the UNCERTAINTY in that commit's timestamp, it does not remove the network latency of reaching a remote replica. CockroachDB can place replicas and leaseholders (the one replica of a range currently responsible for serving that range's reads and writes) to keep hot ranges local to where they're written most, but a write that must update an index range in another region still pays that region's round-trip time. This is the real lever for the "multi-region low-latency reads" trade-off: both systems let you trade strict, transactionally-fresh secondary-index reads for latency by reading with bounded/stale staleness (Spanner's stale reads, CockroachDB's AS OF SYSTEM TIME / follower reads) from a nearby replica instead of the current leaseholder. That gets you a fast local read of a secondary index at the cost of it possibly being a few hundred milliseconds to a few seconds out of date, an explicit eventual-consistency trade you opt into per query rather than a property of the index itself.
Trade-offs and pitfalls
- Minimize the number of secondary indexes on any table with a high write rate; each one is a proportional tax on every write to a covered column, not a one-time cost.
- Prefer covering (
STORING) indexes for read-heavy queries specifically to avoid the extra primary-key fetch, but remember every stored column also has to be kept in sync on every write, so storing everything defeats the purpose. - Use locality (Spanner interleaving, CockroachDB replica/leaseholder placement) to keep an index's writes local to where its base rows are written, before reaching for staleness as the fix.
- For extremely high write throughput where even synchronous, well-placed index maintenance is too expensive, the honest answer is often "don't index it in the primary OLTP store": stream changes out (CDC, a change feed) to an external, independently-scaled search or analytics system instead, and accept that its results are eventually consistent by design rather than accidentally so.
Unlock Full Question Bank
Get access to all Indexing Strategy and Design interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.