𝗣𝗿𝗲𝘃𝗲𝗻𝘁 𝗖𝗮𝗰𝗵𝗲 𝗦𝘁𝗮𝗺𝗽𝗲𝗱𝗲𝘀: 𝗔𝘁𝗼𝗺𝗶𝗰 𝗟𝗼𝗰𝗸𝘀 𝗶𝗻 𝗟𝗮𝗿𝗮𝘃𝗲𝗹
You cache heavy database data for 24 hours. The cache expires. 500 users hit your site at the same time. All 500 requests hit your database. Your CPU hits 100%. Connections run out. Your app crashes. This is a Cache Stampede.
Use Atomic Cache Locks. Only one server process gets a lock to rebuild the cache. Other users wait. This stops your database from crashing.
Do this in Laravel:
- Check the cache first.
- If empty, request a lock via Redis.
- If you get the lock, run your heavy query.
- Save the results to the cache.
- Release the lock.
- If you do not get the lock, wait one second and try again.
This makes your system stable. Hardware failures stop. Redis handles the heavy traffic. Your database stays healthy.
Source: https://dev.to/iprajapatiparesh/prevent-cache-stampedes-atomic-locks-in-laravel-58b5