Build a Persistent Storage Layer for a Mini Database Engine
Data Structure DesignModel answerLast updated
Design and implement the last stage of a database engine: a catalog of databases, schemas, and tables plus durable row insert, read, update, and delete that survives restarts.
You are building the lowest layer of a small relational database. Upstream components have already parsed, validated, and optimized each statement. Your component receives a finished, valid operation and must carry it out against files on disk. Anything acknowledged as complete must still be there after the process is restarted.
Parsing, validation, and query optimization are out of scope.
Namespace
Objects live in three levels: a database holds schemas, and a schema holds tables. A table is defined by an ordered list of column names and column types.
Part 1: Catalog operations
Provide create_database, create_schema, and create_table(columns).
- Every created object must be persisted and visible after a restart.
- Return clear errors for state-dependent failures: creating something that already exists, or creating a child whose parent is missing.
- A crash in the middle of a create must never leave a half-created object behind.
Part 2: Row operations
Provide insert, select, update, and delete on a table.
- Every change must be persisted.
- Describe the row format, the file layout, and how a row is located for update and delete.
- State the time complexity of each operation and the memory it needs.
- Check values against the column types of the table.
What to settle first
Before writing code, agree on interface signatures and state your assumptions on questions like these:
- How do filters arrive: a predicate function, a column-equals-value condition, or a list of row ids picked by the optimizer?
- Which column types exist, and can values be NULL?
- Must a finished write survive a crash right away, or only a clean shutdown?
- Must a statement touching many rows be atomic?
- Is there a single writer or several concurrent sessions?
- Are indexes required, or may reads scan the whole table?
Explain your design, its crash behavior, and how a production-grade version would differ from your simple one.
Hints
Hint 1
Map the namespace onto the file system: one directory per database, one per schema, and a small metadata file per table holding its column definitions.
Hint 2
Make every change atomic by writing to a temporary file, calling fsync, and then renaming it over the target. For row changes, think about an append-only log where update and delete are just new records.
Hint 3
Give each row a stable, monotonically increasing row id so update and delete can name rows without relying on their position in the file. On restart, rebuild state by replaying the log, and ignore a torn record at the tail using a length prefix and checksum.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
- Single writer, multiple readers are not required; I serialize operations with a lock.
- Types:
INT,FLOAT,TEXT,BOOL, all nullable. - Filters arrive as a predicate (a callable) or a list of row ids. Reads may scan the table, with no indexes.
- Durability: once a call returns, the change survives a process or OS crash (fsync before returning).
- A multi-row statement should be atomic. I get this by writing it as one log batch.
Part 1: Catalog
Layout
data/
<db>/
<schema>/
<table>/
meta.json # column names and types, next_row_id
data.log # row records
A directory per level makes the three-level namespace explicit and makes existence checks trivial.
Atomic create. A crash must not leave a half-built object. Two safe patterns:
- Build the object in a temporary name (for example
.tmp-<uuid>), fsync its files, thenrenameit into place. Rename within one file system is atomic on POSIX. Then fsync the parent directory so the rename itself is durable. - For a single file such as
meta.json, writemeta.json.tmp, fsync, rename over the final name, fsync the directory.
On startup, delete any leftover .tmp-* entries.
Errors.
create_databasefails withAlreadyExistsif the directory exists.create_schemafails withNotFound(database)if the parent is missing, orAlreadyExists.create_tabledoes the same for the schema, and may also reject an empty column list or duplicate column names (cheap to check even though upstream validated).
Note the check-then-create race: with concurrent sessions, take a lock around the existence check and the rename, or rely on mkdir failing atomically.
Part 2: Rows
Row identity. Each row gets a row_id from a counter stored in table state. Ids are never reused, so update and delete refer to a row stably, regardless of its physical position.
Design A: append-only log (simple, recommended for the screen).
Each record is: [length][crc32][op][row_id][payload] where op is INSERT, UPDATE, or DELETE.
insert(values): type-check, assignrow_id, append an INSERT record, fsync, update the in-memory map.update(filter, new_values): find matching ids, append UPDATE records with the full new row, fsync.delete(filter): append DELETE tombstones, fsync.select(filter): scan the in-memory map (or the log) and return matching rows.
Restart. Replay the log from the start into a dict[row_id -> row]. INSERT and UPDATE set the entry, DELETE removes it. If the final record is truncated or its CRC fails, it was a torn write from a crash, so stop there and truncate the file to the last good record. Because the caller was never told that write succeeded, discarding it is correct.
Atomic multi-row statements. Write all records of one statement between a BEGIN and COMMIT marker (or as one batch with a single checksum) and fsync once. On replay, ignore batches with no commit.
Compaction. The log grows with every update and delete. When dead records exceed a threshold (say 50 percent), write a fresh log containing only live rows to a temp file, fsync, and rename it over the old one.
Complexity (n live rows, k matching rows).
| Operation | Time | Notes |
|---|---|---|
| insert | O(1) amortized | one append plus fsync |
| select | O(n) | full scan, no index |
| update | O(n + k) | scan to match, k appends |
| delete | O(n + k) | scan to match, k tombstones |
| startup | O(log size) | replay |
Memory is O(n) for the in-memory row map. If tables must exceed RAM, keep only an index row_id -> file offset and read payloads on demand.
Type checking. Compare each value against the column type before writing anything. Reject wrong arity and wrong types, allow NULL. Doing this before the append means a bad statement leaves no trace.
Design B: page-based (production style)
Fixed-size pages (for example 8 KB) with slotted-page layout; a row id is (page, slot). Updates happen in place when they fit. Durability comes from a write-ahead log: log the change, fsync the log, and flush dirty pages lazily, with checkpoints to bound recovery time. A buffer pool caches pages.
Trade-offs.
- The log design is far simpler and has fast sequential writes, but needs compaction and a full replay at startup, and memory holds all rows.
- The page design supports tables larger than memory, in-place updates, and indexes (B-trees), but needs a buffer pool, a WAL, and recovery logic.
Common mistakes
- Skipping
fsync, so "persisted" data sits in the OS cache and is lost on power failure. - Forgetting to fsync the directory after a rename or file creation.
- Using list position as row identity, which breaks after deletes.
- Writing the file in place without a temp-and-rename, which leaves corrupted state after a crash.
- Not handling a torn final record on replay.
- Type-checking after partially applying a multi-row change.
Sketch
class Table:
def insert(self, values):
self._check_types(values)
with self.lock:
rid = self.next_id; self.next_id += 1
self._append([("INS", rid, values)])
self.rows[rid] = values
return rid
def delete(self, pred):
with self.lock:
ids = [r for r, v in self.rows.items() if pred(v)]
self._append([("DEL", r, None) for r in ids]) # one batch, one fsync
for r in ids: del self.rows[r]
return len(ids)
_append serializes the batch with a commit marker and checksum, writes it, and calls os.fsync.
Follow-ups to be ready for
- Adding a hash or B-tree index on a column and keeping it consistent with the log.
- Supporting concurrent writers (locking granularity, MVCC).
- Schema changes (
ALTER TABLE) and how old records are interpreted. - Group commit to amortize fsync cost across many writers.