Vineet Ganti
Database Engines and Cursors: MyISAM, InnoDB, LSM Trees and Reading Results in Pieces
All posts

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.

DatabasesMySQLPostgreSQLLSM TreesStorage Engines

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:

✅ ran here · MySQL 8.4.13
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.

✅ ran here · PostgreSQL 18.6
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.

MyISAMInnoDB
TransactionsNoneFull ACID
LocksTableRow
Index points toA byte offset in the data fileThe primary key
Primary keyOptionalAlways, hidden if you don't define one
Foreign keysNoYes
After a crashThe table may need repairAutomatic recovery

The course's demo inserts a row inside a transaction on each engine, and looks from a second connection:

The same transaction on two engines✅ recorded on MySQL 8.4.13
1 · Session A
START TRANSACTION
OK, 0 rows affected
The engine is InnoDB.
Step 1 of 6

On 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:

A MyISAM read holds up a write to any row✅ recorded on MySQL 8.4.13
1 · Session A
LOCK TABLES t READ
OK, 0 rows affected
A long report on a MyISAM table holds a table-level read lock. This statement makes that lock last long enough to see.
Step 1 of 3

InnoDB always has a clustered key, as the course says. If you don't give it one, it invents one:

✅ ran here · MySQL 8.4.13
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:

✅ ran here · MySQL 8.4.13 · kill -9 during writes
-- 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:

✅ ran here · SQLite 3.53.4
-- 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

  1. A write is appended to a log, and added to a sorted memtable in memory. That's all, so writes are fast.
  2. A full memtable is written out as an immutable, sorted file, an SSTable, at level 0.
  3. Compaction merges files down the levels, keeping only the newest version of each key.
  4. 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:

Memtable (RAM, sorted)
empty
Write-ahead log (disk, append only)
empty
Level 0 (newest first, files can overlap)
no files
Level 1 (one sorted run)
no files
Level 2 (one sorted run)
no files
Write some keys. A full memtable becomes a sorted file, and files merge down the levels.
entries stored 0 for 0 live keysfiles 0write amplification 0.0×compactions 0

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:

✅ ran here · LevelDB, through classic-level · real LevelDB
-- 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:

✅ ran here · PostgreSQL 18.6
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:

✅ ran here · PostgreSQL 18.6 · the same 2,000,000 rows, two ways
-- 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:

A server-side cursorruns in your browser
This box keeps its transaction open between runs, like a real client would. Run the presets in order. The status line says when a transaction is still open.
Real PostgreSQL loads when you press Run: about 6 MB, once per visit.

#What a cursor costs

Client-sideServer-side
First rowAfter all the rows arriveAt once
Client memoryHolds everythingOne batch
ServerDone, and freeHolds a transaction and state
ConnectionAny, and it's statelessStuck to one server
FailureSimple to retryState 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:

An open cursor is a held-open transaction✅ recorded on PostgreSQL 18.6
1 · Session A
BEGIN
BEGIN
A cursor lives inside a transaction.
Step 1 of 6

Stateful 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:

TypeWhat it seesCost
STATICA copy made at openUses tempdb, sees no later changes
KEYSETFixed rows and order, with current valuesKeys stored in tempdb
DYNAMICEvery change as you scrollThe most expensive
FAST_FORWARDForward-only, read-onlyThe cheapest

#Things that can trip you up

  • MyISAM accepts BEGIN. Your code looks transactional and isn't. Check SHOW TABLE STATUS on older schemas.
  • SELECT from 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

  1. ✅ Start MySQL: docker run --name ms1 -d -e MYSQL_ROOT_PASSWORD=password mysql:8.4, then create a table with ENGINE = MyISAM and another with ENGINE = InnoDB, and follow the replay in two sessions. The course's Node version is in its repository.
  2. ✅ For the crash, insert in a loop on both tables, run docker kill -s KILL ms1, start it again, and use CHECK TABLE.
  3. ✅ For SQLite I used Node's built-in node:sqlite with two connections to one file. Any two sqlite3 shells work.
  4. ✅ For LevelDB, npm install classic-level, then put, del and compactRange, and watch the folder.
  5. ✅ For cursors, BEGIN; DECLARE c CURSOR FOR ...; FETCH 50 FROM c;. 🎓 The course's Python version uses a named psycopg2 cursor.

#Glossary

TermMeaning
Storage engineThe layer that stores and fetches rows
Table access methodPostgres's interface for table storage
LSM treeWrites go to a log and memtable, then sorted files that merge in the background
MemtableThe sorted in-memory part of an LSM tree
SSTableAn immutable sorted file
CompactionMerging files, keeping the newest version of each key
TombstoneAn entry that marks a key as deleted
Write amplificationPhysical writes exceeding the logical ones
CursorA 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

ConceptIn one lineWhy it matters
Pluggable engineMySQL picks one per tableThe same SQL can behave differently
MyISAMOffsets, table locks, no transactionsROLLBACK silently does nothing
InnoDBClustered, row locks, recoveryThe safe default
SQLiteOne writer for the whole databaseSimple, and limited by design
Memtable and logThe whole write pathWhy LSM writes are fast
TombstoneDeleting adds an entrySpace comes back at compaction
CompactionRewrites data in the backgroundThe bill for fast writes
Server-side cursorRows on demandLow 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