Append-Only Log Storage Engine with Torn-Write Recovery
Data Structure DesignModel answerLast 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.
| Field | Size | Meaning |
|---|---|---|
crc32 | 4 bytes, unsigned | Checksum of flags + key_len + val_len + key + value |
flags | 1 byte | 0x01 = PUT, 0x02 = TOMBSTONE (delete marker) |
key_len | 4 bytes, unsigned | Key length in bytes |
val_len | 4 bytes, unsigned | Value 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, orNoneif it is absent or deleted.delete: append a TOMBSTONE, force it to disk, drop the key from the index. ReturnTrueif the key was present, otherwiseFalse.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
Falseand 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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a Bitcask-style engine: one append-only log plus an in-memory hash index.
- Index:
key -> (value_offset, value_len). Memory grows with the number of live keys, not with the volume of stored data. - Write path (
put/delete): build the framed record, take the lock, write it at the current end of the log,fsync, then update the index and the end offset. Appends are strictly serialized, so the file is always a sequence of whole records followed by at most one damaged tail. - Read path (
get): look up the entry under the lock, release it, and read the value withos.pread.preadtakes an explicit offset and does not touch a shared file cursor, and bytes below the end of the log are never rewritten, so concurrent readers do not need the lock for the disk read. - Recovery: walk the file from offset 0. For each record, check the header, the bounds, and the CRC. Stop at the first failure, truncate to that offset,
fsync, and use the replayed index. PUT sets an entry, TOMBSTONE removes it, and the last record for a key wins.
Why it is correct
- Durability ordering. The index changes only after
fsyncsucceeds. A reader therefore never sees a value that a crash could erase, and any acknowledged write is a complete record on disk. - Prefix property. Because appends are serialized, a crash can corrupt only the end of the file. Cutting at the first invalid record keeps everything fully written before it and discards the damage, giving the "last clean state".
- Every torn-write shape is covered. A short header (fewer than 13 bytes left), a payload that runs past the end of the file, and a CRC mismatch all stop the scan. Header sanity checks (valid flag, key length in 1..65,536, value length at most 10 MB, tombstone value length 0) run before any read or allocation, so a flipped bit cannot make recovery try to read gigabytes.
- Failed appends. If
pwriteorfsyncraises, truncate back to the old end. Otherwise later records would land after garbage and be lost on the next recovery. - Atomic delete. The membership test and the tombstone append are under the same lock, so two concurrent deletes of one key cannot both return
True, and a missing key writes nothing.
Code
import os, struct, threading, zlib
_HDR = struct.Struct(">IBII") # crc, flags, key_len, val_len = 13 bytes
_HDR_LEN = _HDR.size
_PUT, _DEL = 0x01, 0x02
_MAX_KEY = 65_536
_MAX_VAL = 10 * 1024 * 1024
def _frame(flag: int, key: bytes, value: bytes) -> bytes:
body = _HDR.pack(0, flag, len(key), len(value))[4:] + key + value
return struct.pack(">I", zlib.crc32(body)) + body
class LogKV:
def __init__(self, filepath: str):
self._lock = threading.Lock()
self._fd = os.open(filepath, os.O_RDWR | os.O_CREAT, 0o644)
self._index: dict[bytes, tuple[int, int]] = {}
self._end = 0
self._closed = False
self.recover()
def _pread_full(self, n: int, off: int) -> bytes:
parts = []
while n > 0:
b = os.pread(self._fd, n, off)
if not b:
break
parts.append(b)
n -= len(b)
off += len(b)
return b"".join(parts)
def _append(self, rec: bytes) -> int: # caller holds the lock
start = self._end
try:
view, off = memoryview(rec), start
while view:
n = os.pwrite(self._fd, view, off)
view, off = view[n:], off + n
os.fsync(self._fd)
except BaseException:
os.ftruncate(self._fd, start)
raise
self._end = start + len(rec)
return start
def put(self, key: bytes, value: bytes) -> None:
if not (1 <= len(key) <= _MAX_KEY) or len(value) > _MAX_VAL:
raise ValueError("key or value size out of range")
rec = _frame(_PUT, key, value)
with self._lock:
if self._closed:
raise ValueError("store is closed")
start = self._append(rec)
self._index[key] = (start + _HDR_LEN + len(key), len(value))
def get(self, key: bytes) -> bytes | None:
with self._lock:
if self._closed:
raise ValueError("store is closed")
entry = self._index.get(key)
if entry is None:
return None
off, n = entry
return self._pread_full(n, off) if n else b""
def delete(self, key: bytes) -> bool:
with self._lock:
if self._closed:
raise ValueError("store is closed")
if key not in self._index:
return False
self._append(_frame(_DEL, key, b""))
del self._index[key]
return True
def recover(self) -> None:
with self._lock:
size = os.fstat(self._fd).st_size
index: dict[bytes, tuple[int, int]] = {}
pos = 0
while pos < size:
hdr = self._pread_full(_HDR_LEN, pos)
if len(hdr) < _HDR_LEN:
break
crc, flag, klen, vlen = _HDR.unpack(hdr)
if flag not in (_PUT, _DEL):
break
if not (1 <= klen <= _MAX_KEY) or vlen > _MAX_VAL:
break
if flag == _DEL and vlen != 0:
break
end = pos + _HDR_LEN + klen + vlen
if end > size:
break
payload = self._pread_full(klen + vlen, pos + _HDR_LEN)
if len(payload) != klen + vlen:
break
if zlib.crc32(hdr[4:] + payload) != crc:
break
key = payload[:klen]
if flag == _PUT:
index[key] = (pos + _HDR_LEN + klen, vlen)
else:
index.pop(key, None)
pos = end
if pos < size:
os.ftruncate(self._fd, pos)
os.fsync(self._fd)
self._index, self._end = index, pos
def close(self) -> None:
with self._lock:
if not self._closed:
os.fsync(self._fd)
os.close(self._fd)
self._closed = True
Complexity
put/delete: O(k + v) to encode and write, plus onefsync, which dominates latency (typically from hundreds of microseconds to several milliseconds).get: O(1) average for the lookup plus O(v) to read the value.recover: O(file size), one sequential pass.- Memory: O(live keys x average key size).
Edge cases and trade-offs
- Empty file: the loop never runs, the index is empty and the end offset is 0.
- Empty value: valid;
getreturnsb"", which is distinct fromNone. - Re-putting a deleted key: the later PUT wins on replay.
- Short reads and writes: handled with loops rather than assuming one call transfers everything.
- Directory durability: after creating a new file, fsync the parent directory too, or the file's name can vanish after a crash.
- Throughput: one
fsyncper write is safe but slow. Group commit (batch several writers into one fsync) or a configurable sync policy trades a small durability window for much higher throughput. - Unbounded growth: the log never shrinks, since overwritten and deleted records stay on disk. A real engine adds compaction, which rewrites live records into a new file and atomically renames it. It also needs segment files so compaction does not block writes.
Common mistakes
- Updating the index before the
fsync. - Computing the CRC over the wrong byte range, for example including the CRC field itself.
- Trusting
key_lenorval_lenbefore bounds checks, which allows huge allocations on corrupt data. - Skipping a bad record and continuing the scan instead of truncating. Later bytes may be misaligned garbage that happens to look valid.
- Using a shared file cursor with
seekandreadacross threads, which races. - Writing a tombstone for a key that does not exist.