KV

Versioned key-value storage with CAS, TTL, blocking gets and namespace isolation; writes are replicated before they're acknowledged.

Flo's KV store is versioned key-value storage backed by the Unified Append Log. Every write is Raft-replicated across the cluster before being acknowledged. Reads go directly to the local projection, with no Raft round-trip, so what one reflects depends on the node that answers: a leader's read reflects what it has committed, a follower can lag, and a deposed leader can answer stale until it finds out. See what a read reflects.

Core Concepts

Versioned Writes

Every mutation to a key creates a new version: 1 on its first write, one more on each after.

Put responses include the new version number, which you can use for subsequent CAS updates:

flo kv set counter "1"                   # → version: 1
flo kv set counter "2" --cas-version 1   # → version: 2
flo kv set counter "3" --cas-version 1   # → Error: conflict: cas_version isn't the key's version [conflict/cas_mismatch]

Namespace Isolation

Keys live inside namespaces. The default namespace is used when no -n flag is provided. Keys with the same name in different namespaces are fully independent — they have separate values, versions, and TTLs.

# Create namespaces
flo ns create staging
flo ns create production
 
# Same key, different namespaces
flo kv set db_url "postgres://staging" -n staging
flo kv set db_url "postgres://prod"    -n production
 
# Each returns its own value
flo kv get db_url -n staging      # → postgres://staging
flo kv get db_url -n production   # → postgres://prod

Deleting or overwriting a key in one namespace has no effect on the same key in other namespaces. Conditions like --condition if_absent are also per-namespace — a key can be "new" in one namespace while already existing in another.

Operations

Put

flo kv set mykey "hello world"
FlagDescription
--ttl-ms <ms>Expire after this long: milliseconds, or a number and a unit (500ms, 30s, 5m, 1h, 1d); 0 = no expiry
--condition <when>always (the default), if_absent (only if the key does not exist) or if_present (only if it does)
--cas-version <version>Only set if the key's version is exactly this
-n <namespace>Target namespace
-t <txn-id>Buffer the write in a transaction

A condition and a version may be given together; the write happens only if both hold.

CAS version 0 has a special meaning: it asserts the key must not exist yet. This is equivalent to --condition if_absent but expressed as a version constraint.

Get

flo kv get mykey
flo kv get mykey -o json   # includes version number
FlagDescription
--wait-ms <ms>How long to wait: milliseconds, or a number and a unit (500ms, 30s, 5m); at most 5m; 0 does not wait; a longer wait is refused
--wait-for <what>What to wait for: exists (the default) or change
-o <fmt>Output format: json, table, raw
-n <namespace>Target namespace
-t <txn-id>Read inside a transaction, seeing its buffered writes

The two kinds of wait serve different purposes:

  • --wait-for exists is for coordination — one process creates a key, another waits for it to appear. If the key already exists, it returns immediately.
  • --wait-for change is for watching — subscribe to the next change on an existing key. Even if the key exists now, it waits for a newer version. If nothing changes in time, it returns the current value with its unchanged version, so a watcher can compare and ask again; a key that is gone returns not found.
# Process A: wait for a result to appear
flo kv get job:result --wait-ms 30s
 
# Process B: watch for config changes
flo kv get config:feature-flags --wait-ms 5m --wait-for change

Multi-key get

Fetch many keys in one request. Keys may live on different shards — the server reads each on the shard that owns it, gathers the answers, and returns one entry per requested key, in order (with a found flag distinguishing missing keys from empty values).

flo kv mget user:1 user:2 user:3
flo kv mget user:1 user:2 --output json

An mget reads each key as it stands when it gets there: it isn't one snapshot across shards.

FlagDescription
-o, --output <fmt>table (default), json, raw
-n <namespace>Target namespace

Limited to 256 keys per call. One answer holds about 256 KiB; when the values don't fit, the server answers what does and says where it stopped, and the CLI and SDKs ask again for the rest on their own.

entries, err := client.KV.MGet([]string{"user:1", "user:2", "user:3"}, nil)
if err != nil { return err }
for _, e := range entries {
    if e.Found {
        fmt.Printf("%s = %s (v%d)\n", e.Key, e.Value, e.Version)
    } else {
        fmt.Printf("%s missing\n", e.Key)
    }
}

