KatInterview

Append-Only Log Storage Engine with Torn-Write Recovery

Data Structure DesignModel answer
HardModel answerData Structure Designstorage-engineappend-only-logcrash-recovery

Last updated

Build an embedded byte-oriented key-value store on a checksummed append-only log, with an in-memory index, delete markers, thread safety and recovery that truncates a damaged tail.

Build LogKV, a small embedded key-value store for arbitrary bytes keys and values. All data goes into a single append-only file. An in-memory dictionary lets you find any live key quickly. After a crash, a power cut, or a half-written record, reopening the store must bring it back to the last intact record.

On-disk record layout

Every record is a 13-byte big-endian header followed by a payload.

FieldSizeMeaning
crc324 bytes, unsignedChecksum of flags + key_len + val_len + key + value
flags1 byte0x01 = PUT, 0x02 = TOMBSTONE (delete marker)
key_len4 bytes, unsignedKey length in bytes
val_len4 bytes, unsignedValue length in bytes (0 for tombstones)

The payload is the key bytes followed immediately by the value bytes.

Interface

class LogKV:
    def __init__(self, filepath: str): ...   # opens/creates the file, runs recovery
    def put(self, key: bytes, value: bytes) -> None: ...
    def get(self, key: bytes) -> bytes | None: ...
    def delete(self, key: bytes) -> bool: ...
    def recover(self) -> None: ...
    def close(self) -> None: ...
  • put: append a PUT record, force it to disk, then update the index.
  • get: return the newest value for the key, or None if it is absent or deleted.
  • delete: append a TOMBSTONE, force it to disk, drop the key from the index. Return True if the key was present, otherwise False.
  • recover: scan from offset 0, validate each record, truncate the file at the first invalid record, and rebuild the index by replaying valid records in order.
  • Safe for concurrent readers and writers.

Example

s = LogKV("data.db")
s.put(b"user:101", b"Alice")
s.put(b"user:102", b"Bob")
assert s.get(b"user:101") == b"Alice"
s.delete(b"user:101")
assert s.get(b"user:101") is None
s.close()

s2 = LogKV("data.db")            # reopen, replay the log
assert s2.get(b"user:101") is None
assert s2.get(b"user:102") == b"Bob"

Constraints and edge cases

  • 1 <= len(key) <= 65,536; 0 <= len(value) <= 10,485,760.
  • Recovery must cope with a partial header, a complete header with a short payload, and a checksum mismatch. At the first bad record, cut the file at that record's start and discard everything after it.
  • An empty or brand-new file must work.
  • Deleting a key that does not exist returns False and must not append a tombstone.

Explain your design, justify the ordering of disk and memory updates, and give working code with complexity.

Hints

Hint 1

Keep only a pointer in memory: for each key store the file offset and length of its value, so memory scales with the number of keys rather than the data size.

Hint 2

Order matters: append the record, fsync, and only then change the index. Think about what a reader could observe if the index changed first and the process crashed.

Hint 3

In recovery, validate cheaply before you allocate or read: check the flag, the key and value length bounds, and that the record fits within the file size, and only then compare the CRC. Stop at the first failure and truncate there.

Hint 4

For concurrency, a single lock serializes appends and index updates. Reads can use positional reads (pread) outside the lock, because bytes below the current end of the log never change.