Skip to main content

kachedb

High-Performance Python Client for KacheDB — The Zero-Copy Redis-Compatible & LLM KV-Cache Storage Engine

PyPI Version Python Versions CI License


⚡ Installation

pip install kachedb

Installation Extras:

# Google EmbeddingGemma 2 (ONNX Runtime + Tokenizers, 8K context, 384-d/768-d MRL)
pip install "kachedb[gemma]"

# PyTorch tensor zero-copy support (FP16, BF16, FP32, INT8)
pip install "kachedb[torch]"

# vLLM PagedAttention KV-transfer plugin
pip install "kachedb[vllm]"

# SGLang RadixAttention KV-cache plugin
pip install "kachedb[sglang]"

# Install all plugins & dependencies
pip install "kachedb[all]"

🚀 Quickstart

Synchronous Client

from kachedb import KacheClient

with KacheClient(host="127.0.0.1", port=6379) as client:
    # Standard Redis-compatible operations
    client.set("user:1", "alice", ex=3600)  # SET with 1-hour TTL
    print(client.get("user:1"))  # b"alice"

    # Redis Hashes (sub-25ns in-slot Megaslab storage)
    client.hset("user:profile", mapping={"name": "Alice", "role": "admin"})
    print(client.hget("user:profile", "name"))  # b"Alice"
    print(client.hgetall("user:profile"))  # {b"name": b"Alice", b"role": b"admin"}

    # Batch operations
    client.set("user:2", "bob")
    result = client.mget("user:1", "user:2")  # [b"alice", b"bob"]

    # Check existence & delete
    print(client.exists("user:1"))  # 1
    client.delete("user:1", "user:2")

Async Client

import asyncio
from kachedb import AsyncKacheClient


async def main():
    async with AsyncKacheClient(host="127.0.0.1", port=6379) as client:
        await client.set("key", "value", ex=60)
        result = await client.get("key")
        print(result)  # b"value"


asyncio.run(main())

Pipeline Batching

from kachedb import KacheClient

with KacheClient() as client:
    pipe = client.pipeline()
    pipe.set("a", "1")
    pipe.set("b", "2")
    pipe.set("c", "3")
    pipe.get("a")
    pipe.get("b")
    pipe.get("c")

    results = pipe.execute()
    # ["OK", "OK", "OK", b"1", b"2", b"3"]

🧠 LLM KV-Cache Acceleration (vLLM & SGLang)

KacheDB serves as a high-speed, zero-copy L1/L2 KV-Cache Tier for AI inference engines, bypassing quadratic transformer attention prefill passes via POSIX shared memory (/dev/shm):

1. 🔌 vLLM PagedAttention Integration

Launch vLLM with the KacheDB KV connector:

vllm serve meta-llama/Meta-Llama-3-8B-Instruct \
  --kv-transfer-config '{"kv_connector": "kachedb.vllm.KacheDBConnector", "kv_role": "kv_both"}'

Programmatic Usage:

from kachedb.vllm import KacheDBConnector

connector = KacheDBConnector(rank=0, local_rank=0, block_size=16)

# Restore prefix blocks directly into GPU PagedAttention buffers
matched_states, is_hit = connector.recv_kv_caches_and_hidden_states(
    model_executable=model,
    model_input=model_input,
    kv_caches=gpu_kv_caches,
)

👉 Read the full vLLM Production Integration Guide.


2. 🌳 SGLang RadixAttention Integration

Use KacheDBSGLangConnector to offload and restore dynamic Radix tree branches:

from kachedb.sglang import KacheDBSGLangConnector

connector = KacheDBSGLangConnector(rank=0, local_rank=0, pool_size_mb=2048)

# 1. Offload an evicted Radix tree node (Variable-length token slice)
desc = connector.offload_node(
    node_id=node.id,
    token_ids=node.token_ids,
    k_tensors=node_k_tensors,
    v_tensors=node_v_tensors,
    parent_hash=parent_hash,
)

# 2. Restore cached prefix subtree directly into target GPU/CPU memory
matched_tokens, is_hit = connector.restore_prefix(
    prompt_tokens=incoming_prompt_token_ids,
    target_k_buffers=target_k_buffers,
    target_v_buffers=target_v_buffers,
)

👉 Read the full SGLang Production Integration Guide.


3. 🧠 Semantic Vector Cache with Google EmbeddingGemma 2 (8K Context, 384-d MRL)

Use EmbeddingGemmaAdapter with local ONNX Runtime weights (model.onnx + tokenizer.json) for 8,192-token semantic caching without PyTorch overhead:

from kachedb import EmbeddingGemmaAdapter, KacheClient, SemanticCache

embedder = EmbeddingGemmaAdapter(
    model_path="/path/to/models/embeddinggemma-2",  # or set EMBEDDING_MODEL_PATH
    dimension=384,  # 384 (default MRL slice) or 768 (native)
)

# 1. Direct encoding with asymmetric task prefixes
query_vec = embedder.encode_query("What is an LLM?")
doc_vec = embedder.encode_document("Large Language Models are neural networks...")

