KatInterview

Build a Persistent Storage Layer for a Mini Database Engine

Data Structure DesignModel answer
MediumModel answerData Structure Designstorage-enginepersistencecrash-safety

Last 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.