Skip to main content

rust-py-cache

An ultra-fast local cache for Python, powered by Rust.

A local, in-memory, thread-safe cache with TTL, lazy expiration, and metrics. The core is written in Rust (PyO3 + maturin) on top of a concurrent DashMap; the Python API is minimal. Think of it as a "mini Redis" living inside your Python process.

PyPI Python License: MIT

🌐 Website: rust-py-cache.vercel.app

Installation

pip install rust-py-cache

To work on it locally (requires Rust + maturin):

python -m venv .venv && source .venv/bin/activate
pip install maturin pytest
maturin develop          # compiles the Rust core and installs into the venv
pytest                   # runs the tests

Usage

from rust_py_cache import Cache

cache = Cache()

cache.set("user:1", {"name": "Roberto"}, ttl=60)   # ttl in seconds
user = cache.get("user:1")                          # {"name": "Roberto"}
cache.get("missing", default=0)                     # 0

cache.exists("user:1")        # True (honors TTL)
cache.delete("user:1")        # True if removed, False if absent
cache.len()                   # approximate size
cache.keys()                  # list of keys
cache.cleanup_expired()       # remove expired entries; returns the count
cache.clear()                 # remove everything (keeps counters)
cache.stats()                 # {'hits','misses','sets','deletes','expired','evicted','size'}

Bounded cache with LRU eviction

# Cap the number of keys. When full and a new key arrives, evict the
# least-recently-used entries (a ~3% batch) instead of rejecting the write.
cache = Cache(max_size=1000, eviction_policy="lru")
cache.eviction_policy            # "lru"

# Default policy is "reject": set() returns False when full (and the key is new).
cache = Cache(max_size=1000)     # eviction_policy="reject"
cache.set("a", 1)                # True / False

Background expiration

# A background thread reclaims expired entries every N seconds, so you don't
# have to call cleanup_expired() yourself. It stops when the cache is collected.
cache = Cache(cleanup_interval=30)   # seconds (int/float)

Memoization decorator

@cache.cached(ttl=60)
def add(a, b):
    return a + b

add(2, 3)   # runs and caches
add(2, 3)   # served from cache

# custom key (fixed string or callable):
@cache.cached(ttl=300, key=lambda user_id: f"user:{user_id}")
def load_user(user_id):
    ...

See full examples under examples/ (FastAPI and Django).

API

Constructor: Cache(max_size=None, eviction_policy="reject", cleanup_interval=None). eviction_policy must be "reject" or "lru" (any other value raises ValueError). cleanup_interval (seconds, > 0) enables the background sweeper.

Method Description
set(key, value, ttl=None) Store a value. ttl in seconds (int/float); None = no expiration; ttl <= 0 → ValueError. Overwrites. Returns True, or False when full under eviction_policy="reject" and the key is new.
get(key, default=None) The value, or default if missing/expired (expired entries are removed).
delete(key) True if removed, False if it didn't exist.
exists(key) True/False, honoring TTL.
keys() List of keys (may include expired-but-not-yet-collected ones).
len() / len(cache) Approximate size.
clear() Remove everything (does not reset counters).
cleanup_expired() Remove expired entries; returns how many.
eviction_policy (property) The active policy: "reject" or "lru".
stats() dict with hits, misses, sets, deletes, expired, evicted, size.
@cache.cached(ttl=None, key=None) Memoization decorator.

How it works

  • Serialization: in the MVP, values are serialized with pickle (on the Python side, via PyO3) and stored as opaque bytes (Vec<u8>) in the Rust core.
  • Concurrency: DashMap (a HashMap with per-shard locks) plus AtomicU64 counters, with no global lock on the hot path. Thread-safe, no busy loop.
  • TTL: expiration is lazy by default — an expired key is removed when accessed (get/exists) or via cleanup_expired(). Pass cleanup_interval to also run a background sweeper thread that reclaims expired keys on its own.
  • Eviction: with max_size + eviction_policy="lru", a full cache evicts the least-recently-used entries (recency updated on every get hit) to admit a new key. It removes them in a batch of max_size / 32 (at least 1) per pass, so the O(n) scan that finds them runs once every ~n/32 inserts instead of on every one — amortized O(1) per write, with no global lock on the get/set path. A set on a full 100k-entry cache went from ~620 µs (one full scan per insert, up to 0.2.x) to ~1.6 µs. Right after a pass the cache sits ~3% below max_size.

Limitations

  • The cache is process-local: multiple workers = multiple independent caches.
  • It does not replace Redis for distributed caching.
  • Data is lost when the process restarts.
  • pickle must not be used to deserialize untrusted data.
  • Lazy TTL by default: without cleanup_interval, expired items may linger until accessed or until cleanup_expired() runs.

Development

cargo test          # Rust core tests
maturin develop     # rebuild and install
pytest              # Python tests

If maturin develop complains about both VIRTUAL_ENV and CONDA_PREFIX being set, run conda deactivate first, or use env -u CONDA_PREFIX maturin develop.

Roadmap

Stages and next steps (LRU/LFU eviction, background expiration, configurable serializer, namespaces, etc.) are in ROADMAP.md.

License

MIT

Metadata

Release files for rust-py-cache 0.3.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 rust-py-cache 0.3.0
File Size Uploaded Provenance
rust_py_cache-0.3.0.tar.gz 38.9 kB With provenance Details

Built distributions (wheels)

