Skip to main content

Switching from python-diskcache

The one-line switch from python-diskcache, and everything you might notice afterwards.

If you’re here, the question is a practical one: what breaks? Very little, and on purpose. diskcache-oxide is API compatible with python-diskcache 5.6.3’s Cache and FanoutCache, and it is not data compatible. Keeping diskcache’s API makes switching a one-line change. Leaving its on-disk format behind is what made it possible to fix the design underneath, pickle included. So the switch itself is small, and the rest of this page is about what you’ll notice afterwards: mostly fixes, and now and then something stricter.

diskcache is also unmaintained. Its last release, 5.6.3, came out in August 2023, the repository has had no commits since 2023, and its open issues and pull requests go unanswered. The bugs this page mentions were found by running diskcache-oxide’s test suite against it, and each one has a standalone reproduction in the repository’s upstream/ folder.

For most apps, switching looks like this:

# from diskcache import Cache, Timeout
from diskcache_oxide import Cache, Timeout

cache = Cache('/var/cache/my-app-oxide')

Start with a fresh cache

diskcache-oxide stores its data in diskcache-oxide.sqlite, not diskcache’s cache.db, and never opens or converts a diskcache database. The two can even share a directory without seeing each other’s data. Your cache starts cold after the switch, which for a cache is usually fine. The cleanest switch gives diskcache-oxide a new directory and deletes the old one once every worker has moved. If the two share a directory, diskcache’s files are cache.db* and its value folders, which nest two levels deep (3f/a2/….val); diskcache-oxide’s folders are one level deep and hold .val files directly, so a two-hex-digit folder that contains folders is diskcache’s.

State that isn’t cache

A cold start costs a cache nothing but speed. Some of what apps keep in diskcache isn’t cache, though: sessions, queued jobs, counters, a Deque or Index. Deal with those before you switch. Drain a queue with the old code first, and flush counters. See State that isn’t really cache, which applies here too. For entries you must keep, copy them across once, with every writer stopped:

import time

import diskcache
from diskcache_oxide import Cache

MISSING = object()
old = diskcache.Cache('/var/cache/my-app')
new = Cache('/var/lib/my-app/state/sessions', eviction_policy='none')

for key in old.iterkeys():
    value, expire_time, tag = old.get(key, default=MISSING, expire_time=True, tag=True)
    if value is MISSING:
        continue  # expired, or deleted while copying
    expire = None if expire_time is None else expire_time - time.time()
    if expire is not None and expire <= 0:
        continue
    try:
        new.set(key, value, expire=expire, tag=tag)
    except TypeError as exc:  # a key or value diskcache-oxide can't store without pickle
        print(f'skipped {key!r}: {exc}')

Keys and values go through diskcache-oxide’s rules: a key that isn’t a key type, or a value of a class you haven’t registered, raises TypeError and is skipped. Register your types before the loop, or open the new cache with pickle=True if it really holds arbitrary objects. A Deque or Index has no equivalent yet: copy its items into a work queue or plain keys.

Upgrading diskcache-oxide

During 0.x, a release that changes the on-disk format bumps the minor version and says so first in its changelog entry. 0.2.3 was one: it added tags and the eviction policy, as format 3. Since 0.3.5, a release that meets a cache in another format doesn’t fail: it opens a new, empty cache in the subdirectory diskcache-oxide-format-N and logs a warning, so old and new workers each keep a working cache during a rolling deploy. Once the old workers are gone, remove_old_formats() removes the old cache. A release that keeps the format keeps your caches warm. The details, including what to do about queues and sessions first, are in Upgrading across a format change.

What you might notice

Most of these are fixes. Each one has a conformance test, or an entry in Divergences that explains why. If the switch turns up an exception you haven’t seen before, Errors and what to do about them covers each one.

