Skip to content
vubonPublic

About

The High-Performance, Zero-Copy In-Memory Engine for Redis-Compatible Caching & LLM KV-Cache Offloading

Resources

Code of conduct

Contributing

Security policy

Stars

14 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

90 Commits

Folders and files

KacheDB Banner

The Ultra-High Performance, Zero-Copy In-Memory Engine for Redis-Compatible Caching & LLM KV-Cache Offloading

Version Documentation Throughput Megaslab Allocator Tests Python Version License


⚑ Overview

KacheDB is an open-source, next-generation in-memory engine engineered from first principles in Rust. It unifies microsecond-latency application caching with high-throughput LLM tensor memory management in a single zero-copy architecture:

  • ⚑ Microsecond App Cache: Wire-compatible Redis & Valkey engine (RESP2 / RESP3 wire protocol) powered by an AVX-512 / NEON SIMD Swiss Table, an explicit 2 MB Megaslab bump allocator, S3-FIFO eviction, and strictly bounded $\mathcal{O}(1)$ timing wheels.
  • πŸ” Keyspace & Hash Cursor Scanning: Non-blocking SCAN and HSCAN cursor iteration across 256 shards using home-bucket bit-reversed cursors, zero-allocation glob pattern matching (*, ?, [...]), ReDoS backtracking protection, and 40-byte inline Short String Optimization (SSO).
  • πŸ€– LLM KV-Cache Offloader: Hierarchical &[u32] token prefix tree and zero-copy POSIX Shared Memory (/dev/shm) lock-free SPSC ring buffers for vLLM, SGLang, and PyTorch (17.6M msgs/sec, sub-50ns tensor sharing, 0 socket copies).
  • πŸ”’ Encrypted ACID Durability: Append-Only File (AOF) and Snapshot Format V7 (KDB\x07) with streaming hardware-accelerated AES-256-GCM or ChaCha20-Poly1305 encryption-at-rest.

πŸ₯Š Why KacheDB?

Feature / Metric Redis 7.4 Valkey 8.0 DragonflyDB KacheDB v0.4
Language C C C++ Rust πŸ¦€
Peak GET Throughput 964,654 QPS 1,033,849 QPS 2,296,822 QPS 3,563,603 QPS πŸ‘‘
Peak SET Throughput 924,900 QPS 989,303 QPS 2,047,948 QPS 3,217,341 QPS πŸ‘‘
Mixed 80/20 QPS 940,532 QPS 966,189 QPS 2,009,829 QPS 3,524,141 QPS πŸ‘‘
P50 Tail Latency 3.25 ms 3.09 ms 1.31 ms 0.70 ms πŸ‘‘
Peak Memory (RSS) 1,001 MiB 932 MiB 1.05 GiB 871.4 MiB πŸ‘‘
Memory Architecture jemalloc / Heap jemalloc / Heap Custom Slab 2 MB Megaslab (Bump + Free-list + Compaction)
Hot-Path Alloc Overhead 20–50 ns 20–50 ns 10–25 ns 3.84 ns ($\mathcal{O}(1)$)
Hash Indexing Dict / Chained Hash Dict / Chained Hash dashtable AVX-512 / NEON Swiss Table
Keyspace Cursor Scan Bucket bit-reversed Bucket bit-reversed Segmented scan Home-Bucket Bit-Reversed (256 Shards, ReDoS-Safe Glob)
Lookup Hit Latency 15–30 ns 15–30 ns 8–15 ns 1.96 ns (L1 Cache Line)
Async Network Engine epoll / kqueue epoll / kqueue epoll fiber pool Accept-Dispatch epoll + TCP_NODELAY
TTL Expiration Engine Probabilistic Sampling Probabilistic Sampling Active Scanning $\mathcal{O}(1)$ 3,600-Bucket Timing Wheel
Durability & Snapshots RDB / AOF RDB / AOF Snapshot Snapshot V7 (KDB\x07) + AOF + AEAD Encryption
LLM KV-Cache Prefix Tree ❌ None ❌ None ❌ None βœ… Native &[u32] Token Radix
Zero-Copy PyTorch IPC ❌ TCP Socket Serialization ❌ TCP Socket Serialization ❌ TCP Socket βœ… /dev/shm Lock-Free Ring

πŸš€ 10-Second Quickstart

Option 1: Pre-built Container (GitHub Container Registry)

docker run --privileged --ipc host -p 6379:6379 -d --name kachedb ghcr.io/vubon/kachedb:latest

Option 2: Run with Docker Compose (From Source)

git clone https://github.com/vubon/kachedb.git && cd kachedb
docker compose -f docker/docker-compose.yml up -d --build

Option 3: Build & Run with Cargo (Native)

cargo build --release --workspace

# Start multi-worker daemon with canonical config
./target/release/kachedb-server -c kachedb.conf