Delete

flo kv delete mykey

Deleting a key that doesn't exist succeeds: it prints existed: false, and existed: true when there was one to delete.

FlagDescription
-n <namespace>Target namespace

Scan

flo kv scan                          # the first page of all keys
flo kv scan user:                    # keys starting with user:
flo kv scan user: --limit 50         # 50 names a page
flo kv scan user: --cursor 0300757365723a3432   # the next page
FlagDescription
--limit <n> / -lMost names on the page, 1 to 1024 (default: 1024)
--cursor <hex>Where the last page stopped
-n <namespace>Target namespace

Scan returns names only; read values with get or mget. It walks all shards — keys are returned regardless of which shard they hash to — a page at a time. A page that isn't the last ends with cursor: <hex>; pass it to --cursor for the next. A page can hold fewer names than --limit, even none, while more follow: stop when no cursor is printed, not on a short page. The prefix filter is applied on each shard locally before results are merged.

Names come in key order within a shard, shard by shard. A page resumes after the last name the one before it returned, so a key written or deleted between pages adds or removes only itself: no other name is sent twice or skipped.

Version History

flo kv history mykey
flo kv history mykey --limit 5
flo kv history mykey --before-version 40

Returns the key's versions, newest first, each with its version, the time it was written in Unix milliseconds, and whether it is a delete. History for a key with none returns not found (exit 1).

FlagDescription
--limit <n> / -lMax entries, 1 to 65 (default: 10)
--before-version <v>Only versions older than v
-n <namespace>Target namespace

Each key keeps at most 64 older versions and at most 64 KiB of them, each charged its value's bytes plus 64; the oldest go first while either bound is exceeded, and the newest older version is always kept, however large. So a key with small values keeps 64 versions, one with 4 KiB values about 15, and one large write can evict a key's whole small history. An oldest kept version above 1 means older ones were evicted.

Deletes are versions too (deleted: true): a key's history survives its deletion, and its memory comes back only when the key is removed.

One answer holds 256 KiB, so a history of large values can take several. An answer says more when older kept versions follow; ask again with before_version set to the last version it gave. The CLI does this itself up to --limit, and prints more: true (on stderr with -o raw) when versions remain beyond it.

TTL (Time-to-Live)

Set an expiration on keys:

flo kv set session:abc '{"user":"alice"}' --ttl-ms 1h

The key expires one hour after the write. Expired keys are not found on get (exit 1), as if they were never written. Setting --ttl-ms 0 explicitly means "no expiration."

TTLs are milliseconds, with millisecond resolution. --ttl-ms takes a bare number of milliseconds, or a number and a unit — ms, s, m, h or d, as in 500ms or 1d. kv expire takes the same.

Overwriting a key resets its TTL. If you set a key with --ttl-ms 60s and then overwrite it without a TTL, the new value has no expiration:

flo kv set temp "short-lived" --ttl-ms 5s   # expires in 5s
flo kv set temp "permanent"                 # TTL cleared

TTL combines with conditions. A common pattern is a TTL with --condition if_absent for "set once with expiry":

flo kv set lock:resource "owner-1" --ttl-ms 30s --condition if_absent

Expiry is lazy — keys are checked at read time rather than proactively swept. This means expired keys don't consume I/O until accessed.

Compare-and-Swap (CAS)

CAS enables optimistic concurrency control. Read the current version, then conditionally write only if nobody else has modified the key since:

# Step 1: read current value and version
flo kv get counter -o json
# {"version":7,"value":"41"}
 
# Step 2: update only if version is still 7
flo kv set counter "42" --cas-version 7

If another writer updated the key between your read and write, the CAS fails with [conflict/cas_mismatch] (exit 3) and the original value is preserved.

CAS works across the cluster. You can read the version on one node and CAS-update through another. The version travels in the write's log entry and is checked as the entry applies, in log order, the same on every node: of two writes carrying one version, the first in the log wins and the other is refused. A stale read costs you a refused write, never an overwrite.

Atomicity model

Flo's KV store is built around single-key writes in one log order rather than multi-key transactions. Every mutation goes through Raft as a single committed entry, so each operation applies whole, and every node applies a key's writes in the same order. How durable an acknowledged write is depends on the durability mode.

