Why you need it
The same questions get asked over and over: the same product page, the same profile, the same top ten list. Asking the database every time is slow and wears it out. Keeping a copy of recent answers close by makes repeat visits fast and takes most of the load off the database.
Think of it like this
A chef keeps salt, oil and the most-used knives on the counter, and only walks to the store room for rare things. The first time she needs something new she walks; after that it stays on the counter.
Where you’ll find it
- Facebook: Serves billions of reads a second from memcache, with the database behind it only for misses.
- Redis and Memcached: The two most common caches: Redis and Memcached, both keeping data in memory.
- AWS: ElastiCache runs Redis or Memcached for you, so you do not manage the cache servers.
What to know first
Cache. A fast store that keeps copies of answers. It usually lives in memory, which is far faster than a database reading from disk.
Hit and miss. A hit: the copy is there, the answer is fast. A miss: no copy, so you go to the database.
Hit rate. The share of asks that are hits. 95% means only 5 in 100 reach the database.
How it works
- Look in the cache first. When a request comes in, the server asks the cache for the answer by a key, like
product:shoes. - On a miss, ask the database and keep a copy. If the cache has nothing, the server reads from the database, answers the visitor, and puts a copy in the cache. The first visit is slow; the next ones are fast. This is the animation.
- Why "aside". The cache sits beside the database, not in front of it. Your code decides when to read and fill it. If the cache dies, the app still works, only slower.
- Copies go stale. When the real data changes, the copy is now wrong until it is replaced. Handling that is the hard part: see Invalidation and TTL.
- Caches fill up. Memory is limited, so old copies must be thrown out to make room. See Eviction (LRU).
An example
A product page takes 200 ms to build from the database. A cache answers in 1 ms.
The page gets 1,000 views a second. Without a cache the database builds it 1,000 times a second and struggles.
With a cache and a 99% hit rate, only 10 a second reach the database. Most visitors wait 1 ms instead of 200 ms.
Further reading
- Cache-Aside pattern, Microsoft Azure Architecture Center. A clear, short description of the pattern and its pitfalls. Start with this one.
- Caching best practices, AWS. Lazy loading, write-through and TTLs on one page.
- Scaling Memcache at Facebook, Rajesh Nishtala and others, NSDI 2013. How one of the biggest caches in the world works. Has a video too.