Skip to main content

Storage and WAL

What’s in the cache directory, the on-disk format, how memory and disk stay bounded, eviction policies, tags, and the write-ahead log and checkpoint().

Nobody restarts a cache. It sits inside a worker process for weeks, and whatever it does to memory and disk, it does slowly and out of sight, until an alert fires at a bad hour. So how much a cache uses has to be something you set, not something you discover. This page covers what diskcache-oxide puts on disk, and the settings that keep memory and disk where you put them.

What’s in the directory

Open the directory and this is what you find:

/var/cache/my-app/
├── diskcache-oxide.sqlite        # keys, tags, settings and small values
├── diskcache-oxide.sqlite-wal    # SQLite's write-ahead log
├── diskcache-oxide.sqlite-shm    # SQLite's shared-memory index for the log
└── 3f/
    └── 3fa2…c91e.val             # one large value

A FanoutCache directory holds a small manifest file, diskcache-oxide-fanout, and one numbered folder per shard (000, 001, …), each laid out like the directory above.

After an upgrade across a format change you may also find diskcache-oxide-format-3/ (named for the format, not the release): the new release’s cache, laid out the same way, beside the old one. See below.

The database file carries a format version (PRAGMA user_version), and a build never reads the entries of a database in another format or changes its contents: it reads only the format. During 0.x, a release that changes the format bumps the minor version and says so first in its changelog entry. Caches aren’t migrated: when a release meets a cache in another format, it opens a new one in the subdirectory diskcache-oxide-format-N, N being its own format, logs a warning, and leaves the old one exactly as it was. Once that subdirectory exists, every later open uses it. A FanoutCache moves as a whole, never one shard.

0.2.3 and later write format 3, which added tags and the eviction policy. A cache made by 0.1.2 is format 2, so 0.3.5 opens diskcache-oxide-format-3 beside it (0.2.3 itself raises FormatMismatchError instead). remove_old_formats() removes the old database and its value files once no 0.1.2 worker is left; it removes only what diskcache-oxide wrote, in an older format. See Upgrading across a format change.

Small values inline, large values in files

  • Under 64 KiB (after encoding), a value is stored in its database row. Reading it is one indexed lookup.
  • 64 KiB or more, it’s written to its own file, and the row points to it. This keeps the database small and its page cache hot, and large values stream straight from the file.

Writing a large value never holds the database lock while the bytes go to disk: the value goes to a temporary file first, then inside a short transaction the file is renamed into place and the row updated. The old file is removed after the commit, and file names are never reused.

Large values live one folder deep, in up to 256 folders named by the first two characters of the file’s name (D-042). Deleting a value removes only its file. When the process closes its last handle on the cache, it sweeps those folders: a temp file that no writer has touched for an hour, left by a process killed mid-write, is removed, and a folder left empty goes too, skipping any touched in the last 30 seconds so a busy folder isn’t removed and re-created, all within 100 ms; a close that runs out of time leaves the rest to a later one. clear() runs the same sweep and removes the folders it emptied at once. Background maintenance runs the same sweep hourly, so a process that never closes its caches still has it done. So a cache never has more than 256 value folders, and none sits empty for long. A FanoutCache’s shards skip the sweep at close and get the hourly one; each keeps at most 256 folders.

A reader racing an overwrite always gets a whole value, old or new. If a value’s file really is gone (deleted by hand, or cut short by a crash, since value files aren’t fsynced), get returns the default and the orphaned row is cleaned up, so in and len don’t keep reporting an entry that can’t be read.

Size limit and eviction

cache = Cache('/var/cache/my-app', size_limit=500 * 1024 * 1024, cull_limit=10)
  • size_limit is the cache’s disk budget in bytes: the database plus value files. The default is 1 GiB and the minimum is 1 MiB.
  • When a set() finds the cache over its limit, it evicts up to cull_limit of the least recently stored entries (default 10). cull() evicts down to the limit on demand.
  • volume() reports the current size.

Least-recently-stored eviction means a get never has to write anything, which keeps reads fast and lets any number of processes read in parallel. LRU and LFU aren’t supported, because they make every get a write: 'least-recently-used' and 'least-frequently-used' raise ValueError (D-022, and see the roadmap). The hit and miss counts from stats() follow the same rule. They’re kept in memory, per process, and never written to the database.

eviction_policy='none'

Some entries mustn’t disappear just because the cache got full: a lock, a job claim, the items in a work queue. For a cache that holds those, turn eviction off:

