Storage Internals

How Flo stores data — the Unified Append Log, projections, and recovery.

Philosophy: The Log Is the Database

Most databases maintain two copies of every write: a write-ahead log (WAL) for durability and a primary data structure (B-tree, LSM tree, heap file) for queries. Flo doesn't do this. The log is the primary data structure.

The Unified Append Log captures every mutation — KV puts, queue enqueues, stream appends, time-series writes — as a sequenced, typed entry. The Raft consensus log and the storage log are the same thing. There is no separate WAL.

Everything else — the KV and queue families, the time-series columnar buffers — is derived state, rebuilt deterministically from the log. If you deleted it all and replayed the log from the beginning, you'd get back to exactly the same state.

Unified Append Log (UAL)

The UAL is a sequence of entries, each identified by a monotonically increasing 64-bit index.

Entry Format

Every UAL entry has a 40-byte header followed by a variable-length payload:

┌──────────┬──────────┬───────┬───────────┬────────────┬─────────────┬───────┐
│ CRC32C   │ entry_   │ flags │ raft_term │ raft_index │ timestamp   │ pay-  │
│ (4B)     │ type(2B) │ (2B)  │ (8B)      │ (8B)       │ _ns (8B)    │ load  │
└──────────┴──────────┴───────┴───────────┴────────────┴─────────────┴───────┘

The CRC covers the header and payload together. Payload layout varies by entry type — each projection knows how to parse its own payloads.

Two-Tier Storage

TierImplementationPurpose
Hotmmap'd ring buffer in RAM (default 64 MB)Recent entries for active reads. O(1) by index.
WarmSealed disk segments (.flseg files), memory-mappedHistorical data, bounded by local disk space.

When entries age out of the hot ring, they're flushed to warm segments. A warm store hash map keeps payload copies in memory (default 32 MB) for the stream read path, which fetches record payloads by index, so those reads don't have to go to disk immediately. KV entries are never copied there: the KV projection holds the value, and nothing reads a KV payload from the log.

The warm store holds the newest payloads, so on the default 64 MB ring it mostly duplicates the ring; it serves an entry that wraps the ring's end, or history when the ring is smaller than the store. A stream record past the ring is read back from the durable log: its sealed segment, or the segment writer's buffer if it hasn't been flushed yet. The segment read runs on the node's bulk I/O thread, never on a shard's thread. Each entry is checked against the log's terms before it's used, nothing not yet committed is kept, and recent results are kept in a small per-shard cache (8 MB). A segment that turns out corrupt is damage to the shard. See Tiered Storage for what a client sees.

Segment Format

Each sealed segment is a .flseg file:

[SegmentHeader]   magic "FLO_SEG\0", version, partition id, index range, entry count, commit index at seal
[Entry 0..N]      Sequential entries
[SparseIndex]     Sampled every ~256 entries: index → file offset
[SegmentFooter]   index_offset, index_count, crc32c

The sparse index enables binary search by UAL index without scanning every entry. The footer CRC covers the entire segment — corruption is detected on read.

The durable log

The Raft log of a shard lives in three places: the hot ring, the segment writer's not-yet-flushed buffer, and the sealed segments. The buffer and the segments together hold every entry and are the durable log; the hot ring holds the most recent ones as well. The Raft layer uses the durable log for three things the ring cannot do:

  • Restart applies only what was committed. Each segment records the Raft commit index at the moment it was sealed. On boot, entries at or below the highest such watermark are replayed into the projections; entries above it are loaded into the Raft log only and applied once commit is re-established (immediately on a single node, where commit is re-established at bootstrap). A follower that flushed an uncommitted tail its next leader then truncates never applies that tail. Nothing committed is lost.
  • Truncation reaches the files. When a follower's log conflicts with its leader and a suffix is dropped, the same suffix is dropped from the writer's buffer and from any sealed segment that holds it: the segment is rewritten under its own name with only the entries below the cut, or deleted if nothing remains. The cut is recorded on disk before any file is touched and the record removed after the last one, so a cut interrupted by a crash is finished by the next boot; until it is finished nothing is flushed, and two segments holding the same index refuse to replay rather than picking one. Without this a later flush would put a second entry at the truncated index into a newer file, and replay would apply the wrong one.
  • Catching a peer up from below the ring. A follower that restarted, or was partitioned for longer than the ring holds, needs entries the ring has evicted. The log reads them from the writer's buffer or from the segment that covers the index, so as long as segments exist from index 1 any follower can be repaired from any point without a snapshot.

Projections

Projections are specialized data structures that consume UAL entries and maintain queryable state.

KV Projection

  • Hash table mapping keys to values, plus MVCC version chains (ring buffer, default 8 versions per key)
  • TTL tracking for automatic expiry
  • Reads are O(1) hash table lookups — no Raft round-trip needed
  • Historical lookups walk the version chain

Queues

Queues are a state machine on the log, not a projection: every enqueue, dequeue, complete, fail, touch and lease expiry is an entry every replica applies alike. Each shard keeps a queue's messages, its ready keys ordered by (priority, due time, seq), every lease's deadline, and its dead letters (oldest first, kept until the queue is purged). A dequeue logs a deliver that leases the first due ready messages; the leader's expire duty ends leases past their deadline. A ready message costs its payload plus about 340 bytes of memory.

Stream Projection

Streams have no traditional projection. Stream records are UAL entries with entry_type = stream_append. Reading a stream is reading a range of UAL entries — the log index is the stream offset. Zero copy, no derived state.

Consumer group offsets are stored as KV entries (prefixed with cg:), so the KV projection handles that state.

Time-Series Projection