Conditional & atomic writes

Use the conditional flags on kv set/KV.Put to express "do this only if X". Each is a single Raft entry — no coordinator, no roundtrips, no rollback to worry about.

A condition is decided when its entry applies, not when the write arrives, so racing writers can't both pass, and a new leader's answer counts everything committed before it. That has three effects:

  • A failed condition still costs a replicated commit. The write goes through the log like one that passes, then changes nothing: no version, no history. So does a delete or an expire of a key that isn't there, and an incr that's refused.
  • A key whose TTL has run out by the entry's timestamp is absent: if_absent writes over it, and if_present is refused.
  • In a transaction, a conflict appears at commit, not at the op, and a condition sees that transaction's own earlier writes.
PatternHow
Insert if absent--condition if_absent (or --cas-version 0)
Update only if present--condition if_present
Compare-and-swap by version--cas-version <version>
Atomic create with lease--condition if_absent --ttl-ms <duration>
Atomic counterkv incr
Atomic JSON sub-field updatekv json set

The classic read-modify-write loop becomes:

# 1. Read current state and version (PUT/GET both return the version)
flo kv get account:42 -o json     # → {"version":11,"value":"…"}
 
# 2. Compute new state client-side
# 3. Conditional write — fails if anyone else changed the key
flo kv set account:42 '{"balance":150}' --cas-version 11

If the CAS fails, re-read and retry. For a counter, prefer kv incr — it is unconditional and never conflicts.

CAS-guarded delete and expire

The same version guard is also accepted by delete and expire. This closes the classic distributed-lock race: the holder can release the lock (or extend its lease) only if it still owns the version it acquired.

// Acquire: a put-if-absent with a 30 s TTL returns version
ttl := uint64(30_000)
v, _ := client.KV.Put("lock:job-42", []byte(ownerID),
    &flo.PutOptions{Condition: flo.ConditionIfAbsent, TTLMs: &ttl})
 
// ... do work ...
 
// Release: only the owner deletes — no risk of unlocking after expiry
_, _ = client.KV.Delete("lock:job-42", &flo.DeleteOptions{CASVersion: &v.Version})
v = await client.kv.put("lock:job-42", owner_id.encode(),
    PutOptions(condition=Condition.IF_ABSENT, ttl_ms=30_000))
# ... work ...
# Renew the lease atomically
await client.kv.expire("lock:job-42", 30_000, KVExpireOptions(cas_version=v.version))
# Release: only the owner deletes
await client.kv.delete("lock:job-42", DeleteOptions(cas_version=v.version))

A version mismatch is refused with [conflict/cas_mismatch], as set with --cas-version is; re-read to decide whether to retry or give up.

Multi-key atomicity

For multi-key writes that must commit or fail as a unit, Flo offers per-shard transactions. Operations are buffered on one shard and replicated as one Raft entry on commit. Pick the right tool:

NeedRecommended approach
"Several keys, all-or-nothing"Give the keys the same {tag} and open a transaction — all writes commit atomically as one Raft entry.
"All these keys live together"Give every related key the same {tag}, as in {user:123}:name (see Shard Co-location). Reads and writes stay on one shard.
"Update several fields of one document"Model the state as a single key with a JSON value and use kv json set or CAS on the whole document. One Raft entry, no coordination.
"Atomic counter"Use kv incr — unconditional and conflict-free.
"Long-running multi-step state machine"Use a workflow. Workflows give you durable execution, retries, and compensation steps.
"Idempotent producer / exactly-once write"Use --condition if_absent on a dedupe key (e.g. dedupe:<request-id>) before doing the work.
"Cross-shard transaction"Not supported. Either restructure keys to share a {tag}, or use a workflow with compensating actions.

Counters

kv incr (opcode 0x10B) atomically adds a signed delta to a key holding a 64-bit counter. The first incr on a missing key creates it at the delta value. The operation is unconditional — it never conflicts — and is ideal for rate-limit buckets, sequence generators, and metric accumulators.

flo kv incr visits:home          # +1, returns new value
flo kv incr visits:home -d 10    # +10
flo kv incr visits:home -d -1    # decrement