# Or override via CLI flags directly
./target/release/kachedb-server -p 6379 -w 4

Query via standard redis-cli or kachedb-cli

$ redis-cli -p 6379 SET user:100 "alice" EX 60
OK
$ redis-cli -p 6379 GET user:100
"alice"
$ redis-cli -p 6379 HSET user:100:profile name "alice" role "admin"
(integer) 2
$ redis-cli -p 6379 HGET user:100:profile name
"alice"
$ redis-cli -p 6379 SCAN 0 MATCH "user:*" COUNT 10
1) "0"
2) 1) "user:100"
   2) "user:100:profile"
$ redis-cli -p 6379 HSCAN user:100:profile 0 MATCH "r*"
1) "0"
2) 1) "role"
   2) "admin"
$ redis-cli -p 6379 TYPE user:100:profile
hash
$ redis-cli -p 6379 DBSIZE
(integer) 2

⚑ Supported Cache Commands & Protocol

KacheDB implements the standard RESP2 / RESP3 binary wire protocol. You can use any existing Redis or Valkey client library (redis-py, ioredis, go-redis, redis-rs, jedis) without code modifications:

Core Key-Value & Strings

Command Syntax Description Time Complexity
PING PING [message] Tests server liveness; returns PONG or echoed message. $\mathcal{O}(1)$
SET SET key value [EX seconds] [PX millis] Stores binary value with optional high-resolution TTL expiration. $\mathcal{O}(1)$
GET GET key Retrieves binary value, returning nil if missing or expired. $\mathcal{O}(1)$
MSET MSET key value [key value ...] Atomically stores multiple key-value pairs. $\mathcal{O}(N)$
MGET MGET key [key ...] Batch retrieves multiple keys in a single pipelined operation. $\mathcal{O}(N)$
DEL DEL key [key ...] Removes keys and immediately returns slab slots to the free-list. $\mathcal{O}(N)$
EXISTS EXISTS key [key ...] Returns the count of existing, unexpired keys. $\mathcal{O}(N)$
INCR / DECR INCR key / DECR key Increments or decrements string integer value by 1. $\mathcal{O}(1)$
INCRBY / DECRBY INCRBY key delta / DECRBY key delta Atomically adds/subtracts integer delta to/from value. $\mathcal{O}(1)$
APPEND APPEND key value Appends value to existing string, returning new byte length. $\mathcal{O}(1)$
STRLEN STRLEN key Returns byte length of string value (0 if missing). $\mathcal{O}(1)$

Redis Hash Primitives (Strict $\mathcal{O}(1)$ In-Slot Directory)

Command Syntax Description Time Complexity
HSET HSET key field value [f v ...] Sets field-value pairs in hash; returns count of newly added fields. $\mathcal{O}(M)$
HGET HGET key field Retrieves field value in hash (< 25 ns L1 CPU cacheline probe). $\mathcal{O}(1)$
HDEL HDEL key field [field ...] Removes field(s) from hash; deletes key when empty. $\mathcal{O}(M)$
HEXISTS HEXISTS key field Checks if field exists in hash (returns 1 or 0). $\mathcal{O}(1)$
HLEN HLEN key Returns the number of live fields in the hash. $\mathcal{O}(1)$
HGETALL HGETALL key Returns all fields and values in the hash as a flat array. $\mathcal{O}(N)$

Keyspace & Hash Pattern Scanning

Command Syntax Description Time Complexity
SCAN SCAN cursor [MATCH pattern] [COUNT count] [TYPE type] Incrementally iterates the keyspace across 256 shards with zero heap allocations. $\mathcal{O}(1)$ per step
HSCAN HSCAN key cursor [MATCH pattern] [COUNT count] Iterates through fields and values within a hash using glob pattern matching. $\mathcal{O}(1)$ per step

Database, Server & Observability

Command Syntax Description Time Complexity
DBSIZE DBSIZE Returns the total count of keys in the current database. $\mathcal{O}(1)$
TYPE TYPE key Returns key data type (string, hash, vector, or none). $\mathcal{O}(1)$
EXPIRE / TTL EXPIRE key seconds / TTL key Configures and queries key TTL lifecycle in $\mathcal{O}(1)$ timing wheels. $\mathcal{O}(1)$
PERSIST PERSIST key Removes TTL expiration, making key persistent. $\mathcal{O}(1)$
FLUSHDB FLUSHDB Clears all keys and recycles slab pool memory blocks. $\mathcal{O}(N)$
FLUSHALL FLUSHALL Clears all keys across all database instances. $\mathcal{O}(N)$
BGREWRITEAOF BGREWRITEAOF Compacts the append-only file in the background when AOF is enabled. β€”
INFO INFO [section] Returns real-time telemetry, memory stats, and keyspace diagnostics. $\mathcal{O}(1)$
QUIT QUIT Closes the client connection gracefully. $\mathcal{O}(1)$
COMMAND COMMAND DOCS Returns Redis protocol capability metadata. $\mathcal{O}(1)$

