KacheDB Documentation
The High-Performance, Zero-Copy In-Memory Engine for Redis-Compatible Caching & LLM KV-Cache Offloading
๐ Welcome to the KacheDB Documentation
KacheDB is an open-source, next-generation in-memory storage engine engineered from first principles in Rust. It bridges the gap between traditional microsecond application caching (Redis / Valkey workloads) and multi-gigabyte tensor state offloading for Large Language Model (LLM) inference engines (vLLM, SGLang, PyTorch).
๐บ๏ธ Documentation Sitemap
๐ Getting Started
- Quickstart Guide: Build from source, run via Cargo or Docker, and query via CLI.
- kachedb-cli User Guide: Interactive terminal REPL and built-in throughput benchmark harness.
- Server Configuration & Tuning: Worker threads, CPU pinning, memory pool sizing, and kernel bypass settings.
โก Command Reference
- Core Key-Value Commands:
GET,SET,MGET,MSET,DEL,EXISTS,INCR,DECR,APPEND,STRLEN,DBSIZE,TYPE,FLUSHDB,FLUSHALL,PING. - Redis Hash Primitives:
HSET,HGET,HDEL,HEXISTS,HLEN,HGETALL, in-slot directory architecture, and Megaslab packing. - Keyspace & Hash Cursor Scanning:
SCAN,HSCAN, home-bucket bit-reversed cursors across 256 shards, ReDoS-safe zero-alloc glob matching, and inline SSO. - TTL & Key Lifecycle Commands:
EXPIRE,PEXPIRE,EXPIREAT,PEXPIREAT,TTL,PTTL,PERSIST, and the background Timing Wheel. - SIMD Semantic Vector Commands:
VADD,VSEARCH,VADD_BATCH,VSEARCH_BATCH,VDEL,VSTATS,VINDEX, ARM NEON / AVX2 kernels. - Server Observability & Introspection:
INFO,COMMAND DOCS,HELLO 2/3,AUTH,CLIENT SETNAME/GETNAME/ID/LIST,BGREWRITEAOF,QUIT.
๐๏ธ System Architecture
- System Architecture Overview: High-level system design, thread-per-core model, and the physical memory hierarchy.
- 2 MB Megaslab Memory Engine: Slotted slab bump allocator, 64-byte cache-line alignment, and S3-FIFO quota manager.
- Token Radix Prefix Tree: Hierarchical
&[u32]token prefix tree, sub-microsecond prefill lookup, and Epoch RCU concurrency. - Zero-Copy Shared Memory IPC: POSIX
/dev/shmlock-free ring buffers and PCIe line-rate tensor sharing. - Snapshot Encryption-at-Rest: Hardware-accelerated AES-256-GCM / ChaCha20-Poly1305 streaming AEAD encryption, HKDF key derivation, and
KDB\x07snapshots.
๐ค Production Integration Guides
- vLLM Integration Guide: Drop-in PagedAttention KV connector for vLLM inference servers.
- SGLang Integration Guide: RadixAttention tree-branching prefill offloading with SGLang.
- Semantic Caching Guide: High-throughput sync and async prompt caching with
kachedb-pyand FastEmbed/HuggingFace. - Antigravity IDE Integration Guide: Autonomous agent memory and semantic caching for Antigravity IDE coding agents.
๐ Performance & Benchmarks
- Consolidated Master Benchmark Report: Criterion micro-benchmarks, latency percentiles, and hardware comparisons against Redis 7.4, Valkey 8.0, and DragonflyDB.
- Benchmark Artifacts & Logs: Raw test outputs, multi-phase scaling reports, and reproducibility scripts.
๐ Quickstart Guide
Get up and running with KacheDB in less than 60 seconds.
๐ฆ Installation & Deployment Options
Option 1: Run with Pre-Built Docker Image (Recommended for Cloud/Production)
KacheDB publishes official multi-architecture container images (linux/amd64 and linux/arm64) to the GitHub Container Registry:
# Run with host IPC for zero-copy POSIX Shared Memory support
docker run --privileged --ipc host -p 6379:6379 -d --name kachedb ghcr.io/vubon/kachedb:latest
Verify the container is running:
docker logs kachedb
Option 2: Build & Run from Source with Cargo
Prerequisites
- Rust Toolchain: 2024 edition (
rustc >= 1.85.0) - OS: Linux (kernel 5.10+ recommended for
io_uring) or macOS (Apple Silicon / Intel withkqueue)
# 1. Clone the repository
git clone https://github.com/vubon/kachedb.git
cd kachedb
# 2. Compile release binaries across all workspace crates
cargo build --release --workspace
# 3. Start the KacheDB multi-core daemon on default port 6379 with 4 worker threads
./target/release/kachedb-server -p 6379 -w 4
Option 3: Run with Docker Compose
git clone https://github.com/vubon/kachedb.git
cd kachedb
docker compose -f docker/docker-compose.yml up -d --build
โก Connecting to KacheDB
1. Using the Interactive kachedb-cli
KacheDB includes a built-in terminal CLI with colorized output and syntax assistance:
# Start interactive REPL connected to localhost:6379
./target/release/kachedb-cli -p 6379
Try some basic commands:
127.0.0.1:6379> PING
PONG
127.0.0.1:6379> SET user:100 "alice" EX 60
OK
127.0.0.1:6379> GET user:100
"alice"
127.0.0.1:6379> TTL user:100
(integer) 58
127.0.0.1:6379> INCR counter
(integer) 1
127.0.0.1:6379> INFO
# Server
kachedb_version:0.3.0
os:macos
arch_bits:64
...
2. Using Standard redis-cli
Because KacheDB implements the standard Redis RESP2/RESP3 wire protocol, you can use any existing redis-cli tool:
# Connect using standard redis-cli
redis-cli -p 6379
127.0.0.1:6379> MSET key1 "val1" key2 "val2"
OK
127.0.0.1:6379> MGET key1 key2 missing_key
1) "val1"
2) "val2"
3) (nil)
3. Using the Official Python SDK (kachedb-py)
Install the client SDK:
pip install kachedb
Synchronous usage:
from kachedb import KacheClient
with KacheClient(host="127.0.0.1", port=6379) as client:
client.set("greeting", "Hello from Python", ex=300)
val = client.get("greeting")
print(val) # b'Hello from Python'
Asynchronous usage (asyncio):
import asyncio
from kachedb import AsyncKacheClient
async def main():
async with AsyncKacheClient(host="127.0.0.1", port=6379) as client:
await client.set("session:abc", "active_data", ex=120)
res = await client.get("session:abc")
print(res)
asyncio.run(main())
๐ฏ Next Steps
- Explore all supported operations in the Core Key-Value Command Reference.
- Learn about active memory reclamation in TTL & Key Lifecycle Guide.
- Perform nearest-neighbor vector queries in the SIMD Vector Search Guide.
- Offload LLM prompt prefill compute in the vLLM Integration Guide.
๐ป kachedb-cli User Guide
kachedb-cli is the native command-line interface and benchmarking utility for KacheDB. It provides an interactive REPL with formatted RESP rendering, auto-reconnect capabilities, and a high-performance live throughput benchmarking harness.
๐ ๏ธ Usage & Command-Line Flags
kachedb-cli [OPTIONS]
kachedb-cli snapshot-info <FILE.kdb>
Options Reference
| Flag | Long Flag | Description | Default |
|---|---|---|---|
-h | --host <HOST> | Target KacheDB server hostname or IP address | 127.0.0.1 |
-p | --port <PORT> | Target KacheDB server TCP port | 6379 |
-b | --bench | Execute a high-speed throughput benchmark | false |
-n | -n <NUM> | Total number of requests in benchmark mode | 10,000 |
snapshot-info <FILE> | Offline inspection of binary snapshot format, cipher, and CRC32 | ||
--help | Display command help and usage flags |
๐ฌ Interactive REPL Mode
Starting kachedb-cli without --bench enters interactive REPL mode:
./target/release/kachedb-cli -h 127.0.0.1 -p 6379
Banner & Prompt
Upon connection, kachedb-cli displays the ASCII logo and prompt:
_ __ _ _____ ____ _____ _ _____
| |/ / | | | __ \| _ \ / ____| | |_ _|
| ' / __ _ ___| |__ ___| | | | |_) | | | | | |
| < / _` |/ __| '_ \ / _ \ | | | _ <| | | | | |
| . \ (_| | (__| | | | __/ |__| | |_) | |____| |____ _| |_
|_|\_\__,_|\___|_| |_|\___|_____/|____/ \_____|______|_____|
Connecting to KacheDB at 127.0.0.1:6379...
โก Connected to KacheDB. Type commands or 'help' / 'quit'.
127.0.0.1:6379>
โก REPL Commands & Examples
1. Key-Value & Strings
127.0.0.1:6379> SET user:1 "Alice Smith"
OK
127.0.0.1:6379> GET user:1
"Alice Smith"
127.0.0.1:6379> APPEND user:1 " (Admin)"
(integer) 19
127.0.0.1:6379> GET user:1
"Alice Smith (Admin)"
127.0.0.1:6379> STRLEN user:1
(integer) 19
2. Atomic Counters
127.0.0.1:6379> INCR visits
(integer) 1
127.0.0.1:6379> INCRBY visits 10
(integer) 11
127.0.0.1:6379> DECR visits
(integer) 10
127.0.0.1:6379> DECRBY visits 5
(integer) 5
3. Expiration & TTL Management
127.0.0.1:6379> SET session:temp "xyz" EX 60
OK
127.0.0.1:6379> TTL session:temp
(integer) 58
127.0.0.1:6379> PERSIST session:temp
(integer) 1
127.0.0.1:6379> TTL session:temp
(integer) -1
4. Redis Hash Primitives
127.0.0.1:6379> HSET user:100 name "Alice Smith" role "admin" email "alice@example.com"
(integer) 3
127.0.0.1:6379> HGET user:100 name
"Alice Smith"
127.0.0.1:6379> HEXISTS user:100 role
(integer) 1
127.0.0.1:6379> HLEN user:100
(integer) 3
127.0.0.1:6379> HGETALL user:100
1) "name"
2) "Alice Smith"
3) "role"
4) "admin"
5) "email"
6) "alice@example.com"
127.0.0.1:6379> HDEL user:100 role
(integer) 1
5. Vector Ingestion & Nearest Neighbor Search
# Store a 4-dimensional vector in index 'docs' with ID 'doc:1'
127.0.0.1:6379> VADD docs doc:1 4 "\x00\x00\x80?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" PAYLOAD "Introduction to KacheDB" EX 3600
OK
# Search index 'docs' for closest vector matches
127.0.0.1:6379> VSEARCH docs "\x00\x00\x80?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" TOPK 1 THRESHOLD 0.8
1) 1) "doc:1"
2) "1.000000"
3) "Introduction to KacheDB"
# Check vector index statistics
127.0.0.1:6379> VSTATS docs
1) "dimension"
2) (integer) 4
3) "total_vectors"
4) (integer) 1
5) "active_vectors"
6) (integer) 1
6) "memory_bytes"
8) (integer) 64
6. Introspection & Diagnostics
127.0.0.1:6379> INFO
# Server
kachedb_version:0.3.0
os:macos
arch_bits:64
process_id:48123
tcp_port:6379
uptime_in_seconds:342
# Memory
used_memory:134217728
used_memory_human:128.00M
used_memory_peak:134217728
megaslabs_allocated:64
slab_slots_active:1024
fragmentation_ratio:1.00
# Stats
total_connections_received:42
total_commands_processed:15234
instantaneous_ops_per_sec:0
keyspace_hits:14200
keyspace_misses:1034
7. Built-in REPL Helper Commands
help: Displays a quick command reference card.clear: Clears the terminal screen.quit/exit: Closes the connection and exits the CLI.
๐ฅ Live Benchmark Mode (--bench)
You can measure raw network round-trip throughput and latency using the built-in benchmark harness:
# Run a 100,000-request pipelined benchmark against localhost
./target/release/kachedb-cli -p 6379 --bench -n 100000
Example Benchmark Output
๐ฅ Connecting to 127.0.0.1:6379 for live benchmark (100,000 requests)...
โก Pipelining 100,000 PING commands...
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
KacheDB Live Benchmark Report
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Requests: 100,000
Total Elapsed: 34.28 ms
Throughput: 2,916,742 ops/sec
Average Latency: 342.8 ns / op
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ Offline Snapshot Inspection Mode (snapshot-info)
kachedb-cli provides an offline diagnostic subcommand to inspect KacheDB binary snapshots (dump.kdb) without launching a server or connecting over TCP:
./target/release/kachedb-cli snapshot-info /var/lib/kachedb/dump.kdb
What snapshot-info Inspects:
- File Size & Integrity: Reads and verifies IEEE 802.3 CRC32 checksum trailer over the entire snapshot file.
- Format Version: Identifies
KDB\x02(legacy unencrypted),KDB\x03(authenticated snapshot format),KDB\x04(typed KV records + Redis Hash entries),KDB\x05(named KV records),KDB\x06(exact key identity, including empty keys), andKDB\x07(AOF checkpoints and HNSW graphs). - Creation Timestamp: Displays the Unix epoch creation timestamp.
- Encryption Status: Checks whether encryption is active (
ENABLEDvsDisabled (Plaintext)). - Cipher Suite: Identifies
AES-256-GCMorChaCha20-Poly1305. - Cryptographic Metadata: Displays the 256-bit random HKDF salt and 96-bit master nonce in hexadecimal format.
Example Inspection Output
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ฆ KacheDB Snapshot Inspection: "dump.kdb"
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
File Size: 430 bytes (0.42 KB)
Checksum (CRC32): 0x295f2f0d [VALID]
Format Version: v4 (Typed KV + Redis Hashes)
Created Timestamp: 1790481552 (Unix Epoch)
Flags: 0x00000001
Encryption: ENABLED
Cipher Suite: AES-256-GCM (Hardware Accelerated)
Salt (256-bit): dafd90590dc19b358f8e76fd11a0430b07dc0b5881c063987a3c7619379147ff
Master Nonce: b8fe98eb980ea4d551497618
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ๏ธ Server Configuration & Tuning
This guide covers operational parameters, memory pool configuration, CPU core pinning, and kernel bypass tuning for KacheDB.
๐ Daemon Command-Line Arguments (kachedb-server)
The kachedb-server binary accepts several command-line flags to control hardware allocation and network binding:
./target/release/kachedb-server [OPTIONS]
Options Reference
| Flag | Long Option | Description | Default | Recommended Production |
|---|---|---|---|---|
-c | --config <PATH> | Path to configuration file (e.g., kachedb.conf) | None | /etc/kachedb/kachedb.conf |
-p | --port <PORT> | TCP listening port | 6379 | 6379 |
-w | --workers <NUM> | Number of worker threads (1 per CPU core) | Auto (all physical cores) | Equal to physical CPU cores |
--pool-mb <MB> | Megaslab memory pool allocated per core in megabytes | 64 | 256 or 1024 | |
--maxclients <NUM> | Maximum simultaneous client connections | 10000 | 10000โ65535 | |
--requirepass <PASS> | Password required for client authentication via AUTH | None | Set strong password | |
--snapshot / --no-snapshot | Enable or disable periodic binary snapshotting | true | true | |
--snapshot-file <PATH> | Path to binary snapshot file (dbfilename) | dump.kdb | /var/lib/kachedb/dump.kdb | |
--snapshot-interval <SECS> | Interval in seconds between snapshots | 300 | 300โ900 | |
--snapshot-encryption | Enable AES-256-GCM / ChaCha20 streaming encryption | false | true (for sensitive/KV data) | |
--snapshot-cipher <CIPHER> | AEAD cipher (aes-256-gcm or chacha20-poly1305) | aes-256-gcm | aes-256-gcm | |
--snapshot-key <KEY> | Secret passphrase or 64-character hex key | None | Passphrase or hex string | |
--snapshot-key-file <PATH> | Path to 32-byte raw binary master key file | None | /etc/kachedb/snapshot.key | |
--aof | Enable Append-Only File (AOF) persistence | false | true (if durability needed) | |
--aof-path <PATH> | Path to Append-Only File log | kachedb.aof | /var/lib/kachedb/kachedb.aof | |
--appendfsync <POLICY> | AOF disk sync policy (always, everysec, no) | everysec | everysec | |
--shm <true|false> | Enable POSIX Shared Memory (/dev/shm) IPC | true | true | |
--tls-cert <PATH> | Path to TLS server certificate PEM file | None | Optional | |
--tls-key <PATH> | Path to TLS private key PEM file | None | Optional | |
--tls-ca <PATH> | Optional path to CA certificate for mTLS verification | None | Optional |
๐ Configuration File (kachedb.conf)
KacheDB supports declarative configuration using a canonical kachedb.conf file:
# Network & Binding
bind 127.0.0.1
port 6379
maxclients 10000
# Worker Threads & Memory
workers 4
pool_mb_per_core 256
# IPC & LLM Tensor Streaming
shm yes
# Binary Snapshotting & Encryption-at-Rest
snapshot yes
dbfilename dump.kdb
snapshot-interval 300
snapshot-encryption yes
snapshot-encryption-cipher aes-256-gcm
# snapshot-encryption-key-file /etc/kachedb/snapshot.key
snapshot-encryption-key "your_secret_passphrase_here"
# Persistence (Append-Only File)
appendonly no
appendfilename kachedb.aof
appendfsync everysec
# Security
# requirepass my_secret_token
To launch kachedb-server using the configuration file:
./target/release/kachedb-server -c /path/to/kachedb.conf
Note: Any explicit CLI flags will take precedence over directives inside the configuration file.
๐งต Thread-per-Core Topology & CPU Pinning
KacheDB operates on a shared-nothing, thread-per-core architecture:
- Each active worker thread is pinned to a dedicated physical CPU core using
core_affinity. - Zero Cross-Core Contention: Each worker thread owns its private 2 MB Megaslab arena pool and independent Swiss Table shard.
- Request execution requires no global mutex locks, eliminating lock contention and cache-line bouncing.
Example: Running on a Dedicated 8-Core Node
# Pin 8 workers to cores 0..7 with 512 MB memory per core (4 GB total)
./target/release/kachedb-server -p 6379 -w 8 --pool-mb 512
๐งฑ Memory Sizing & S3-FIFO Quota Management
Memory is managed through uniform 2 MB Megaslabs:
- Rather than calling
malloc()on every request, KacheDB pre-allocates contiguous megaslab page frames. - Per-Core Sizing: If
--pool-mbis set to256on a 4-core machine, total initial memory allocated across the daemon is $4 \times 256\text{ MB} = 1.024\text{ GB}$. - Elastic Borrowing: The dynamic
WorkloadQuotamanager elastically allocates megaslabs between application key-value cache and tensor memory based on current demand.
RESP request limits
A connection can buffer up to 64 MiB of unread RESP input. Each command can use up to 64 MiB including framing, 2 MiB per argument, and 65,536 arguments including the command name. The limits apply to plaintext and TLS connections. Pipelined commands each get a separate command budget. A request that exceeds a protocol limit closes the connection.
AOF Durability and Repair
Set appendfsync in the configuration file or pass --appendfsync when launching the server.
| Policy | When a write returns success | Full queue |
|---|---|---|
always | After the record is written and synced | Waits up to one second before rejecting the write |
everysec | After publication and queueing, with a background sync about once per second | Rejects immediately |
no | After publication and queueing, with the OS responsible for routine flushing | Rejects immediately |
A rejected admission leaves the data unchanged. An error reporting an uncertain outcome means the change was already published and its record may be on disk. The server rejects further writes once it detects AOF failure. Successful checkpoints and clean shutdowns sync the journal under every policy.
Background compaction writes a self-contained base and collects up to 64 MiB or 65,536 later records while the active journal continues receiving writes. If the delta budget is exhausted, the server abandons the rewrite and keeps the active journal. After a successful swap, startup uses the embedded base. Its integrity is checked by CRC32, and it is stored in plaintext like the rest of the AOF.
Startup validates journal framing and requires a compatible snapshot when the journal depends on one. It automatically removes an incomplete final record only when the length header is intact and checksummed. For framing damage or an ambiguous tail, stop the server and use the offline repair command:
kachedb-server --aof-repair --aof-file /var/lib/kachedb/kachedb.aof
Repair writes a separate copy of the original journal, then truncates at the end of the last valid frame. A damaged embedded base payload requires recovery from another copy. All records after that point are discarded. If the retained prefix ends before a required snapshot checkpoint, startup reports the mismatch.
๐ Snapshot Encryption-at-Rest Configuration
KacheDB provides zero hot-path overhead streaming AEAD encryption for on-disk snapshots (dump.kdb).
Configuration Directives & CLI Flags
kachedb.conf Directive | CLI Flag Equivalent | Default | Description |
|---|---|---|---|
snapshot-encryption yes|no | --snapshot-encryption, --no-snapshot-encryption | no | Enable or disable authenticated streaming encryption for snapshots. |
snapshot-encryption-cipher <name> | --snapshot-cipher <cipher> | aes-256-gcm | AEAD cipher suite: aes-256-gcm (hardware-accelerated) or chacha20-poly1305. |
snapshot-encryption-key-file <path> | --snapshot-key-file <path> | None | Path to a 32-byte binary master key file (recommended for production). |
snapshot-encryption-key <string> | --snapshot-key <key> | None | 64-character hexadecimal key or variable-length passphrase (derived via HKDF-SHA256). |
Example CLI Launch
# Start daemon with hardware AES-256-GCM encryption using a binary key file
./target/release/kachedb-server -c kachedb.conf \
--snapshot-encryption \
--snapshot-cipher aes-256-gcm \
--snapshot-key-file /etc/kachedb/snapshot.key
For the comprehensive wire format (KDB\x03) and security architecture, see Snapshot Encryption-at-Rest.
๐ง Linux Kernel & io_uring Tuning
For maximum throughput on Linux (> 2.5M QPS), apply the following kernel optimizations:
1. somaxconn & TCP Backlog
sudo sysctl -w net.core.somaxconn=65535
sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535
2. POSIX Shared Memory Limits (/dev/shm)
Ensure /dev/shm has sufficient space for high-volume LLM KV-cache offloading:
# Verify current /dev/shm size
df -h /dev/shm
# Remount /dev/shm with 32 GB (if serving 70B+ LLM inference nodes)
sudo mount -o remount,size=32G /dev/shm
3. File Descriptor Limits
ulimit -n 1048576
๐ณ Production Docker Configuration
Here is the recommended production docker-compose.yml:
services:
kachedb:
image: ghcr.io/vubon/kachedb:latest
container_name: kachedb
privileged: true
ipc: host
network_mode: host
restart: always
command: ["-p", "6379", "-w", "4", "--pool-mb", "256"]
ulimits:
nofile:
soft: 1048576
hard: 1048576
memlock:
soft: -1
hard: -1
๐ Core Key-Value Commands
KacheDB implements the standard Redis / Valkey RESP2 and RESP3 binary wire protocol for standard key-value operations. All keys and values are treated as raw byte slices (&[u8]) and stored with zero heap allocation overhead inside 64-byte aligned Megaslab slots.
๐ Command Summary
| Command | Syntax | Complexity | Description |
|---|---|---|---|
PING | PING [message] | O(1) | Tests server liveness; returns PONG or echoed message. |
GET | GET key | O(1) | Retrieves binary value; returns nil if missing or expired. |
SET | SET key value [EX seconds] [PX millis] | O(1) | Stores binary value with optional TTL expiration. |
MGET | MGET key [key ...] | O(N) | Batch retrieves multiple keys in a single pipelined operation. |
MSET | MSET key value [key value ...] | O(N) | Atomically stores multiple key-value pairs. |
DEL | DEL key [key ...] | O(N) | Deletes keys and immediately frees Megaslab slots. |
EXISTS | EXISTS key [key ...] | O(N) | Returns the count of existing, unexpired keys. |
INCR | INCR key | O(1) | Atomically increments string integer value by 1. |
DECR | DECR key | O(1) | Atomically decrements string integer value by 1. |
INCRBY | INCRBY key delta | O(1) | Atomically increments string integer value by delta. |
DECRBY | DECRBY key delta | O(1) | Atomically decrements string integer value by delta. |
APPEND | APPEND key value | O(1) | Appends value to existing string, returning new byte length. |
STRLEN | STRLEN key | O(1) | Returns length of string value in bytes (0 if missing). |
DBSIZE | DBSIZE | O(1) | Returns the total number of stored keys in the database. |
TYPE | TYPE key | O(1) | Returns the string representation of the key's type (string, hash, vector, or none). |
FLUSHDB | FLUSHDB | O(N) | Removes all keys from the currently selected database. |
FLUSHALL | FLUSHALL | O(N) | Removes all keys from all databases and resets Megaslab allocators. |
SCAN | SCAN cursor [MATCH pattern] [COUNT count] [TYPE type] | O(1) per call | Incrementally iterates the keyspace with non-blocking cursors. See Keyspace Scanning. |
๐ ๏ธ Detailed Command Reference & Examples
SET & GET
Stores and retrieves binary-safe values up to 2 MB per slot.
Syntax
SET key value [EX seconds] [PX milliseconds]
GET key
kachedb-cli Example
127.0.0.1:6379> SET user:100 "Alice"
OK
127.0.0.1:6379> GET user:100
"Alice"
127.0.0.1:6379> SET session:temp "abc123xyz" EX 30
OK
127.0.0.1:6379> GET missing_key
(nil)
Python SDK Example
with KacheClient() as client:
client.set("user:100", "Alice")
val = client.get("user:100") # b'Alice'
MSET & MGET
MSET applies the entire batch in memory. If validation or allocation fails, existing keys keep their values and TTLs. The last value wins when a key appears more than once. MGET reads all requested keys under shared shard locks, so a concurrent MSET appears as a complete update.
Syntax
MSET key value [key value ...]
MGET key [key ...]
kachedb-cli Example
127.0.0.1:6379> MSET config:theme "dark" config:lang "en" config:tz "UTC"
OK
127.0.0.1:6379> MGET config:theme config:lang config:missing config:tz
1) "dark"
2) "en"
3) (nil)
4) "UTC"
INCR, DECR, INCRBY, DECRBY
Atomic integer arithmetic executed in-place on string values. If the key does not exist, it is initialized to 0 before applying the operation.
Syntax
INCR key
DECR key
INCRBY key delta
DECRBY key delta
kachedb-cli Example
127.0.0.1:6379> INCR page_views
(integer) 1
127.0.0.1:6379> INCRBY page_views 100
(integer) 101
127.0.0.1:6379> DECR page_views
(integer) 100
127.0.0.1:6379> DECRBY page_views 50
(integer) 50
APPEND & STRLEN
String manipulation and length inspection.
Syntax
APPEND key value
STRLEN key
kachedb-cli Example
127.0.0.1:6379> SET doc:title "KacheDB"
OK
127.0.0.1:6379> APPEND doc:title " Architecture"
(integer) 20
127.0.0.1:6379> GET doc:title
"KacheDB Architecture"
127.0.0.1:6379> STRLEN doc:title
(integer) 20
DEL & EXISTS
Key deletion and existence verification.
Syntax
DEL key [key ...]
EXISTS key [key ...]
kachedb-cli Example
127.0.0.1:6379> EXISTS user:1 user:2
(integer) 1
127.0.0.1:6379> DEL user:1 user:2
(integer) 1
127.0.0.1:6379> EXISTS user:1
(integer) 0
DBSIZE
Returns the count of active, unexpired keys stored in the database.
Syntax
DBSIZE
kachedb-cli Example
127.0.0.1:6379> SET k1 "v1"
OK
127.0.0.1:6379> SET k2 "v2"
OK
127.0.0.1:6379> DBSIZE
(integer) 2
TYPE
Returns the underlying data structure type of the specified key (string, hash, vector, or none).
Syntax
TYPE key
kachedb-cli Example
127.0.0.1:6379> SET greeting "hello"
OK
127.0.0.1:6379> TYPE greeting
string
127.0.0.1:6379> HSET user:100 name "Alice"
(integer) 1
127.0.0.1:6379> TYPE user:100
hash
127.0.0.1:6379> TYPE nonexistent
none
Type Safety & Type Guards: KacheDB enforces strict type checking. Executing string operations (
GET,APPEND,STRLEN,INCR, etc.) against a key holding a hash will return(error) WRONGTYPE Operation against a key holding the wrong kind of value. In batch reads,MGETreturns(nil)for non-string keys. See Redis Hash Primitives for full details on hash operations.
FLUSHDB & FLUSHALL
Deletes all keys in the database and recycles Megaslab blocks back to the free-list.
Syntax
FLUSHDB
FLUSHALL
kachedb-cli Example
127.0.0.1:6379> DBSIZE
(integer) 1000
127.0.0.1:6379> FLUSHDB
OK
127.0.0.1:6379> DBSIZE
(integer) 0
SCAN
Incrementally iterates the keyspace across 256 shards using home-bucket bit-reversed cursors without blocking or allocating temporary buffers.
Syntax
SCAN cursor [MATCH pattern] [COUNT count] [TYPE type]
kachedb-cli Example
127.0.0.1:6379> SCAN 0 MATCH "user:*" COUNT 10
1) "0"
2) 1) "user:100"
For detailed algorithmic properties, composite cursor layout, and glob pattern rules, see the dedicated Keyspace & Hash Cursor Scanning Guide.
๐ฆ Redis Hash Primitives
KacheDB provides high-performance, strictly $\mathcal{O}(1)$ Redis Hash commands (HSET, HGET, HDEL, HEXISTS, HLEN, HGETALL) over the standard RESP2 and RESP3 wire protocol.
Unlike traditional in-memory stores that rely on linked-list linear scans (listpack) or pointer-chasing heap structures (dictEntry), KacheDB implements an in-slot open-addressing directory packed directly inside pre-allocated 64-byte aligned Megaslab slots.
๐ Command Summary
| Command | Syntax | Complexity | Description |
|---|---|---|---|
HSET | HSET key field value [field value ...] | $\mathcal{O}(M)$ | Sets field-value pairs in the hash. Probing each pair is strictly $\mathcal{O}(1)$. Returns the count of newly added fields. |
HGET | HGET key field | Strict $\mathcal{O}(1)$ | Retrieves the binary value of the specified field; returns (nil) if the key or field is missing. |
HDEL | HDEL key field [field ...] | $\mathcal{O}(M)$ | Removes field(s) from the hash. Returns the number of fields removed. Deletes the key if the hash becomes empty. |
HEXISTS | HEXISTS key field | Strict $\mathcal{O}(1)$ | Returns 1 if the field exists in the hash, or 0 if the key or field does not exist. |
HLEN | HLEN key | $\mathcal{O}(1)$ | Returns the number of live fields in the hash; returns 0 if the key does not exist. |
HGETALL | HGETALL key | $\mathcal{O}(N)$ | Returns a flat array of all field-value pairs [field1, val1, field2, val2, ...]; returns an empty list if the key does not exist. |
HSCAN | HSCAN key cursor [MATCH pattern] [COUNT count] | $\mathcal{O}(1)$ per step, $\mathcal{O}(F)$ full hash | Iterates through fields and values within a hash using glob pattern matching. |
- $M$ = number of fields in the request; $N$ = total live fields stored in the hash; $F$ = total live fields matching the scan criteria.
๐๏ธ Architecture & Strict $\mathcal{O}(1)$ In-Slot Directory
Traditional Redis stores hashes in two encodings:
listpack($\le 512$ fields): Linear byte array where every read and write is $\mathcal{O}(N)$ linear scan withmemmove()memory reallocation.dict($> 512$ fields): Chained hash table with 3 heap allocations per field (dictEntry, keysds, valuesds), consuming 50โ80 bytes of pointer overhead per field and pointer-chasing CPU cache misses (~80โ120 ns).
The KacheDB In-Slot Directory
KacheDB embeds both data payload and open-addressing hash table directory directly into a single slab slot:
+---------------------------------------------------------------------------------------+
| Header (8B) | Payloads Area (f1:v1, f2:v2, ...) | Directory Buckets (Tail of Slot) |
| count: u16 | Contiguous raw byte slices | Open-addressing table of K buckets |
| deleted: u16 | Length-prefixed keys & values | [hash32: u32, offset: u16, ...] |
+---------------------------------------------------------------------------------------+
- Sub-25 ns Lookups: Probing computes
bucket_idx = hash32 & (K - 1). At load factor $\le 0.70$, probes resolve in 1.1โ1.3 bucket steps, executing within the exact same 64-byte L1 CPU cache line. - Zero Heap Allocations: For requests with 8 or fewer field pairs, operations allocate zero heap memory (
SmallVecstack buffer). - App-Cache Megaslab Isolation: Hashes strictly reside in
AppSmall(128 B),AppMedium(512 B), orAppLarge(4 KB) slots. Slots are automatically upgraded as fields grow. - Type Safety: The key type is tracked via
value_type = VALUE_TYPE_HASHin the 64-byte SwissTable entry. String commands (GET,APPEND,INCR) reject hash keys with-WRONGTYPE Operation against a key holding the wrong kind of value.
๐ ๏ธ Detailed Command Reference & Examples
HSET
Sets one or more field-value pairs in a hash. If the key does not exist, a new hash is created. If a field already exists, its value is overwritten.
Syntax
HSET key field value [field value ...]
kachedb-cli / redis-cli Example
127.0.0.1:6379> HSET user:1000 name "Alice Smith" email "alice@example.com" role "admin"
(integer) 3
127.0.0.1:6379> HSET user:1000 role "superadmin" age "32"
(integer) 1
HGET
Retrieves the value associated with field in the hash stored at key.
Syntax
HGET key field
kachedb-cli / redis-cli Example
127.0.0.1:6379> HGET user:1000 name
"Alice Smith"
127.0.0.1:6379> HGET user:1000 role
"superadmin"
127.0.0.1:6379> HGET user:1000 missing_field
(nil)
HDEL
Removes the specified field(s) from the hash. If all fields are deleted, the parent key is removed from the database and its slab slot is reclaimed.
Syntax
HDEL key field [field ...]
kachedb-cli / redis-cli Example
127.0.0.1:6379> HDEL user:1000 age non_existing
(integer) 1
127.0.0.1:6379> HEXISTS user:1000 age
(integer) 0
HEXISTS
Determines if a hash field exists.
Syntax
HEXISTS key field
kachedb-cli / redis-cli Example
127.0.0.1:6379> HEXISTS user:1000 email
(integer) 1
127.0.0.1:6379> HEXISTS user:1000 phone
(integer) 0
HLEN
Returns the number of live fields contained in the hash.
Syntax
HLEN key
kachedb-cli / redis-cli Example
127.0.0.1:6379> HLEN user:1000
(integer) 3
HGETALL
Returns all fields and values of the hash stored at key as a flat array of alternating [field1, value1, field2, value2, ...].
Syntax
HGETALL key
kachedb-cli / redis-cli Example
127.0.0.1:6379> HGETALL user:1000
1) "name"
2) "Alice Smith"
3) "email"
4) "alice@example.com"
5) "role"
6) "superadmin"
HSCAN
Iterates over fields and values of the hash stored at key matching an optional glob pattern.
Syntax
HSCAN key cursor [MATCH pattern] [COUNT count]
Parameters
key: Name of the hash to scan.cursor: Cursor position (0to start).MATCH pattern(optional): Glob pattern matching field names (*,?,[a-z],\).COUNT count(optional, default: 10): Hint for number of field-value elements to return.
kachedb-cli / redis-cli Example
127.0.0.1:6379> HSCAN user:1000 0 MATCH "*mail"
1) "0"
2) 1) "email"
2) "alice@example.com"
๐ Client Integration Examples
Native Python (kachedb)
from kachedb import KacheClient
with KacheClient(host="127.0.0.1", port=6379) as client:
client.hset("session:agent_42", mapping={"model": "claude-3-7-sonnet", "step": "12", "tokens": "8450"})
# Streaming field-value iteration with generator
for field, value in client.hscan_iter("session:agent_42", match="*"):
print(f"{field.decode('utf-8')} = {value.decode('utf-8')}")
Python (redis-py)
import redis
client = redis.Redis(host="127.0.0.1", port=6379, decode_responses=True)
# Set multiple fields
client.hset("session:agent_42", mapping={
"model": "claude-3-7-sonnet",
"step": "12",
"tokens": "8450",
"status": "active"
})
# Retrieve a single field
model = client.hget("session:agent_42", "model")
print(f"Active Model: {model}")
# Query existence and length
assert client.hexists("session:agent_42", "tokens") == 1
field_count = client.hlen("session:agent_42")
print(f"Total fields: {field_count}")
# Stream fields and values via hscan_iter
for field, value in client.hscan_iter("session:agent_42", match="s*"):
print(f"{field} -> {value}")
# Fetch all fields as a dictionary
session_data = client.hgetall("session:agent_42")
print(session_data)
# {'model': 'claude-3-7-sonnet', 'step': '12', 'tokens': '8450', 'status': 'active'}
# Delete fields
client.hdel("session:agent_42", "status")
๐พ Durability & Snapshots (Format V7)
AOF hash records store the resulting field-value pairs and absolute expiration deadline. An explicit zero deadline represents a persistent hash. Legacy hash AOF records use the recorded evaluation second during replay, so a hash recreated at its original deadline starts with only the new fields.
Plaintext and encrypted V7 snapshots preserve original key bytes, value types, hash field-value pairs, and the AOF checkpoint when available. Snapshot recovery rules
๐ Keyspace & Hash Cursor Scanning (SCAN, HSCAN)
KacheDB provides non-blocking, cursor-based iterations over the entire keyspace and individual Redis Hashes via SCAN and HSCAN. Both commands follow the Redis wire protocol and work seamlessly with existing Redis and Valkey client libraries.
Unlike traditional in-memory stores that can stall the server during full table scans or allocate large intermediate buffers, KacheDB implements home-bucket bit-reversed cursor iteration, a zero-allocation glob matcher, and inline Short String Optimization (SSO) to scan millions of keys with zero heap allocations and sub-microsecond latency per batch.
๐ Command Summary
| Command | Syntax | Complexity | Description |
|---|---|---|---|
SCAN | SCAN cursor [MATCH pattern] [COUNT count] [TYPE type] | $\mathcal{O}(1)$ per step, $\mathcal{O}(N)$ full keyspace | Iterates through the entire keyspace across all 256 shards using a 64-bit composite cursor. |
HSCAN | HSCAN key cursor [MATCH pattern] [COUNT count] | $\mathcal{O}(1)$ per step, $\mathcal{O}(F)$ full hash | Iterates through fields and values within a Redis hash stored in a Megaslab slot. |
- $N$ = total keys in the database; $F$ = total fields stored in the target hash.
๐ Architecture & Algorithmic Design
1. 64-Bit Composite Cursor Across 256 Shards
KacheDB partitions the keyspace across 256 independent Swiss Table shards to enable concurrent worker execution without lock contention:
+-----------------------------------+---------------------------------------------------------+
| Bits 63..56 (8 bits: Shard Index) | Bits 55..0 (56 bits: Home-Bucket Bit-Reversed Cursor) |
+-----------------------------------+---------------------------------------------------------+
0 .. 255 Shard-local Swiss Table bucket index
- Shard Progression: The scan begins at composite cursor
0. Once a shard completes its bucket cycle, the high 8 bits increment to advance to the next shard (cursor = (shard_idx + 1) << 56). When all 256 shards have been scanned, cursor0is returned, signaling completion. - Empty Database Optimization: If
sharded.len() == 0,SCANimmediately returns["0", []]in $\mathcal{O}(1)$ time without traversing shards. - Shard Batching: When scanning sparsely populated shards, KacheDB automatically sweeps up to
SHARD_BATCH_BUCKETS = 256buckets per iteration, preventing empty-page roundtrip thrashing over TCP.
2. Home-Bucket Bit-Reversed Cursor Iteration
Standard linear counters (0, 1, 2, ...) miss keys or produce duplicates when a hash table dynamically doubles or halves in size during an active scan.
KacheDB uses bit-reversed radix counting:
- Incrementing from the highest significant bit to the lowest guarantees that when a table doubles ($M \to 2M$), entries in bucket $B$ only ever split into bucket $B$ and $B + M$.
- The bit-reversed traversal visits parent and split buckets contiguously, ensuring zero dropped keys and strictly bounded duplicates even under continuous writes, rehashing, and tombstone compactions.
3. Inline SSO & Overflow Key Storage
To keep memory density high and cache-line lookups blazing fast:
- Keys $\le 40$ Bytes: Stored directly inside the 64-byte aligned
HashEntrypayload (inline_key), avoiding pointer indirection and eliminating secondary heap allocations. - Keys $> 40$ Bytes: Stored in the shard's
overflow_keysmap, referenced by slot index and automatically purged upon deletion, overwrite, or expiration.
4. Zero-Allocation Glob Pattern Matcher
Pattern filtering via MATCH runs on borrowed byte slices (&[u8]) without allocating temporary strings or regex engines:
- Supported Wildcards:
*: Matches any sequence of characters (including empty). Single-star patterns (prefix*,*suffix,*substr*) use a linear search fast-path with zero backtracking, guaranteeing immunity to ReDoS (Regular Expression Denial of Service) attacks.?: Matches exactly one byte.[abc]/[a-z]: Matches any character in the set or range.[^abc]/[^a-z]: Negated character classes.\: Escapes special characters (\*,\?,\[, etc.).
- Prefix Fast-Path: The
CompiledPatternanalyzer extracts exact prefixes before the first wildcard (e.g.user:session:*extracts prefixuser:session:). Non-matching candidate keys are rejected before running character matching.
๐ ๏ธ Detailed Command Reference
SCAN
Iterates over the keyspace.
Syntax
SCAN cursor [MATCH pattern] [COUNT count] [TYPE type]
Parameters
cursor(integer, required): The cursor position. Pass0to begin a new scan. Use the returned cursor in subsequent calls until the server returns0.MATCH pattern(string, optional): Glob-style pattern. Only keys matching the pattern are returned.COUNT count(integer, optional, default: 10): Work budget hint representing the number of bucket slots to examine per call.TYPE type(string, optional): Filters keys by their data type:string,hash, orvector. Keys of other types are skipped without payload retrieval.
Return Value
An array of two elements:
- The next cursor as a string (e.g.
"144115188075855872", or"0"when finished). - An array of matched keys.
redis-cli / kachedb-cli Example
127.0.0.1:6379> MSET user:101 "Alice" user:102 "Bob" session:901 "active" config:env "prod"
OK
# Scan matching user:* prefix
127.0.0.1:6379> SCAN 0 MATCH "user:*" COUNT 10
1) "0"
2) 1) "user:101"
2) "user:102"
# Filter strictly by data type
127.0.0.1:6379> SCAN 0 TYPE hash
1) "0"
2) (empty list or set)
HSCAN
Iterates over the fields and values of a Redis Hash stored at key.
Syntax
HSCAN key cursor [MATCH pattern] [COUNT count]
Parameters
key(string, required): Key of the hash to scan.cursor(integer, required): Cursor position (always0to start).MATCH pattern(string, optional): Glob-style pattern applied to field names.COUNT count(integer, optional, default: 10): Maximum number of field-value pairs to return.
Return Value
An array of two elements:
- The next cursor (
"0"indicates iteration complete). - A flat array of alternating field-value pairs:
[field1, value1, field2, value2, ...]. If the key does not exist or has expired,["0", []]is returned. If the key holds a non-hash value,-WRONGTYPEis returned.
redis-cli / kachedb-cli Example
127.0.0.1:6379> HSET order:9801 item "laptop" price "1200" status "shipped" sku "TECH-100"
(integer) 4
# Match fields starting with 's'
127.0.0.1:6379> HSCAN order:9801 0 MATCH "s*"
1) "0"
2) 1) "status"
2) "shipped"
3) "sku"
4) "TECH-100"
๐ Client Integration Examples
Python (kachedb Client SDK)
The native kachedb Python package provides both low-level paged methods and high-level generator iterators:
from kachedb import KacheClient
with KacheClient(host="127.0.0.1", port=6379) as client:
# 1. Populate test data
for i in range(100):
client.set(f"device:sensor:{i}", f"val_{i}")
client.hset("device:metadata", mapping={"vendor": "Acme", "fw_version": "2.4.1", "status": "online"})
# 2. Generator-based streaming keyspace iteration (recommended)
print("--- Streaming SCAN Iteration ---")
for key in client.scan_iter(match="device:sensor:*", count=25):
print(f"Discovered key: {key.decode('utf-8')}")
# 3. Manual page-by-page SCAN
cursor = 0
all_keys = []
while True:
cursor, keys = client.scan(cursor, match="device:sensor:*", count=50)
all_keys.extend(keys)
if cursor == 0:
break
print(f"Total keys retrieved: {len(all_keys)}")
# 4. Streaming Hash iteration
print("--- Streaming HSCAN Iteration ---")
for field, value in client.hscan_iter("device:metadata", match="*"):
print(f"Field: {field.decode('utf-8')} -> Value: {value.decode('utf-8')}")
Python (redis-py)
Because KacheDB is fully wire-compatible with RESP2/RESP3, standard Redis libraries work out-of-the-box:
import redis
r = redis.Redis(host="127.0.0.1", port=6379, decode_responses=True)
# Scan keyspace with pattern match
for key in r.scan_iter(match="device:sensor:*", count=50):
print("Key:", key)
# Scan hash fields
for field, value in r.hscan_iter("device:metadata"):
print(f"{field} = {value}")
๐พ Snapshot Durability & Recovery (Format V7)
Snapshot V7 (KDB\x07) stores the original bytes of every key. A zero-length key is an empty key. Distinct keys with the same digest remain independent. Key lengths use 16 bits, so writes accept keys up to 65,535 bytes.
V6 snapshots and V5 snapshots with known key bytes can still be loaded. V2โV4 snapshots with KV entries and V5 snapshots with anonymous entries require migration from a source containing the original keys, such as a complete AOF. Startup reports a migration error and preserves the original snapshot.
When AOF is enabled, a snapshot stores the generation and highest included AOF sequence. Recovery validates that pair before restoring the snapshot and applies only later log records. An older snapshot paired with a nonempty legacy AOF without a provable base requires migration from a known complete source. See the AOF configuration and repair procedure.
โฑ๏ธ TTL & Key Lifecycle Commands
KacheDB provides high-resolution time-to-live (TTL) expiration support with dual-engine memory reclamation:
- Sub-Nanosecond Passive Expiry: On
GET/EXISTSqueries, the Swiss Table verifies the cached second timestamp in ~0.5 ns. - Active O(1) Background Timing Wheel: A lock-free 3,600-bucket per-core circular wheel proactively evicts expired keys and returns 2 MB Megaslab slots back to the free-list every second without waiting for read traffic.
๐ Command Summary
| Command | Syntax | Return Value | Complexity | Description |
|---|---|---|---|---|
EXPIRE | EXPIRE key seconds | 1 or 0 | O(1) | Sets timeout on key in seconds. |
PEXPIRE | PEXPIRE key milliseconds | 1 or 0 | O(1) | Sets timeout on key in milliseconds. |
EXPIREAT | EXPIREAT key unix_seconds | 1 or 0 | O(1) | Sets expiration deadline as an absolute Unix timestamp. |
PEXPIREAT | PEXPIREAT key unix_millis | 1 or 0 | O(1) | Sets expiration deadline as an absolute millisecond timestamp. |
TTL | TTL key | integer | O(1) | Returns remaining TTL in seconds (-2 if missing, -1 if no TTL). |
PTTL | PTTL key | integer | O(1) | Returns remaining TTL in milliseconds (-2 if missing, -1 if no TTL). |
PERSIST | PERSIST key | 1 or 0 | O(1) | Removes timeout, persisting the key indefinitely. |
๐ ๏ธ Command Details & Examples
EXPIRE & PEXPIRE
Sets a relative timeout from the current time.
kachedb-cli Example
127.0.0.1:6379> SET user:auth "token_xyz123"
OK
# Expire in 60 seconds
127.0.0.1:6379> EXPIRE user:auth 60
(integer) 1
# Check remaining seconds
127.0.0.1:6379> TTL user:auth
(integer) 59
# Check remaining milliseconds
127.0.0.1:6379> PTTL user:auth
(integer) 58942
# Attempting to expire a non-existent key returns 0
127.0.0.1:6379> EXPIRE missing_key 30
(integer) 0
EXPIREAT & PEXPIREAT
Sets an absolute Unix epoch deadline timestamp.
kachedb-cli Example
# Expire at Unix timestamp 1893456000 (Jan 1, 2030)
127.0.0.1:6379> EXPIREAT user:auth 1893456000
(integer) 1
127.0.0.1:6379> TTL user:auth
(integer) 109895658
PERSIST
Removes the timeout from a key, converting it back to a permanent key.
kachedb-cli Example
127.0.0.1:6379> PERSIST user:auth
(integer) 1
# TTL returns -1 for unexpired keys without timeout
127.0.0.1:6379> TTL user:auth
(integer) -1
๐๏ธ Architecture: How the Timing Wheel Works
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ HashedTimingWheel (3,600 Circular 1-Second Buckets) โ
โ โ
โ Slot 0 Slot 1 Slot 2 ... Slot 3599 โ
โ โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ โ
โ โ Entries โ โ Entries โ โ Entries โ โ Entries โ โ
โ โโโโโโฌโโโโโ โโโโโโฌโโโโโ โโโโโโฌโโโโโ โโโโโโฌโโโโโ โ
โ โ โ โ โ โ
โ โผ โผ โผ โผ โ
โ KeyHash 1 KeyHash 2 KeyHash 3 KeyHash N โ
โ [BlockID 5] [BlockID 9] [BlockID 2] [BlockID 14] โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โฒ
โ Current Second Pointer (Advances every 1.0s)
[ Event Loop Tick ]
- In-Place Mutation:
EXPIREandPERSISTmutateexpiry_sec: u32in the 64-byteTableEntryin-place. - Zero Allocation Jitter: Scheduling a key in the timing wheel appends to a per-bucket pre-allocated array.
- Double-Free Safety: When the 1-second tick advances, the worker thread executes
table.remove_if_matching(key_hash, slab_block_id). If the key was updated or replaced by a newSETcommand, the stale entry is safely ignored without double-deallocating slab blocks.
๐ง SIMD Semantic Vector Commands
KacheDB features a hardware-accelerated SIMD Vector Search Engine (kachedb-vector) built directly into the storage core. It enables sub-microsecond nearest-neighbor vector lookups, semantic caching, and LLM prompt similarity matching with zero external dependencies.
โก Hardware SIMD Acceleration
- ARM NEON (
aarch64): 128-bitvfmaq_f32with 4-way loop unrolling (16 floats per loop iteration) delivering $< 120\text{ ns}$ dot products on Apple Silicon and AWS Graviton. - x86_64 AVX2 / FMA: 256-bit
_mm256_fmadd_pswith 4-way loop unrolling (32 floats per iteration) delivering $> 40\text{ GB/s}$ throughput. - Normalized Cosine Similarity: All stored vectors are automatically $L_2$-normalized upon ingestion, transforming cosine distance calculation into a single high-speed inner dot product: $$\text{CosineSimilarity}(\vec{u}, \vec{v}) = \sum_{i=1}^{D} u_i \cdot v_i$$
๐ Command Summary
| Command | Syntax | Complexity | Description |
|---|---|---|---|
VADD | VADD index id dim vector_bytes [PAYLOAD text] [EX sec] | O(D) | Ingests vector embedding into named index with optional payload and TTL. |
VADD_BATCH | VADD_BATCH index id1 vec1 payload1 id2 vec2 payload2 ... | O(B ยท D) | Batch ingests multiple vectors into named index in a single operation. |
VSEARCH | VSEARCH index query_bytes [TOPK k] [THRESHOLD min_score] | O(N ยท D) | Nearest-neighbor cosine search returning matched IDs, scores, and payloads. |
VSEARCH_BATCH | VSEARCH_BATCH index q1 q2 ... [TOPK k] [THRESHOLD min_score] | O(B ยท N ยท D) | Parallel multi-query batch nearest-neighbor search. |
VDEL | VDEL index id | O(1) | Deletes vector from named index. |
VSTATS | VSTATS index | O(1) | Returns index dimension, active vector count, and memory consumption. |
VINDEX CREATE | VINDEX CREATE name DIM dim [M m] [EF_CONSTRUCTION ef_c] ... | O(1) | Creates and configures a dedicated HNSW vector index. |
VINDEX DROP | VINDEX DROP name | O(1) | Drops a vector index and frees associated memory slots. |
VINDEX INFO | VINDEX INFO name | O(1) | Returns configuration and metrics for a named index. |
๐ ๏ธ Detailed Command Reference & Examples
VADD
Ingests a single float32 vector into a named index. The vector is provided as raw little-endian IEEE 754 float32 byte buffers.
Syntax
VADD <index> <id> <dim> <vector_bytes> [PAYLOAD <payload>] [EX <seconds>]
kachedb-cli Example
# Insert a 4-dimensional vector with payload and 1-hour expiration
127.0.0.1:6379> VADD faq q:101 4 "\x00\x00\x80?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" PAYLOAD "To reset password, go to Settings -> Security." EX 3600
OK
VSEARCH
Performs nearest-neighbor cosine similarity search across all vectors in the index.
Syntax
VSEARCH <index> <query_bytes> [TOPK <k>] [THRESHOLD <min_similarity>]
kachedb-cli Example
# Search index 'faq' for top 1 match with similarity >= 0.80
127.0.0.1:6379> VSEARCH faq "\x00\x00\x80?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" TOPK 1 THRESHOLD 0.80
1) 1) "q:101"
2) "1.000000"
3) "To reset password, go to Settings -> Security."
VDEL & VSTATS
Index management and telemetry.
kachedb-cli Example
127.0.0.1:6379> VSTATS faq
1) "dimension"
2) (integer) 4
3) "total_vectors"
4) (integer) 1
5) "active_vectors"
6) (integer) 1
7) "memory_bytes"
8) (integer) 64
127.0.0.1:6379> VDEL faq q:101
(integer) 1
VADD_BATCH & VSEARCH_BATCH
High-throughput bulk ingestion and multi-vector querying.
Syntax
VADD_BATCH <index> <id1> <vec1_bytes> [payload1] ...
VSEARCH_BATCH <index> <q1_bytes> <q2_bytes> ... [TOPK <k>] [THRESHOLD <min_similarity>]
VINDEX CREATE, VINDEX INFO & VINDEX DROP
Lifecycle management for named HNSW vector index topologies.
Syntax
VINDEX CREATE <name> DIM <dim> [M <m>] [EF_CONSTRUCTION <ef_c>] [EF_SEARCH <ef_s>] [METRIC <COSINE|L2|IP>] [QUANTIZATION <NONE|SQ8>]
VINDEX INFO <name>
VINDEX DROP <name>
kachedb-cli Example
# Create an index for 1536-dimensional OpenAI embeddings
127.0.0.1:6379> VINDEX CREATE embeddings DIM 1536 METRIC COSINE QUANTIZATION SQ8
OK
# Inspect index topology
127.0.0.1:6379> VINDEX INFO embeddings
1) "name"
2) "embeddings"
3) "dimension"
4) (integer) 1536
5) "metric"
6) "COSINE"
7) "quantization"
8) "SQ8"
# Drop index when no longer needed
127.0.0.1:6379> VINDEX DROP embeddings
OK
๐ Python SDK (kachedb-py) Example
Using vectors is seamless via kachedb-py:
from kachedb import KacheClient
with KacheClient() as client:
# 1. Ingest vector embedding (automatically packs float lists to IEEE-754 bytes)
embedding = [0.12, -0.45, 0.88, 0.05]
client.vadd(
index="products",
item_id="item:1001",
vector=embedding,
payload="Ergonomic Mechanical Keyboard",
ex=86400,
)
# 2. Query nearest vectors
query_vector = [0.10, -0.40, 0.85, 0.04]
results = client.vsearch(
index="products",
query_vector=query_vector,
top_k=3,
threshold=0.85,
)
for item_id, score, payload in results:
print(f"Matched {item_id} (Score: {score:.4f}): {payload}")
๐ Server Observability & Introspection
KacheDB provides self-describing runtime introspection compatible with modern Redis tooling, GUI clients (such as Redis Insight and TablePlus), and monitoring agents.
๐ Command Summary
| Command | Syntax | Description |
|---|---|---|
INFO | INFO [section] | Returns server, memory, traffic, keyspace, and vector statistics. |
HELLO | HELLO [protover [AUTH user pass] [SETNAME name]] | Protocol handshake negotiating RESP2 or RESP3 and returning connection metadata. |
AUTH | AUTH [username] <password> | Authenticates the connection when requirepass is configured. |
CLIENT | CLIENT <SETNAME | GETNAME | ID | LIST> | Inspects and configures client connection state. |
COMMAND | COMMAND [DOCS] | Returns server capability descriptors for client auto-discovery. |
BGREWRITEAOF | BGREWRITEAOF | Starts background AOF compaction when AOF is enabled. |
QUIT | QUIT | Gracefully closes the client connection. |
๐ ๏ธ Detailed Command Reference & Examples
INFO
Outputs multi-section server metrics in standard Redis key-value format.
Syntax
INFO [server | memory | stats | keyspace | vector]
kachedb-cli Example
127.0.0.1:6379> INFO
# Server
kachedb_version:0.3.0
os:macos
arch_bits:64
process_id:48123
tcp_port:6379
uptime_in_seconds:1250
# Memory
used_memory:134217728
used_memory_human:128.00M
used_memory_peak:134217728
megaslabs_allocated:64
slab_slots_active:5120
fragmentation_ratio:1.00
# Stats
total_connections_received:128
total_commands_processed:150240
instantaneous_ops_per_sec:0
keyspace_hits:148000
keyspace_misses:2240
# Keyspace
db0:keys=5120,expires=450,avg_ttl=1820
# VectorEngine
active_indices:3
total_vectors:10240
vector_memory_bytes:655360
simd_kernel:auto
HELLO
Negotiates RESP wire protocol version with the server (supports version 2 and version 3).
Syntax
HELLO 3 [SETNAME client_name]
kachedb-cli Example
127.0.0.1:6379> HELLO 3 SETNAME my_worker
1) "server"
2) "kachedb"
3) "version"
4) "0.3.0"
5) "proto"
6) (integer) 3
7) "id"
8) (integer) 1
9) "mode"
10) "standalone"
11) "role"
12) "master"
13) "modules"
14) (empty array)
CLIENT
Manages client connection names and identifiers.
Subcommands
CLIENT SETNAME <name>: Assigns a human-readable name to the current TCP connection.CLIENT GETNAME: Retrieves the assigned name (ornil).CLIENT ID: Returns the unique client connection ID.CLIENT LIST: Returns connected client details.
kachedb-cli Example
127.0.0.1:6379> CLIENT SETNAME web_app_1
OK
127.0.0.1:6379> CLIENT GETNAME
"web_app_1"
127.0.0.1:6379> CLIENT ID
(integer) 1
COMMAND & COMMAND DOCS
Provides capability introspection so GUI tools and drivers can discover supported commands dynamically without crashing.
kachedb-cli Example
127.0.0.1:6379> COMMAND DOCS
OK
AUTH
Authenticates a client connection when password protection is enabled with requirepass.
Syntax
AUTH [username] <password>
kachedb-cli Example
127.0.0.1:6379> GET secret_key
(error) NOAUTH Authentication required.
127.0.0.1:6379> AUTH my_secure_password
OK
127.0.0.1:6379> GET secret_key
"confidential_data"
BGREWRITEAOF
Compacts the active AOF in the background. AOF persistence must be enabled, and one rewrite can run at a time. Normal writes continue while the replacement is built. The command acknowledges that the job started. The server log reports when it finishes or aborts.
BGREWRITEAOF
+Background append only file rewriting started
The writer installs the new file only after it has synced the captured base and subsequent mutations. The installed AOF can recover even when an external snapshot belongs to the previous generation. AOF durability and repair
๐๏ธ System Architecture Overview
KacheDB is built from first principles in Rust to solve the fundamental memory, OS, and serialization bottlenecks of modern database architectures.
โก The Dual-Engine Topology
+-----------------------------------------------------------------------------------------------+
| CLIENT INTERFACES |
| [RESP3 Wire Protocol (Redis/Valkey Clients)] [Zero-Copy Tensor IPC / Python SDK] |
+-----------------------------------------------------------------------------------------------+
โ
+-----------------------------------------------------------------------------------------------+
| INDEXING SUBSYSTEM |
| 1. SIMD Swiss Hash Table (3.09 ns Point Lookups, S3-FIFO Eviction Tracking) |
| 2. Token Radix Prefix Tree (&[u32] Longest Prefix Match for LLM KV-Cache Prefills) |
| 3. 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) |
| - S3-FIFO Dynamic Quota Management (Elastic Workload Quotas) |
+-----------------------------------------------------------------------------------------------+
โ
+-----------------------------------------------------------------------------------------------+
| ZERO-COPY TRANSPORT LAYER |
| - Local: POSIX Shared Memory (/dev/shm) Lock-Free SPSC Ring Buffers (17.66M msgs/sec) |
| - Network: Linux io_uring (SQPOLL Fixed Buffers) / macOS kqueue (Edge-Triggered Workers) |
+-----------------------------------------------------------------------------------------------+
๐ฅ Why Traditional In-Memory Databases Hit a Wall
Traditional in-memory engines (e.g. Redis, Memcached) struggle when scaling to tens of millions of operations per second or serving multi-megabyte AI tensors due to three physical hardware constraints:
1. The Generality Tax (Heap Fragmentation & Pointer Chasing)
- General-purpose databases support variable-size dynamic keys and polymorphic data structures, relying on standard dynamic allocators (
jemalloc,malloc). - Every non-contiguous pointer chase incurs an L1/L2/L3 CPU cache miss (~50โ100 ns stall), degrading memory bandwidth.
- KacheDB Solution: Pre-allocates uniform 2 MB Megaslabs with fixed size classes and 64-byte cache line alignment, eliminating runtime malloc overhead down to 3.84 ns.
2. Kernel Context-Switching Overhead
- Standard POSIX socket operations (
read(),write(),epoll_wait()) require constant transitions between user-space and kernel-space. - Processing millions of small network packets saturates the CPU with interrupt handling and buffer copies.
- KacheDB Solution: Utilizes Linux
io_uringwith SQPOLL for zero-syscall kernel-bypass socket polling and an Accept-Dispatcher ring for even worker CPU saturation.
3. The Tensor Serialization Penalty
- Traditional key-value protocols serialize all responses over TCP sockets.
- For an LLM KV cache (hundreds of megabytes of FP16/BF16 attention matrices), serializing and copying through kernel socket buffers to Python completely destroys latency gains.
- KacheDB Solution: Direct POSIX Shared Memory (
/dev/shm) lock-free SPSC ring buffers, allowing PyTorch and vLLM to map tensors directly from host RAM at PCIe line rate without socket copies.
๐งต Thread-per-Core Execution Model
- Each physical CPU core runs an independent
WorkerThreadpinned viacore_affinity. - Each worker owns an isolated
SlabPool,SwissTableshard, andTimingWheel. - Zero cross-thread locks during request execution ensures linear throughput scaling across 4, 8, 32, or 64 cores.
๐งฑ 2 MB Megaslab Memory Engine
The kachedb-core memory subsystem completely eliminates runtime malloc and free allocation jitter by managing storage through structured 2 MB Megaslabs with 64-byte L1 CPU cache-line alignment.
๐ Memory Slab Geometry
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 2 MB Megaslab Page Frame (2,097,152 Bytes) โ
โ โโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Slot 0 (64B-Aln) โ Slot 1 (64B-Aln) โ Slot 2 (64B-Aln) โ Slot N (64B-Aln) โ โ
โ โ [ Payload Data ] โ [ Payload Data ] โ [ Payload Data ] โ [ Payload Data ] โ โ
โ โโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
1. Cache-Line Alignment (64-byte)
- Every allocated slot is guaranteed to start on a 64-byte boundary via
libc::posix_memalign. - Zero False Sharing: Multi-core writes to neighboring slots never cross CPU L1 cache line boundaries, eliminating cache invalidation stalls.
2. Standard Size Classes
| Class Name | Slot Size | Slots per 2 MB Megaslab | Primary Workload |
|---|---|---|---|
AppSmall | 128 Bytes | 16,384 | Session IDs, token auths, atomic counters, short strings |
AppMedium | 512 Bytes | 4,096 | JSON user profiles, metadata records |
AppLarge | 4,096 Bytes (4 KB) | 512 | Large document blobs, web cache pages |
Tensor64KB | 65,536 Bytes (64 KB) | 32 | LLM KV attention block (16 tokens FP16) |
Tensor256KB | 262,144 Bytes (256 KB) | 8 | LLM KV attention block (64 tokens BF16) |
โก Bump Pointer + Free-List Recycling
Allocation in KacheDB occurs in two stages:
- Fast-Path Bump Allocation: If the active 2 MB arena has unallocated capacity, it increments a local cursor in $\approx 3.84\text{ ns}$.
- Free-List Slot Recycling: When keys are overwritten, deleted, or expired, their
BlockIdis pushed to a lock-free LIFO free-list for immediateO(1)slot reuse.
๐ Dynamic S3-FIFO Workload Quotas
KacheDB implements the state-of-the-art S3-FIFO (Simple, Scalable, Small-footprint FIFO) cache eviction algorithm:
- Small Queue (10% capacity): Acts as a high-speed filter against scan pollution and one-off burst keys.
- Main Queue (90% capacity): Stores frequency-accessed keys with multi-chance bit tracking.
- Ghost Queue: Tracks key signatures after eviction to detect re-access and promote directly into the Main Queue.
- Elastic Borrowing: The
WorkloadQuotamanager balances memory pools between Redis key-value workloads and LLM tensor memory elastically.
๐ณ Token Radix Prefix Tree
The kachedb-radix subsystem implements a hierarchical token prefix tree optimized for LLM attention prompt prefill reuse (such as vLLM PagedAttention and SGLang RadixAttention).
โก The LLM Prefill Problem
During LLM inference, requests operate in two phases:
- Prefill Phase: Computes the Key and Value ($K, V$) attention matrices across all layers for the prompt tokens. Computational complexity is
O(Nยฒ)with respect to sequence length. - Decode Phase: Autoregressively generates tokens one by one using previously computed $K, V$ states.
For long multi-turn prompts (e.g. system prompts, few-shot examples, large codebases, 16Kโ128K tokens):
- Recomputing a 32K token prefill on an NVIDIA H100 GPU takes $200\text{--}500\text{ ms}$.
- Restoring precomputed KV tensors from KacheDB takes $< 20\text{ ms}$.
- Result: Offloading attention states cuts Time-To-First-Token (TTFT) by 5ร to 15ร.
๐ฒ Tree Topology & Chunked Edges
[ Root (Parent Hash = 0) ]
โ
โโโโโโโโโโโโโโดโโโโโโโโโโโโโ
โผ โผ
"You are an assistant" "System Prompt: Coding"
[Chunk: 16 Tokens] [Chunk: 16 Tokens]
โ โ
โโโโโโโโโดโโโโโโโโ โ
โผ โผ โผ
"Turn 1: Python" "Turn 1: Rust" "User Prompt: Refactor"
[Block ID 4] [Block ID 9] [Block ID 12]
1. Compressed Edge Hops ([u32; 16])
- Rather than storing 1 token per node hop, KacheDB edges compress 16 tokens per block.
- Traversal complexity drops from
O(L)toO(L / 16). - A 1,024-token prompt prefix matches in $2.45\ \mu\text{s}$ ($> 10,000\times$ faster than GPU recomputation).
2. Epoch-Based RCU Concurrency (EpochTree)
- Multi-reader concurrency is managed via lock-free Read-Copy-Update (RCU) snapshots using
arc-swap. - Reader inference threads access snapshots with $\approx 1\text{ ns}$ atomic load overhead without locking writers.
3. Reference Counting & Pinning
- Active attention decoders pin tree nodes (
ref_count++), ensuring active conversation blocks are never evicted while a request is in flight. - Eviction uses Bottom-Up Hierarchical LRU, pruning leaf turns while protecting shared root system prompts.
๐ Zero-Copy Shared Memory IPC
The kachedb-shm subsystem implements high-throughput, zero-copy inter-process communication (IPC) between the KacheDB daemon and Python / PyTorch / CUDA inference engines via POSIX Shared Memory (/dev/shm).
โก The Socket Serialization Bottleneck
Transferring large attention tensors (50 MB โ 2 GB) over standard TCP loopback sockets suffers from severe throughput degradation:
- Python creates a socket payload โ serializes tensor buffers.
- Kernel performs socket
send()/ context switch into kernel space โ copies into socket ring buffers. - Daemon
recv()/ context switch into user space โ deserializes data into memory. - Total latency penalty: 15โ40 ms, completely negating prefill savings.
๐๏ธ KacheDB Zero-Copy Architecture
โโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโ
โ KacheDB Rust Daemon โ โ vLLM / PyTorch Worker โ
โ โโโโโโโโโโโโโโโโโโโโโโ โ โ โโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Megaslab Memory โ โ โ โ torch.Tensor โ โ
โ โ (Direct Slot Ptr) โ โ โ โ (Zero-Copy View) โ โ
โ โโโโโโโโโโโฌโโโโโโโโโโโ โ โ โโโโโโโโโโโโฌโโโโโโโโโโ โ
โโโโโโโโโโโโโผโโโโโโโโโโโโโ โโโโโโโโโโโโโโผโโโโโโโโโโโโ
โ โ
โผ โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ POSIX Shared Memory Region (/dev/shm/kachedb_0) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ 192-byte Lock-Free SPSC Ring Header (3 Isolated 64B Lines) โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ
โ โ Cache-Line Aligned Megaslab Page Frames (Multi-GB Storage) โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
1. Lock-Free SPSC Ring Buffer
- Operates a Single-Producer Single-Consumer queue transferring
TensorBlockDescriptormetadata frames. - Throughput: Delivers 17.66 Million messages/sec (56.6 ns per slot) across process boundaries.
2. Cache-Line Isolation (0 False Sharing)
- The 192-byte ring header is partitioned into three isolated 64-byte cache lines:
- Cache Line 0: Read cursor & consumer state
- Cache Line 1: Write cursor & producer state
- Cache Line 2: Ring capacity & flags
- Multi-core reader and writer threads never trigger CPU L1 cache invalidation races.
3. Adaptive Spin-Then-Park Strategy
- Fast-path transfers use busy-spinning for $< 50\text{ ns}$ handoffs.
- Falls back to OS thread parking if the queue remains empty or full for $> 100\ \mu\text{s}$, conserving CPU cycles during idle periods.
๐ Snapshot Encryption-at-Rest (dump.kdb)
KacheDB provides zero-overhead, authenticated streaming encryption-at-rest for binary snapshots (dump.kdb). This guarantees cryptographic confidentiality and tamper-proof integrity for stored vectors, payloads, and key-value pairs without compromising in-memory query performance.
๐๏ธ Architecture & Threat Model
1. Zero Hot-Path Invariant
In-memory SwissTable reads/writes and SIMD vector dot products operate strictly on plaintext in memory. Encryption and decryption occur entirely out-of-band:
- Background Writing: Handled exclusively by the asynchronous
SnapshotWorkerthread. - Boot Hydration: Decryption streams sequentially through 64 KiB buffers before populating in-memory SwissTable slots and vector registries.
Zero CPU cycles or lock contention are added to client queries.
[ Client Query ] โโโบ [ SwissTable / SIMD Vector Index ] (Plaintext Memory, 3.09ns)
โ
(Async Snapshot Thread)
โผ
[ 64 KiB Chunk Buffering ]
โ
(AES-256-GCM / ChaCha20-Poly1305)
โผ
[ KDB\x07 Authenticated Ciphertext Stream ]
โ
[ dump.kdb on Disk ]
2. Threat Mitigation
- Data Exfiltration / Cold Storage Theft: An adversary stealing
dump.kdbor disk backups cannot extract vector embeddings, user payloads, parent keys, or cached data without the 256-bit master key. - Tampering & Bit-Flipping: Every 64 KiB chunk contains an authenticated 16-byte Poly1305 / GHASH tag. Any modified byte fails AEAD authentication, aborting snapshot hydration immediately.
- Block Reordering & Truncation: Per-chunk nonces are derived as $Nonce_i = MasterNonce \oplus i$, and chunk index $i$ is bound to the Additional Authenticated Data ($AAD = i$). Any attempt to reorder or omit chunks results in an authentication failure.
โก Supported Cipher Suites
KacheDB supports two symmetric Authenticated Encryption with Associated Data (AEAD) cipher suites:
| Cipher Suite | Flag Code | Implementation | Performance | Best Use Case |
|---|---|---|---|---|
aes-256-gcm (Default) | 0 | Hardware-accelerated AES-NI / ARMv8 Crypto | > 4 GB/sec streaming | Production on modern x86_64 and aarch64 (Apple Silicon, AWS Graviton) |
chacha20-poly1305 | 1 | Constant-time software streaming AEAD | ~1.5 GB/sec | Embedded architectures or platforms lacking hardware AES acceleration |
๐ Key Ingestion & Management
KacheDB supports three methods of key configuration:
1. Raw 32-Byte Master Key File (Recommended for Production)
The most secure method for production deployments. Point KacheDB directly to a 32-byte cryptographic random binary file:
# Generate a cryptographically secure 32-byte random key file
openssl rand -out /etc/kachedb/snapshot.key 32
chmod 600 /etc/kachedb/snapshot.key
Configure in kachedb.conf:
snapshot-encryption yes
snapshot-encryption-cipher aes-256-gcm
snapshot-encryption-key-file /etc/kachedb/snapshot.key
2. 64-Character Hexadecimal String
Provide a raw 256-bit key formatted as 64 hexadecimal characters:
snapshot-encryption yes
snapshot-encryption-key "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
3. Passphrase with HKDF-SHA256 Key Derivation
If a variable-length user passphrase is provided, KacheDB derives a 256-bit master key using HKDF-SHA256:
- Salt: A cryptographically secure 32-byte random salt generated per-snapshot and written into the file header.
- Info Label:
b"kachedb-snapshot-v1" - Zeroization: The in-memory
EncryptionKeyis securely zeroized viastd::ptr::write_volatileupon drop.
snapshot-encryption yes
snapshot-encryption-key "your_strong_secret_passphrase_here"
๐ฆ Wire Format Specification (KDB\x07)
Snapshot V7 retains the encrypted envelope introduced in V3. The payload includes an optional AOF checkpoint and HNSW graph state.
+---------------------------------------------------------------------------------+
| Offset | Field | Size (Bytes) | Description |
+--------+------------------------+--------------+--------------------------------+
| 0 | Magic Header | 4 | b"KDB\x07" |
| 4 | Timestamp | 8 | Unix Epoch seconds (u64 LE) |
| 12 | Flags | 4 | Bit 0: Encrypted (1=yes, 0=no) |
| | | | Bits 1..3: Cipher Suite Code |
+--------+------------------------+--------------+--------------------------------+
| IF ENCRYPTED (Flags & 0x01 != 0): |
| 16 | Salt | 32 | HKDF 256-bit salt |
| 48 | Master Nonce | 12 | 96-bit base nonce |
| 60..N | Encrypted Stream | Variable | Sequence of 64 KiB AEAD chunks |
| | - Chunk Length | 4 | Ciphertext + 16-byte tag (u32) |
| | - Ciphertext + Tag | Chunk Length | AEAD encrypted block |
| | - EOF Sentinel | 4 | 0x00000000 (u32 LE) |
+--------+------------------------+--------------+--------------------------------+
| IF UNENCRYPTED (Flags & 0x01 == 0): |
| 16..N | Plaintext Stream | Variable | Vector & SwissTable sections |
+--------+------------------------+--------------+--------------------------------+
| N..N+4 | Checksum Trailer | 4 | IEEE 802.3 CRC32 (u32 LE) |
+---------------------------------------------------------------------------------+
Backward Compatibility
- Legacy plaintext snapshots can be read without an encryption key. KV entries without original key bytes require migration. Snapshot recovery rules
- Unencrypted
KDB\x03snapshots (flags = 0) hydrate state directly with zero decryption overhead.
๐ Offline Diagnostic Inspection (kachedb-cli)
Use kachedb-cli snapshot-info to inspect and verify snapshot files on disk without launching the full server:
kachedb-cli snapshot-info /var/lib/kachedb/dump.kdb
Example Inspection Output
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ฆ KacheDB Snapshot Inspection: "/var/lib/kachedb/dump.kdb"
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
File Size: 430 bytes (0.42 KB)
Checksum (CRC32): 0x295f2f0d [VALID]
Format Version: v3 (Authenticated Snapshot)
Created Timestamp: 1790481552 (Unix Epoch)
Flags: 0x00000001
Encryption: ENABLED
Cipher Suite: AES-256-GCM (Hardware Accelerated)
Salt (256-bit): dafd90590dc19b358f8e76fd11a0430b07dc0b5881c063987a3c7619379147ff
Master Nonce: b8fe98eb980ea4d551497618
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ค vLLM Integration Guide
This guide walks through configuring KacheDB as a high-speed external KV-cache offloading tier for vLLM (PagedAttention).
โก Overview
By offloading PagedAttention KV-cache blocks from GPU VRAM to KacheDB's zero-copy POSIX Shared Memory (/dev/shm), vLLM inference instances achieve:
- Up to 10,000ร faster prompt prefill for repeated system prompts, few-shot examples, and multi-turn chat sessions.
- Zero socket serialization overhead using PyTorch tensor memory views.
- Seamless multi-GPU and distributed tensor parallel support.
๐ฆ Installation & Setup
- Start the KacheDB daemon with
--ipc hostor native POSIX Shared Memory enabled:
./target/release/kachedb-server -p 6379 -w 4 --pool-mb 512
- Install the KacheDB Python client with PyTorch support:
pip install kachedb[torch]
๐ Programmatic Integration Example
The KacheDBConnector handles prefix caching, block hashing, and zero-copy restoration automatically:
import torch
from kachedb.vllm import KacheDBConnector
# 1. Initialize the connector for the active GPU worker rank
connector = KacheDBConnector(
rank=0,
local_rank=0,
block_size=16,
pool_size_mb=256,
)
# 2. Simulated PagedAttention tensor for 2 transformer layers
# Shape: [num_blocks=4, 2 (K/V), num_heads=8, block_size=16, head_dim=64]
kv_shape = (4, 2, 8, 16, 64)
kv_caches = [
torch.randn(kv_shape, dtype=torch.float16),
torch.randn(kv_shape, dtype=torch.float16),
]
# 3. Offload KV cache blocks to KacheDB
prompt_tokens = [101, 2054, 2003, 1037, 2742, 102]
connector.offload_kv_cache(
prompt_tokens=prompt_tokens,
kv_caches=kv_caches,
)
# 4. On subsequent requests, restore matching prefix blocks
new_request_tokens = [*prompt_tokens, 999, 1000]
target_kv_caches = [
torch.zeros(kv_shape, dtype=torch.float16),
torch.zeros(kv_shape, dtype=torch.float16),
]
matched_tokens, is_hit = connector.restore_kv_cache(
prompt_tokens=new_request_tokens,
target_kv_caches=target_kv_caches,
)
if is_hit:
print(f"โ
Cache Hit! Restored {matched_tokens} tokens from KacheDB zero-copy.")
๐ฒ SGLang RadixAttention Integration Guide
This guide describes integrating KacheDB with SGLang's RadixAttention hierarchical tree-branching engine.
โก Overview
SGLang manages KV-caches as a dynamic Radix Tree across multiple conversational branches and tool calls. KacheDB's KacheDBSGLangConnector maps SGLang tree nodes directly to lock-free memory frames:
- Arbitrary Slice Lengths: Variable-length token chunks hashed via chained Blake2b.
- Hierarchical Multi-Branch Restoration: Restores branched tree paths in a single pass.
- Multi-Precision Support: Native support for
FP16,BF16(LLaMA default),FP32, andINT8.
๐ Programmatic Integration Example
import torch
from kachedb.sglang import KacheDBSGLangConnector
# 1. Initialize connector
connector = KacheDBSGLangConnector(
rank=0,
local_rank=0,
pool_size_mb=256,
)
num_heads = 4
head_dim = 64
num_layers = 2
dtype = torch.bfloat16
# 2. Node 1: Root System Prompt (10 tokens)
root_tokens = list(range(10))
k_root = [torch.randn((num_heads, 10, head_dim), dtype=dtype) for _ in range(num_layers)]
v_root = [torch.randn((num_heads, 10, head_dim), dtype=dtype) for _ in range(num_layers)]
desc_root = connector.offload_node(
node_id=1,
token_ids=root_tokens,
k_tensors=k_root,
v_tensors=v_root,
parent_hash=0,
)
# 3. Node 2: Child Branch Turn (20 tokens)
child_tokens = list(range(10, 30))
k_child = [torch.randn((num_heads, 20, head_dim), dtype=dtype) for _ in range(num_layers)]
v_child = [torch.randn((num_heads, 20, head_dim), dtype=dtype) for _ in range(num_layers)]
connector.offload_node(
node_id=2,
token_ids=child_tokens,
k_tensors=k_child,
v_tensors=v_child,
parent_hash=desc_root.node_hash,
)
# 4. Restore Full 30-Token Sequence (Root + Child)
full_prompt = list(range(30))
target_k = [torch.zeros((num_heads, 30, head_dim), dtype=dtype) for _ in range(num_layers)]
target_v = [torch.zeros((num_heads, 30, head_dim), dtype=dtype) for _ in range(num_layers)]
matched_count, is_hit = connector.restore_prefix(
prompt_tokens=full_prompt,
target_k_buffers=target_k,
target_v_buffers=target_v,
)
if is_hit:
print(f"๐ฒ SGLang Restored {matched_count} tokens across Radix tree hierarchy!")
๐ฌ Semantic Caching Guide
This guide explains how to use KacheDB's Semantic Cache Engine to intercept and cache LLM completions based on semantic intent and cosine similarity, saving 100% of GPU compute and token costs on semantic cache hits.
โก How Semantic Caching Works
Traditional caching requires an exact character-for-character string match ("What is KacheDB?" vs "what is kachedb?").
KacheDB's SemanticCache computes a dense vector embedding for incoming prompts and searches the in-memory SIMD vector index using normalized Cosine Similarity:
- Cache HIT: If similarity $\ge \text{threshold}$ (default
0.85), KacheDB immediately returns the cached LLM answer in $< 50\ \mu\text{s}$ without invoking the LLM. - Cache MISS: The application queries the LLM and writes the answer to KacheDB for future semantic matches.
๐ Synchronous Usage (SemanticCache)
from kachedb import KacheClient, SemanticCache
# 1. Connect to KacheDB
client = KacheClient(host="127.0.0.1", port=6379)
# 2. Initialize the semantic cache (auto-detects FastEmbed or SentenceTransformers)
cache = SemanticCache(
client=client,
index_name="customer_support_faq",
similarity_threshold=0.85,
ttl_seconds=86400, # 24 hours
)
# 3. Store a Q&A pair in the semantic cache
cache.set(
prompt="How do I change my billing address?",
response="Go to Account Settings -> Billing -> Edit Address.",
)
# 4. Query with a semantically equivalent but differently worded prompt
query = "Where can I update my billing location?"
match = cache.get(query)
if match:
print(f"๐ฏ Cache HIT! (Similarity: {match.similarity:.2f})")
print(f"Response: {match.value}")
else:
print("โ Cache MISS")
โก Asynchronous Usage (AsyncSemanticCache)
For non-blocking asyncio inference servers (such as FastAPI, vLLM, or LiteLLM):
import asyncio
from kachedb import AsyncKacheClient, AsyncSemanticCache
async def main():
async with AsyncKacheClient(host="127.0.0.1", port=6379) as client:
cache = AsyncSemanticCache(
client=client,
index_name="async_chat_cache",
similarity_threshold=0.88,
)
# Store response
await cache.set(
prompt="Explain quantum entanglement briefly",
response="Quantum entanglement is a physical phenomenon where particles remain connected so that actions performed on one affect the other.",
)
# Retrieve asynchronously
result = await cache.get("What is quantum entanglement in simple terms?")
if result:
print(f"โก Async Hit: {result.value}")
asyncio.run(main())
๐ Pluggable Embedding Backends
KacheDB supports multiple embedding backends via kachedb.semantic.embedders:
FastEmbedAdapter: Ultra-fast local ONNX Runtime embeddings (pip install fastembed).SentenceTransformersAdapter: HuggingFacesentence-transformersmodels.OpenAIAdapter: Remote OpenAI embedding API (text-embedding-3-small).CallableAdapter: Custom function wrapping any embedding model (Callable[[str], list[float]]).
๐ค Antigravity IDE Integration: Autonomous Agent Memory
KacheDB functions as a high-speed, sub-microsecond persistent memory and semantic context engine for AI coding agents in Google Antigravity IDE.
By pairing KacheDB with Antigravity IDE via the Model Context Protocol (MCP), coding agents eliminate redundant file reads, preserve architecture decisions across sessions, and recall codebase solutions in < 50 nanoseconds without spending LLM tokens.
โก Why Agent Memory Matters
Modern AI IDE agents operate with bounded context windows and ephemeral memory:
- The Problem: On every user prompt or debugging session, an agent typically re-reads dozens of source files, re-indexes directory structures, and re-reasons through architecture rules from scratch. This burns thousands of input tokens and introduces multi-second latency.
- The KacheDB Solution: KacheDB acts as an out-of-band L1/L2 memory hierarchy for the agent:
- L1 Exact Match (SwissTable): Repeated questions or known tasks resolve via prompt alias shortcuts in < 50 ns with 0 ms LLM reasoning overhead.
- L2 Semantic Recall (SIMD Vector Engine): Conceptual queries execute SIMD dot-product scans in ~150 ยตs, filtered by 64-bit tag bitmasks.
- L3 Unabridged Parents (Hierarchical Storage): Large explanations (>1,500 chars) are automatically chunked with breadcrumb headers while maintaining sub-microsecond pointers to their parent context document.
[ User Prompt in Antigravity ]
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโ
โ Antigravity Agent โ
โโโโโโโโโโโโฌโโโโโโโโโโโโ
โ (1. Pre-Execution Cache Check via MCP)
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ KacheDB Core โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ SwissTable (Exact) โ โ SIMD Vector Index โ โ
โ โ < 50 ns Hit โ โ 150 ยตs Recall โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโดโโโโโโโโโ
[ Cache Hit ] [ Cache Miss ]
โ โ
โผ โผ
(Instant Answer) (Agent Researches & Implements)
โ
โผ (2. Post-Execution Knowledge Persistence)
[ kache_save_context ] โโโบ Stored for all future prompts
๐ ๏ธ Step 1: Configure the MCP Server
KacheDB provides an official Model Context Protocol server: kachedb-mcp.
1. Install kachedb-mcp
Ensure Python 3.10+ is installed with uv or pip:
# Run directly via uvx (recommended)
uvx kachedb-mcp
# Or install in your virtual environment
pip install kachedb-mcp
2. Register in Antigravity IDE MCP Config
Add KacheDB to your Antigravity IDE MCP configuration file (mcp_config.json):
{
"mcpServers": {
"kachedb": {
"command": "uvx",
"args": ["--refresh", "kachedb-mcp"],
"env": {
"KACHEDB_HOST": "127.0.0.1",
"KACHEDB_PORT": "6379",
"KACHEDB_AUTO_CHUNK": "true"
}
}
}
}
The server exposes 8 autonomous memory tools:
kache_semantic_search: Hybrid exact-symbol + SIMD vector retrieval with adaptive fallback.kache_save_context: Saves agent knowledge with hierarchical chunking, 64-bit tag bitmasks, and exact prompt aliases.kache_get: Sub-microsecond exact key-value read from SwissTable.kache_set: Fast write into SwissTable memory pool.kache_get_parent_document: Retrieves full unabridged parent documents for chunk matches.kache_delete: Reclaims key and slab memory.kache_stats: Reports active memory, slabs, vectors, and server health.kache_telemetry: Reports real-time cache hits, vector hits, exact hits, tag filter skips, and LLM inference time saved.
๐ Step 2: Set Up Antigravity Agent Rules
Antigravity IDE discovers and executes agent rules located in .agents/AGENTS.md (or .agents/rules/*.md) in your workspace root.
Create .agents/AGENTS.md with the following production-tested template:
# AGENTS.md โ KacheDB Autonomous Caching & Memory Rules
# =========================================================
# These rules apply to ALL AI agents working inside this workspace.
## ๐ด MANDATORY PRE-EXECUTION CACHE CHECK (RULE 1)
**Before doing ANY extensive file reading, research, or answering architecture questions:**
1. Call `kache_semantic_search` or `kache_get` as your FIRST step:
```json
{
"query": "<user_query_or_topic>",
"exact_first": true,
"resolve_parent": true
}
- If relevant cached knowledge exists:
- USE THE CACHED CONTEXT DIRECTLY.
- Do NOT re-read dozens of source files or repeat costly reasoning for already-solved problems.
- If no cache exists, proceed to research and remember to persist your solution in Step 2.
๐ข MANDATORY POST-EXECUTION KNOWLEDGE PERSISTENCE (RULE 2)
Whenever you complete one of the following:
- Answer a technical explanation or architecture question
- Solve a non-trivial bug or build failure
- Add or modify a major feature or API component
- Run benchmarks or performance measurements
- Define or update an architecture decision (ADR)
Call kache_save_context in the SAME turn:
{
"topic": "<topic_slug>",
"prompt_alias": "<user_exact_query>",
"content": "<full_answer_or_summary>",
"tags": ["<tag1>", "<tag2>"],
"auto_chunk": true
}
- Always supply
prompt_alias="<user_exact_query>": This registers a sub-microsecond exact shortcut in SwissTable so identical prompts return in < 50 ns with 0 ms LLM time. - Large documents (> 1,500 chars) are automatically chunked with breadcrumb headers and linked to their parent document.
๐ REAL-TIME TELEMETRY & HEALTH CHECKS
- Verify cache status and token savings using
kache_stats()andkache_telemetry(). - Ensure connection stays healthy on
127.0.0.1:6379.
---
## ๐ Step 3: Verify the Autonomous Loop
Once configured, verify the workflow in Antigravity IDE:
1. **Ask a complex architecture question:**
> *"How does snapshot encryption-at-rest work in KacheDB?"*
- The agent notices no cache exists, researches the source code, and writes a detailed explanation.
- At the end of the turn, the agent automatically executes:
`kache_save_context(topic="snapshot_encryption", prompt_alias="How does snapshot encryption-at-rest work in KacheDB?", content=..., tags=["encryption", "snapshot", "architecture"])`.
2. **Ask the same or related question in a fresh chat session:**
> *"How does snapshot encryption-at-rest work in KacheDB?"*
- The agent immediately calls `kache_semantic_search` or `kache_get`.
- **Result:** SwissTable returns an exact shortcut hit in **< 50 ns**! The agent provides the answer instantly without touching a single file on disk.
3. **Check Telemetry:**
Run `kache_telemetry()` or check through the MCP inspector:
```json
{
"total_requests": 14,
"cache_hits": 9,
"exact_hits": 6,
"vector_hits": 3,
"tag_filter_skips": 42,
"estimated_tokens_saved": 48500,
"estimated_usd_saved": "$0.145",
"avoided_embedding_ms": 3200
}
๐ฎ Future IDE Support
Support and templates for Cursor (.cursor/rules/), Claude Code (CLAUDE.md), and Windsurf (.windsurfrules) are currently in active testing and will be published in upcoming documentation updates.
OpenAI Semantic Reverse Proxy (kachedb-proxy)
The kachedb-proxy service is a lightweight, standalone reverse proxy that bridges AI developer tools (Cursor, Aider, Continue.dev, LiteLLM, LangChain, and OpenAI SDKs) with KacheDB's in-memory SIMD vector cache.
๐๏ธ Architecture & Packet Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CLIENT: Cursor / Aider / OpenAI SDK โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ POST /v1/chat/completions
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ KACHEDB-PROXY (localhost:8080) โ
โ 1. Extract messages & canonicalize prompt text โ
โ 2. Compute local 384-dim embedding via FastEmbed/ONNX in 2-4 ms ($0 cost) โ
โ 3. SIMD vector query to KacheDB daemon (127.0.0.1:6379, < 0.3 ms) โ
โโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ
[ SEMANTIC HIT (>= 0.85) ] [ SEMANTIC MISS ]
โ โ
โผ โผ
โก Return Cached Response (JSON/SSE) ๐ Forward to Upstream LLM
- Latency: < 5 ms - Pass client auth headers
- Upstream Cost: $0.00 - Stream chunks to client
- Header: X-KacheDB-Cache: HIT - Async VADD to KacheDB
๐ Quickstart
1. Start KacheDB Server
./target/release/kachedb-server -p 6379
2. Launch kachedb-proxy
cargo run --release --manifest-path kachedb-proxy/Cargo.toml -- \
--port 8080 \
--upstream https://api.openai.com/v1 \
--kachedb-port 6379
3. Connect Cursor / IDE
Set OpenAI Base URL in Cursor settings:
http://localhost:8080/v1
โ๏ธ Configuration Reference
| Parameter | Environment Variable | Default | Description |
|---|---|---|---|
--port | KACHEDB_PROXY_PORT | 8080 | Local HTTP listening port |
--upstream | UPSTREAM_BASE_URL | https://api.openai.com/v1 | Target LLM endpoint |
--kachedb-host | KACHEDB_HOST | 127.0.0.1 | KacheDB daemon IP |
--kachedb-port | KACHEDB_PORT | 6379 | KacheDB daemon port |
--threshold | SIMILARITY_THRESHOLD | 0.85 | Cosine similarity threshold (0.0โ1.0) |
--ttl | CACHE_TTL_SECONDS | 86400 | Expiration time for cached responses (seconds) |
--embedding-model | EMBEDDING_MODEL | bge-small-en-v1.5 | On-device ONNX embedding model |
KacheDB โ Consolidated Master Benchmark Report
Date: 2026-08-17
Engine: KacheDB v0.1.0
Status: โ
All 4 Phases Complete & Verified
1. Executive Summary
KacheDB is an in-memory storage engine designed from scratch in Rust to address the memory bottlenecks of modern AI and high-concurrency microservices:
- Sub-4 ns Memory Allocation: Replaces runtime
malloc/freewith 64-byte aligned 2 MB Megaslab arenas, achieving 3.93 ns allocation latency regardless of slot size (128 B to 256 KB). - L1 Cache-Speed Point Queries: SIMD-probed Swiss Table hash index delivers 3.15 ns lookup hit latency with lock-free S3-FIFO eviction flags.
- ~10,000ร TTFT Speedup for LLM KV-Cache: Hierarchical
&[u32]Radix Prefix Tree matches a 1,024-token sequence in 2.61 ยตs, skipping costly GPU attention prefill. - 15.04 Million msgs/sec Zero-Copy IPC: POSIX Shared Memory (
/dev/shm) lock-free SPSC ring buffers stream tensor descriptors across processes in 66.47 ns per message with zero serialization and zero memory copies. - 10.2 Million QPS per Core: Ingests, parses, executes, and encodes standard Redis RESP commands over TCP in 97.63 ns end-to-end.
2. Test Environment
| Metric | Specification |
|---|---|
| Operating System | macOS 26.5.2 (Darwin 25F84) |
| Architecture | arm64 (Apple Silicon) |
| Cores | 8 Physical / 8 Logical Cores |
| System Memory | 16 GB Unified Memory |
| Rust Toolchain | rustc 1.97.1 / cargo 1.97.1 |
| Optimization Profile | release (opt-level = 3) |
| Benchmarking Suite | Criterion.rs v0.5.1 (100 samples per test, 3s warmup) |
3. Detailed Subsystem Benchmark Matrix
Phase 0: Memory Allocation & Swiss Hash Table
| Crate | Benchmark Target | Measured Latency | Target / Industry Baseline |
|---|---|---|---|
kachedb-core | Arena Slot Allocation (AppSmall 128 B) | 3.93 ns | < 20 ns target (5.1ร faster) |
kachedb-core | Arena Slot Allocation (AppMedium 512 B) | 3.92 ns | < 20 ns target |
kachedb-core | Arena Slot Allocation (AppLarge 4 KB) | 3.96 ns | < 20 ns target |
kachedb-core | Arena Slot Allocation (Tensor64KB 64 KB) | 3.97 ns | < 20 ns target |
kachedb-core | Arena Slot Allocation (Tensor256KB 256 KB) | 4.11 ns | < 20 ns target |
kachedb-core | Pool Alloc + Dealloc Cycle (AppSmall) | 5.76 ns | < 20 ns target |
kachedb-core | Pool Alloc + Dealloc Cycle (Tensor64KB) | 7.06 ns | < 20 ns target |
kachedb-hash | Swiss Table Lookup Hit (1M keys preloaded) | 3.15 ns | L1 cache probe speed |
kachedb-hash | Swiss Table Lookup Miss | 8.27 ns | Fast group termination |
Phase 1: LLM Token Radix Tree & POSIX Shared Memory
| Crate | Benchmark Target | Measured Latency | Throughput / Speedup |
|---|---|---|---|
kachedb-radix | Prefix Lookup Hit (128 tokens / 8 blocks) | 253.85 ns | ~31.7 ns per block hop |
kachedb-radix | Prefix Lookup Hit (1,024 tokens / 64 blocks) | 2.61 ยตs | ~10,000ร faster than GPU prefill |
kachedb-radix | Prefix Lookup Hit (4,096 tokens / 256 blocks) | 19.98 ยตs | Deep context chain lookup |
kachedb-radix | Insert 1,024-token sequence (64 new nodes) | 2.41 ยตs | ~37.6 ns per node |
kachedb-radix | Hierarchical Bottom-up LRU Eviction | 568.13 ns | Sub-microsecond memory reclaim |
kachedb-shm | Single-Thread 128B Slot Roundtrip | 89.39 ns | Lock-free push + pop |
kachedb-shm | Cross-Thread SPSC Ring Streaming | 66.47 ns / msg | 15.04 Million msgs/sec |
Phase 2: Wire Protocol & Asynchronous TCP Pipeline
| Crate | Benchmark Target | Measured Latency | Single-Core Capacity |
|---|---|---|---|
kachedb-proto-resp | Zero-Alloc GET Frame Parse & Decode | 68.80 ns | 14.53 Million cmds/sec |
kachedb-proto-resp | Zero-Alloc SET Frame Parse & Decode | 96.15 ns | 10.40 Million cmds/sec |
kachedb-proto-resp | Zero-Alloc MGET Frame Parse & Decode (4 keys) | 153.06 ns | 6.53 Million cmds/sec |
kachedb-proto-resp | Frame Bulk String Serialization | 8.25 ns | 121.2 Million frames/sec |
kachedb-net | Full GET Hit Pipeline Execution | 97.63 ns | 10.24 Million requests/sec / core |
kachedb-net | Full SET + DEL Cycle Execution | 267.58 ns | 3.74 Million write cycles/sec |
Phase 3: Multi-Core Server Daemon & Python Bindings
| Subsystem | Operation | Measured Performance | Context |
|---|---|---|---|
kachedb-cli | Live Server Loopback Ping-Pong (10K reqs) | 48,493 req/sec (20.62 ยตs/req) | Synchronous unpipelined TCP |
bindings/python | 64-byte Header Validation & Recovery | < 1 ยตs | 0 heap allocations |
bindings/python | Zero-Copy Tensor Extraction (np.frombuffer) | Instantaneous (< 50 ns) | 0 bytes copied (direct memory view) |
4. Reproducing Benchmarks
All benchmarks can be reproduced locally with:
# Run all crate micro-benchmarks
cargo bench --workspace
# Or run individual crate benchmarks
cargo bench -p kachedb-core
cargo bench -p kachedb-hash
cargo bench -p kachedb-radix
cargo bench -p kachedb-shm
cargo bench -p kachedb-proto-resp
cargo bench -p kachedb-net
KacheDB: Standardized Benchmark Reproduction Protocol
Document Version: 1.0
Target Engine: KacheDB v0.1.0+
This guide provides the exact methodology, hardware parameters, and commands to independently reproduce the published performance numbers for KacheDB.
1. Hardware & Environment Reference
To achieve identical peak throughput numbers, tests should be run on a dedicated bare-metal or high-priority virtualized host:
- CPU: Multi-core modern x86_64 or ARM64 (e.g. Apple Silicon M-series, AMD EPYC 9004, or Intel Xeon 4th Gen)
- Linux Kernel: Linux 6.8+ (for SQPOLL kernel thread pooling and
io_uringmultishot socket support) - RAM: Minimum 16 GB DDR4/DDR5
- IPC Mount:
/dev/shm(POSIX Shared Memory mounted astmpfs)
2. One-Command Turnkey Reproduction (Docker Linux)
Run the full end-to-end multi-core benchmark in an isolated Linux container with kernel io_uring + SQPOLL:
# From the repository root:
make benchmark-reproduce
This runs the automated suite inside Docker with --privileged and --ipc host, measuring:
- PING Throughput & Latencies (50 concurrent clients, pipeline 16)
- SET Throughput & Latencies (50 concurrent clients, pipeline 16, 64-byte payload)
- GET Throughput & Latencies (50 concurrent clients, pipeline 16)
3. Local Micro-Benchmarks (Criterion.rs)
Run the statistical Criterion micro-benchmarks with nanosecond-level resolution:
# Memory Allocator & Pool Benchmarks
cargo bench -p kachedb-core
# Swiss Table Point Index Benchmarks
cargo bench -p kachedb-hash
# Full Workspace Benchmarks
cargo bench --workspace
Measured Baselines:
arena::allocate (128 B): ~3.84 nspool::allocate+deallocate: ~5.40 nsswiss_table::lookup hit: ~3.09 nsradix::lookup (1,024 tokens): ~2.45 ยตs
4. Live Multi-Core TCP Benchmarks (kachedb-bench)
Start the multi-worker server and load generator manually:
# Build release binaries
cargo build --release --workspace
# Start server on 4 dedicated cores
./target/release/kachedb-server -p 6379 -w 4 &
SERVER_PID=$!
sleep 1
# Run PING benchmark
./target/release/kachedb-bench -p 6379 -n 100000 -c 50 --pipeline 16 --command PING
# Run SET benchmark
./target/release/kachedb-bench -p 6379 -n 100000 -c 50 --pipeline 16 --command SET
# Run GET benchmark
./target/release/kachedb-bench -p 6379 -n 100000 -c 50 --pipeline 16 --command GET
# Run Redis Hash benchmarks (v0.3.0+)
./target/release/kachedb-bench -p 6379 -n 100000 -c 50 --pipeline 16 -t HSET
./target/release/kachedb-bench -p 6379 -n 100000 -c 50 --pipeline 16 -t HGET
./target/release/kachedb-bench -p 6379 -n 100000 -c 50 --pipeline 16 -t HMIX
# Terminate server
kill $SERVER_PID