Storage & Persistence Architecture
Across enterprise in-memory fleets spanning hundreds to thousands of nodes, server count is governed almost entirely by live physical resident memory (used_memory_rss) plus snapshot Copy-on-Write (CoW) headroom, while dual-socket multi-core CPUs typically sit at 10%–20% average utilization.
Built atop the Linux Foundation's BSD-3-Clause Valkey 8.1.8 mainline, Engula 2.3.0 keeps the upper Redis 7.2 / Valkey 7.2+ wire parser, single-threaded command execution ordering, and 16,384-slot Cluster state machine intact while re-engineering the storage, coroutine scheduling, physical snapshot, and replication kernel beneath the hash-slot boundary.
1. Four-Layer Physical Memory Architecture
Traditional per-object allocators create separate heap allocations for every hash-chain entry, key string header, reference-counted object wrapper, and value payload—compounded by allocator size-class rounding and multi-day slab retention under variable-length writes. Engula eliminates those overheads across four orthogonal layers:
Layer 1: 64-Byte Cache-Line Bucket Slots & Logical Record IDs
- Pointer-free bucket layout: Replaces per-key doubly linked hash nodes with cache-aligned 64-byte open-addressed buckets supporting SIMD tag probing, minimizing random pointer-chasing stalls across DRAM pages.
- Embedded heat bits & logical indirection: Embeds primary LRU/LFU heat bits directly inside each bucket slot (avoiding random dereferences during eviction sampling) and stores compact logical record identifiers rather than raw heap pointers—allowing background defragmentation to relocate live records atomically without scanning or rewriting the hash table.
Layer 2: Unified Compact Records & Lossless Inline Codecs (2.3.0)
Incoming writes pack the key, variable-length TTL integer, and value payload contiguously into active writable blocks, cutting per-key internal metadata from roughly 66 bytes down to 32 bytes. High-frequency structured key patterns are compressed inline with zero dictionary-decompression cost:
- Standard 36-character UUID key-suffix codec (new in 2.3.0): Automatically encodes trailing
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx UUID strings into fixed 16-byte binary representations while preserving exact lowercase or uppercase formatting (mixed-case strings and keys ending in {hash_tag} remain untouched), saving a measured 18.0 bytes per key across 2M-key benchmarks.
- Decimal integer & hexadecimal key-suffix codecs: Losslessly pack numeric IDs and fixed-width hex digests while preserving leading zeros and letter case.
Layer 3: Shared-Dictionary Block Compression & Isolated Block Arena
- Hot/cold physical separation: Foreground writes append uncompressed compact records into active mutable blocks so the single-threaded write path never blocks on synchronous dictionary compression.
- Batch-sampled shared dictionaries + single-record decompression: Once a batch of cold records accumulates, background coroutines sample recurring JSON field names and schema prefixes to train a shared compression dictionary (Zstandard / LZ4) and compress each record individually into read-only blocks. Sub-kilobyte structured values achieve strong dictionary compression while point reads decompress only the single requested record.
- Dedicated block allocator arena (new in 2.3.0): Compressed blocks allocate from an isolated allocator arena that returns freed physical pages to the OS on an independent ~1,000 ms decay cadence, preventing small control allocations from pinning sparse OS pages. Across a 6-hour variable-length overwrite and delete soak, Redis 7.2.14 stayed pinned at 4,865 MB RSS while Engula 2.3.0 held flat at 415–417 MB RSS.
Million-member sorted sets (ZSET) in classic skiplists pay heavy per-element node and multi-level forward-pointer overhead. Engula 2.3.0 integrates the Linux Foundation Valkey open-source community's contiguous-leaf sorted-set B+ tree (upstream valkey-io/valkey PR 4359, BSD-3-Clause) verbatim:
- Memory & cache-locality gains: Packing elements into cache-aligned 512-byte leaf nodes cuts per-member footprint on 2M-member sorted sets from ~90–94 bytes down to ~51–55 bytes (over 40% savings) across
ZRANK, score/lex range queries, set algebra, GEO, and module iterators.
- Compatibility mode & upstream bug-fix contributions: Under default Redis 7.2 compatibility mode,
OBJECT ENCODING continues reporting skiplist for legacy script compatibility, paired with portable runtime AVX2 / SSE2 / NEON SIMD dispatch. During dual-encoding randomized differential verification, Engula's kernel team uncovered 6 subtle edge-case regressions (upstream Issue 4619) and contributed all fixes directly back into valkey-io/valkey mainline across PR 4637, PR 4644, and PR 4645.
2. Microsecond Stackful Coroutines & Read-Path Acceleration
Interruptible Stackful Coroutines
Initial block compression, proportional recompression, sparse-block compaction, and asynchronous large-key reclamation all execute inside cooperative stackful coroutines governed by microsecond execution budgets:
- Coroutines advance only during event-loop idle gaps and on idle I/O threads, saving register context and yielding immediately whenever client sockets become readable.
- Under sustained 50,000 ops/s write-storm benchmarks, stackful coroutines hold 4-thread foreground P99 at 2.0–2.2 ms (eliminating the 3.63 ms lock-contention spikes seen with dedicated worker threads) with 0 urgent synchronous compression stalls.
I/O-Thread Lazy Reply Decompression & Staged Prefetching
With multi-threaded network I/O enabled (io-threads 4 recommended in production), Engula decouples main-thread command serialization from multi-core reply decompression:
- Lightweight main-thread reference placeholders: On hot read commands (
GET, MGET, HMGET), the main thread resolves the hash slot, checks ACL/TTL state, and enqueues a lightweight block-reference placeholder into the client reply buffer—incrementing the block reference count without decompressing payload bytes on the main thread.
- Parallel I/O-thread decompression & hardware prefetching: Multiple I/O threads decompress records against shared dictionaries and serialize RESP frames in parallel during socket flush. In 2.3.0, staged software prefetching on 100-field
HMGET hides DRAM latency to deliver a 5.2× throughput gain over 2.2.0, scaling overall throughput to 315.7k RPS at 8 I/O threads (4.07× over single-threaded execution).
- Synchronous materialization boundaries: Commands that mutate payloads in place or consume values inside the main thread (
GETEX, SETRANGE, range slices, HSCAN, and Lua scripts) materialize records synchronously on the main thread, preserving exact single-threaded transactional semantics.
3. Native v4 Physical Block Snapshots & CoW Containment
Sequential Block Snapshots & Direct Slot Placement
With engula-rdb 1 (default), BGSAVE and SAVE write native v4 physical block snapshots (backward-compatible with reading v3 files from 2.2.2 / 2.2.3):
- Two-stage save & rehash-free load: Stage 1 streams pre-compressed memory blocks and shared dictionaries sequentially without per-key decompression or re-encoding; Stage 2 snapshots physical hash-slot positions across all 16,384 per-slot sub-tables in Cluster mode so cold loads skip per-key hash recomputation and rehashing.
- Standard process fork with progressive per-block page release: Engula 2.3.0 uses standard POSIX fork semantics for background snapshots, with lower fork latency due to smaller OS page tables. Crucially, the snapshot child releases OS physical page mappings immediately after writing each multi-page block while the parent suspends background compaction and routes incoming writes to fresh blocks.
- Measured benchmarks (vs. Redis 7.2): On the public 8 GB suite, String background snapshot save runs 13.7× faster (3.71 s vs. 50.86 s) and cold load runs 6.1× faster (2.39 s vs. 14.62 s). Under 50k ops/s random overwrites on 2M × 1 KB keys, background snapshot Copy-on-Write overhead drops from +2,324 MB (+74%) on Redis 7.2.14 to +141 MB (+14%) on Engula 2.3.0.
Three-Mode Validated Startup Recovery & Runtime Fail-Stop
To prevent media bit-rot or power-loss truncation from causing silent state corruption, Engula enforces end-to-end integrity gates (see Backup & Restore):
- Runtime Fail-Stop isolation: Any checksum mismatch on compressed blocks or internal metadata logs diagnostics, writes
engula-corruption.marker, and halts the process immediately for HA failover rather than serving corrupted bytes.
- Adaptive 3-mode startup load: Clean snapshots take the constant-time footer-reconciled fast path; benign fork-window orphan records are swept with zero key loss via filtered reference-closure bitmaps; corruption markers or Standalone-to-Cluster topology changes trigger per-record rebuild validation bounded by
engula-rdb-validate-max-drop-ratio (default 100 ppm, 128-record floor).
4. Cross-DC Resumable Replication, Dual-Buffered Switchover & Predictive Eviction
- PSYNC2 offset-resumable WAN replication & Dual-Channel fast fullsync: Across transient cross-DC link flaps and Sentinel/Cluster failovers, replicas resume from exact byte offsets in the replication backlog (
+CONTINUE with zero RDB re-transmission; 5.55 s median Sentinel failover RTO). When a full resync is required, capability-negotiated native block transfer paired with Dual-Channel Replication (dual-channel-replication-enabled) completes a 12M-key diskless fullsync in 1.83 s vs. 29.3 s (16× faster) while cutting peak replication buffers by 86% (27.9 MB vs. 200.2 MB); attaching a stock Redis 7.2 or Valkey replica automatically falls back to standard REDIS0011 logical RDB streaming.
- Dataset-scoped dual-buffered switchover & active-AOF guard: With
repl-diskless-load swapdb, incoming fullsync payloads build inside an isolated preload workspace while the active dataset continues serving reads, swapping pointers atomically upon completion or discarding cleanly on mid-transfer network drop with zero serving blackout. Release 2.3.0 also enforces an active-AOF dataset-reset guard to prevent primary/replica persistence divergence.
- 10-second EWMA predictive eviction:
engula-evict-forecast-lead-ms continuously projects net memory growth via EWMA and initiates smooth background eviction and synchronous defragmentation 10,000 ms before hitting the maxmemory wall.
Related Documentation