MySQL
medium 32 minMySQL is an open-source relational database whose InnoDB engine keeps each table's rows inside its primary key index.
See it run
The primary key tree, the three logs, replicas and range locks, one step at a time.
Operations
Find a row
One table, one title index. Count the walks.
Step 1 of 5
The table is an index
| title index | its key | page shelf | the row | |
|---|---|---|---|---|
| 1 | Bees | 10 | 10 | Bees, 8 pages |
| 2 | Cats | 30 | 20 | Dogs, 5 pages |
| 3 | Dogs | 20 | 30 | Cats, 9 pages |
Clustered by key
Rows are kept in primary key order: 10, 20, 30. The title index holds titles and keys.
Step 1: The table is an index
def by_key(key): return clustered.walk(key) # the leaf holds the rowdef by_title(title, columns): key = title_index.walk(title) if columns <= {"title", "id"}: # covering return title, key return clustered.walk(key) # second walk- Cost
- 1 or 2 walks
- You get
- Rows by key
Say "covering index" when every needed column is in it.
In the real world
The same mysql doing real jobs. Pick one and step through it.
Replicas copy mistakes. A backup and the binary log do not.
Step 1 of 6
Sunday
| source | replica | restore server | |
|---|---|---|---|
| orders | 1,000 | 1,000 | - |
Backup taken
A full backup of 1,000 orders is stored.
Step 1: Sunday
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A random text key
majorEvery secondary index copies it, and inserts land all over the tree.
Wrongid CHAR(36) PRIMARY KEY-- random UUID as textRightid BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEYRead, compute, write
criticalThe plain SELECT may be old. Two buyers get the last ticket.
Wrongn = select("stock")update("stock", n - 1)RightUPDATE items SET stock = stock - 1WHERE id = 7 AND stock > 0Replica as a backup
criticalIt repeats the mistake within moments.
Wrongbackups = [replica]Rightbackups = [nightly_full, archived_binlogs]test_restore(weekly=True)Wrong type in a comparison
majorA text column compared with a number is converted row by row, so the index is not used.
WrongWHERE phone = 5550100RightWHERE phone = '5550100'
Interview tips
How to explain it
- The table is the primary key tree.
- Undo, redo, binary log.
- Copies follow the binary log.
Choose the key
- Short, growing, never changed.
- Compound when reads are per tenant.
- Covering indexes for hot queries.
Say what can be lost
- Asynchronous: the last commits.
- Semi-sync: nothing, until it falls back.
- Group: agreed by a majority.
Do not
- Write to both ends of plain replication.
- Shard before indexes and cache.
- Trust settings written for older versions.