python-diskcache 5.6.3 diskcache-oxide
Values Pickled msgpack (default) or JSON with exact type tags. Pickle is opt-in with pickle=True.
Unrepresentable values Pickled TypeError at set(), unless pickle=True
bool(cache) False when empty Always True; NullCache is False
Timeout Subclasses Exception Subclasses TimeoutError
directory Optional (makes a temp dir) Required
Clock Reads time.time() Reads the clock in Rust; pass clock= to control it
size_limit Anything (tiny values silently empty the cache) At least 1 MiB
expire=True / timeout=True Treated as 1 TypeError
disk=, eviction_policy= Supported No disk=; eviction_policy= is 'least-recently-stored' or 'none', and LRU and LFU raise ValueError
Queues (push, pull, peek, peekitem) Any key in the range is an item; peek writes Only keys of the queue’s exact shape; peek never writes; pull decodes first; Cache only
Tags Compared numerically (1, 1.0 and True are one tag); tag positional Any key type, compared by exact type; tag= keyword-only on set and add
transact() tx is None tx is the cache; see transact() below
FanoutCache Supported Supported, with differences; see FanoutCache below
Keys Anything picklable str, bytes, int, float, bool, None and tuples of those; see Keys below
memoize Supported Supported, with the same keys; see Keys below
retry= Positional; cache[k] retries forever Keyword-only; cache[k] raises Timeout
stats() Persisted, shared by every process Per process, in memory (D-049)
check() Supported Supported, with differences (D-050)
len() and iteration Count and list expired entries until something removes their rows Leave them out the moment they expire (D-060)
Between calls Nothing happens: expired rows, an over-limit cache and stray files wait for a call, so apps schedule expire() Background maintenance looks after every open cache, every 5 minutes by default; nothing to schedule (D-061)
Locks, semaphores, throttle, barrier, Averager, memoize_stampede Supported Supported, with differences; see Coordination
DjangoCache diskcache.DjangoCache: always a FanoutCache (8 shards by default), writes retrying a 10 ms lock wait silently diskcache_oxide.DjangoCache, a plain Cache unless OPTIONS['shards'], errors that raise unless durable (D-062); see Django cache backend
Deque, Index, disk=, read= Supported Not available

DjangoCache: change 'BACKEND' to 'diskcache_oxide.DjangoCache', SHARDS to OPTIONS['shards'] and DATABASE_TIMEOUT to OPTIONS['timeout'], and drop MAX_ENTRIES for size_limit. Django cache backend has the rest.

Settings passed as keywords

diskcache takes its settings as keyword arguments (Cache(directory, statistics=1)). diskcache-oxide’s constructors list theirs explicitly, so a diskcache-only keyword raises TypeError: unexpected keyword argument. Here’s where each went:

  • size_limit, cull_limit: the same, persisted in the cache (size_limit at least 1 MiB)
  • eviction_policy: the same name; 'least-recently-stored' or 'none'
  • sqlite_cache_size: the same name, in 4 KiB pages per connection; default 256 (1 MiB), not diskcache’s 8192
  • statistics: gone; call cache.stats(enable=True), which counts per process, in memory (D-049)
  • tag_index: gone; tags are always indexed
  • disk_min_file_size: gone; values of 64 KiB or more always go to files
  • disk_pickle_protocol: gone; no pickle by default; pickle=True uses the highest protocol
  • sqlite_journal_mode: gone; always WAL, checked at open
  • sqlite_synchronous: gone; always NORMAL, as diskcache’s default
  • sqlite_mmap_size, sqlite_auto_vacuum: gone; not configurable

New settings with no diskcache counterpart: serializer, pickle, types, clock, max_connections, wal_size_limit, wal_checkpoint, maintenance_interval, on_decode_error and durable, and on a FanoutCache, raise_on_mismatch. Cache and FanoutCache list them.

Values: no pickle unless you ask

diskcache pickles every value. That’s convenient, but anyone who can write to the cache directory can make your app run arbitrary code the next time it reads, and objects that were never meant to be cached get stored without complaint.

