FyroDB documentation
Architecture
FyroDB's concurrent data path, compact storage, and adaptive memory maintenance.
Overview
FyroDB combines seven key architectural decisions:
- Thread-per-core I/O — one epoll loop per configured worker via
mio, withSO_REUSEPORTfor TCP anddupsocket cloning for Unix domain sockets - Guarded concurrent hash map — sharded open addressing with atomic table publication, EBR lifetime protection, map admission and per-entry read/write guards; shards start at 8,192 slots
- Borrowed parsing and direct replies — parse from the read buffer and serialize protected values directly; eligible large replies use bounded scatter/gather
- Batched writes & run coalescing — all epoll events processed before flushing responses;
try_fast_tailparses write runs directly into stack arrays - Compact, adaptive storage — inline keys and values, right-sized shard memory, compact collection encodings, and background memory reclamation
- Embedded Lua 5.4 scripting — Redis-compatible runtime with SHA1 chunk caching, re-entrant in-process command execution, and generational GC
- In-process L1 DB Cache routing — direct memory query routing between PostgreSQL proxy and KV store, completely bypassing loopback network hops
Data Flow
Client → TCP (SO_REUSEPORT) → Worker Thread (epoll)
→ read(socket) → RESP Parser (zero-copy, SIMD memchr)
→ Command Dispatch (3-tier: inline → first-byte → enum)
→ Store Operation (command isolation, map admission, entry guards, EBR)
→ Response Build (inline bulk headers, batched)
→ write(socket) → Client
Guarded concurrent hash map
Memory layout
The current 64-bit build has a 24-byte CompactKey, 24-byte SmallStr, 24-byte FyroDB enum, 32-byte StoreValue and a 64-byte, cache-line-aligned Entry<StoreValue> (#[repr(C, align(64))]). Compile-time and regression assertions cover these layouts. Payload allocations are additional memory.
CompactKey stores up to twenty-three bytes inline and has a special inline representation for eligible twenty-four-byte keys; the key fills the space the entry's 64-byte alignment would otherwise leave as padding. SmallStr stores up to twenty-three value bytes inline. Longer strings allocate payload storage. Empty shards begin with 8,192 slots and grow as needed.
CustomMap owns the map-level Access admission state, cache-padded shard metadata, published slot-table addresses, a write-observer hook and snapshot control. A shard has an insertion/growth gate and a parking_lot growth mutex. Entries hold immutable keys, a packed atomic state and mutable values. The packed state carries occupied/lock bits, reader-count information, sequence/hash information and snapshot state.
Protection layers
- Command isolation: normal commands acquire a shared worker slot. EVAL, EVALSHA, EXEC and WATCH use exclusive command admission, serializing atomic operations and waiting for ordinary commands to leave every slot. Nested redis.call/redis.pcall dispatch reuses that isolation scope.
- Map read/write admission: try_read_epoch admits a read-only batch only when no writer has registered; its second check pairs with writer registration. Writers register before waiting for admitted readers to drain. Existing writers may proceed concurrently on different entries. Thread-local nesting avoids duplicate registration for an already-held map and preserves out-of-order drops across nested maps.
- Entry read/write guards: ordinary value reads acquire a shared reader count in the packed entry state. Writers acquire the entry lock and wait for readers to leave. A map read epoch can replace repeated entry admission for an eligible batch, but it is not interchangeable with EBR. For inline strings (≤ 23 bytes), an optimistic seqlock read path clones the 24-byte SmallStr onto the caller's stack and validates state sequence consistency before serializing, bypassing reader-count CAS increments entirely while guaranteeing zero tearing under concurrent writes.
- EBR: a pin keeps retired entries and tables alive while raw pointers are examined. EBR alone does not permit concurrently reading and mutating a Rust String, Vec or collection.
- Snapshot and watch hooks: writers capture required pre-images before mutation, publish completion with the existing ordering, then notify the observing hooks. WATCH invalidation includes direct and optimized batch writes.
The sequentially consistent map-admission handshake and acquire/release entry operations remain intact. A sequence recheck after reading an unprotected mutable value is not a substitute for a read guard.
Reader and writer flow
A reader pins EBR, probes slots, validates the occupied state and full key, acquires the appropriate value protection, checks expiry/type and reads or serializes while that protection remains held. Fallback reads and collection iteration use guarded access. The guard is released before the pin can permit reclamation.
A writer enters command isolation and map write admission, probes the entry, acquires its write lock, captures a snapshot pre-image if required, mutates the value, releases the entry state and issues write-observer/durability notifications. New inserts also coordinate with shard growth. In-place overwrites avoid allocation only when existing capacity and representation suffice.
Unrelated keys still share admission counters, allocator/cache/memory bandwidth and command-isolation machinery. Contended entry operations may spin, back off or yield. There is no wait-free lookup, bounded-retry, starvation-free or linear CPU-scaling guarantee for the complete value path.
Retained large-payload algorithms
- Bounded scatter/gather GET: eligible string runs use stack RESP headers and IoSlice arrays for up to 256 replies. Each unique entry has one read guard; a fixed 512-slot ownership index resolves duplicate pointers and validates key/hash aliases. The global read epoch is released after entry guards are acquired, while the EBR pin and entry guards retain payload lifetime.
- Partial-write ownership: send attempts are bounded. Bytes that were not accepted by the socket are copied into the connection-owned output buffer before payload guards drop, preserving response order through short writes, EINTR, WouldBlock and later mutations.
- Repeated-key routing: multicore repeated large replies can use the guarded vectored path. Single-worker repeats retain the buffered copy/repeat path because the vectored alternative regressed that cohort.
- SET prefetch tiles: small multicore payloads use a shorter prefetch tile; ordinary and large payloads retain the wider batch. Key/state checks, snapshot capture, write admission and per-entry locks remain in both paths.
- Large overwrite copies: selected values of at least 8 KiB can use an AVX non-temporal copy on supported x86-64 CPUs. Alignment/tails are handled and streaming stores are fenced before completion is published. Consecutive duplicates or hash repetition select cached copying conservatively; unsupported CPUs use the ordinary copy.
- Allocation discipline: these changes use bounded local arrays rather than persistent per-key/per-connection metadata. Payload growth, fallback buffering and snapshots can still allocate.
Implementation lives in crates/customhash/src/access.rs and shard.rs, src/storage/store/isolation.rs and watch.rs, and src/handler/conn/fast_path.rs and bulk.rs. The repository architecture document links each source file.
Rejected experiments
Counter-striping variants and a later handler that retained write admission across adjacent deep small-SET batches passed correctness checks but did not establish acceptable end-to-end gains. They are not in the retained runtime. The latter reduced one diagnostic locked-access instruction count by about 0.48%, while TCP medians were mixed, including slower cases. No new speedup is credited to it.
The six added regressions cover deep binary pipelines and command boundaries, malformed/partial packets, nested admission cleanup, expiry/large-payload transitions, concurrent SET/read/SAVE and WATCH aborts. The retained source passed 789 workspace tests, zero failures, and 14 io-uring-feature large-reply tests. Evidence, full coverage and graphs.
Compact Values and Collections
- Strings use
SmallStr, keeping values up to 23 bytes inline; JSON uses a boxed recursive value representation - Hashes use compact sequential storage before promotion; lists use a quicklist of packed chunks
- Sets use sorted integers for numeric members (with $O(1)$ sequential push fast paths), a compact vector for small sets, and promote to a hash set only when needed;
sadd_added_flags_intostreams:1\r\n/:0\r\nresponses directly to connection buffers - Pipelined
JSON.GETruns prefetch cache slots and entries in parallel, streaming raw JSON payloads viawrite_bulk_raw - Promotion and demotion thresholds depend on collection type; the compact form is retained while its workload and size permit
- Sorted sets use sorted chunks of up to 256 entries plus a member-to-score index for large sets; chunk lengths support rank and range traversal
- Fast float formatting uses
ryufor zero-allocation floating point serialization
Memory Allocation and Reclamation
FyroDB uses the internal rust-zmalloc layer backed by mimalloc. Live allocated
bytes are tracked by per-CPU striped counters over every allocation, so
used_memory in INFO is the analogue of Redis's zmalloc_used_memory and
mem_fragmentation_ratio is a real rss / used figure rather than rss / rss.
That is what makes the purge and defragmentation triggers below able to fire at
all.
Memory maintenance runs outside command hot paths:
- EBR garbage collection and mimalloc collection every 10 seconds
- Fragmentation checks every 60 seconds; when RSS exceeds live bytes by more than 20%, a cursor walks one shard per tick and rebuilds a bounded number of values, so a large keyspace is never materialized at once
- Underutilized shard-table compaction every 120 seconds
FLUSHALL/FLUSHDBperform quiescent EBR collection before allocator purge
Pub/Sub
- Arc snapshot — publish reads an Arc-cloned subscriber list (zero locks)
- First-byte pattern index — patterns bucketed by first character, PUBLISH only checks relevant bucket
- Lock-free delivery & batched fanout — SegQueue per subscriber, batched worker fanout, uniform
CachedFramesharing, and 1 MBSO_SNDBUFtuning on subscriber sockets - Protocol conformance — per-channel subscribe/unsubscribe response emission directly into connection buffers without temporary
Vecallocations
Redis Lua Scripting Engine
FyroDB embeds a full Redis-compatible Lua 5.4 scripting runtime powered by mlua:
- Commands:
EVAL,EVALSHA,SCRIPT LOAD,SCRIPT EXISTS, andSCRIPT FLUSH - Pre-compiled SHA1 digest caching: Scripts are compiled once and executed repeatedly via SHA1 digest lookup with zero compile latency
- Re-entrant in-process execution:
redis.callandredis.pcallinvoke the server's command dispatcher directly against local storage without TCP loopback or process hops - Generational GC & memory limits: Isolated script state with generational garbage collection prevents memory growth across long sessions
- Zero-allocation conversions: Direct streaming between Lua primitives and RESP protocol frames
DB Cache Proxy & In-Process L1 Routing
The PostgreSQL caching proxy sits in front of upstream PostgreSQL instances while sharing memory with the KV engine:
- In-process L1 routing: Query cache hits resolve directly from shared memory structures (
L1Cache), bypassing TCP network hops - 8-slot hot query cache: Bypasses hash and normalization logic on hot repeated queries within active connections
- Zero-allocation parameter parsing: Decodes extended protocol parameters directly from wire slices
- mio worker event loop: N worker threads multiplex client connections with coalesced batch flushing (
flush_out_batched)
Vector and Full-Text Search
FT.* queries run on a persistent, optionally pinned thread pool while the network workers keep serving other clients. Job dispatch uses a lock-free SegQueue<Job> per priority tier (index builds run low), so submission never takes a lock.
HNSW graphs use fixed-stride u32 level-0 blocks for cache-line-aligned neighbour lists. Thread-local Scratch buffers hold visited-set epochs, candidate heaps, Int8 query codes, and ACORN working sets — zero hot-path allocation after warmup. Arena buffers shrink at each power-of-two node count milestone, improving cache density on streaming inserts as well as bulk builds.
FLAT fields batch concurrent queries into one parallel scan. For fields with 64 or more dimensions, the scan reads an int8 copy of each vector (a quarter of the bytes) together with a bound on its quantization error. A vector is skipped only when even its best possible distance cannot reach the current top-k. The remaining candidates are scored on their full-precision vectors, so results match a full f32 scan. The int8 copy adds about a quarter to a FLAT field's index memory.
Int8 HNSW graphs store the same error bound per node. Results are re-scored against the stored documents in order of their lower bound, and scoring stops once no remaining candidate can enter the top-k.
Negated filter sets resolve as a sorted merge over the ascending id range, using O(output) space instead of a boolean array per query.
Concurrency Model
main thread
├── N worker threads (epoll, one per core)
├── expiry/maintenance thread (incremental TTL scan every second)
├── RDB saver thread (per-slot iteration every 5min)
└── signal thread (SIGTERM → drain → save → exit)
No global lock exists on a command hot path. Workers contend only on the atomic state of the individual entry they update; table growth and compaction are isolated per shard.
In cluster mode a write no longer takes a process-wide mutex. Each worker owns an in-flight counter, and slot migration or replica snapshot bootstrap engages a fence that drains those counters — they need "no writes in flight", not mutual exclusion between writers. Slot ownership resolves through a flat 16384-entry table shared by every connection and revalidated with a single atomic load on a version counter.
See Cluster for setup and operations.
Benchmarks and current status
The current runtime is checkpoint d5a178b, image 3d5ef33d50f9. Benchmarks leads with the normal Go TCP suite, then standard clients, large payloads, memory, hot keys and rejected trials. Historical best-of-three numbers are kept separately. The latest admission-reuse experiment was reverted; no speedup from that candidate is shipped.
EBR prevents reclamation; value guards prevent concurrent mutation races; command isolation preserves Lua and transaction atomicity. None can be removed merely because a microbenchmark improves.