Binary-Safe Storage: All keys and values are treated as raw byte slices (&[u8]). Store JSON strings, raw binary tensors, Protobuf buffers, images, or compressed blobs up to 2 MB per slot without encoding overhead.


πŸ“ System Architecture

+-----------------------------------------------------------------------------------------------+
|                                      CLIENT INTERFACES                                        |
|   [RESP3 Wire Protocol (Redis/Valkey Clients)]     [Zero-Copy Tensor IPC / Python SDK]        |
+-----------------------------------------------------------------------------------------------+
                                               |
+-----------------------------------------------------------------------------------------------+
|                                       INDEXING SUBSYSTEM                                      |
|   1. SIMD Swiss Hash Table (1.96 ns Point Lookups, 256 Shards, S3-FIFO Eviction Tracking)     |
|   2. Keyspace Scanning (Bit-Reversed Radix Cursors, ReDoS-Safe Zero-Alloc Glob Matching)      |
|   3. Token Radix Prefix Tree (&[u32] Longest Prefix Match for LLM KV-Cache Prefills)          |
|   4. Per-Core Hashed Timing Wheel (3,600 Circular Buckets for O(1) Memory Reclamation)        |
+-----------------------------------------------------------------------------------------------+
                                               |
+-----------------------------------------------------------------------------------------------+
|                                  CORE SLAB & ARENA ENGINE                                     |
|   - 2 MB Megaslab Page Frames (64-byte Cache-Line Aligned Slots, 0 False Sharing)             |
|   - Zero Runtime Heap Allocation Jitter (Bump-pointer + Free-list Recycling)                  |
|   - Dynamic S3-FIFO Workload Quota Manager (App Cache vs Tensor Cache Elastic Pool)           |
+-----------------------------------------------------------------------------------------------+
                                               |
+-----------------------------------------------------------------------------------------------+
|                                 STORAGE & ZERO-COPY TRANSPORT                                 |
|   - POSIX Shared Memory (/dev/shm) Lock-Free SPSC Ring Buffer IPC (17.66M msgs/sec)           |
|   - Accept-Dispatch Thread-per-Core TCP Engine (epoll + TCP_NODELAY / mio) (3.56M QPS)        |
|   - Encrypted Durability (AOF + Snapshot V7 KDB\x07 with AES-256-GCM / ChaCha20)      |
+-----------------------------------------------------------------------------------------------+

🏎️ Benchmark Performance

πŸ“Š Comparative In-Memory Storage Benchmark

Environment: Docker Linux (Isolated 4 CPUs, 4 GB RAM per container), memtier_benchmark (50 clients, 4 threads, 16 pipeline, 64-byte value)

Storage Engine SET (Writes/sec) GET (Reads/sec) Mixed 80/20 (QPS) Latency P50 (ms) Latency P99 (ms) Peak RAM (RSS)
REDIS 7.4 924,900.44 964,653.69 940,532.39 3.25 ms 5.57 ms 1,001 MiB
VALKEY 8.0 989,302.62 1,033,848.62 966,188.94 3.09 ms 5.15 ms 932 MiB
DRAGONFLY 2,047,947.57 2,296,821.72 2,009,828.87 1.31 ms 3.78 ms 1.05 GiB
KACHEDB πŸ‘‘ 3,217,341.21 3,563,602.65 3,524,140.89 0.70 ms 3.54 ms 871.4 MiB πŸ‘‘

πŸ”¬ Subsystem Micro-Benchmarks

All micro-benchmarks evaluated with Criterion.rs in release mode (opt-level = 3):

Subsystem Operation Measured Latency Throughput / Hardware Metric
kachedb-core Megaslab Slot Allocation (AppSmall 128 B) 3.94 ns Flat $\mathcal{O}(1)$ bump allocator
kachedb-core Multi-Arena Pool Allocate + Free (AppSmall) 11.97 ns Elastic quota-safe allocation
kachedb-hash Swiss Table Point Query Hit (1M keys) 1.96 ns 510.2 Million lookups/sec / core
kachedb-hash Swiss Table 1M Keys Sequential Insert 25.85 ms βˆ’44.5% speedup via tombstone compaction
kachedb-hash Zero-Alloc Glob Pattern Matching (prefix*) 4.21 ns Linear single-star fast-path (ReDoS immune)
kachedb-radix 1,024-token Prompt Prefix Match (64 blocks) 2.48 Β΅s ~10,000Γ— speedup vs GPU prefill
kachedb-radix Bottom-up LRU Leaf Eviction 403.1 ns Sub-microsecond tensor memory reclaim
kachedb-shm POSIX Shared Memory Push/Pop Roundtrip 83.18 ns / msg 12.0 Million msgs/sec (single-thread)
kachedb-proto-resp Streaming Zero-Alloc RESP GET Decoding 86.17 ns Zero heap allocations on borrowed slice
kachedb-net Accept-Dispatch TCP Engine (Linux epoll) 0.70 ms (P50) 3.56 Million QPS (Docker Linux)
kachedb-net macOS mio / kqueue TCP (4 Workers, 100 Clients) 16 Β΅s (P50) 4.32 Million SET/s, 3.92M GET/s