diskcache-oxide stores values as msgpack (or JSON), and tags the types those formats would otherwise change, so tuples, sets, frozensets, datetimes, dates, Decimals, big ints, NaN, nested bytes and non-str dict keys all come back exactly as stored. Something that can’t be represented raises TypeError when you store it, not later when you read it:

cache.set('job', MyJob())
# TypeError: values of type MyJob can't be stored without pickle (only exact built-in types round-trip)

If you really do need to cache arbitrary objects, opt in for that cache:

objects = Cache('/var/cache/my-app-objects', pickle=True)

A cache opened without pickle=True never unpickles. If it finds a pickled value written by a pickle=True peer, it raises UnsafeValueError and leaves the value alone. More in Serialization.

Keys

Keys can be str, bytes, int (64-bit), float, bool, None, and tuples of those, nested. diskcache takes anything picklable and pickles what it doesn’t store natively; diskcache-oxide never pickles a key, so a list, a dict, an object, a subclass such as an IntEnum, or an int past 64 bits raises TypeError. Keys are compared by exact type: 1, 1.0 and True are three keys, where diskcache makes 1 and 1.0 one.

iterkeys() lists every str key first, in sorted order, then the other types (None, bools, ints, floats, bytes, tuples), each sorted; iterkeys(prefix=...) lists only str keys. diskcache sorts numbers, then text, then bytes.

memoize works as diskcache’s, and f.__cache_key__(...) returns the same tuple, with two differences: every argument must be a key type (leave one out with ignore=), and typed=True stores each argument type’s name rather than the class.

retry=True is accepted wherever diskcache takes it, as a keyword, and retries only Timeout. Dictionary syntax never retries: cache[k] raises Timeout after timeout, where diskcache’s waits forever.

transact()

with cache.transact(): works as it does in diskcache: the block’s calls on the entering thread commit together on exit and roll back on an exception, a nested block joins the outer one, its exit commits nothing, and an exception caught inside the outer block keeps the inner writes. What differs (details in Transactions):

  • tx is the cache instead of None, and a second Cache handle on the same directory joins the transaction instead of waiting for it (D-029).
  • A transaction on a second cache whose write lock another thread holds raises TransactionBusy, a Timeout subclass, at once, and retry=True retries only Timeout, never TransactionBusy. diskcache waits, and its retry=True loops on any OperationalError (D-030).
  • Another thread may end it. Its commit or rollback runs within the transaction’s timeout, and the owner’s own exit then raises TransactionAborted (a RuntimeError) unless it committed (D-031). The object transact() returns can be entered once.
  • A block that didn’t commit raises at its exit with TransactionAborted, a RuntimeError, for example after a write inside it failed on a full disk.
  • durable=True, which diskcache doesn’t have, still raises when a transaction can’t begin and for any failure inside one (D-028).
  • Forking inside your own transaction leaves the child unable to use that cache: every call on it there raises ForkedInsideTransactionError (a RuntimeError) at once, instead of stalling for the timeout (D-020).
  • It belongs to a thread, not an asyncio task, as in diskcache: don’t await inside the block.

FanoutCache

