Storage Backends

Pluggable storage for FSM state persistence. Choose between in-memory for development, Redis for production, or implement your own.

Choosing a Backend

BackendPersistenceDistributedExtra depBest For
MemoryStorage❌ In-processnoneDevelopment, testing
SQLiteStorage v0.5✅ File on diskaiosqliteSingle-process bots that need persistence
RedisStorage✅ Survives restartredisProduction, multi-instance
CustomPostgreSQL, MongoDB, etc.

BaseStorage Interface

All storage backends implement this abstract interface:

MethodDescription
get_state(id)Retrieve state document by identifier
set_state(id, state, *, ttl=None)Overwrite state with optional TTL
delete_state(id)Remove state; returns True if key existed
compare_and_set(id, new, *, expected, ttl)Atomic CAS — writes only if current value equals expected
increment(id, amount=1, *, ttl=None)v0.5.0 — Atomic counter increment; returns new count. Used by RateLimitMiddleware
list_keys(pattern)List keys matching a glob pattern
clear_namespace()Delete all keys in the storage namespace
health()Return True if storage is reachable
start() / stop()Lifecycle — connect/disconnect and start/stop background tasks

increment() v0.5.0

Atomic counter used internally by RateLimitMiddleware but available for any use-case (feature flags, visit counters, etc.).

# MemoryStorage — asyncio lock, in-process
count = await storage.increment("visits:42", ttl=86400)

# RedisStorage — INCRBY + EXPIRE, O(1)
count = await redis_storage.increment("visits:42", amount=1, ttl=86400)

# SQLiteStorage — UPSERT, serialised per-key
count = await sqlite_storage.increment("visits:42")

print(count)  # int — new total after increment

Quick Setup

Memory (development)
from kurigram_addons import KurigramClient, MemoryStorage

app = KurigramClient(
    "my_bot",
    bot_token="...",
    storage=MemoryStorage(default_ttl=3600),  # 1h TTL
)
SQLite (single-process persistence)
from kurigram_addons import KurigramClient, SQLiteStorage

app = KurigramClient(
    "my_bot",
    bot_token="...",
    storage=SQLiteStorage("fsm.db"),  # WAL mode, auto-cleanup
)
Redis (production, multi-instance)
import redis.asyncio as redis
from kurigram_addons import KurigramClient
from pyrogram_patch.fsm import RedisStorage

redis_client = redis.Redis(host="localhost", port=6379)
app = KurigramClient(
    "my_bot",
    bot_token="...",
    storage=RedisStorage(redis_client, prefix="mybot:"),
)