πŸ“¦ Workspace Crates

kachedb/
β”œβ”€β”€ crates/
β”‚   β”œβ”€β”€ kachedb-core/             # 64-byte aligned Megaslab allocator, SlabPool & HashedTimingWheel
β”‚   β”œβ”€β”€ kachedb-hash/             # SIMD Swiss Table, bit-reversed SCAN, ReDoS-safe glob, S3-FIFO & inline SSO
β”‚   β”œβ”€β”€ kachedb-radix/            # Token prefix tree with lock-free EpochTree RCU concurrency
β”‚   β”œβ”€β”€ kachedb-vector/           # SIMD vector indexing, SQ8 quantization & HNSW search
β”‚   β”œβ”€β”€ kachedb-proto-tensor/     # 64-byte TensorBlockDescriptor & PagedAttention layouts
β”‚   β”œβ”€β”€ kachedb-shm/              # Zero-copy POSIX /dev/shm SPSC ring buffer IPC
β”‚   β”œβ”€β”€ kachedb-proto-resp/       # Zero-allocation streaming RESP2/RESP3 wire parser
β”‚   β”œβ”€β”€ kachedb-net/              # Thread-per-core async TCP engine (io_uring / mio) with non-blocking SCAN
β”‚   β”œβ”€β”€ kachedb-server/           # Multi-core daemon runtime executable with Snapshot V7 & AOF
β”‚   β”œβ”€β”€ kachedb-cli/              # Interactive CLI admin, REPL & KDB\x07 forensic inspection tool
β”‚   └── kachedb-bench/            # Standalone multi-connection pipelined load generator
β”œβ”€β”€ bindings/
β”‚   └── python/                   # Zero-copy Python client (scan_iter, hscan_iter, PyTorch & vLLM IPC)
β”œβ”€β”€ docs/
β”‚   β”œβ”€β”€ commands/                 # Complete command references (core-kv, hashes, scanning, vector)
β”‚   β”œβ”€β”€ architecture/             # Deep dive architecture specifications
β”‚   β”œβ”€β”€ rfcs/                     # Formal Architecture Decision Records (ADRs)
β”‚   └── benchmarks/               # Standardized benchmark reproduction protocol
└── docker/                       # One-command reproducible Linux io_uring container

🐍 Python Zero-Copy Client & PyTorch Integration

from kachedb import KacheClient

# Connect to KacheDB daemon over TCP
with KacheClient(host="127.0.0.1", port=6379) as client:
    # 1. Standard Redis-compatible caching with TTL
    client.set("session:user_1", "active_payload", ex=3600)
    print("Session:", client.get("session:user_1"))

    # 2. Redis Hash operations
    client.hset("user:1:profile", mapping={"name": "Alice", "role": "admin"})
    print("Role:", client.hget("user:1:profile", "role"))

    # 3. Streaming keyspace iteration with zero-allocation generator
    for key in client.scan_iter(match="session:*", count=50):
        print("Discovered key:", key.decode("utf-8"))

    # 4. Streaming Hash iteration
    for field, val in client.hscan_iter("user:1:profile", match="*"):
        print(f"Field: {field.decode('utf-8')} -> {val.decode('utf-8')}")

    # 5. Zero-copy KV-cache tensor extraction from /dev/shm (< 50 ns, 0 bytes copied)
    tensor = client.read_tensor_zero_copy(core_id=0, byte_offset=0)
    print("Zero-copy PyTorch Tensor Shape:", tensor.shape)

πŸ“š Documentation & Architecture Guides

Complete documentation, command references, and integration guides are available in the docs/ directory:


πŸ§ͺ Reproducing Benchmarks

To reproduce our performance benchmarks in an isolated Linux environment:

# Run one-command reproducible benchmark suite inside Docker
make benchmark-reproduce

For hardware specifications and step-by-step instructions, see docs/benchmarks/reproducibility.md.


🀝 Contributing

We welcome contributions from systems and AI infrastructure engineers! Please review:


πŸ“„ License

Dual-licensed under either of:

at your option.

About

The High-Performance, Zero-Copy In-Memory Engine for Redis-Compatible Caching & LLM KV-Cache Offloading

Resources

Code of conduct

Contributing

Security policy

Stars

14 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages