FanoutCache: sharded caches
A plain Cache is one SQLite database file, which makes it a shop with one checkout lane. Every writer in every process queues on its one write lock, and every read takes a lock in its shared-memory file, which processes reading the same database contend for. So past two or three worker processes a plain Cache gets slower, not faster, even when nobody writes. A FanoutCache opens more lanes. It’s one cache spread over several SQLite databases, called shards. Each key lives in exactly one shard, chosen by a fixed hash of the key, so reads and writes of different keys go to different files and stop contending on one. It has the same methods as Cache for single keys, and it’s one directory, shared by any number of threads and processes.
from diskcache_oxide import FanoutCache
cache = FanoutCache('/var/cache/my-app-rate-limits', shards=8)
cache.set('ip:203.0.113.7', 1, expire=60)
cache.incr('ip:203.0.113.7')
cache.shard_of('ip:203.0.113.7') # 0 to 7, the same in every process and every releaseShould you use it?
Use a FanoutCache for a cache that several processes or many threads use heavily: a web server with several worker processes (a web garden), reading or writing, many threads on free-threaded Python, or a write-heavy load. It’s faster in all three, by up to 4x (up to 6x with 8 processes only reading), and it costs about 10 MiB more memory per process than a plain Cache. A plain Cache stays the default, and the recommended setup uses one for every cache: it’s smaller, it keeps fewer files, and it’s the only kind with queues and full transactions. Make the one cache your worker processes use most a FanoutCache when its numbers matter. A site with one worker process (several threads on a GIL build) gains little from it.
The numbers below come from the benchmark in the repository (bench/fanout.py, the released 0.3.5 wheels, a Mac Studio with 18 cores, 1 KB values over 50,000 keys, every key in each worker’s plan, three rounds; bench/results/fanout-3.14.10-studio.txt and fanout-3.14.10t-studio.txt).
Several processes. Each worker process opens the cache and does 99 reads to 1 write, on Python 3.14:
| Processes | Plain Cache | FanoutCache(shards=8) |
|---|---|---|
| 1 | 375k ops/s | 428k |
| 4 | 519k | 1,004k |
| 8 | 261k | 1,094k |
- It removes the one-file ceiling. A plain Cache stops climbing past a few processes and then falls. The writes aren’t what does it: with no writes at all it falls the same way, from 836k ops/s at 2 processes to 296k at 8, while a
FanoutCache(8)climbs to 1,741k (bench/read_procs.pyon a MacBook Pro, M5 Pro, Python 3.14;bench/results/read-procs-3.14.10-macbook-m5-pro.md). The cause is the operating system’s, not SQLite’s or ours: every read of a WAL-mode database takes and releases a shared lock on the-shmfile, and the kernel serializes those calls when several processes make them on one file. A loop that does nothing but take and release that lock falls the same way, and so do Python’s ownsqlite3module and diskcache’s plain Cache (bench/results/read-sentinel-2026-11-24.md). It’s severe on macOS. On an x86-64 Linux host a plain Cache doesn’t fall: it keeps climbing, at 86% of a directory per process at 3 processes, and bends only past 4, where it does 502k reads a second at 8 againstFanoutCache(8)’s 751k. A FanoutCache keeps climbing: 4.2x a plain Cache at 8 processes. A pre-forking server (gunicorn, uvicorn workers) with a worker per core is this case. - Writes make the gap wider. At 90 reads to 10 writes with 8 processes, a plain Cache gets 138k ops/s and a FanoutCache 431k (3.1x); at 50:50, 38k against 116k.
Several threads in one process. Threads share one handle, with hot keys (a few keys read far more than the rest, as a real site’s pages are):
| Threads | 3.14t: plain Cache | 3.14t: FanoutCache(shards=8) |
3.14: plain Cache | 3.14: FanoutCache(shards=8) |
|---|---|---|---|---|
| 1 | 482k ops/s | 551k | 497k | 575k |
| 4 | 666k | 981k | 491k | 556k |
| 8 | 503k | 858k | 498k | 560k |
- On free-threaded Python, a FanoutCache lets threads scale. At 8 threads it’s 1.7x a plain Cache with hot keys and 2.0x with keys spread evenly (663k against 338k), and 2.2x at 90:10 (275k against 127k). The free-threaded thread runs were the noisiest here, spreading up to 13% between rounds. With a few threads on Linux it’s the other way round: on an x86-64 host (3.14t, 1,000 reads to 1 write) a plain Cache is faster at 2 and 3 threads (326k against 271k at 2), and a FanoutCache pulls ahead from 4 (601k against 523k) and leads at 8 (766k against 596k). Threads reading one file overlap, and SQLite then skips the lock system calls a read otherwise makes, while threads spread over 8 shards rarely overlap: at 2 threads a plain Cache makes 0.23 of those calls a get and a FanoutCache 1.88 (
bench/threads.py,bench/scaling/fcntl_per_get.py). Those calls cost more on Linux, so for 2 or 3 threads in one process a plain Cache is the better choice there. - On GIL builds, threads are flat for every cache, as the GIL says they must be, and a FanoutCache is 12-16% ahead at every thread count.
Large values. A FanoutCache keeps the slowest writes of large values far shorter: with 64 KiB values and one thread, the p99.9 of a set (over 1,000 or more per round) is 2.8-4.4 ms on a plain Cache and 0.07-0.12 ms on a FanoutCache, on 3.14 and 3.14t, with keys spread evenly or hot. Each shard’s database and write-ahead log are smaller, so a checkpoint has less to copy (sizing group in the same results).
What it costs. Each shard has its own SQLite connections and page caches, so a process holds more memory. Growth of each process’s own (private) memory over its baseline, with 99:1 and 1 KB values (macOS phys_footprint; RSS would also count file pages mapped into memory, which are shared and reclaimable):
| Case | Plain Cache | FanoutCache(shards=8) |
|---|---|---|
| 1 thread, 3.14 | 2.6 MiB | 11.8 MiB |
| 1 thread, 3.14t | 3.9 MiB | 14.1 MiB |
| 8 threads, 3.14t | 20.3 MiB | 30.0 MiB |
- About 10 MiB more per process than a plain Cache, so about 80 MiB across 8 workers. Most of it is page cache: by default each connection gets a 1 MiB page cache, and a thread that touches every shard of 8 holds 8 of them where a plain Cache thread holds 1. Where memory matters more than the last bit of speed, pass
sqlite_cache_size=64to give each a 256 KiB page cache instead. Across 1 KB to 64 KiB values and a realistic mix of sizes, for threads and worker processes, it cut the extra private memory by about two thirds (one thread or process: 4.4-4.9 MiB against 12.0-12.6) and cost 0-5% in almost every case, with no loss of stability. The exception is many threads on free-threaded Python with small values: 8 threads with 1 KB values ran about 15% slower (558k ops/s against 663k), still 1.6x a plain Cache. The default stays at 256 pages for that reason (bench/results/fanout-sizing2-3.14.10-studio.txtandfanout-sizing2-3.14.10t-studio.txt, and the page-cache group infanout-3.14.10t-studio.txt; see Choosingshardsandmax_connections). - More files. Each shard is a database, a write-ahead log and a shared-memory file, and the process holds descriptors for them (below).
- Less for a single process with few writes. A read-mostly cache in one process on a GIL build gains about 10% for that memory and those files.
Single-key reads and writes cost the same as on Cache plus the hash, which is about the cost of one more string hash, while no transaction is open in the process (see transact(key=) below).
The layout and the hash
A FanoutCache directory looks like this:
my-app-rate-limits/
diskcache-oxide-fanout the manifest
000/diskcache-oxide.sqlite shard 0
001/diskcache-oxide.sqlite shard 1
...
Each shard is an ordinary diskcache-oxide database. The manifest records the shard count and the hash. A key’s shard is XXH3-64 (seed 0) of its type byte and its UTF-8 bytes, mapped onto the shard count. That hash is part of the on-disk format and is frozen: pinned by golden vectors in the test suite, so every process and every release sends a key to the same place. A future scheme would get a new format number, never a change in place.
Because the shard count decides where every key lives, it’s recorded, and a different shards= never changes it. The cache opens with the count it has and logs a warning, once per process, instead of quietly losing data. Pass raise_on_mismatch=True to make it an error instead:
FanoutCache('/var/cache/my-app-rate-limits', shards=16)
# WARNING: FanoutCache at /var/cache/my-app-rate-limits has 8 shards but shards=16 was asked for; using the 8 it has. ...
FanoutCache('/var/cache/my-app-rate-limits', shards=16, raise_on_mismatch=True)
# LayoutMismatchError: this FanoutCache has 8 shards but shards=16 was requested; changing the count needs a new directoryshards=None (the default) uses the stored count, or creates 8. Changing the count means a new directory. One case still raises without raise_on_mismatch: a size_limit or max_connections that fits the count you asked for but can’t be split over the stored one (each shard needs at least 1 MiB and one connection), which gives LayoutMismatchError: this FanoutCache has 8 shards but shards=4 was asked for, and its settings don't fit 8 shards: .... Raise the setting, or leave shards out. raise_on_mismatch covers the count only: a root in another on-disk format opens in its versioned subdirectory either way (below). Creating the manifest uses a hard link, so a filesystem without them (FAT, exFAT, SMB, some FUSE mounts) raises OSError saying so.
Plain Cache and FanoutCache directories don’t mix
A Cache opened on a FanoutCache’s directory, or on one of its shard directories, raises LayoutMismatchError, and so does a FanoutCache opened on a plain Cache’s directory. The refused open creates nothing, so a typo doesn’t leave a directory that neither kind can open. LayoutMismatchError is both a ValueError and a FormatMismatchError. If a registry hits it, the lookup returns a NullCache and reports it like any failed open. That holds for a shard directory in any on-disk format.
A root in another on-disk format, whether its manifest or any of its shards, opens as a whole in the root’s diskcache-oxide-format-N subdirectory, a new root with its own shards and the count you ask for (or 8), and logs a warning, as a plain Cache does. One shard never moves on its own. remove_old_formats() removes the old root’s shards, highest first, and its manifest last. See Upgrading across a format change. A registry that meets another shard count than its registration’s opens the folder with the count on disk and warns instead (Caches).
Choosing shards and max_connections
shards is 1 to 256. Eight is a good start: the benchmark’s write scaling is already flat by 4 processes at 8 shards. More shards spread writes further but cost file descriptors (below) and give each shard a smaller share of size_limit. Pick it once, because it’s permanent for the directory.
max_connections is the most SQLite connections the process opens for the whole FanoutCache, split across the shards (max_connections // shards each, with the first max_connections % shards getting one more). It must be at least shards, and the default is two per shard with a floor of 8 in all: 16 at the default 8 shards. With one per shard, threads sharing a handle waited for a shard’s only connection and read 16-31% below a plain Cache; two gets 97-98% of the read rate of 32. SQLite’s page caches for the whole cache are then about 16 × sqlite_cache_size (16 MiB at the defaults, against a plain Cache’s 8). A busy shard only gets its share, so if a measurement shows one hot shard waiting for a connection, raise it. It doesn’t matter across processes, since each process has its own connections.
File descriptors. Each connection holds its shard’s database and WAL open, and each shard adds its -shm file and a pin. The descriptors inside the root stay within 2 × max_connections + 2 × shards, however many threads you run: 48 at the defaults, measured at 32-34 with 64 threads on 3.14t. That’s a ceiling, reached only when that many threads hit the same shards at once, since a shard opens its second connection only then, where stock diskcache’s FanoutCache holds 264. close() leaves none. Opening needs about 4 per shard, so 256 shards need more than 1,024, Linux’s usual default ulimit -n. If there aren’t enough, opening raises OSError with errno EMFILE, and a message giving the shard count, the descriptors needed, the limit and how many are already open. A failed open leaves no descriptor behind.
size_limit is a total. Each shard gets floor(size_limit / shards) and culls on its own, and each needs at least 1 MiB, so the total must be at least shards MiB (ValueError otherwise). A new root with none given gets 1 GiB in all. cache.size_limit reads back the total (the sum of the shards’ floored shares). A key that happens to land in a full shard evicts from that shard, even if the others have room.
Background maintenance
Background maintenance treats each shard as a cache of its own. Each shard gets its own turn, spread across the interval with the process’s other caches, and the hourly folder sweep, which shards skip at close. maintenance_interval= applies to every shard, and so does a clock= handle’s veto, which works per database file. On a shard with the default two connections, the background WAL checkpoint runs only when neither connection is in use.
maintenance_stats() sums turns, removed and failures across the shards. interval is the largest any shard has, and last_error comes from the first shard, in shard order, that has one. A maintenance thread that couldn’t be started counts in failures too, as on Cache.
Maintenance calls: one budget, partial failures
clear(), expire(), cull() and checkpoint() run over every shard. Their timeout= (default: the handle’s) bounds the whole call, not each shard. The handle’s timeout also bounds opening, len() and volume() as one budget, and close() uses at most 1 s of it for checkpoints. A shard reached after the deadline still gets one try with no wait, so idle shards are always done.
A shard that fails doesn’t stop the others. Afterwards the call raises the first failure’s own type, so except Timeout works, with attributes saying how far it got:
try:
cache.clear(timeout=5)
except Timeout as exc:
exc.failed_shards # (3,): the indexes of the shards that failed
exc.removed # entries removed in all, including what a failed shard removed before it failedremoved is the total removed in all, including what a failed shard removed before it failed, except for checkpoint(), which has none; checkpoint() returns True only if every shard’s log was reset. Writes made while a removal runs survive on every shard, as on Cache. durable=True doesn’t swallow any of these.
Timeouts on single keys
On a FanoutCache, diskcache silently turns a busy shard into a dropped write: set gives False after 10 ms. diskcache-oxide behaves as Cache does: a busy shard raises Timeout after timeout (60 seconds by default), and so do cache[k], cache[k] = v and del cache[k]. If you want a miss instead, say so with durable=True, which also logs and counts the failures, with one report for the whole FanoutCache.
Iteration order
iter(cache) yields every key once, shard 0 to the last, each shard in its insertion order. That is not the cache’s insertion order, and not stock’s, since the shards hold different keys. iterkeys(prefix=, reverse=) merges the shards into one sorted order, the same order a plain Cache gives, and holds no connection between yields. reversed(cache) walks the shards from the last to shard 0, each newest first. Neither is a snapshot: a concurrent write may or may not be seen, never twice.
In a Caches registry
Pass shards= to register and the name opens a FanoutCache, with the same settings as any other cache:
caches = Caches('/var/cache/my-app', timeout=1.0, durable=True)
caches.register('general')
caches.register('rate_limits', shards=8, max_connections=16)
caches['general'].get('greeting')
caches.fanout('rate_limits').incr('ip:203.0.113.7')Plain caches are read with caches[name] and sharded ones with caches.fanout(name), because their transact takes a key. Reading a name the wrong way raises TypeError. Passing shards at all is what picks the kind, so shards=None still registers a FanoutCache; leave it out for a plain cache. A failed open becomes a NullCache, disable(), stats(), clear() and close_all() work the same, and fanout(name) is typed FanoutCache | NullCache. See Caches.
Typing
ShardedCacheLike is a protocol for “a CacheLike whose transact takes key=”. Both FanoutCache and NullCache satisfy it, so code that works with either a sharded cache or a switched-off one can be annotated with it:
from diskcache_oxide import ShardedCacheLike
def bump(cache: ShardedCacheLike, key: str) -> None:
with cache.transact(key=key) as tx:
tx.set(key, tx.get(key, 0) + 1)What FanoutCache doesn’t have
memoize, stats(), check(), reset(), reversed(), pickling, retry=, tags and evict(tag) (which removes the tag from every shard) and eviction_policy= (every shard’s) work as on Cache. The queue calls push, pull, peek and peekitem are on Cache only, because a queue spread over shards would have no order; keep a work queue in a plain Cache. diskcache’s cache(), deque() and index() sub-collections and read()/read= aren’t here either (see the roadmap). directory is required and there’s no disk=, as for Cache.
The constructor takes shards as a keyword: stock’s FanoutCache(path, 4) means four shards, but here the second argument is timeout, so write shards=4.