alata.
Digging Deeper

Cache

File, Redis, database, and memory caching with TTLs, locks, and cache-aside helpers.

Alata ships a cache layer with a pluggable store behind a single facade — file, Redis, database, memory, or null, wired up by the framework's providers at boot. Your application code just imports Cache and calls it, in async or sync contexts alike. A fresh scaffold defaults to the zero-dependency file store; switch to Redis (or the database store) for multi-worker deployments.

from alata.cache import Cache

await Cache.aput("greeting", "hello", ttl=300)
value = await Cache.aget("greeting")   # "hello"
await Cache.aforget("greeting")

Configuration

Cache configuration lives in config/cache.py:

config/cache.py
from config.settings import settings

CACHE_CONFIG = {
    # Default store. Override via CACHE_STORE env var.
    "default": settings.CACHE_STORE,
    # Global key prefix — prevents collisions when multiple apps share a backend.
    "prefix": settings.CACHE_PREFIX,
    # Named stores available through Cache.store(name).
    "stores": {
        "redis": {"driver": "redis", "connection": "cache"},
        # "table" names the cache table (locks live in "{table}_locks"),
        # "connection" picks a named database connection. Requires the
        # shipped create_cache_table migration to have run.
        "database": {"driver": "database", "table": "alata_cache", "connection": "default"},
        "file": {"driver": "file", "path": None},
        "memory": {"driver": "memory"},
        "null": {"driver": "null"},
    },
}
KeyDefaultPurpose
defaultfileName of the store to use by default (CACHE_STORE env).
prefixalata_cache:Prepended to every key. Lets multiple apps share one backend safely.
stores—Named store definitions; each picks a driver (redis, database, file, memory, null) plus driver options.
strict_lockingTrueWhether lock acquisition fails when Redis is down (see Locks).
async_client_binding—Optional container binding name whose async Redis client the cache should reuse.

The database driver

The database driver keeps the cache in a relational table — shared across every worker and server that talks to the same database, with no Redis required. Options: table (default "alata_cache") names the entry table, connection a named database connection, prefix overrides the global key prefix. Locks live in a companion {table}_locks table so flushing the cache can never release a held lock.

The scaffold ships a create_cache_table migration that creates both tables (alata_cache: key, value, expiration; alata_cache_locks: key, owner, expiration) — ./alata migrate picks it up like any other migration. If you configure a custom table name, rename the tables in that migration to match. On MySQL the migration also pins the key column to the utf8mb4_bin collation, so keys compare byte-for-byte the way they do on PostgreSQL; MySQL's default collation is case- and accent-insensitive, which would let User:ABC, user:abc and user:abç share a single row.

Only a connectivity failure degrades this driver into misses and no-op writes. Anything structural — the cache migration never ran, the table was renamed, a column is the wrong width — raises out of reads as loudly as it does out of writes, so a misconfigured cache announces itself instead of reading as eternally empty.

Writes upsert with the database's native conflict clause, and increment is a single atomic upsert statement, so counters — including the rate limiter's fixed windows — are correct under concurrency across processes. Expired rows are treated as misses and deleted on read.

Keys are limited to 255 characters, including the global prefix — the width of the key column. A longer key raises ValueError naming the limit rather than being silently dropped. Hash the user-supplied part of long keys, or widen the column in your migration and raise DatabaseCacheStore.KEY_MAX_LENGTH to match.

CacheProvider registers the default store as cache in the service container. Stores are created on first use. A Redis store uses its configured named connection from config/redis.py (see Named Redis connections).

The cache degrades gracefully. If Redis is unreachable — at boot or mid-flight — reads return None and writes are silent no-ops. The degradation is deliberate but never silent: the first failure is logged at WARNING (once per store), the rest at debug. Clients are re-resolved on every operation, so the cache starts working again on its own once Redis recovers — no restart, and no process stuck with rate limiting permanently off. The provider falls back to a no-op store only when no Redis connection is registered at all, which is a configuration fact rather than an outage.

While degraded, counters do not accumulate — so anything counting attempts (the rate limiter most of all) sees zero and lets every request through. Treat the WARNING as an alerting signal.

The Cache API

Cache stores string values. Methods follow the framework-wide naming rule: the plain name (get, put, ...) is synchronous, and the a-prefixed twin (aget, aput, ...) is the one to await. The examples below run in async contexts — handlers, queue tasks — so they use the a-prefixed forms.

Retrieving and storing

# Read — returns None on a miss, or your default
value = await Cache.aget("stats:daily")
value = await Cache.aget("stats:daily", default="0")

# Write — ttl is in seconds; None means no expiry
await Cache.aput("stats:daily", "42", ttl=3600)
await Cache.aput("config:banner", "on")          # no expiry

# Existence and removal
if await Cache.ahas("stats:daily"):
    ...
await Cache.aforget("stats:daily")

A non-positive ttl is not "expire immediately" — the write is silently skipped. Pass ttl=None for a key that should live forever.

Cache-aside with aremember

aremember returns the cached value if present, otherwise runs your callback, stores the result, and returns it. The callback may be sync or async. It is async-only — there is no sync counterpart:

async def fetch_dashboard(user_id: str) -> dict:
    return await Cache.aremember(
        f"dashboard:{user_id}",
        ttl=300,
        callback=lambda: build_dashboard(user_id),  # sync or async
    )

By default aremember serializes with json.dumps and deserializes with json.loads, so dicts and lists round-trip transparently: you get the structured object back on both cache hits and misses. Pass your own serializer/deserializer pair for other types. A callback returning None is not cached.

Counters