A counter and a string value cannot share a key. incr against a key whose value isn't an 8-byte counter is refused with [bad_request/wrong_type] (exit 3). Inside a transaction incr prints OK: the new value isn't known until commit.

Recipe: per-minute rate limiter

minute = int(time.time() // 60)
key = f"rl:{user_id}:{minute}"
count = (await client.kv.incr(key)).value
if count == 1:
    await client.kv.expire(key, 120_000)  # auto-expire old buckets
if count > LIMIT:
    raise RateLimited()

TTL lifecycle

TTLs are set at write time via --ttl-ms / PutOptions.TTLMs, but you can also adjust them later:

OpEffect
kv expire <key> --ttl-ms <duration>Set the TTL on an existing key, from now, without rewriting the value
kv expire <key> --ttl-ms 0Clear the TTL: make the key permanent

expire takes --cas-version and --txn like delete; a missing key is not found (exit 1).

Each is a single Raft entry. Use it to extend session leases, refresh distributed locks, or promote a temporary value to permanent without losing it.

Existence check

kv exists (opcode 0x115) answers whether the key exists, and its version, without transferring the value, so it is much cheaper than get for large values.

flo kv exists user:123    # exists: true and version: <n>, exit 0; or exists: false and version: 0, exit 1

JSON paths

For keys whose value is a JSON document, three operations let you read or mutate sub-fields without round-tripping the whole document:

OpWirePurpose
kv json get <key> [--path <path>]0x10CExtract path from the JSON document. Path defaults to $ (the whole document).
kv json set <key> <document> [--path <path>]0x10DAtomically set the value at path. $ replaces the document (and creates the key if missing); any other path needs an existing document.
kv json del <key> [--path <path>]0x10ERemove the value at path. $ deletes the key.

Paths use a tiny JSONPath subset: $, .field, .field.nested, [index]. The operations are atomic per Raft entry — a sub-field update is a single committed write, not a read-modify-write loop.

The answer to json get carries the document's current version alongside the JSON (-o json shows it); json set and json del answer the new version (json del at $ answers none, since the key is gone). Use that version to drive CAS on subsequent writes. A path with nothing at it is not found (exit 1); a key whose value isn't JSON is refused with wrong_type. The JSON ops don't run inside transactions.

Recipe: status enrichment

flo kv set order:42 '{"id":42,"items":3,"status":"new"}'
flo kv json set order:42 '"shipped"' --path '$.status'
flo kv json get order:42 --path '$.status'      # → "shipped"

The json set is a single Raft entry; concurrent writers updating different fields on the same document still each succeed atomically (last writer wins per field).

Transactions

Per-shard transactions buffer multiple writes on one shard and commit them atomically as one Raft entry. A transaction is pinned to the {tag} of the key it begins with, or the whole key if it has none, and every key in it must route the same way: give them all the same {tag}, as in {user:42}:name. A key that routes elsewhere is refused with [bad_request/keys_not_colocated], and nothing of it runs. The transaction id names its slot, so commit and rollback take nothing else.

OpWirePurpose
kv txn begin <key>0x110Open a new transaction pinned to the key's {tag}. Returns its id (txn) and the routing hash it is pinned to (pinned).
kv txn commit <txn-id>0x111Apply all buffered ops atomically. Returns the op count and the commit_index.
kv txn rollback <txn-id>0x112Discard buffered ops. A transaction that isn't open (already committed, rolled back or dropped as idle) is refused with no_such_transaction.

Inside a transaction, set, get, delete, incr, expire and exists accept a --txn <id> flag; writes are buffered until commit. Reads inside the transaction see the buffered writes, a conditional one too: it reads as written until the commit decides it. scan, mget, history and the JSON ops take no transaction.

Server caps: 64 ops and 256 KiB of keys and values per transaction, unless the operator sets them higher or lower (at most 256 ops and 1 MiB), 1024 open transactions per shard (past that, txn begin is refused with too_many_transactions).

A commit applies whole or not at all. If one of its ops can't apply when the commit does (a condition or --cas-version that doesn't hold; an incr on a value that isn't a counter, or one that would overflow; an expire of a key that's gone or past its TTL by then), the whole commit is refused with that op's reason and position, as in the transaction's op 2: not found; nothing in the transaction applied, and none of its writes apply. The status is that op's: conflict (exit 3) for a condition or --cas-version, bad_request (exit 3) for an incr, not_found (exit 1) for an expire.

