Introduction to storage
easy 24 minHow a database keeps data: pages on disk, a buffer pool of pages in memory, indexes that find the right page, and a write-ahead log that makes a commit survive a crash.
See it run
What a storage engine does with pages, memory and a log when you read, write, crash and search.
Operations
Read through the buffer pool
A page is served from memory when it is there, and loaded from disk when it is not.
Step 1 of 4
Start
In memory
empty
Log since checkpoint
empty
Four empty frames
The pool is empty. Pages 1 to 8 are on disk.
Step 1: Start
def get_page(pool, page_id): if page_id in pool: pool.move_to_end(page_id) # hit return pool[page_id] make_room(pool) # miss pool[page_id] = read_from_disk(page_id) return pool[page_id]- Cost
- 100 ns or 100 µs
- Survives a crash
- Not needed
- Random hard disk read
- about 10 ms
Say hit and miss costs side by side. The hit rate decides the average.
In the real world
The same introduction to storage doing real jobs. Pick one and step through it.
A shop opens. The same four pages serve almost every request.
Step 1 of 4
Cold start
In memory
P2
Log since checkpoint
empty
Slow at first
The server restarted during the night. Every first read is a miss.
Step 1: Cold start
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Confirming before the flush
criticalA power cut then loses a change the client believes is safe.
Wronglog.append(record)reply("committed")log.flush()Rightlog.append(record)log.flush()reply("committed")Writing the page before its log record
criticalAfter a crash the page holds a change that nothing explains, so it cannot be undone.
Wrongwrite_to_disk(page)log.flush()Rightlog.flush()write_to_disk(page)Evicting a dirty page without writing it
criticalThe newest version existed only in memory, and the next reader loads a stale page from disk.
Wrongdel pool[victim]Rightif victim in dirty: log.flush() write_to_disk(victim)del pool[victim]An index on every column
minorEach insert must update each index, and unused indexes take memory from useful pages.
Wrongfor col in table.columns: create_index(col)Rightfor col in columns_in_hot_queries: create_index(col)
Interview tips
How to explain it
- Pages are the unit, the pool is the cache, the log is the promise.
- Say what is in memory and what is on disk at each step.
Memory trick
- Hotel lobby: popular guests stay, the rest check out.
- Diary before action: log first.
Numbers to say
- 100 ns, 100 µs, 10 ms.
- Pages of 4 to 16 KB.
- 99% hits still means 1% of the reads pay 1,000 times more.
Watch out
- Write calls without a flush.
- Scans that empty the cache.
- Recovery time nobody has measured.