increment adds to a counter key atomically and returns the new count. A missing (or expired) key is created at amount and stamped with ttl seconds; an existing key keeps its original expiry, so increments never extend the window — which is what makes fixed-window counting correct.

store = Cache.store("file")
attempts = await store.aincrement("login:u1", 1, ttl=60)

Every driver agrees on the two edge cases:

CaseBehavior
ttl of zero or lessThe counter is created with no expiry. (put treats a non-positive ttl differently — it skips the write entirely — because a counter that expires the moment it is created can never accumulate, silently disabling rate limiting.)
The existing value is not an integerThe stored value is left untouched and 0 is returned. It is never destroyed and never replaced by a counter.

The redis and database drivers increment with a single atomic statement. The file driver cannot, so it serializes its read-modify-write behind a short-lived guard file scoped to the key. Only the writer that took a guard releases it, and a guard is taken over only once its expiry has genuinely passed — a crashed holder. A writer that waits out FileCacheStore._GUARD_TIMEOUT_SECONDS (5s) raises CacheGuardTimeoutError rather than stealing a live guard and dropping counts. For counters under heavy multi-process contention, prefer redis or database.

Bulk removal

# Delete every key under a prefix (the global prefix is applied on top)
deleted = await Cache.aforget_by_prefix("dashboard:user123:")

# Clear the whole store
await Cache.aflush()

Prefixes are matched literally. Characters that would be wildcards in the backend's own pattern language — *, ?, [, ], \ for Redis, % and _ for SQL — are escaped, so forget_by_prefix("q[abc]:") deletes exactly the keys starting with q[abc]: and nothing else.

When a global key prefix is configured, flush deletes only your app's prefixed keys — it will not wipe another application's data on a shared Redis, and two file stores pointed at one directory with different prefixes never clear each other. Locks are out of reach entirely: on every driver they live in a namespace of their own (see Atomic locks), so neither flush nor forget_by_prefix can release a lock somebody is holding — clearing the cache is not a lock reset.

Atomic locks

Cache.alock acquires a lock in the selected store and returns an owner token, or None if the lock is already held. Pass the token back to aunlock so you only ever release your own lock — the release is an atomic compare-and-delete, immune to the race where your TTL expires and another process acquires the lock between check and delete:

token = await Cache.alock("reports:rebuild", ttl=60)
if token is None:
    return  # someone else is doing it

try:
    await rebuild_reports()
finally:
    await Cache.aunlock("reports:rebuild", owner=token)

Sync contexts use the plain Cache.lock / Cache.unlock pair — same semantics, same token protocol.

Locks are namespaced apart from values on every driver — a lock: sub-namespace under the global prefix on Redis, a table of their own on the memory store, separate locks/ files on the file store, and the companion {table}_locks table on the database store. A lock and a cache value under the same logical key are different entries that never interact: writing or forgetting the value cannot release the lock, holding the lock never shadows the value, and flush/forget_by_prefix operate on values only.

The strict_locking config key decides what happens when Redis is unavailable: with True (the default) lock returns None — acquisition fails, so the protected operation can be skipped; with False it returns a synthetic token and lets the operation proceed without mutual exclusion.

Sync usage

For code that runs outside an event loop — console commands, migrations, scripts — call the plain names, using the selected cache store. Drop the a prefix and the await:

value = Cache.get("key")
Cache.put("key", "value", ttl=300)
Cache.forget("key")
Cache.has("key")
Cache.forget_by_prefix("dashboard:")

Async and Sync covers which variant belongs in which context.

Named stores

Cache.store(name) selects a store from CACHE_CONFIG["stores"]. Add another entry there to configure a named store; no extra provider is needed. An explicit container binding under cache.<name> takes precedence. Unknown names raise CacheStoreNotConfiguredError.

store = Cache.store("null")
await store.aput("ignored", "value")

Testing

Swap the facade's store without touching the container:

Cache.fake()        # NullCacheStore — all reads miss, writes vanish
Cache.fake_dict()   # DictCacheStore — in-memory with real TTLs, for asserting values
Cache.restore()     # back to the real store
def test_caches_dashboard():
    fake = Cache.fake_dict()
    try:
        ...
        assert fake.get("dashboard:u1") is not None
    finally:
        Cache.restore()

Key prefixing

The Redis store prepends CACHE_CONFIG["prefix"] (default alata_cache:) to every key. Your code always works with logical keys — Cache.get("stats:daily") reads alata_cache:stats:daily from Redis. The prefix applies to forget_by_prefix too, and scopes flush to your own keys.

Named Redis connections

The cache rides on the framework's Redis provider, which is useful in its own right. config/redis.py declares named connections:

config/redis.py
from config.settings import settings

CONNECTIONS = {
    "default": {"url": settings.REDIS_URL},
    "cache":   {"url": settings.REDIS_CACHE_URL or settings.REDIS_URL},
    "queue":   {"url": settings.REDIS_QUEUE_URL or settings.REDIS_URL},
}

For each entry with a non-empty URL, RedisProvider registers two lazy container singletons:

  • redis.<name> — a sync client (decode_responses=True), pinged at first resolution; resolves to None if Redis is unreachable. The ping is bounded (3s connect, 5s operation), so a host that drops packets rather than refusing them fails fast instead of stalling startup.
  • redis.<name>.async — an async client that connects lazily on first command.
from alata.container import container

redis = container.make("redis.default.async")
await redis.sadd("online", user_id)

Connections that share a URL are deduplicated: when REDIS_CACHE_URL is unset and falls back to REDIS_URL, redis.cache is an alias for the same physical client as redis.default — no wasted connections. On application shutdown the provider closes every client that was actually resolved.

Add another named entry to make it available as redis.<name> and redis.<name>.async.

On this page