Data Engineering/Database Engineering · Part 11 of 14
·16 min read
Database Engines and Cursors: MyISAM, InnoDB, LSM Trees and Reading Results in Pieces
What a storage engine is, how MyISAM and InnoDB really differ, why LSM trees write so fast, and when a cursor beats fetching everything, with real MySQL, SQLite and LevelDB, a working LSM tree, and a server crashed on purpose.
So far "the database" has meant one thing. Underneath, there's a layer that does the plain work of putting bytes on disk and finding them again, and in some databases you can swap it. That layer is the storage engine.
This post covers the course's tour of engines, then its section on cursors. I ran the claims I could: the same transaction on two MySQL engines, a server crashed during writes, a real single-writer SQLite, and real LevelDB, where deleting everything made the files bigger.
#What a storage engine is
A database server does a lot: it accepts connections, parses SQL, plans queries and replicates. Underneath all that is a library that stores rows and gets them back. Separating the two means one server can offer several engines, and one engine can be reused by many servers.
MySQL is the classic example. Here are the engines in a stock mysql:8.4:
SELECT engine, support, transactions FROM information_schema.engines WHERE support <> 'NO' ORDER BY engine;
+--------------------+---------+--------------+
| engine | support | transactions |
+--------------------+---------+--------------+
| ARCHIVE | YES | NO |
| BLACKHOLE | YES | NO |
| CSV | YES | NO |
| InnoDB | DEFAULT | YES |
| MEMORY | YES | NO |
| MRG_MYISAM | YES | NO |
| MyISAM | YES | NO |
| PERFORMANCE_SCHEMA | YES | NO |
+--------------------+---------+--------------+
8 rows in set (0.01 sec)
Only one of them supports transactions, and that's the default.
SELECT amname, CASE amtype WHEN 't' THEN 'table' ELSE 'index' END AS kind FROM pg_am ORDER BY amtype DESC, amname;
amname | kind
--------+-------
heap | table
brin | index
btree | index
gin | index
gist | index
hash | index
spgist | index
(7 rows)
#MyISAM and InnoDB
These are the two engines the course compares, and the difference is the whole of post 1 and post 2 in one table.
| MyISAM | InnoDB | |
|---|---|---|
| Transactions | None | Full ACID |
| Locks | Table | Row |
| Index points to | A byte offset in the data file | The primary key |
| Primary key | Optional | Always, hidden if you don't define one |
| Foreign keys | No | Yes |
| After a crash | The table may need repair | Automatic recovery |
The course's demo inserts a row inside a transaction on each engine, and looks from a second connection:
START TRANSACTIONOn MyISAM, START TRANSACTION and ROLLBACK both returned OK and did nothing at all. That's the dangerous part: nothing warns you.
Locks show the other big difference. Here a long read holds up a write to a different row entirely:
LOCK TABLES t READInnoDB always has a clustered key, as the course says. If you don't give it one, it invents one:
CREATE TABLE no_key (name varchar(20)) ENGINE = InnoDB;
Query OK, 0 rows affected (0.02 sec)
INSERT INTO no_key VALUES ('a');
Query OK, 1 row affected (0.01 sec)
SELECT i.name AS index_name, i.type FROM information_schema.innodb_indexes i JOIN information_schema.innodb_tables t USING (table_id) WHERE t.name LIKE '%/no_key';
+-----------------+------+
| index_name | type |
+-----------------+------+
| GEN_CLUST_INDEX | 1 |
+-----------------+------+
1 row in set (0.04 sec)
#Crashing both
The course says a crash can corrupt a MyISAM table. I inserted into a table on each engine from two clients and killed the server with SIGKILL:
-- two clients insert into a MyISAM table and an InnoDB table, then
$ docker kill -s KILL mysql
(restart)
CHECK TABLE m; -- MyISAM
test.m check warning: 1 client is using or hasn't closed the table properly
test.m check status: OK
CHECK TABLE i; -- InnoDB
test.i check status: OK
REPAIR TABLE m;
test.m repair status: OK
-- rows the InnoDB client saw committed, and rows that survived
committed: 8960
InnoDB table now: 8960
MyISAM table now: 9504
InnoDB's row count exactly matched what the client had seen committed, which is recovery doing its job. MyISAM's CHECK TABLE warned that the table hadn't been closed properly, and a repair was needed to clear that. In this run its data turned out fine, so I can't say I saw corruption. This was a process kill, where the operating system's cache survives, as post 1 explained. The point stands that InnoDB proves its state with a log, and MyISAM has no log to prove anything with.
#The engine family
The course's talk covers many engines, which fall into two families:
- Aria: MyISAM with crash safety, from MariaDB, used for its system tables.
- XtraDB: a fork of InnoDB, which MariaDB used by default until 10.2 switched back to InnoDB.
- Berkeley DB: a key-value library from 1994, now Oracle's, used by early Bitcoin Core.
- SQLite: a whole database in a library, from Richard Hipp, in 2000.
- LevelDB and RocksDB: LSM key-value stores. MyRocks plugs RocksDB into MySQL.
#SQLite: one writer at a time
The talk says SQLite uses table-level locks and can write in parallel. Neither matched what I found: it's a database-level write lock. This is the real library, opened twice:
-- connection A holds a write transaction
BEGIN IMMEDIATE; INSERT INTO t ...;
-- connection B tries to write a different row
ERROR: database is locked
-- connection B reads, in the default rollback-journal mode
{"n":1}
PRAGMA journal_mode = WAL;
-- A writes again, B reads
{"n":2}
-- and B tries to write
ERROR: database is locked
Connection B couldn't write, even to another row, because a writer holds the whole database. In WAL mode readers and a writer don't block each other, and the docs are explicit: there can still be only one writer at a time. That's fine for what SQLite is for, and it's why it's everywhere. (The talk also mentions Web SQL, which browsers have removed.)
#LSM trees
B-trees update pages in place. An insert may rewrite a whole page for one row, in a random place, and that's what the SSD discussion in post 2 was about. A log-structured merge tree never updates anything in place.
DataMetadata
- A write is appended to a log, and added to a sorted memtable in memory. That's all, so writes are fast.
- A full memtable is written out as an immutable, sorted file, an SSTable, at level 0.
- Compaction merges files down the levels, keeping only the newest version of each key.
- A read checks the memtable, then files from newest to oldest, which is why engines keep Bloom filters on them.
Here's a working one, with tiny limits so that you can see every step. Write some keys, delete one, compact, and crash it:
Watch three things. A delete adds a tombstone, so the entry count goes up. Write amplification climbs as compaction rewrites data. And a crash loses the memtable, and the log puts it back.
Now the real thing. LevelDB, with 200,000 writes, then 200,000 deletes:
-- 200,000 puts, about 120 bytes each
232800 writes per second
2.9 MB on disk, 99 table files, 1 log file
leveldb.stats
Compactions
Level Files Size(MB) Time(sec) Read(MB) Write(MB)
--------------------------------------------------
2 99 3 0 0 3
-- delete every key
0 keys left, and still 4.3 MB on disk, 128 table files, 1 log file
db.compactRange(first, last)
0.0 MB on disk, 0 table files, 1 log file
Three results stand out. 232,800 writes a second, on one thread. Deleting every key left zero keys, and more disk used than before, because deletes are new entries. And compactRange then reclaimed everything.
The trade-off is worth stating plainly. An LSM tree exchanges write cost now for read cost and background work later: a read may check several files, and compaction uses disk bandwidth. B-trees suit read-heavy work, and LSM trees suit write-heavy work. Cassandra, HBase, RocksDB and Bigtable are all in this family, the last being the design LevelDB came from.
#Cursors
Now a different problem. A query matches 2 million rows. Where do they go?
By default the driver fetches everything into client memory. A server-side cursor keeps the query open on the server, and hands out rows when asked. In SQL:
BEGIN;
DECLARE c CURSOR FOR SELECT id FROM grades WHERE g BETWEEN 90 AND 100;
FETCH 3 FROM c;
id
----
90
91
92
(3 rows)
FETCH 2 FROM c;
id
----
93
94
(2 rows)
CLOSE c;
COMMIT;
The course compares the two in Python. I did the same in Node:
-- client side: one query, every row comes back
SELECT id, g, name FROM grades;
2,000,000 rows in 1541.6 ms, about 365 MB of client memory
-- server side: a cursor, 50 rows at a time
DECLARE c CURSOR FOR SELECT id, g, name FROM grades;
1.1 ms
FETCH 50 FROM c;
1.2 ms
FETCH 50 FROM c;
0.7 ms
FETCH LAST FROM c; -- the server has to work through everything
36.9 ms
The first row of the cursor arrived in about 2 ms, against 1.5 seconds and 365 MB for everything. Note the last line: FETCH LAST took 37 ms, because the server has to work through all the rows to get there. Cursors don't make the total work smaller. They spread it out.
Try it. This box keeps its transaction open between runs, as a real client would:
#What a cursor costs
| Client-side | Server-side | |
|---|---|---|
| First row | After all the rows arrive | At once |
| Client memory | Holds everything | One batch |
| Server | Done, and free | Holds a transaction and state |
| Connection | Any, and it's stateless | Stuck to one server |
| Failure | Simple to retry | State is lost |
The cost is on the last row of that table's middle: an open cursor is an open transaction. It holds locks, and it keeps old row versions alive. Here it blocks a schema change for as long as a client takes to page through:
BEGINStateful connections also fight with pools and horizontal scaling. The course's own preference is client-side fetching with a LIMIT, or keyset pagination, and using a cursor only for jobs that really stream.
📘 The course also includes Microsoft's reference on SQL Server cursors, which offers four types:
| Type | What it sees | Cost |
|---|---|---|
STATIC | A copy made at open | Uses tempdb, sees no later changes |
KEYSET | Fixed rows and order, with current values | Keys stored in tempdb |
DYNAMIC | Every change as you scroll | The most expensive |
FAST_FORWARD | Forward-only, read-only | The cheapest |
#Things that can trip you up
- MyISAM accepts
BEGIN. Your code looks transactional and isn't. CheckSHOW TABLE STATUSon older schemas. SELECTfrom a MyISAM table can block writes. Locks are per table.- Assuming a default engine. It's per table in MySQL, and old dumps may specify MyISAM.
- SQLite with many writers. Expect
database is locked. Set a busy timeout, and keep write transactions short. - Deleting to free space on an LSM store. Space comes back only after compaction, and may rise first.
- Forgetting a cursor is in a transaction. Long-lived cursors hold back
VACUUM, and block DDL. - Cursors with connection pools. A cursor needs the same connection for its whole life.
#Reproduce this yourself
- ✅ Start MySQL:
docker run --name ms1 -d -e MYSQL_ROOT_PASSWORD=password mysql:8.4, then create a table withENGINE = MyISAMand another withENGINE = InnoDB, and follow the replay in two sessions. The course's Node version is in its repository. - ✅ For the crash, insert in a loop on both tables, run
docker kill -s KILL ms1, start it again, and useCHECK TABLE. - ✅ For SQLite I used Node's built-in
node:sqlitewith two connections to one file. Any twosqlite3shells work. - ✅ For LevelDB,
npm install classic-level, thenput,delandcompactRange, and watch the folder. - ✅ For cursors,
BEGIN; DECLARE c CURSOR FOR ...; FETCH 50 FROM c;. 🎓 The course's Python version uses a namedpsycopg2cursor.
#Glossary
| Term | Meaning |
|---|---|
| Storage engine | The layer that stores and fetches rows |
| Table access method | Postgres's interface for table storage |
| LSM tree | Writes go to a log and memtable, then sorted files that merge in the background |
| Memtable | The sorted in-memory part of an LSM tree |
| SSTable | An immutable sorted file |
| Compaction | Merging files, keeping the newest version of each key |
| Tombstone | An entry that marks a key as deleted |
| Write amplification | Physical writes exceeding the logical ones |
| Cursor | A handle for reading a result a piece at a time |
#Summary
A storage engine is the layer that actually stores rows, and MySQL's choice of engines makes the differences easy to see: MyISAM's speed comes from having no transactions, no row locks and no recovery, and InnoDB has all three. LSM trees take another path, trading in-place updates for appends, flushes and compaction, which gives very fast writes and moves the cost into the background. Cursors solve a different problem: a client that can't take everything at once. They give a fast first row and low memory, in exchange for a transaction held open on the server.
#Concepts at a glance
| Concept | In one line | Why it matters |
|---|---|---|
| Pluggable engine | MySQL picks one per table | The same SQL can behave differently |
| MyISAM | Offsets, table locks, no transactions | ROLLBACK silently does nothing |
| InnoDB | Clustered, row locks, recovery | The safe default |
| SQLite | One writer for the whole database | Simple, and limited by design |
| Memtable and log | The whole write path | Why LSM writes are fast |
| Tombstone | Deleting adds an entry | Space comes back at compaction |
| Compaction | Rewrites data in the background | The bill for fast writes |
| Server-side cursor | Rows on demand | Low memory, held transaction |
#Test yourself
A MyISAM table is used inside BEGIN ... ROLLBACK, and no error appears. What happened to the row?
It stayed. MyISAM has no transactions, so the insert took effect at once and was visible to other sessions, and ROLLBACK had nothing to undo. No warning appeared in this run.
In an LSM tree, why can deleting data make the files bigger?
A delete is a new entry, a tombstone, that hides older values. Those values and the tombstone all stay on disk until compaction merges them away. In real LevelDB the files grew from 2.9 MB to 4.3 MB before compaction reclaimed everything.
Why are LSM writes so fast, and what pays for it?
A write is a log append and a memtable insert, with no random page rewrites. It's paid for by reads that may check several files, and by compaction, which rewrites data in the background.
Connection B can't write to a SQLite database while connection A has a write transaction open, even for a different row. What does WAL mode change?
Readers no longer block on the writer, and the writer doesn't block readers. There's still only one writer at a time, so B's write fails with database is locked, as the run showed.
What's the main risk of a server-side cursor in a busy system?
It's an open transaction. It holds locks that can block DDL, keeps old row versions from being cleaned up, and ties the client to one connection, so it fits badly with pools and scaling out.
#Open questions and gaps
- I saw the MyISAM crash warning, not real corruption, since a process kill leaves the operating system cache intact.
- 🎓 Aria, XtraDB, Berkeley DB, RocksDB and MyRocks are described from the course, with history corrected against sources. I ran none of them.
- The cursor comparison used Node, and the course used Python and
psycopg2, so the numbers differ, and the 365 MB depends on the client. - 📘 The SQL Server cursor table is from Microsoft's documentation, summarised.
#Sources
- Hussein Nasser, Fundamentals of Database Engineering
- MySQL 8.4 docs: Alternative Storage Engines, The InnoDB Storage Engine
- PostgreSQL docs: Table Access Method Interface, DECLARE
- SQLite docs: Write-Ahead Logging
- LevelDB, and classic-level for Node
- Microsoft: DECLARE CURSOR
- Chrome for Developers: Deprecating and removing Web SQL