# Delete nothing: invalidating a Django cache by moving one number

By Farhad Rezaei (https://farhad-rezaei.com) · Published 2026-11-24
Canonical: https://farhad-rezaei.com/blog/delete-nothing-cache-invalidation-by-version
Product: Fundai (https://fundai.ir/en)

> Keep one version number per company in the cache key and invalidate by incrementing it, never by deleting. The hard part is the writers: Django's bulk_create and bulk_update skip save signals, so every bulk path must move the version itself, after its write commits. A failed run then leaves the last good copy, and a failed invalidation is logged and bounded by a 24-hour expiry.

[Fundai](https://fundai.ir/en) is the stock-research platform for the Tehran Stock Exchange that I co-founded in 2023. Listed companies file reports through the year, and after each round of filings Fundai rebuilds the affected companies: the raw tables arrive from the filings first, then a fundamentals run derives the cumulative tables, the totals rows and the order in which products are listed. In [One rebuild, not twenty](https://farhad-rezaei.com/blog/one-rebuild-not-twenty) I wrote about stopping one expensive rebuild from turning into twenty. This is the other half of caching: knowing when a cached page has gone wrong.

For up to a day after each round of filings, an investor could open a company's report and get it half built, with the raw tables in and the derived figures not yet there. Whoever opened it in that window also pinned that version in the cache for everyone else, for the full 24 hours.

In the last piece, the restaurant's specials board got a new number whenever the menu changed, so nobody had to walk around taking down old copies. The numbering turned out to be the easy part. The hard part was making sure every cook who changes the menu remembers to bump it.

## How the cache knows what's current

Every company keeps a version number per area of data, stored under a key like `cc:ver:raw:{company}`, and every cached response for that company has the version baked into its key. Invalidating a company means moving that number:

```python
def bump_company(domain, company):
    key = f"cc:ver:{domain}:{company}"
    try:
        try:
            cache.incr(key)
        except ValueError:  # no version stored yet
            cache.set(key, 1, timeout=None)
    except Exception:
        logger.exception("cache invalidation failed for %s/%s", domain, company)
```

Once the version moves from 7 to 8, every reader looks under 8, misses, and builds fresh from the database. Nothing is deleted. Deleting would mean knowing every key a company has, one for each combination of filters a reader can choose, and a build that started before the delete could still write its old result back afterwards. Incrementing is atomic and costs one operation, and a late build lands under version 7, which nobody reads any more. The version key itself never expires, on purpose: if it silently reset to 1, an old entry stored under version 1 could come back to life.

## Where the half-built report came from

Here's the sequence on a filing day. A filing arrives and the scraper saves the raw rows one at a time. Each save fires Django's `post_save` signal, which moves the company's version from 7 to 8. An investor opens the report, misses at version 8, and the server builds it from a database that has the raw tables but not yet the derived ones, then caches that result under 8. The fundamentals run finishes and writes the cumulative tables, the totals rows and the product order with `bulk_create` and `bulk_update`. Those don't call `save()` and don't send signals, so the version stays at 8, and the half-built report is served until the 24-hour expiry.

The cache was only ever invalidated by the signals, and the writers that mattered most didn't send any.

![A filing day before the fix, where bulk writes left the version at 8 and a half-built report was served until expiry, and after, where the run commits and then moves the version to 9.](https://farhad-rezaei.com/images/blog/delete-nothing-cache-invalidation-by-version/versions.svg)

## Every writer moves the version itself

The fix makes invalidation explicit wherever data is written in bulk. `invalidate_company` and `invalidate_symbols` now move the version after the fundamentals run commits, when the display order is synced, at the end of the annual-forecast rebuild and the financial-year update, after the monthly side-table jobs, and in the two operation-income scripts that bulk-write rows readers are served. The signals stay, because they still cover row-by-row writes from the scraper and the admin.

Two product decisions shaped where the calls go. The bump happens after the write commits, so a run that fails leaves the cache alone: readers keep the last complete copy instead of a half-written one. And a no-op doesn't count as a change: syncing a display order that hasn't changed keeps the version, so a quiet run doesn't throw away a warm cache for nothing. One part of a company's data, a holding's dividends, is keyed by its own extra version, so it can be cleared on its own while the rest of the company stays cached.

## How I checked it

The change came with tests that pin each decision. A finished fundamentals run moves the company's version, and a run that fails leaves it where it was. A new display order moves the version, and an unchanged one doesn't. These run against Django's in-memory cache rather than Redis, so they prove the writers call the bump, not how Redis behaves under load; the incrementing itself is a single `INCR`, which Redis performs atomically.

The failure policy is deliberate and stated in the code. If reading the version fails, the request skips the cache and builds from the database: slower, never wrong. If moving the version fails, the error is logged loudly for alerting, and readers can see stale data until the 24-hour expiry, which is the safety net and not the mechanism. Old entries under retired versions also keep using memory until they expire.

## What carries over

- An invalidation scheme is only as good as its list of writers. Bulk paths, scripts and jobs skip model signals.
- Move the version after the write commits, so a failed write leaves the last good copy in place.
- A version key must outlive everything keyed by it.
- Don't invalidate on a write that changed nothing.
- Decide what a failed invalidation means before it happens. Here it means stale for at most a day, and loud.

For an investor, the report now changes when the filing does, and it never stops halfway. The design behind that is small, one number per company and a rule that every writer moves it, and the reliability comes from the parts around it: committing before invalidating, failing loud, and keeping a hard expiry as a backstop.

## Further reading

- Cache versioning in Django's cache framework: https://docs.djangoproject.com/en/5.2/topics/cache/#cache-versioning
- Django's bulk_create caveats, including signals: https://docs.djangoproject.com/en/5.2/ref/models/querysets/#bulk-create
- Redis INCR: https://redis.io/docs/latest/commands/incr/
- Scaling Memcache at Facebook (NSDI 2013): https://www.usenix.org/conference/nsdi13/technical-sessions/presentation/nishtala
