r/SQL • • 4d ago

Discussion Keeping a Redis cache in sync when jobs and manual SQL also write to the same tables

I've got Postgres with a Redis cache in front. The app deletes the cache key after it updates a row, and that part works. What I'm unsure about is everything else that writes to those tables:

  1. background jobs doing bulk `UPDATE`s
  2. someone fixing data in psql
  3. migrations and backfills
  4. another service sharing the same database

None of those go through the app's update, then delete the key path, so as far as I can tell, the cache just stays stale until the TTL runs out.

How are you handling this? Do your jobs and scripts clear the cache too, do you rely on the TTL, or did you move to something based on logical replication or Debezium? Has one of these other writers ever bitten you?

1 Upvotes

16 comments sorted by

2

u/rathboma 4d ago

I use rails, so usually add a hook in the ORM to do it automatically. So when changing any record the cache gets updated.

That means you've just got to be careful about always using the ORM to make changes.

You can also do it on-read and have a short ttl. So on read it checks the cache, then if no entry it queries the database and adds to the cache, but yes then you can get a stale cache, so the ttl has to be short.

For the Beekeeper Studio cloud services we do the first version (ORM integration).

1

u/ResistPast3564 4d ago

That makes sense. "Always use the ORM" is the part I'd worry about, though. In Rails, update_all, delete_all and insert_all skip callbacks, and so does raw SQL in a migration or a console fix. Has that ever caught you out, and do you have a way to enforce it, or is it mostly team discipline?

1

u/rathboma 4d ago

Try your best, but sometimes there are bugs. If it's a real cache and isn't totally required you can always rely on the ttl or even wipe it after every migration and lazy populate on read also

1

u/rathboma 4d ago

You might not even need a cache if you optimize postgres enough.....

1

u/ResistPast3564 4d ago

Fair, wiping after migrations is a simple rule. When one of those bugs did slip through, how did you notice it? Was it a user report, or did it show up some other way?

1

u/rathboma 4d ago

User report, yep

1

u/FunAd6672 3d ago

That works until someone bypasses the ORM.

0

u/Woman_with_tools 4d ago

ORM hook is fine until someone runs a raw UPDATE from a psql prompt and suddenly your cache is lying to you for the next hour.

1

u/rathboma 4d ago

Yes that's the danger

1

u/Free-Good9203 4d ago

orm callbacks always leak the moment someone runs a bulk update or manual psql fix. if you want invalidation at the database boundary without pulling in kafka and debezium, a tiny `AFTER INSERT OR UPDATE OR DELETE` trigger that calls `pg_notify('cache_inv', table_name || ':' || id)` plus a lightweight worker listening via `LISTEN` and deleting the redis key catches every write path including raw sql. pair it with a short ttl as a safety net in case the listener briefly disconnects.

1

u/ResistPast3564 4d ago

Nice and simple. Do you run this in production? One thing I'd wonder about is NOTIFY isn't stored, so anything sent while the worker is down or reconnecting is just gone. Have you seen it miss deletes that way, or does the short TTL cover it well enough?

1

u/Free-Good9203 4d ago

yes, for soft caches like catalog pages or profile data, `LISTEN/NOTIFY` plus a 30 to 60s ttl covers brief worker restarts well enough (and on reconnect you can optionally flush or bump a namespace prefix if you want zero lingering keys).

when a missed delete actually hurts (permissions, billing state, feature flags), the clean step up without pulling in kafka or debezium is a tiny outbox table: the trigger inserts the cache key into `cache_inv_outbox` and only uses `pg_notify` as a wakeup ping. the worker drains it in batches, so if it goes down for a deploy it just catches up from where it left off instead of losing events. one caveat either way: if your background jobs update 50k+ rows in one query, avoid firing `pg_notify` per row or you'll flood the notify queue; use a `FOR EACH STATEMENT` trigger or bump a single table version key instead.

1

u/jshine13371 4d ago

If you want your cache to immediately refresh for every DML change that happens in the database, it no longer is a cache and now is the database. Hence the reason caching is natively TTL based.

1

u/Discordbothost 4d ago

A reader can fetch the old row, then put it back in Redis after a write commits and clears the key. To test that race, pause a reader between its SELECT and cache write, run a psql update and let invalidation finish, then resume the reader.

1

u/ayamlejen 3d ago

One way around the lost-NOTIFY problem is an outbox table: a trigger writes the changed key into a small cache_invalidations table in the same transaction, and a worker reads those rows, deletes the Redis keys, then deletes the rows. Because it's a real table, nothing is lost if the worker is down. It just catches up when it's back. If you don't want triggers on every table, logical replication (Debezium, or a small consumer on pgoutput/wal2json) sees every write, including psql fixes and migrations, at the cost of more moving parts.

1

u/MongooseWonderful198 18h ago

If every writer cannot call the same invalidation code, move the signal next to the database commit. One practical pattern is an outbox row written in the same transaction as the data change; a worker publishes the affected key/version to Redis and retries until acknowledged. Manual SQL and backfills must use the same stored procedure or explicitly enqueue the outbox event.

Put the row version in the cache value and in the invalidation event. Then a delayed event cannot delete or replace a newer cache entry. TTL remains the final safety net, not the mechanism that makes external writers correct.