Skip to main content

Redis-like in-memory cache engine for Python — zero dependencies

Project description

ZeroCache 🚀

Redis-like in-memory cache engine for Python — zero dependencies.

CI PyPI Python License: MIT Coverage


✨ Features

Feature Details
Zero dependencies Pure Python standard library only
Redis-like API String/Hash/List/Set/SortedSet + Pipeline + Pub/Sub
16-shard locking Per-shard RLock — parallel ops on different keys
Heap-based TTL O(log n) expiry sweep every 100 ms
Async-native async_get/set/... via run_in_executor, never blocks event loop
Persistence Crash-safe atomic snapshot with zlib compression
LRU eviction Per-shard LRU, O(1) eviction via OrderedDict
@cached decorator Works with both sync and async functions
FastAPI ready get_cache() as a Depends dependency
Type annotations PEP 561 typed package, mypy strict compatible

📦 Installation

pip install zero-cache

Requires Python 3.10+.


⚡ Quick Start

from zerocache import ZeroCache

cache = ZeroCache()

# String
cache.set("user:name", "Alice", ttl=300)
cache.get("user:name")          # → "Alice"

# Hash
cache.hset("user:1", "name", "Alice")
cache.hget("user:1", "name")    # → "Alice"

# List
cache.rpush("queue", "task1", "task2")
cache.lpop("queue")             # → "task1"

# Set
cache.sadd("tags", "python", "cache")
cache.sismember("tags", "python")  # → True

# Sorted Set
cache.zadd("leaderboard", {"alice": 100, "bob": 85})
cache.zrange("leaderboard", 0, -1)  # → ["bob", "alice"]

🚀 Async Usage

import asyncio
from zerocache import ZeroCache

cache = ZeroCache()

async def main():
    await cache.async_set("key", "value", ttl=60)
    result = await cache.async_get("key")
    print(result)  # → "value"

asyncio.run(main())

🎯 @cached Decorator

from zerocache import cached

@cached(ttl=300)
async def get_user(user_id: int):
    return await db.fetch(user_id)

@cached(key_prefix="compute", ttl=60)
def compute_heavy(n: int) -> int:
    return n ** n

🔄 Pipeline

results = (
    cache.pipeline()
        .set("a", 1)
        .set("b", 2)
        .incr("a")
        .get("b")
        .execute()
)
# → [True, True, 2, 2]

📡 Pub/Sub

import asyncio
from zerocache import ZeroCache

cache = ZeroCache()

async def listener():
    queue = await cache.subscribe("events")
    msg = await queue.get()
    print(f"Received: {msg}")

async def publisher():
    await asyncio.sleep(0.1)
    await cache.publish("events", {"type": "user_login", "user_id": 42})

asyncio.run(asyncio.gather(listener(), publisher()))

🌐 FastAPI Integration

from fastapi import FastAPI, Depends
from zerocache import ZeroCache, get_cache

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int, cache: ZeroCache = Depends(get_cache)):
    cached = cache.get(f"item:{item_id}")
    if cached:
        return cached
    result = {"id": item_id, "name": "Widget"}
    cache.set(f"item:{item_id}", result, ttl=60)
    return result

⚙️ Configuration

cache = ZeroCache(
    maxsize=100_000,          # Total key capacity
    num_shards=16,            # Lock shard count (power of 2)
    persist_path=".cache.db", # Snapshot file
    auto_save_interval=30,    # Seconds between auto-saves
    compress=True,            # zlib compression for snapshots
    load_on_start=True,       # Resume from disk on startup
    track_hits=True,          # Count per-key hits
    intern_keys=True,         # sys.intern() for less RAM
)

📊 Benchmark

Approximate throughput on a modern CPU (single thread):

Operation ops/sec
set ~1,200,000
get (hit) ~1,500,000
hset ~900,000
zadd ~700,000

🤝 Contributing

See CONTRIBUTING.md for guidelines.


📄 License

MIT — see LICENSE.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pyzerocache-1.1.1.tar.gz (29.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pyzerocache-1.1.1-py3-none-any.whl (19.8 kB view details)

Uploaded Python 3

File details

Details for the file pyzerocache-1.1.1.tar.gz.

File metadata

  • Download URL: pyzerocache-1.1.1.tar.gz
  • Upload date:
  • Size: 29.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for pyzerocache-1.1.1.tar.gz
Algorithm Hash digest
SHA256 9ceb5525a30eb34881ebe5953c6db636a416813649e468dce393ad87bae017b7
MD5 963d1d4866dc0634339068b0d7eaed16
BLAKE2b-256 96dd4691481399d75064cff01922daadf665c3ec83146b50b1897760c0e7864c

See more details on using hashes here.

Provenance

The following attestation bundles were made for pyzerocache-1.1.1.tar.gz:

Publisher: public.yml on Zeustakeshi/Zero-cache

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file pyzerocache-1.1.1-py3-none-any.whl.

File metadata

  • Download URL: pyzerocache-1.1.1-py3-none-any.whl
  • Upload date:
  • Size: 19.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for pyzerocache-1.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 8b4633cb4fe3e8fd081a266743ef3dac1a88cc7ca2bd82f41241d793f9efbadf
MD5 e5ed956cbbd589a5efe8008484969dd7
BLAKE2b-256 fa75c1f7f35d2ec34d86bf2e2cd7a3a93b988b4c8caf8752a77fa48e0897bf8b

See more details on using hashes here.

Provenance

The following attestation bundles were made for pyzerocache-1.1.1-py3-none-any.whl:

Publisher: public.yml on Zeustakeshi/Zero-cache

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page