FlipCache backdrop
2024 → 20264 min read–
FlipCache logo

FlipCache

A Python package that serves hot reads from local memory and keeps Redis as the shared store, with typed values, TTLs and bounded FIFO/LRU dictionaries for threaded and async code.

Status
Open source on PyPI
Local hit vs Redis GET
~230× faster on localhost
Release
1.3.1 (PyPI)
Stack
Pythonredis-pypytestfakeredis

My Tahrirchi Telegram bot kept each user's state and current session in Redis. Redis is fast, but every read is still a round trip. So I put a small dictionary in the bot's own memory in front of it: read locally when you can, fall back to Redis when you can't, write to both.

In April 2024 I pulled that class out of the bot, cleaned it up and published it as FlipCache. It's a small, MIT-licensed Python package on PyPI, and I maintain it alone.

pip install flipcache

What it does#

How FlipCache reads and writesView

A FlipCache looks like a dictionary:

from redis import Redis
from flipcache import FlipCache, et

cache = FlipCache(
    "analytics",
    local_max=256,
    expire_time=et.FIFTEEN_MINUTES,
    value_type="json",
    value_default={"hits": 0},
    refresh_expire_time_on_get=True,
    redis_protocol=Redis(decode_responses=True),
)

payload = cache["user-42"]   # missing: a copy of the default is stored in both tiers
payload["hits"] += 1
cache["user-42"] = payload

Reads check local memory first. A hit returns right away with no Redis call. On a miss, FlipCache reads from Redis, decodes the value and keeps it locally for next time. If Redis doesn't have it either, you get a copy of value_default, already written back, or None.

Writes go to both tiers: the local copy for the next read, Redis for everything else, with the TTL you set. Keys are namespaced (analytics:user-42), so several caches can share one Redis.

Values can be strings, ints, JSON, or anything with your own encoder and decoder, like pickle or a dataclass. FlipCache insists on decode_responses=True unless you bring your own codecs, which rules out a whole class of bytes-versus-str bugs.

The tradeoffs#

A local copy is fast because nobody else can see it, and that cuts both ways:

  • The local tier has no TTL. It can hand you a value that Redis has already expired. If exact expiry matters more than speed, set local_max=0 and every read goes to Redis.
  • Other processes don't find out about your writes. Two workers each keep their own local copy, and nothing invalidates them. FlipCache fits data that one process owns, like a bot's per-user state, better than data many processes edit.
  • Local eviction is first in, first out. When the local tier is full, the oldest inserted key goes, even if it's the one you read most.

What I found while writing this#

Writing this case study meant rereading the code, and I found three real bugs. All three are fixed in 1.3.1:

  1. The TTL constants crashed. et.FIFTEEN_MINUTES was defined as ONE_HOUR / 4, which is a float, and redis-py refuses a float TTL. The example above used to fail on its first write. The constants are ints now, and expire_time accepts ints, floats and timedelta.
  2. Hot keys expired. refresh_expire_time_on_get only refreshed the Redis TTL when a read missed the local tier. The keys read most often never missed, so they were exactly the ones Redis expired. Now a local hit refreshes too, but at most once per half TTL per key, so most reads still stay in memory.
  3. Defaults were shared. Every missing key got the same default object. Run the counter example above for one user and the next new user started at one hit. Each key now gets its own copy.

The package had no tests, which is how they survived. It has 66 now, running offline against fakeredis.

How fast#

On my machine, with Redis 7.4 running locally and 10,000 keys:

OperationTime per call
Redis GET27 µs
FlipCache read, local hit0.12 µs
FlipCache read, local hit, TTL refresh on0.23 µs
FlipCache read with local_max=026 µs
Redis SET27 µs
FlipCache write27 µs

A local hit is about 230 times faster than a Redis read, and that's with Redis on the same machine. Over a real network the gap only grows. Writes cost the same as plain Redis, because they still go to Redis.

The small helpers#

FlipCache also ships the bounded dictionaries it's built from, for when you don't need Redis at all: FIFODict and LRUDict, plus thread-safe versions with a lock and async-safe versions with aget and aset. My AiogramX library uses LRUDict to keep track of live Telegram widgets. Version 1.2 added them a day before AiogramX 3.0 came out, which tells you which project needed them.

Stack#

Python, redis-py, pytest, fakeredis.

A cache is a promise that the copy is good enough. FlipCache makes that promise smaller, and now it keeps it.

Need a similar system?

If you are building a bot, automation workflow, or platform feature, I can help with architecture and implementation.

Discuss a project

More projects

Related systems, decisions, and outcomes.