Skip to main content

⚡ lightning-disk-kv

This project is an absurdly fast, sharded Key-Value storage engine designed for high-throughput Python applications.

It is a drop-in solution for machine learning pipelines that need to store millions of embeddings (or other data type) samples efficiently. It solves the Global Interpreter Lock (GIL) bottleneck by offloading hashing, serialization, and disk I/O to parallel Rust threads.

🚀 Key Features

  • True Parallelism: Writes to multiple LMDB shards simultaneously using all CPU cores.
  • Zero-Copy Vectors: Specialized "Fast Path" for numpy arrays that writes raw bytes to disk (no pickling).
  • Generic Storage: Capable of storing arbitrary Python objects (Strings, Dicts, Lists) via optimized parallel pickling.
  • Crash Safe: Based on LMDB (Lightning Memory-Mapped Database), offering proven reliability.
  • Redis Compatible: Includes a wrapper that mimics the redis-py API for easy integration.

📦 Installation

Option A: Install via Pip (Recommended)

pip install lightning_disk_kv

Option B: Build from Source

If you are modifying the Rust code or building for a specific architecture:

# Requires Rust and Maturin
maturin develop --release

⚡ Usage Guide

1. Initialization

Initialize the database by specifying a base directory. The storage engine automatically handles sharding (splitting data across multiple files) to maximize write speed.

from lightning_disk_kv import LDKV

# Initialize with 5 shards.
# 'map_size' is the maximum virtual memory size. 
# It does NOT consume this amount of RAM immediately.
# Default is ~1TB, which is safe for 64-bit systems.
db = LDKV(
    base_path="./my_database", 
    num_shards=5, 
    map_size=100 * 1024**3  # 100 GB limit
)

2. Storing Vectors (The "Fast Path")

Use store_vectors when dealing with Numpy embeddings. This bypasses Python's overhead entirely by reading memory directly from C-pointers.

Requirement: Data must be np.float32.

import numpy as np

# Create dummy data
ids = [1, 2, 3]
vectors = np.random.rand(3, 128).astype(np.float32)

# Store in parallel
db.store_vectors(vectors, ids)

# Retrieve
# Returns a list of numpy arrays, or None if the ID doesn't exist
results = db.get_vectors([1, 999])

print(results[0].shape)  # (128,)
print(results[1])        # None

3. Storing Objects (The "Generic Path")

Use store_data for strings, dictionaries, images, or lists. While this uses pickle internally, the serialization and disk writing happen in parallel threads, making it significantly faster than standard loops.

ids = [100, 101]
data = [
    "A simple string", 
    {"key": "value", "meta": [1, 2, 3]}
]

db.store_data(data, ids)

results = db.get_data([100])
print(results[0]) # "A simple string"

4. Redis Compatibility API

We provide a redis-py compatible wrapper. This allows you to use lightning-disk-kv as an embedded, persistent Redis replacement without running a separate server process.

from lightning_redis import LDKV_RedisCompat

# Initialize (replaces host/port with a file path)
r = LDKV_RedisCompat(base_path="./redis_data", decode_responses=True)

# Basic Key-Value
r.set('foo', 'bar')
print(r.get('foo'))  # 'bar'

# TTL (Time To Live) - key automatically removed after 5 seconds
r.set('temp_key', 'hidden', ex=5)

# Atomic Counters
r.incr('visitor_count', amount=1)

# Hash Maps
r.hset('user:100', mapping={'name': 'Alice', 'role': 'admin'})
print(r.hgetall('user:100')) # {'name': 'Alice', 'role': 'admin'}

5. Management & Syncing

# Check total number of items across all shards
count = db.get_data_count()
print(f"Total items: {count}")

# Delete items
db.delete_data([1, 100])

# Force flush to disk
# The engine uses OS buffers for maximum speed. 
# Call .sync() to ensure data is physically written to the drive.
db.sync()

⚠️ Configuration & Safety