TS data has no dedicated disk files. All ts_write entries are appended to the shared UAL (same .flseg segments as KV, queue, and stream data).

  • Write buffers — per-series, per-field in-memory buffers (1024 points capacity)
  • Block index — in-memory metadata: min/max timestamp, point count, UAL index range
  • Series metadata lives in KV projection under _ts:meta:* keys

When a write buffer fills, flushBuffer() records a block metadata entry (timestamps + UAL index range) and discards the raw points. Reconstructing historical block data requires replaying the UAL in [ual_index_start..ual_index_end]. This means hot reads (from the write buffer) are fast, while cold reads (from flushed blocks) require UAL replay.

One apply path

Every committed entry is applied by exactly one function, whether it was just written on this node, replicated from a peer, or replayed from a segment at boot: the entry goes into the partition (the projection router, plus the hot ring for the types that read back from the log) and then to the applier registered for its type. A live write proposes the entry, applies it through that path, and only then reads its response from projection state — the same state a restart rebuilds.

The projection router owns the three in-memory projections:

Entry TypesDestination
kv_put, kv_delete, kv_incr, kv_expire, kv_batchKV Projection
queue_enqueue, queue_deliver, queue_settle, queue_release, queue_extend, queue_expire, queue_purgeThe queue machine
ts_write, ts_write_batchTS Projection

Every other type — stream appends, trims and deletes, consumer-group commits, namespaces, actions, workflows, processing jobs — has one registered applier in its subsystem, and an entry type may have one or the other, never both; the server refuses to start otherwise. Raft's own control entries (raft_noop, raft_config, raft_snapshot) belong to the consensus layer and have no applier. Blocking reads wake on the apply, not on the request that caused it.

No Snapshots Yet

Projections live in RAM, and nothing writes a snapshot of them yet. The log is never compacted: every segment from index 1 stays on disk, and a restart replays all of them. A new member is replicated the whole log from index 1. Snapshots and compaction are planned.

Crash Safety

ScenarioWhat You LoseWhy It's OK
Crash during UAL appendThe uncommitted entryWasn't acknowledged to client
Power loss (no fsync)At most ~1ms of entriesBounded by group commit interval

Recovery

When a node restarts, each shard:

  1. Opens the log — finds its segments in segs/; a .flseg.tmp is a flush a crash cut short and is discarded
  2. Replays — feeds every entry from index 1 through the one apply path (the same code a live write and a replicated entry take), rebuilding the Raft log from the same pass
  3. Is ready for traffic

A segment that won't read, or a hole in the log, is damage: the shard stops replaying there and goes offline, naming it, rather than serving a state with entries missing. On a single node, flo server salvage cuts that shard's log back to the entries before the damage, so it can serve again with what it kept.

Directory Layout

{data_dir}/
├── FORMAT                              # Data directory format (a number)
├── SYSTEM                              # Topology lock (shard count, version)
├── 00000/                              # Shard 0 (zero-padded 5 digits)
│   ├── HARDSTATE                       # Raft node id, current term, vote (28 bytes)
│   ├── segs/
│   │   ├── 0000000001.flseg            # UAL segment (10-digit zero-padded first index)
│   │   ├── 0000000257.flseg
│   │   └── *.flseg.tmp                 # Transient (in-flight writes only)
├── 00001/
│   ├── HARDSTATE
│   └── segs/
└── ...{shard_count - 1}/

FORMAT

One number and a newline: the layout the directory is written in, 25 today. It is checked before anything else in the directory is read, and a binary reads only its own format. There is no migration.

  • An empty directory gets FORMAT first. Empty allows lost+found, dotfiles, and the lock, PID file and admin socket a server leaves.
  • A newer format is refused: data directory format 26, this binary reads format 25 (/var/lib/flo/FORMAT); start a flo that reads format 26.
  • An older format is refused: data directory /var/lib/flo was written by an older Flo (format 24); this server needs format 25. There is no migration: run flo server wipe --data-dir /var/lib/flo. A Flo directory without FORMAT (one with SYSTEM or a shard directory) is refused the same way, saying (before format gating). Empty it with flo server wipe, or start the older release.
  • A non-empty directory with no Flo data is refused, without suggesting a wipe, since it may be something else's: /var/lib is not a Flo data directory and isn't empty (it holds postgresql); check data_dir.
  • A FORMAT that isn't a format number, or isn't a file, is refused, naming what it holds.

The server, flo server inspect, force-members, repair skip and salvage refuse these alike, and exit with code 78. Keep config files and logs outside the data directory.

SYSTEM

Written once on first boot. A start asking for another shard count is refused, naming both counts (topology mismatch: the data was written for a shard count of 8, and this start asks for 4). There is no partition count to record: keys route over a fixed 4096 slots on every node. Format:

{
  "shards": 8,
  "created_at": 1772033477938,
  "version": "1.0.0"
}

HARDSTATE

One per shard — a fixed 28-byte, CRC-protected record of the node's identity and its Raft hard state: node id, current term, and the vote cast in that term. It is rewritten (.tmp → fsync → rename) before the node grants a vote or adopts a new term, never on the write path. On restart the node resumes one term past the stored one, so a node can neither vote twice in a term nor re-enter a term it already left. The stored node id also fixes the node's cluster identity: once written, it survives restarts and port changes, and a configured [cluster] node_id that disagrees with it is refused at startup with NodeIdMismatch.

The Raft log itself is the segment files — index 1 (the first leadership no-op) onward. On boot the node rebuilds its in-memory Raft log (last index, term index, and the hot-ring tail) from the same pass over segs/ that replays projections.

Atomic Writes

Segments and HARDSTATE are written atomically via .tmp → fdatasync → rename. If the process crashes before the rename, the previous file remains valid.