System designLoading progress…

Write and storage costs

Explain how indexes change work and how transactions protect application invariants under concurrency.

Write and storage costs

Every index is extra data that must be kept up to date. 10,000,000 rows with a 24-byte entry means 240 MB per index, 960 MB for four. Each insert writes the table row and one entry per index, so 1,000 inserts a second with four indexes is 5,000 writes a second. Reads get cheaper, ingestion gets slower: add an index only when the reads it speeds up outweigh the writes it slows.

secondary indexes4inserts per second1000reads per second that use the next index500
storage: 10,000,000 rows × 24 B × 4 = 960,000,000 bytes writes per insert: 1 + 4 = 5 → 5,000 writes/s at 1,000 inserts/s one more index: saves 1,000 ms/s of reading (2 ms each) and costs 500 ms/s of extra writes (0.5 ms each) → worth it

An index is a second copy of part of the data that must be kept in step on every write. It makes some reads cheaper and every write dearer.

Change the number of indexes and the workload.

Predict first. Is an extra index free when the application mostly writes?

Chapter context

Databases execute concurrent requests against shared state. Fast lookup and correct updates are separate concerns: an index can improve a query while the application still loses updates or violates a cross-row rule.

Chapter reference: math, worked example & code

This section belongs to the whole chapter, so it is the same on every lesson in it and may cover a different lesson's topic. The code for the experiment you just ran is inside the experiment itself.

Math and notation

For an idealized search tree with effective fanout f and N distinguishable leaves, log base f of N gives a rough depth scale. Actual pages, occupancy and row-pointer costs differ. For an optimistic update, change value and version only when the stored version equals the version read by the caller.

Worked example

Two callers read count=10 at version 1 and each intends to increment. Unconditional writes of 11 lose one increment. With an atomic expected-version check, the first writes 11/version 2; the second stale attempt is rejected. After rereading, it can write 12/version 3. The model below demonstrates the condition, not database transaction implementation.

Reference code

The following example uses the Python standard library and does not call a remote service.

state={'count':10,'version':1}
def update(expected):
    if state['version'] != expected: return False
    state['count']+=1
    state['version']+=1
    return True
assert update(1)
assert not update(1)
assert update(2)
assert state == {'count':12,'version':3}

Python examples are provided for study and local execution; this page does not execute Python.

Common mistakes

A transaction's isolation level matters. A unique application-side check is race-prone without a database-enforced invariant. Index depth estimates are not actual query-latency measurements.