How can I fix Redis cache invalidation and locking?
#1
I’m trying to implement a simple caching layer for my API responses using Redis, but I’m running into a problem where stale data keeps getting served after an update. My current setup invalidates the key on a POST request, but it seems like race conditions might be causing old data to be rewritten. I’m not sure if my approach to cache invalidation is fundamentally flawed or if I just need a different locking strategy.
Reply
#2
I had something similar last quarter. Invalidate on POST, but two requests could both read the pre-invalidation value, then one write would win and a stale value came back. We added a per-key lock using Redis SETNX and a short lock TTL, then did a single refresh path guarded by that lock. It cut the window considerably, though it wasn't perfect.
Reply
#3
A lot of stale data came from async updates that touched the same key. We started tagging responses with a version and only serving if the version matched what we expected; updates would bump the version and force a refresh. It helped, but required change in the client logic too.
Reply
#4
Could the real problem be the timing of invalidation rather than the locking itself? If the GET arrives before the write completes, you could still serve old data even with a lock.
Reply
#5
We also tried shaving TTLs down and adding a lightweight in-process cache just for hot keys, but that introduced another stale path. Honestly, I’m not fully sure what fixed it, but the combo of lock + short TTL plus a revocation note on update helped.
Reply


[-]
Quick Reply
Message
Type your reply to this message here.

Image Verification
Please enter the text contained within the image into the text box below it. This process is used to prevent automated spam bots.
Image Verification
(case insensitive)

Forum Jump: