Skip to main content

Examples & Recipes

Real-world examples fetched from the repository and production patterns for concurrent coordination, TTL, and persistence.

v3.1.1
Updated from GitHub 10/18/2026
Edit on GitHub
Filter:

Session Store with Auto-TTL & Auditing

TTLConcurrencyPersistence

a realistic session-store example.

examples/session_store.py
GitHub
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Hemanshu Vaidya
"""session_store.py - a realistic session-store example.
Shows: TTL-based session expiry, reactive logging of session lifecycle
events (useful for auditing/security monitoring), and atomic() for a
per-session request counter that's safe even if a session is hit by
concurrent requests.
Run: python examples/session_store.py
"""
import time
from nimbuskv import NimbusKV
SESSION_TTL_SECONDS = 60 * 30 # 30 minutes
def create_session(store: NimbusKV, user_id: str) -> str:
session_id = f"sess_{user_id}_{int(time.time())}"
store.set(
f"session:{session_id}",
{"user_id": user_id, "created_at": time.time(), "requests": 0},
ttl=SESSION_TTL_SECONDS,
)
return session_id
def touch_session(store: NimbusKV, session_id: str) -> None:
"""Bump the request counter for a session -- safe under concurrent
requests for the same session, no lock held."""
key = f"session:{session_id}"
def _bump(session):
if session is None:
return session # already expired/gone -- nothing to bump
session = dict(session)
session["requests"] += 1
return session
store.atomic(key, _bump, default=None)
def main():
with NimbusKV() as store:
# Log every session lifecycle event -- this is the kind of thing
# you'd wire into real audit logging or a security dashboard.
def audit_log(key, event, old, new):
if event == "expire":
print(f"[audit] session expired: {key}")
elif event == "set" and old is None:
print(f"[audit] session created: {key}")
store.subscribe(audit_log, key=None)
session_id = create_session(store, user_id="alvin")
print("Created session:", session_id)
for _ in range(5):
touch_session(store, session_id)
session = store.get(f"session:{session_id}")
print("Session state:", session)
assert session["requests"] == 5
# Simulate a short-lived demo session to show expiry firing --
# not something you'd normally do with a real 30-minute TTL.
demo_id = "demo_session"
store.set(f"session:{demo_id}", {"user_id": "demo"}, ttl=1)
print("Waiting for demo session to expire...")
time.sleep(1.5)
print("Demo session after expiry:", store.get(f"session:{demo_id}"))
if __name__ == "__main__":
main()

Producer / Consumer Worker Pool with wait_for()

ConcurrencyAsync

producer/consumer coordination without polling.

examples/worker_pool.py
GitHub
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Hemanshu Vaidya
"""worker_pool.py - producer/consumer coordination without polling.
This is the example that actually demonstrates why NimbusKV's reactivity
matters, not just its caching: multiple worker threads pick up jobs and
report results, a dispatcher waits on completion with wait_for() instead
of a sleep-and-poll loop, and atomic() coordinates a shared "jobs done"
counter safely across threads.
Run: python examples/worker_pool.py
"""
import threading
import time
from nimbuskv import NimbusKV
def worker(store: NimbusKV, worker_id: int, job_queue: list, lock: threading.Lock):
"""A worker thread that pulls jobs off a shared list and reports
results into the store. (The job queue itself uses a plain lock
here for simplicity -- NimbusKV isn't a queue, it's the shared
state / coordination layer around one.)
"""
while True:
with lock:
if not job_queue:
return
job_id = job_queue.pop()
time.sleep(0.1) # simulate work
result = job_id * job_id
store.set(f"job:{job_id}:result", result)
store.atomic("jobs_completed", lambda v: (v or 0) + 1)
print(f"[worker {worker_id}] finished job {job_id} -> {result}")
def main():
with NimbusKV() as store:
store.set("jobs_completed", 0)
n_jobs = 8
job_queue = list(range(1, n_jobs + 1))
queue_lock = threading.Lock()
workers = [
threading.Thread(target=worker, args=(store, i, job_queue, queue_lock))
for i in range(3)
]
for w in workers:
w.start()
# The dispatcher doesn't poll or sleep-loop to know when all jobs
# are done -- it blocks on wait_for(), which is driven by the
# subscription system and unblocks the instant the condition is
# actually met.
print("Dispatcher waiting for all jobs to complete...")
store.wait_for("jobs_completed", lambda v: v == n_jobs, timeout=30)
print("All jobs completed.")
for w in workers:
w.join()
results = {job_id: store.get(f"job:{job_id}:result") for job_id in range(1, n_jobs + 1)}
print("Results:", results)
if __name__ == "__main__":
main()

High-Concurrency Atomic Counters

Concurrency

Safely update shared numeric counters across multiple concurrent threads using atomic() without races or lost updates.

recipes/atomic_counter.py
from nimbuskv import NimbusKV
import threading
store = NimbusKV()
store.set("hit_count", 0)
def increment_hits():
for _ in range(1000):
store.atomic("hit_count", lambda current: (current or 0) + 1)
threads = [threading.Thread(target=increment_hits) for _ in range(10)]
for t in threads: t.start()
for t in threads: t.join()
print("Final Hits:", store.get("hit_count")) # Exactly 10000

Async Operations with SQLite Mirroring

AsyncPersistence

Use aget() and aset() in an asyncio loop with SQLite write-through persistence. Reads stay non-blocking in memory.

recipes/async_sqlite.py
import asyncio
from nimbuskv import NimbusKV
async def main():
# SQLite persistence: in-memory live reads + async background write-through
with NimbusKV(backend="sqlite:cache.db") as store:
await store.aset("user:101", {"name": "Alice", "role": "admin"}, ttl=300)
user = await store.aget("user:101")
print(f"Loaded: {user['name']} (TTL active)")
asyncio.run(main())

Atomic Multi-Key Batch Swap

Concurrency

Update multiple related keys simultaneously with mset() so concurrent readers never see a partial state update.

recipes/multi_key_batch.py
from nimbuskv import NimbusKV
with NimbusKV() as store:
# Readers will either see both new values or neither, never partial
store.mset({
"order:402:status": "COMPLETED",
"order:402:paid_at": "2026-10-11T09:00:00Z",
"inventory:item_9:stock": 42
})
results = store.mget(["order:402:status", "inventory:item_9:stock"])
print(results) # {'order:402:status': 'COMPLETED', 'inventory:item_9:stock': 42}