AlgoViz

MySQL

medium 32 min

MySQL 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 indexits keypage shelfthe row
1Bees1010Bees, 8 pages
2Cats3020Dogs, 5 pages
3Dogs2030Cats, 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

sourcereplicarestore server
orders1,0001,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

    major

    Every secondary index copies it, and inserts land all over the tree.

    Wrong
    id CHAR(36) PRIMARY KEY-- random UUID as text
    Right
    id BIGINT UNSIGNED AUTO_INCREMENT   PRIMARY KEY
  • Read, compute, write

    critical

    The plain SELECT may be old. Two buyers get the last ticket.

    Wrong
    n = select("stock")update("stock", n - 1)
    Right
    UPDATE items SET stock = stock - 1WHERE id = 7 AND stock > 0
  • Replica as a backup

    critical

    It repeats the mistake within moments.

    Wrong
    backups = [replica]
    Right
    backups = [nightly_full, archived_binlogs]test_restore(weekly=True)
  • Wrong type in a comparison

    major

    A text column compared with a number is converted row by row, so the index is not used.

    Wrong
    WHERE phone = 5550100
    Right
    WHERE 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.