FanoutCache is covered in full in FanoutCache: sharded caches. The differences from diskcache’s, each with an entry in Divergences:

  • shards is keyword-only (FanoutCache(path, shards=4)). FanoutCache(path, 4) is a four-second timeout here. The constructor is FanoutCache(directory, timeout=None, *, shards=None, ...), and directory is required (D-039).
  • The shard count is recorded, and a different shards= never silently sends keys to other shards: the cache opens with the stored count and logs a warning, or raises LayoutMismatchError if you pass raise_on_mismatch=True. shards=None uses the stored count, or creates 8 (D-032).
  • A plain Cache and a FanoutCache refuse each other’s directories with LayoutMismatchError, and nothing is created by the refused open (D-038).
  • Shards are chosen by XXH3, not adler32, so which shard a key lands in differs from diskcache’s, and shard_of(key) tells you. Iteration goes shard by shard, and iterkeys(prefix=, reverse=) gives the merged sorted order (D-033).
  • A busy shard raises Timeout after timeout (60 seconds by default) instead of silently giving False or the default after 10 ms. durable=True gives the miss answers, and logs them (D-034).
  • Maintenance shares one timeout across the shards, doesn’t retry forever, and reports partial progress: a failure raises with failed_shards and removed (D-035).
  • size_limit is a total, split evenly with at least 1 MiB per shard, and it reads back as the total, not shard 0’s share (D-036).
  • max_connections is a total across the shards, so file descriptors are bounded and not one per thread per shard. It must be at least shards (D-037). With 8 shards, diskcache’s FanoutCache holds 152 descriptors at 8 threads and 536 at 32, where diskcache-oxide’s holds 32, and under a 256 limit it fails at 15 threads. If a diskcache app has failed with sqlite3.OperationalError: unable to open database file under a low ulimit -n, this is likely why.
  • transact() takes a key and covers one shard: with cache.transact(key=k): where diskcache’s with cache.transact(): locks every shard. Calls for keys on other shards inside the block raise ValueError, reads included. A ported bare transact() raises TypeError (D-040).
  • No queue calls. push, pull, peek and peekitem are on Cache only, since a queue spread over shards would have no order. Use a plain Cache for a queue.
  • Not there: cache(), deque() and index(), and read() and read= (D-039). memoize, retry=, stats(), check(), reset(), reversed(), pickling, tags with evict(), eviction_policy= and settings as attributes all work as on Cache.

Truthiness

In diskcache, an empty cache is falsy, so if cache: quietly skips caching right after every deploy, when the cache is empty. In diskcache-oxide, bool(Cache) is always True and bool(NullCache) is always False, so if cache: means “is caching on?”. Both have an enabled property that says the same thing.

Tests that patch time.time

diskcache reads time.time() in Python, so tests could advance its clock with unittest.mock.patch or a freezegun-style fixture. diskcache-oxide reads the clock natively, which keeps a Python call off every operation. To make it follow a patched clock, pass clock=:

cache = Cache(tmp_path, clock=lambda: time.time())

with patch('time.time', return_value=1000.0):
    cache.set('k', 'v', expire=10)
with patch('time.time', return_value=1015.0):
    assert cache.get('k') is None

Things that just get better

You don’t have to change anything for these:

  • Reads take about half the time, and threaded throughput no longer collapses as threads are added. See Performance.
  • A child process forked while another thread was writing can always write. In diskcache it can stall for the full 60-second timeout.
  • clear() keeps writes that land while it runs, expire() removes every expired entry, and a read during an overwrite never misses.
  • File descriptors and memory are bounded by a connection pool, not by how many threads touched the cache. A FanoutCache bounds them for the whole root, not per shard.
  • Opening a cache and reading from it doesn’t write to the database. Background maintenance does, when it has work and once an hour to coordinate the processes; pass maintenance_interval=0 for a cache a process must never write.

What diskcache doesn’t have

Once you’ve switched, a few things are there that diskcache never offered:

  • durable=True answers a busy lock or a full disk as a miss on single-key calls and logs it once a minute, so a cache outage costs speed instead of failed requests.
  • NullCache switches caching off without touching call sites, and Caches names an app’s caches, opens each on first use and hands out a NullCache while one can’t open.
  • register_type() stores your own classes, dataclasses and library types without pickle.
  • A FanoutCache transaction locks one shard instead of all of them.
  • Background maintenance: one thread per process removes expired entries and their files, trims a cache left over size_limit, checkpoints a grown write-ahead log and clears stray temporary files, for every open cache. An expire() you ran from cron keeps working, but has little left to do.
  • Free-threaded Python (3.14t and 3.15t) is supported and tested on every change.