locks = Cache('/var/lib/my-app/state/coordination', eviction_policy='none')

Under 'none', no write and no cull() evicts for size. Expired entries are still removed: each write sweeps up to cull_limit of them, and background maintenance removes the rest, as an explicit expire() or cull() does (cull() returns how many it removed). The cache can grow past size_limit, so give the entries an expire and keep them apart from your general-purpose cache, which should go on evicting.

The policy and both limits are stored in the cache, so every process shares them. Each write reads the policy afresh, so a change made from one process applies to every other at its next write, and a handle opened with eviction_policy=None (the default) keeps whatever is stored. reset() reads or changes one of them without reopening:

cache.reset('eviction_policy')            # 'least-recently-stored'
cache.reset('size_limit', 2 * 2**30)      # stored, and returned

Tags

A tag from set(..., tag=...) is stored in the entry’s own row. A partial index covers only the rows that have one, so untagged entries cost nothing extra, and evict(tag) finds a tag’s entries through the index instead of scanning the cache. Like clear(), it works in chunks and removes the entries that had the tag when it started, leaving ones written while it runs.

Memory: max_connections and sqlite_cache_size

diskcache gives each thread its own connection with a 32 MiB page cache plus a 64 MiB memory map, so its memory grows with your thread count. diskcache-oxide bounds it:

cache = Cache(
    '/var/cache/my-app',
    max_connections=8,       # connections per database file, per process (default 8)
    sqlite_cache_size=256,   # 4 KiB pages per connection: 1 MiB (default)
)

SQLite’s memory for a directory stays around max_connections × sqlite_cache_size pages, 8 MiB per process by default, however many threads use it. The 1 MiB default is the smallest size that left hot reads, writes and the threaded benchmarks unchanged. If your cache is large and read uniformly at random, raising it helps: 2,000 pages measured about 17% faster on that workload.

The write-ahead log

SQLite’s write-ahead log (WAL) is a ledger of recent changes kept beside the database, and it’s what lets readers and a writer work at the same time: the writer appends to the ledger while readers keep reading the book. Every so often SQLite folds the ledger back into the book and starts over. The catch in a multi-process app is that it can only start over when it finds a moment with no readers, and with readers in other processes that moment may never come. A burst of writes (a big fill, or a clear()) grows the log to fit the burst, and then it stays that size. diskcache-oxide’s soak tests saw logs over 1 GiB next to databases of a few MiB.

diskcache-oxide handles this in layers, from free and always on to explicit.

Always on: wal_size_limit

cache = Cache('/var/cache/my-app', wal_size_limit=64 * 1024 * 1024)   # the default

This tells SQLite to trim the log back to half the limit (32 MiB by default) whenever it resets, and scales how often SQLite checkpoints automatically. These are connection settings, so they never pause anything. At normal load they keep the log at a few MiB.

On demand: checkpoint()

cache.checkpoint()   # True if the log was reset and truncated

checkpoint() copies the log into the database and truncates it to zero. It waits briefly for in-flight reads, retrying up to the cache’s timeout, and returns False instead of raising if other processes keep the database busy. Call it when a short pause suits your app: at shutdown, in a maintenance job, or after a large clear().

At close

close() runs the same checkpoint when this is the process’s last handle on the cache and the log is over half the limit, waiting at most a second. A small log, the usual case, costs nothing extra. Pass close(checkpoint=False) to skip it.

Opt-in: automatic checkpoints

cache = Cache('/var/cache/my-app', wal_checkpoint='auto')

With 'auto', writes check the log (at most every 250 ms or 64 writes) and checkpoint it when it’s over the limit, with the interpreter released. Readers in other processes can get in the way for a moment, so it tries the final truncation up to 8 times, a couple of milliseconds each, before backing off for a second. It never fails a write. It isn’t the default because on a saturated disk the write that triggers the checkpoint can still pause for a long time, and no write should pay for housekeeping unless you asked for it. Background maintenance (below) checkpoints a log past half the limit on its own turn, so 'auto' is only for logs that grow faster than that. Writes queue behind a checkpoint for tens of milliseconds, so a timeout under about 35 ms can time out behind one.

The limit is a target, not a bound

wal_size_limit says where the log should stay, not where it’s guaranteed to stay. Sustained writes from several processes near flat out can take it to tens of times the limit: we measured 6 GiB on free-threaded 3.15 and 21 GiB on 3.14 in 10 minutes, against a 64 MiB limit. It’s much smaller below flat out, for example 250 MiB at about 2,600 writes per second across 3 writers in auto.