# Open (prints txn: <id> and pinned: <hash>), write, commit
TXN=$(flo kv txn begin '{user:42}:name' | sed -n 's/^txn: //p')
flo kv set '{user:42}:name' "Jane"   --txn $TXN
flo kv incr '{user:42}:visits'       --txn $TXN
flo kv set '{user:42}:last_seen' "$(date -u +%s)" --txn $TXN
flo kv txn commit $TXN           # → commit_index: N, ops: 3

Transactions survive across stateless connections — they are owned by their id, not by the TCP connection. So a transaction that goes 30 seconds without a request is dropped with its buffered ops, freeing its slot when a client crashes before commit; any request in it, even one refused, counts as use. A later request on a dropped transaction is refused with no_such_transaction, and nothing of it is written. flo_kv_txns_reaped_total{shard_id} counts the drops.

When to use transactions vs. JSON or workflows

PatternUse
Atomic update of 2–10 related keys sharing a {tag}Transaction
Atomic update of fields inside one documentkv json set
Atomic counter incrementkv incr
Multi-step business process across shards / external systemsWorkflow

Shard Co-location

Each key routes to a shard by its hash. To keep related keys on one shard, for a transaction or for locality, put the same {tag} in each key: the text between the first { and the next } is what routes.

flo kv set '{user:123}:name' "Alice"
flo kv set '{user:123}:email' "alice@co.io"
flo kv set '{user:123}:prefs' '{"theme":"dark"}'