Understanding map_size

LMDB uses a memory map. You must set map_size larger than the maximum data you ever intend to store.

  • Don't worry about RAM: Setting this to 1TB does not use 1TB of RAM. It simply reserves virtual address space.
  • Error handling: If you exceed this limit, you will get a MapFull error.

Durability vs. Speed

To achieve maximum throughput, lightning_disk_kv sets the MDB_NOSYNC flag by default.

  • Application Crash: Data is safe.
  • OS Crash / Power Cut: Data currently in the OS buffer (last few seconds) might be lost.
  • Best Practice: If data durability is critical (e.g., you can't re-generate the data), call db.sync() periodically or after a large bulk insert.

🛠 Building from Source (Advanced)

If you cannot install via pip, you must compile the Rust backend manually.

  1. Install Rust:
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
    
  2. Install the builder:
    pip install maturin
    
  3. Compile: Navigate to the project root and run:
    maturin develop --release
    

Metadata

Release files for lightning-disk-kv 1.1.2

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

Source distribution (sdist)

Source distribution for lightning-disk-kv 1.1.2
File Size Uploaded Provenance
lightning_disk_kv-1.1.2.tar.gz 20.3 kB Without provenance Details

Built distributions (wheels)

Table of built distributions (wheels) for lightning-disk-kv 1.1.2
File Interpreter ABI Platform
lightning_disk_kv-1.1.2-cp38-abi3-win_amd64.whl CPython 3.8 abi3 Windows x86-64 Details
lightning_disk_kv-1.1.2-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl CPython 3.8 abi3 Linux glibc 2.17+ x86-64 Details
lightning_disk_kv-1.1.2-cp38-abi3-macosx_11_0_arm64.whl CPython 3.8 abi3 macOS 11.0+ ARM64 Details

Total release size: 1.4 MB

Release files / lightning_disk_kv-1.1.2.tar.gz

Download URL lightning_disk_kv-1.1.2.tar.gz
Size 20.3 kB
Tags Source
SHA-256 checksum
How to use checksums
189bae73f9f8aecc28a08268db935703e40e548b414fedd325656fe5490d4fa7
BLAKE2b-256 checksum
How to use checksums
0def5297c18a5efff954886b4aef68be07bbc36c5b1a9e6b158cdd76ba25fed8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.13.3

Release files / lightning_disk_kv-1.1.2-cp38-abi3-win_amd64.whl

Download URL lightning_disk_kv-1.1.2-cp38-abi3-win_amd64.whl
Size 344.9 kB
Tags CPython 3.8 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
72fc52469ed580aca400b7f8e9152c41d70b81c51d36d51a9a6704b69999e0e9
BLAKE2b-256 checksum
How to use checksums
a07e4292bd010bfd46c283f1e085655f0f31ebd09007cdf88500c09ae18327f9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.13.3

Release files / lightning_disk_kv-1.1.2-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Download URL lightning_disk_kv-1.1.2-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Size 526.0 kB
Tags CPython 3.8 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
59c4ecebe08fa5aabd79becdab627221bf7633edb932e194f9f27fbcb8eae8cb
BLAKE2b-256 checksum
How to use checksums
ae9fb3f4f3c0b45b0ab6aa89e26987837ef4223377b91eee77ce9ead773b2d63
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.13.3

Release files / lightning_disk_kv-1.1.2-cp38-abi3-macosx_11_0_arm64.whl

Download URL lightning_disk_kv-1.1.2-cp38-abi3-macosx_11_0_arm64.whl
Size 465.0 kB
Tags CPython 3.8 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
733f8f8f5480917db07efca7da74758a300334da2e1557249b1de63b9f41af2d
BLAKE2b-256 checksum
How to use checksums
a76974857b796ec465ecfa8829c8e52529d70406605b7cd9051184dbbb641d73
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.13.3

Security for lightning-disk-kv 1.1.2

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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