In the default manual mode, with busy readers in other processes, the log grows until something checkpoints: background maintenance does, every maintenance_interval, when its readers let it. If your app writes faster than that, use wal_checkpoint='auto'. A script should call checkpoint() or close() after a large fill.

Background maintenance

One thread per process, of the library’s own, looks after every cache open in that process (D-061). It holds no Python state, so it never takes the GIL, and it costs nothing while it waits.

Task How often What it does
Expiry and trimming every maintenance_interval Removes expired entries and their value files, then, if the cache is over size_limit, evicts the least recently stored, cull_limit at a time, until it’s under. Never evicts under eviction_policy='none' or with cull_limit=0 (diskcache’s “I cull myself”).
The write-ahead log every maintenance_interval If the log is over half of wal_size_limit, copies it into the database without holding the write lock, then truncates it if nothing’s left to copy. Skipped when the copy would take the cache’s last free connection (always with max_connections=1), while a checkpoint from a request is backing off, and when a writer in this process is waiting.
Value folders hourly, or every maintenance_interval if that’s longer Removes temporary files a killed writer left (an hour old) and empty value folders, on a FanoutCache’s shards too.

maintenance_interval is set when a cache is opened, in seconds: None for 300, 0 for off, otherwise 1 second to a day. It’s per process and isn’t stored in the cache. The shortest nonzero interval any handle on the directory asked for wins, and a handle that asks for 0 doesn’t count; the interval never lengthens while a handle on the cache is open, and handles that have since closed still count until every handle on it has. A cache’s first turn comes one to two intervals after it’s first opened in the process, so a short script never runs one.

  • Taking turns. The caches in a process are spread across the interval: four caches on a 5-minute interval get their turns about 75 seconds apart. The processes sharing a cache take turns through two rows in its settings table, so eight workers don’t all sweep the same cache; the shortest interval among them sets the pace.
  • Never in a request’s way. It never waits for a lock: if a request in this process holds the write lock, or one is waiting for it, the turn steps aside and comes back a second later. It writes in chunks of about 130 µs for 100 small rows, so a request in the same process waits at most one chunk; a writer in another process can wait for a few chunks, never past the turn’s 50 ms.
  • A cache with nothing to do is only read, except for one write an hour to coordinate the folder sweep. A cache that must never be written by this process (a read-only replica, a backup) should pass maintenance_interval=0: maintenance is off for a cache in a process only when every handle opened on it there asked for 0; an earlier handle that asked for an interval keeps it on until every handle on the cache has closed.
  • Forks and close. The thread stops before every os.fork() and starts again after it, in the parent and in the child, so Python never warns about forking a multi-threaded process. A process that forks without Python’s at-fork hooks (a C-level fork()) gets no stop; pass maintenance_interval=0 there. The last close() on a cache waits for a turn in progress on it, at least 50 ms and otherwise within its own deadline (D-018).
  • clock=. The thread only knows the real time, so a cache opened with clock= gets no background maintenance in this process until every handle on the directory has closed, and asking for an interval with it raises ValueError.
  • Reporting. maintenance_stats() returns the interval, turns, entries removed, failures and the last error. A failure is logged once per streak of failures, as a WARNING on the diskcache_oxide logger, by the next single-key call on the cache. A turn that keeps finding the write lock held for 3 intervals counts as a failure too.

Since maintenance may get there first, an explicit expire() or cull() can return less than it would have, and volume() and the log’s size change without a call.

Maintenance calls

For when you want it done now. All of these work in chunks, release the database between chunks so other writers get in, and are safe to call while other processes use the cache:

  • expire() removes every expired entry and its value file.
  • clear() removes every entry that existed when it started, and keeps writes that land while it runs.
  • cull() removes expired entries, then evicts down to size_limit (nothing under eviction_policy='none').
  • evict(tag) removes every entry that had the tag when it started.

check() compares the database with the value files and returns what doesn’t match, as a list of warnings.WarningMessage: SQLite’s integrity check, entries whose value file is missing or the wrong size, files older than an hour that no entry names, and stored totals that don’t add up. It runs in short steps, apart from SQLite’s integrity check. check(fix=True) also repairs what it found: it removes the broken entries and the unknown files in value folders, sweeps empty value folders, corrects the totals, then runs VACUUM. VACUUM rewrites the whole database, needs room for a temporary copy of it in SQLITE_TMPDIR, TMPDIR or /tmp, and makes writers and forks wait while it runs, so run fix=True in a maintenance window, not from a request.