Design a Self-Describing Columnar File Format for Time-Series Data
System DesignModel answerLast updated
Design the binary layout, writer/reader interfaces, and operational invariants for an append-friendly columnar file format suited to high-throughput time-series workloads.
Context
A quantitative research platform stores billions of sensor or market events per day. Each event is a row in a wide table — potentially 20–40 typed columns — but most queries touch only two or three of them (e.g., event_time and a single measurement field). Row-oriented formats like CSV or newline-delimited JSON force the reader to deserialize every field just to extract the ones it needs, wasting I/O bandwidth at scale.
Your task is to design a compact, self-describing, append-friendly columnar file format — a simplified version of something like Apache Parquet — along with clean read and write interfaces.
What you need to define
1. Binary layout specification
Define the exact on-disk structure, including:
- File header (magic bytes, version, flags)
- How rows are partitioned into row groups (horizontal slices of, say, 64 K–1 M rows)
- How each row group stores per-column column chunks made up of one or more data pages (and optionally a dictionary page)
- The fixed-size page header fields (value counts, null counts, encoding, codec, lengths, checksum)
- A self-describing footer written at the end of the file that contains the schema, per-chunk offset/length/statistics, and any user metadata
- A fixed-size tail (footer length + CRC + magic) so a reader can locate the footer with two seeks
2. Writer and reader class interfaces
Write Python or C++ pseudo-code for:
ColumnarFileWriter— buffers column data in memory, flushes complete row groups to the sink, and writes the footer onclose()ColumnarFileReader— reads and validates the footer, exposes column projection (reading only requested columns) and row-group pruning via per-chunk min/max statistics
3. Invariants and edge cases
Address:
- How partial writes and file truncation are detected and rejected
- All-null columns (missing min/max statistics, predicate behaviour)
- Variable row-group sizes (the last group is almost always smaller)
- CRC validation at both the page and footer level
4. Testing strategy
Describe how you would verify:
- Round-trip correctness for all supported types and encodings
- That projection genuinely avoids touching un-requested column data
- Encoding regressions (e.g., delta encoding producing wrong values after a codec change)
- Corruption detection at the page and footer level
Constraints and assumptions
- Supported types for this exercise:
INT32,INT64,FLOAT64; all fields may be nullable - Integer byte order: little-endian throughout
- Files are write-once / read-many; no in-place updates
- The writer must stream in a single forward pass — no seeking back to patch the header
- Compression is pluggable: at minimum
RAW,LZ4, and a delta + bit-packing scheme for monotonic integer columns (e.g., nanosecond timestamps)
Expected output
A structured written answer covering all four areas above. Include concrete byte-level field tables where they clarify the layout, and commented pseudo-code for the interfaces. Call out trade-offs explicitly — do not just describe one option.
Hints
Hint 1
Start from the reader's perspective: what is the minimum information a reader needs to locate one column chunk inside one row group using a single contiguous read? Work backwards to determine what the footer must contain and where it must live on disk.
Hint 2
A streaming writer cannot seek back to patch a header once rows have been written. This is why the footer goes at the very end. Think about how a fixed-size tail (footer_len + CRC + magic) lets the reader find the footer with exactly two seeks regardless of file size.
Hint 3
Delta encoding works well for monotonically increasing timestamps because consecutive differences are small and can be bit-packed into far fewer bits than the raw 8-byte values. Consider what structural invariant (monotonicity) must hold for this to be safe, and how you would signal encoding choice per column chunk in the metadata.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
What a strong answer covers
This is a systems-fundamentals question. The interviewer wants to see four concrete things: a precise byte layout, a writer that streams in one forward pass, a reader that turns projection and pruning into a small number of contiguous reads, and explicit invariants that make corruption detectable. Generalities are not enough — pin down the exact fields.
Scale and workload assumptions
- Roughly 1–10 TB of events per day; a typical query touches 2–5 of ~30 columns.
- Row groups of 64 K–1 M rows. A single
INT64column chunk of 1 M rows is 8 MB uncompressed; after delta + bit-packing on timestamps this commonly shrinks 4–8×. - Files are immutable after
close(). There are no concurrent writers. - All multi-byte integers are little-endian.
Binary layout
┌──────────────────────────────────────────────────────────┐
│ HEADER 16 B │
│ magic[4] = "CLMN" | version u16 | flags u16 | │
│ reserved[8] │
├──────────────────────────────────────────────────────────┤
│ ROW GROUP 0 │
│ COLUMN CHUNK for field 0 │
│ [DICT PAGE]? [DATA PAGE]+ │
│ COLUMN CHUNK for field 1 ... │
│ ... │
├──────────────────────────────────────────────────────────┤
│ ROW GROUP 1 ... │
├──────────────────────────────────────────────────────────┤
│ FOOTER METADATA (variable length, TLV / protobuf-style) │
├──────────────────────────────────────────────────────────┤
│ TAIL 12 B │
│ footer_len u32 | footer_crc32 u32 | magic[4] │
└──────────────────────────────────────────────────────────┘
Page header — 24 bytes, fixed
| Offset | Field | Type | Notes |
|---|---|---|---|
| 0 | page_type | u8 | 0 = DATA, 1 = DICT |
| 1 | encoding | u8 | 0 = PLAIN, 1 = DICT_RLE, 2 = DELTA_BITPACK |
| 2 | codec | u8 | 0 = RAW, 1 = LZ4, 2 = SNAPPY |
| 3 | reserved | u8 | |
| 4 | num_values | u32 | slots, including nulls |
| 8 | null_count | u32 | |
| 12 | uncompressed_len | u32 | |
| 16 | compressed_len | u32 | |
| 20 | crc32 | u32 | over the compressed body |
The page body (compressed as a unit) contains:
- Validity bitmap — RLE/bit-packed; omitted entirely when
null_count == 0. - Values — only the non-null values, densely packed. This avoids storing sentinel values for nulls and keeps the compressed block smaller.
Footer contents
- Schema: list of
(field_id u16, name, type, nullable). - Row groups: for each group,
num_rowsand a list of chunk records:field_id,file_offset,compressed_len,uncompressed_lennum_pages,null_countmin,max(absent when the chunk is entirely null)encodingsbitmask
- User metadata: arbitrary key-value strings.
Because each chunk record carries its file offset and length, the reader can fetch any column chunk with exactly one pread — the central property that makes projection cheap.
Why the footer is at the end
The writer streams row groups forward without knowing total file size in advance. Putting the footer last means the writer never seeks. The fixed 12-byte tail lets the reader find the footer with two seeks: one to read the tail, one to read the footer block.
Writer interface
import os, struct, zlib
from dataclasses import dataclass, field
MAGIC = b"CLMN"
TAIL_FMT = struct.Struct("<II4s") # footer_len, footer_crc32, magic
@dataclass
class ChunkMeta:
field_id: int
offset: int
compressed_len: int
uncompressed_len: int
num_pages: int
null_count: int
min: object # None when all-null
max: object
class ColumnarFileWriter:
def __init__(self, sink, schema,
row_group_rows: int = 1 << 20,
page_bytes: int = 1 << 20,
codec: str = "LZ4"):
self.sink = sink
self.schema = schema
self.row_group_rows = row_group_rows
self.page_bytes = page_bytes
self.codec = codec
self.buffers = {f.field_id: ColumnBuffer(f) for f in schema}
self.row_groups: list = []
self.pos = 0
self._write(MAGIC + struct.pack("<HH8x", 1, 0)) # header
def write_batch(self, columns: dict) -> None:
"""Append a dict of {column_name: array} to the in-memory buffers."""
for f in self.schema:
self.buffers[f.field_id].append(columns[f.name])
if self._buffered_rows() >= self.row_group_rows:
self.flush_row_group()
def flush_row_group(self) -> None:
n = self._buffered_rows()
if n == 0:
return
chunks = []
for fid, buf in self.buffers.items():
start = self.pos
pages = buf.encode_pages(self.page_bytes, self.codec)
for p in pages:
self._write(p.header_bytes() + p.body)
chunks.append(ChunkMeta(
fid, start,
compressed_len=self.pos - start,
uncompressed_len=sum(p.uncompressed_len for p in pages),
num_pages=len(pages),
null_count=buf.null_count,
min=buf.min, # None if all-null
max=buf.max,
))
buf.reset()
self.row_groups.append((n, chunks))
def close(self) -> None:
self.flush_row_group()
footer = encode_footer(self.schema, self.row_groups)
self._write(footer)
tail = TAIL_FMT.pack(len(footer), zlib.crc32(footer), MAGIC)
self._write(tail)
self.sink.flush()
os.fsync(self.sink.fileno())
def _write(self, data: bytes) -> None:
self.sink.write(data)
self.pos += len(data)
def _buffered_rows(self) -> int:
first = next(iter(self.buffers.values()))
return len(first)
Reader interface
class CorruptFile(Exception): pass
class ColumnarFileReader:
def __init__(self, f):
self.f = f
size = os.fstat(f.fileno()).st_size
if size < 16 + TAIL_FMT.size:
raise CorruptFile("file too small")
# Read and validate tail
tail_raw = os.pread(f.fileno(), TAIL_FMT.size, size - TAIL_FMT.size)
flen, fcrc, magic = TAIL_FMT.unpack(tail_raw)
if magic != MAGIC:
raise CorruptFile("bad magic in tail")
footer_start = size - TAIL_FMT.size - flen
if footer_start < 16 or flen == 0:
raise CorruptFile("invalid footer length")
raw_footer = os.pread(f.fileno(), flen, footer_start)
if zlib.crc32(raw_footer) != fcrc:
raise CorruptFile("footer CRC mismatch")
self.meta = decode_footer(raw_footer)
# Validate all chunk offsets fall within [16, footer_start)
self.meta.validate_offsets(16, footer_start)
def read(self, columns: list[str], predicates: list = ()):
"""
Yield (num_rows, {col_name: array}) for each surviving row group.
predicates: list of (col_name, op, value) using chunk min/max to prune.
Columns not in `columns` are never read from disk.
"""
for rg in self.meta.row_groups:
if not self._may_match(rg, predicates):
continue
out = {}
for col in columns:
m = rg.chunk_for(col)
raw = os.pread(self.f.fileno(), m.compressed_len, m.offset)
out[col] = decode_chunk(memoryview(raw), self.meta.field(col))
yield rg.num_rows, out
def _may_match(self, rg, predicates) -> bool:
for col, op, val in predicates:
m = rg.chunk_for(col)
if m.min is None:
# All-null chunk — no comparison predicate can be satisfied
return False
if op == ">" and not (m.max > val): return False
if op == ">=" and not (m.max >= val): return False
if op == "<" and not (m.min < val): return False
if op == "<=" and not (m.min <= val): return False
if op == "=" and not (m.min <= val <= m.max): return False
return True
Reader optimisation: when multiple requested column chunks are adjacent in the file (e.g., sequentially laid-out fields of the same row group), coalesce them into a single larger pread to reduce syscall overhead. For RAW/PLAIN pages, wrapping the buffer with np.frombuffer on a memoryview avoids a copy entirely.
Structural invariants
Every file must satisfy these on write and be checked on read:
- All chunk offsets are strictly increasing and fall within
[16, footer_start). - The sum of
num_valuesacross all pages in a chunk equals the row group'snum_rows. null_count ≤ num_rowsfor every chunk.- A chunk with
null_count == num_rowsmust havemin == Noneandmax == None. - Every
field_idreferenced in a row group chunk record exists in the footer schema.
Partial writes: if the process crashes before close() completes, the tail magic bytes will be absent or corrupt. The reader detects this in the first two checks and raises CorruptFile, leaving the partial file safely unreadable rather than silently returning incomplete data.
Variable last row group: the final row group will almost always contain fewer than row_group_rows rows. The num_rows field in the row group metadata is the ground truth; readers must not assume uniform group sizes.
Delta + bit-packing for timestamps
Nanosecond timestamps in a tick feed are monotonically increasing with small deltas (often 1–100 µs = 1 000–100 000 ns). Storing raw INT64 costs 8 bytes/value; delta encoding followed by bit-packing commonly reduces this to 1–2 bytes/value. The encoding choice is stored in the page header, so the reader knows exactly how to decode each page without consulting external metadata. The invariant that must hold for delta encoding to be safe: values within a chunk must be in non-decreasing order. If out-of-order events are possible, fall back to PLAIN.
Testing strategy
Round-trip correctness: for each type and encoding combination, generate a random column, write it, read it back, and assert bitwise equality. Cover all-null columns, single-row groups, and groups of exactly row_group_rows and row_group_rows + 1 rows.
Projection isolation: instrument the pread calls (or substitute a spy file object) and verify that reading column A never issues a read that overlaps the byte range of column B.
Predicate pruning: write a file where only one row group contains values satisfying a predicate. Assert that read() with that predicate returns exactly one group and that the byte-range reads for skipped groups never occur.
Corruption detection: flip individual bytes in a page body, in the footer block, and in the tail magic, and assert that each case raises CorruptFile. Truncate the file to various lengths and verify the same.
Encoding regression: store the encoded bytes of a reference column as a golden file. After any codec or encoding change, regenerate and diff; any unexpected change is a regression.
Common mistakes to avoid
- Storing min/max for all-null chunks — the reader cannot distinguish "no values" from "value equals the sentinel."
- Writing footer metadata before all row groups are flushed — this forces a seek or a two-pass write.
- Using signed integers for offsets or lengths — a 4 GB+ file overflows
int32. - Omitting the validity bitmap for columns declared non-nullable — schema alone is not sufficient if the writer can receive null inputs due to upstream bugs; validate at write time and fail loudly.
- Forgetting to
fsyncbefore returning fromclose()— the file looks complete but can be partially absent after a crash.