EzyGang

py-cachify vs cashews vs aiocache vs fastapi-cache: which one survives a cache stampede

100 requests at an empty key, seven setups, one and four FastAPI workers. On four workers only two of them kept the database to one call.

Contents
  1. The setup
  2. Round 1: one worker
  3. Round 2: four workers
  4. Round 3: speed
  5. Round 4: Redis traffic
  6. Turning it on in py-cachify
  7. Conclusion

Every Python cache looks the same in its README: wrap a slow function and the second call comes back instantly. The first call is where they differ. In a cache stampede, 100 requests ask for a key that isn’t cached yet. Each one misses and runs the slow function, so the database gets all 100 at once.

So I put the four async caches people use with FastAPI through exactly that: py-cachify (mine, full disclosure), cashews, aiocache and fastapi-cache.

The setup

Each library got its own FastAPI app, set up the way its README shows, all on one Redis 8.2. Every endpoint calls a fake query that sleeps 200 ms and adds one to a counter. The counter says exactly how many requests got past the cache.

Where a library has a stampede option, it ran twice, with and without it. That makes seven setups. py-cachify ran with its default @cached and with StampedeProtect.LOCK, cashews with @cache with and without lock=True, and aiocache with @cached and @cached_stampede. fastapi-cache’s @cache has no lock option, so it ran once.

The test is 100 requests at a key nobody has asked for yet, all sent within 6 ms of each other on the median. Each setup got 20 of those bursts on one uvicorn worker and 20 on four, on 2 CPUs of an AMD EPYC box. Versions were the latest on PyPI on 26 November: py-cachify 3.3.0, cashews 7.6.0, aiocache 0.12.3 and fastapi-cache2 0.2.2.

Round 1: one worker

Calls that reached the fake query per burst of 100, median of 20 bursts:

py-cachify, default
1
py-cachify, StampedeProtect.LOCK
1
cashews, @cache
1
cashews, lock=True
1
aiocache, @cached
100
aiocache, @cached_stampede
1
fastapi-cache, @cache
100

Two setups fall over right away. aiocache’s plain @cached and fastapi-cache sent all 100 requests to the database in every burst. The other five held it to one call.

Not one cold request failed or timed out in the whole run. From here on it’s only about how many got through, and how fast.

Round 2: four workers

Most real FastAPI apps run more than one worker. Four workers are four separate processes, and they don’t share memory.

py-cachify, default
4 (2-4)
py-cachify, StampedeProtect.LOCK
1
cashews, @cache
4 (2-4)
cashews, lock=True
1
aiocache, @cached
100 (36-100)
aiocache, @cached_stampede
75.5 (1-100)
fastapi-cache, @cache
100 (45-100)

The plain decorators from py-cachify and cashews still stop the stampede inside each process, so the query runs once per worker. The range dips to 2 when a worker got to the key after the value was stored, or got no requests in that burst.

aiocache’s @cached_stampede was perfect on one worker and falls apart here. Its lock waits on an asyncio.Event that only exists in the process holding the lock. The other three workers never get the memo and go straight to the database, a median of 75.5 calls per burst.

That leaves two. py-cachify with StampedeProtect.LOCK and cashews with lock=True made one call per burst on four workers, in all 20 bursts each.

Round 3: speed

Times in ms. The cold column is the median request at the client, and the 200 ms query is its floor:

Library and settingCold request, 4 workersOne cached hit, 4 workers100 cached hits at once, 1 worker
py-cachify, default2791.80101
py-cachify, StampedeProtect.LOCK2731.52102
cashews, @cache2562.3254
cashews, lock=True2703.6967
aiocache, @cached3622.19114
aiocache, @cached_stampede4321.50143
fastapi-cache, @cache3761.1890

On cold requests the two finalists finished 3 ms apart. Cached hits are where they split. A single hit costs 1.2 to 2.3 ms everywhere except cashews’ lock=True, which takes the Redis lock even on a cached value and pays 3.7 ms for it.

The last column goes to cashews. When 100 requests hit a cached key at once on one worker, cashews shares one Redis read between them. py-cachify does a read per request. That’s 54 ms against 101.

Round 4: Redis traffic

With four workers, cashews’ lock=True sent a median of 459 Redis commands per burst, nearly all SET and PING. Its waiting workers retry the lock in a loop without sleeping. py-cachify’s waiters check every 100 ms, and its whole burst took 122 commands for the same single call to the database.

They didn’t wait long for it, either. The other three workers got the value a median of 18 ms after the one that computed it. Of those 60 answers, 59 came within the 100 ms py-cachify’s docs promise.

Turning it on in py-cachify

The lock is one argument on cached. This is the endpoint from the run, where backend is the 200 ms fake:

from contextlib import asynccontextmanager

from fastapi import FastAPI
from py_cachify import StampedeProtect, cached, init_cachify
from redis.asyncio import from_url


@asynccontextmanager
async def lifespan(_: FastAPI):
    init_cachify(async_client=from_url('redis://redis:6379/0'))
    yield


app = FastAPI(lifespan=lifespan)


@app.get('/lock/{item_id}')
@cached('lock-{item_id}', ttl=300, stampede_protect=StampedeProtect.LOCK)
async def locked(item_id: str) -> dict:
    return await backend('lock', item_id)

The lock expires after 30 seconds unless you change it in init_cachify. If your slow query can take longer than that, pass LockConf(exp=...) with a bigger number, or a second worker will start computing too.

Conclusion

On one worker, py-cachify, cashews and aiocache’s @cached_stampede all keep a stampede down to one call. cashews was the quickest of them on both cold and cached bursts. aiocache’s plain @cached and fastapi-cache don’t protect you at all.

On more than one worker, a plain cache decorator runs the query at least once per worker. Only a lock in Redis gets it down to one. py-cachify’s StampedeProtect.LOCK and cashews’ lock=True both did that in every burst. py-cachify’s lock used about a quarter of the Redis traffic and had cheaper cached hits, so it’s the one I’d use, keeping in mind who wrote it.

More posts

  1. I gave Claude Code 8 real tickets with and without aposlop agent skills, and it wrote 59% less code

    Ran Claude Code on 8 real Django and ripgrep tickets, with and without my skills. With them it wrote 59% less code, and once argued a feature away.

  2. Aposlop marks as much duplicate code as jscpd's three passes, in one run

    On five well-known repos, one aposlop run marks 9.8% of the code as copied. That's as much as jscpd's three passes, in 2,460 groups against 5,339 pairs.