All three keys route to the same shard because they share the tag user:123. The tag is part of the key: read and write it whole. {} is a tag too, an empty one, so every key holding {} routes together; a key with no } after its first { routes by the whole key, as one with no braces does.

Cluster Behavior

In a multi-node cluster:

  • Writes are proposed to the Raft leader and replicated to a majority before being acknowledged.
  • Reads are served from the local shard's projection — no Raft round-trip needed.
  • Data replicates to all nodes. A key written on node 1 is readable from node 2 and node 3 after replication.
  • Node failures are tolerated as long as a majority (quorum) of nodes remain healthy. A 3-node cluster survives 1 node failure.
  • CAS and conditional writes are decided as their entries apply, in log order, so every node decides them alike.

Reads from a halted shard

A halted shard refuses writes but still answers reads, from the state just before the entry it halted at, and marks each answer stale. Every KV read result in the SDKs carries it as stale (Stale in Go): get, mget, scan, history, exists and JSON get. A key missing on a stale answer may only be missing as of the halt, so get and JSON get report it as a distinct error rather than as absent: flo.ErrStaleNotFound in Go (flo.IsStale and flo.IsNotFound both hold), StaleNotFoundError in JavaScript and Python (a NotFoundError with stale true), error.StaleNotFound in Zig. A plain missing key is reported as before. The CLI doesn't show the mark, and the SDKs don't yet carry it on reads outside KV.

SDK Examples

client := flo.NewClient("localhost:9000")
client.Connect()
defer client.Close()
 
// Put returns a PutResult with the new version
res, _ := client.KV.Put("mykey", []byte("hello"), nil)
fmt.Println("committed at version", res.Version)
 
// Put with TTL
ttl := uint64(3_600_000) // one hour, in milliseconds
client.KV.Put("session:abc", []byte(`{"user":"alice"}`), &flo.PutOptions{
    TTLMs: &ttl,
})
 
// Get returns *GetResult (nil if not found) — contains both value and version
if r, _ := client.KV.Get("session:abc", nil); r != nil {
    fmt.Printf("%s @ v%d\n", r.Value, r.Version)
}
 
// CAS update — read version from Get, conditional write
r, _ := client.KV.Get("counter", nil)
err := client.KV.Put("counter", []byte("42"), &flo.PutOptions{
    CASVersion: &r.Version,
})
if flo.IsConflict(err) {
    // Another writer modified the key — re-read and retry
}
 
// Conditional write (only if key doesn't exist)
client.KV.Put("lock:resource", []byte("owner-1"), &flo.PutOptions{
    Condition: flo.ConditionIfAbsent,
    TTLMs:       flo.Uint64Ptr(30_000),
})
 
// Atomic counter
n, _ := client.KV.Incr("visits:home", nil) // n.Value, n.Version
 
// TTL lifecycle
client.KV.Expire("lock:resource", 60_000, nil) // extend lease to 60 s
client.KV.Expire("lock:resource", 0, nil)      // clear the TTL
ok, _ := client.KV.Exists("lock:resource", nil)
 
// JSON path operations
client.KV.JsonSet("order:42", "$.status", []byte(`"shipped"`), nil)
status, _ := client.KV.JsonGet("order:42", "$.status", nil)
 
// Wait up to 5 s for the key to appear
r, _ = client.KV.Get("job:result", &flo.GetOptions{WaitMs: 5000})
 
// Prefix scan with pagination
result, _ := client.KV.Scan("user:", &flo.ScanOptions{Limit: ptr(uint32(100))})
for _, key := range result.Keys {
    fmt.Println(key)
}
// result.Cursor is nil on the last page; pass it in ScanOptions.Cursor for the next
 
// Version history
history, _ := client.KV.History("counter", &flo.HistoryOptions{Limit: ptr(uint32(5))})
for _, v := range history {
    fmt.Printf("v%d: %s (at %d ms)\n", v.Version, v.Value, v.AtMs)
}
 
// Namespace-scoped operations
client.KV.Put("config", []byte("staging-db"), &flo.PutOptions{
    Namespace: "staging",
})
r, _ = client.KV.Get("config", &flo.GetOptions{Namespace: "staging"})
 
// Transaction — multiple writes on one shard, atomic commit
txn, _ := client.KV.Begin("user:42", nil)
_, _  = txn.Put("user:42:name", []byte("Jane"), nil)
_     = txn.Incr("user:42:visits", 1)
result, err := txn.Commit()
if err != nil {
    _ = txn.Rollback() // idempotent
}
fmt.Printf("committed %d ops at index %d\n", result.OpCount, result.CommitIndex)

Use Cases

Distributed Locks

Use --condition if_absent with --ttl-ms as a simple distributed lock with automatic expiry:

# Acquire lock (fails if already held)
flo kv set lock:payment "worker-7" --ttl-ms 30s --condition if_absent
 
# Release lock
flo kv delete lock:payment

The TTL acts as a safety net — if the lock holder crashes, the lock auto-expires.

Configuration Store

Store configuration per environment using namespaces, and watch for changes with --wait-for change:

# Set config
flo kv set feature:dark-mode "true" -n production
 
# Watch for config changes (long-poll)
flo kv get feature:dark-mode --wait-ms 5m --wait-for change -n production

Job Coordination

Use --wait-ms for producer/consumer coordination where one process publishes a result and another waits for it:

# Worker: process job and publish result
flo kv set job:abc:result '{"status":"done","output":"..."}' --ttl-ms 1h
 
# Requester: wait for result (up to 60 seconds)
flo kv get job:abc:result --wait-ms 60s

Internals

The KV store is implemented as a KV Projection — a hash table with MVCC version chains, derived from the Unified Append Log.

PropertyValue
Max key size4096 bytes, in any namespace
Key bytesAny except NUL (0x00), which is refused
Max value size~256 KB
Max namespace length63 bytes
Version history per key64 older versions and 64 KiB of them, oldest evicted first; the newest older version is always kept
Default list limit100 (pages of up to 1,024)
Reserved key prefixes_action:, _worker:, _sys:, _internal:, _flo:

Write path: kv_put → Raft propose → majority commit → UAL append → KV projection update → response to client.

Read path: kv_get → KV projection lookup → response. No Raft involvement.

Recovery: On server restart, the projection is rebuilt by replaying the log. A node serves reads once that's done; a cluster member with async_flush, or a new leader, refuses them for a retry until it has caught up.

TTL enforcement: Lazy — expired keys are detected at read time rather than proactively swept. This avoids background I/O for expiry.

Tombstones: A delete of a live key writes a tombstone entry to the UAL. A delete of a key that isn't live goes through the log and changes nothing. Prior versions remain in the version history and are queryable via history. A tombstone and its history stay in memory until the key is removed; nothing purges them sooner.