Table of built distributions (wheels) for rust-py-cache 0.3.0
File
rust_py_cache-0.3.0-cp310-abi3-win_amd64.whl CPython 3.10 abi3 Windows x86-64 Details
rust_py_cache-0.3.0-cp310-abi3-musllinux_1_2_x86_64.whl CPython 3.10 abi3 Linux musl 1.2+ x86-64 Details
rust_py_cache-0.3.0-cp310-abi3-musllinux_1_2_aarch64.whl CPython 3.10 abi3 Linux musl 1.2+ ARM64 Details
rust_py_cache-0.3.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl CPython 3.10 abi3 Linux glibc 2.17+ x86-64 Details
rust_py_cache-0.3.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl CPython 3.10 abi3 Linux glibc 2.17+ ARM64 Details
rust_py_cache-0.3.0-cp310-abi3-macosx_11_0_arm64.whl CPython 3.10 abi3 macOS 11.0+ ARM64 Details
rust_py_cache-0.3.0-cp310-abi3-macosx_10_12_x86_64.whl CPython 3.10 abi3 macOS 10.12+ x86-64 Details

Total release size: 2.5 MB

Release files / rust_py_cache-0.3.0.tar.gz

Download URL rust_py_cache-0.3.0.tar.gz
Size 38.9 kB
Tags Source
SHA-256 checksum
How to use checksums
4ba443e10b900a438f4593bb0323692dfed9dfff387c28ec83c02609f7671a8b
BLAKE2b-256 checksum
How to use checksums
6f1358a3821f553e742d6489a0516deae9815f58c7aa9ee8fd0c3d2a40b5b9a0
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 Oct 20, 2026.

Transparency log

Release files / rust_py_cache-0.3.0-cp310-abi3-win_amd64.whl

Download URL rust_py_cache-0.3.0-cp310-abi3-win_amd64.whl
Size 180.4 kB
Tags CPython 3.10 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
8893e8e0fd01399037eba4600f26e0d5dcfadf42e2353cf3cf0367248a5b9fae
BLAKE2b-256 checksum
How to use checksums
a459e573ee2a7accd3c9366a2edfd99937ee917a2f7a9dd4cf5f49ee6ce62857
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 Oct 20, 2026.

Transparency log

Release files / rust_py_cache-0.3.0-cp310-abi3-musllinux_1_2_x86_64.whl

Download URL rust_py_cache-0.3.0-cp310-abi3-musllinux_1_2_x86_64.whl
Size 543.5 kB
Tags CPython 3.10 Linux musl 1.2+ x86-64 abi3
SHA-256 checksum
How to use checksums
cb8f6619dcd9a316491b5d33366fbf606c11f7c30abd842d7cc888c2ad19f034
BLAKE2b-256 checksum
How to use checksums
53fb4e04ad4a0b0297f2d7ab4f0cd59ad4c827ab823615ef0a5ae248da31ff7c
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 Oct 20, 2026.

Transparency log

Release files / rust_py_cache-0.3.0-cp310-abi3-musllinux_1_2_aarch64.whl

Download URL rust_py_cache-0.3.0-cp310-abi3-musllinux_1_2_aarch64.whl
Size 511.6 kB
Tags CPython 3.10 Linux musl 1.2+ ARM64 abi3
SHA-256 checksum
How to use checksums
13daf31801dd4fc7360284a1751b5d77d1903adf14cf1a2f2ec1b68c9b2135fd
BLAKE2b-256 checksum
How to use checksums
fa1716cefa41931ff50f5187ab8db8fec3f9904c6ed56a24d493854cb9ee71c9
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 Oct 20, 2026.

Transparency log

Release files / rust_py_cache-0.3.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Download URL rust_py_cache-0.3.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Size 337.9 kB
Tags CPython 3.10 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
d3dfb4cba07066e0fced46698bf721a9c79b16e0fe8f9a50f96fec9b26700e52
BLAKE2b-256 checksum
How to use checksums
bed699821e36994dbb0298066f2f18b8bc406375ef1ea22a8e637b65b42efbf7
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 Oct 20, 2026.

Transparency log

Release files / rust_py_cache-0.3.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl

Download URL rust_py_cache-0.3.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Size 335.2 kB
Tags CPython 3.10 Linux glibc 2.17+ ARM64 abi3
SHA-256 checksum
How to use checksums
7ef9ffba74479fb3b7dc951b40e6262e0c05fa446508ce82b43daa6b99a5626d
BLAKE2b-256 checksum
How to use checksums
e6e6354ec48f9057703602f32eb4ffb6ebc194a16edb0ec4bb31e6289ec8e6e2
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 Oct 20, 2026.

Transparency log

Release files / rust_py_cache-0.3.0-cp310-abi3-macosx_11_0_arm64.whl

Download URL rust_py_cache-0.3.0-cp310-abi3-macosx_11_0_arm64.whl
Size 291.8 kB
Tags CPython 3.10 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
463c3527479e51a6834f1fffab21bd00a122e17faca051c90c0f9704ae8d0a1e
BLAKE2b-256 checksum
How to use checksums
fad630a7d7508ed01d0a2882bf26f9c85f8d05ee076e62d1e441ed06753543d8
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 Oct 20, 2026.

Transparency log

Release files / rust_py_cache-0.3.0-cp310-abi3-macosx_10_12_x86_64.whl

Download URL rust_py_cache-0.3.0-cp310-abi3-macosx_10_12_x86_64.whl
Size 296.3 kB
Tags CPython 3.10 abi3 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
d44e85c73c7a8c8e74ff65e1443fb13bb9f42c8ebd834517ebf6105749a8bfd7
BLAKE2b-256 checksum
How to use checksums
a085a895d4927f39c045ce183ed5f9640dceec8403be1427dc6e1a5fa48ce320
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 Oct 20, 2026.

Transparency log

Security for rust-py-cache 0.3.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

All 8 files in this release have been uploaded with provenance metadata.

Select from 8 files

Attestation for rust_py_cache-0.3.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 Oct 20, 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.

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