# 2. Synchronous or Asynchronous Semantic Cache
with KacheClient(host="127.0.0.1", port=6380) as client:
    cache = SemanticCache(client=client, index_name="llm_cache", embedder=embedder)
    cache.set("What is an LLM?", "Large Language Models are neural networks...")
    hit = cache.get("In short explain LLM?")
    if hit:
        print(f"Hit ({hit.similarity:.3f}): {hit.value}")

⚡ Master Proof-of-Speed Benchmarks

Evaluated on Meta-Llama-3-8B Topology (32 Layers, 8 KV Heads, FP16) connected to the live KacheDB storage engine:

Context Length KV Cache Size 🔴 Cold GPU Recompute 🟢 SGLang + KacheDB ⚡ Speedup
512 tokens 64.0 MB 2,429.8 ms 7.99 ms 304.1× ⚡
1,024 tokens 128.0 MB 607.9 ms 7.17 ms 84.8× ⚡
2,048 tokens 256.0 MB 1,425.1 ms 9.61 ms 148.3× ⚡
4,096 tokens 512.0 MB 3,164.2 ms 10.14 ms 312.2× ⚡
8,192 tokens 1,024.0 MB 5,541.6 ms 9.25 ms 599.1× ⚡
16,384 tokens 2,048.0 MB (2GB) 26,081.1 ms (26.1s) 18.71 ms 1,393.9× ⚡

📋 Supported Commands

All commands follow the KacheDB RESP2/RESP3 wire protocol:

Command Method Description
PING client.ping() Test server liveness
SET client.set(key, value, ex=, px=) Store value with optional TTL
GET client.get(key) Retrieve value
MGET client.mget(*keys) Batch retrieve multiple keys
DEL client.delete(*keys) Delete keys
EXISTS client.exists(*keys) Count existing keys

🏗️ Architecture

┌──────────────────────────────────────────────────────────┐
│                     Your Python App                      │
│             (vLLM / SGLang / FastAPI / etc.)             │
├──────────────────────────────────────────────────────────┤
│                   kachedb Python SDK                     │
│  ┌──────────────┐  ┌──────────────┐  ┌────────────────┐  │
│  │ KacheClient  │  │  AsyncKache  │  │    Pipeline    │  │
│  │  (sync TCP)  │  │    Client    │  │    Batching    │  │
│  └──────┬───────┘  └──────┬───────┘  └───────┬────────┘  │
│         │                 │                  │           │
│  ┌──────┴─────────────────┴──────────────────┴────────┐  │
│  │            RESP2/RESP3 Protocol Engine             │  │
│  │         (64KB buffered encoder + decoder)          │  │
│  └──────────────────────┬─────────────────────────────┘  │
│                         │                                │
│  ┌──────────────────────┴─────────────────────────────┐  │
│  │        ConnectionPool / AsyncConnectionPool        │  │
│  │    (Thread-safe / asyncio.Queue, health checks)    │  │
│  └──────────────────────┬─────────────────────────────┘  │
├─────────────────────────┼────────────────────────────────┤
│                   TCP + /dev/shm                         │
├──────────────────────────────────────────────────────────┤
│                  KacheDB Server (Rust)                   │
│         io_uring / kqueue │ POSIX SHM │ Megaslab         │
└──────────────────────────────────────────────────────────┘

🧪 Development & Quality Gates

# Clone
git clone https://github.com/vubon/kachedb-py.git
cd kachedb-py

# Install in editable dev mode with all extras
pip install -e ".[all,dev]"

# Run full test suite (124+ tests)
pytest tests/ -v

# Code formatting & linting
ruff check src/ tests/
ruff format --check src/ tests/

# Strict type checking
mypy src/

🔗 Documentation & Guides


📄 License

Dual-licensed under either of:

Metadata

Release files for kachedb 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for kachedb 0.4.0
File Size Uploaded Provenance Actions
kachedb-0.4.0.tar.gz 89.8 kB With provenance Details for kachedb-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for kachedb 0.4.0
File Interpreter ABI Platform Actions
kachedb-0.4.0-py3-none-any.whl Python 3 none any Details for kachedb-0.4.0-py3-none-any.whl

Total release size: 155.5 kB

Release files / kachedb-0.4.0.tar.gz

Download URL kachedb-0.4.0.tar.gz
Size 89.8 kB
Tags Source
SHA-256 checksum
How to use checksums
d4e1c11ba01dd82dc86d92b86b0ba1dae8cc37bc1208a52ba470132a188431fa
BLAKE2b-256 checksum
How to use checksums
17dd955ad807942defba5808c8d06d49e965dcc2fad9a9ac3bf4d07d290d1f64
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

Release files / kachedb-0.4.0-py3-none-any.whl

Download URL kachedb-0.4.0-py3-none-any.whl
Size 65.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
505241b30b212ee687f70baac5402c8840cc5bdd9b8dd6159f011db8fff11493
BLAKE2b-256 checksum
How to use checksums
4a40a2d067c3d011347915d057758f3bdb9c752e296f7b610d989e5119b8862f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

Security for kachedb 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for kachedb-0.4.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page