Imagine a friend asks you: "Hey, what's your phone number?".

Now imagine they ask again the next day. And the next. And the day after that. Fifty different times, fifty different friends.

At some point you stop digging through your contacts to find it. You just know it. It lives in your head, ready to go.

Congratulations, you just invented caching.

Caching is one of the simplest ideas in all of computing, and one of the most powerful: if you've already worked out an answer, remember it instead of working it out again.

That's the whole idea. This post is about how it works, where it lives, and the one thing about it that makes even experienced developers grumpy.

According to recent reports, in Part 4 we looked at API gateways, the front door of your backend. Today we're going behind the door, to the places where your app quietly keeps its memory.

In a recent development, every time your app answers a question, it does work. Sometimes a lot of it:.

In a recent development, now think about how often people ask for the same thing. The homepage. A popular product. Today's exchange rate. A trending post. Thousands of people want identical answers. (Related: YouTube ‘Co-Views’ try to guess how many people are wat...)

Recent findings suggest that doing all that work from scratch every single time is like walking to the library to look up the same fact for every person who asks. A cache is a sticky note on your desk with the answer already written on it.

Industry observers note that here's something that surprised me when I first learned it: caching doesn't happen in one place. It happens at almost every step between a user and your data. Think of it like a series of shortcuts, each one closer to the person asking. (Related: Industry News: These are the Senate Democrats backing S...)

Sources indicate that 1. The browser cache. Your own browser saves images, scripts, and styles so it doesn't re-download them on every visit. This is the closest cache to the user, and the fastest, because there's no network trip at all.

Sources indicate that 2. The CDN cache. Back in Part 1, we saw copies of your content sitting on servers around the world. Same idea, one step further back.

Sources indicate that 3. The reverse proxy / gateway cache. From Parts 3 and 4: your front door can remember responses and answer repeat questions itself.

4. The application cache. This is the one this post focuses on. Your app keeps frequently needed data in fast memory so it doesn't keep asking the database. It's where tools like Redis come in.

In a recent development, 5. The database's own cache. Even your database remembers recent results internally. You get this one for free.

Recent findings suggest that A request travels down this chain and stops at the first place that already knows the answer. The earlier it stops, the faster the user gets their response. A really good cache setup means most requests never get past the first couple of layers.

Recent findings suggest that now, how does application caching actually work? The most common approach is so simple it almost feels like cheating. It's called cache-aside (or lazy loading), and it goes like this:.

That's it. The first person pays the full price. Everyone after them gets the express lane. If you remember the CDN article, it's the exact same "first visitor warms it up" pattern.

It has been revealed that caching has its own little vocabulary. Here's the cheat sheet, so nobody can fluster you in a meeting:.

It has been revealed that if you only remember one pair, make it hit and miss. Almost every caching conversation is secretly about how to get more of the first and fewer of the second.

In a recent development, you'll hear "just put it in Redis" constantly. Here's what that means in plain words.

In a recent development, redis is a database that lives in memory (RAM) instead of on disk. Memory is dramatically faster than disk, which is why it's perfect for caching. It stores simple key-value pairs, like a giant dictionary: "user:42" → {their profile}.

Recent findings suggest that two honest notes. First, memory is more expensive than disk, so you cache the valuable stuff, not everything. Second, a cache is allowed to forget. If Redis restarts and loses everything, your app should just fall back to the database and refill it. A cache is a convenience, never your only copy of anything vital.

There's an old joke in programming: "There are only two hard things in computer science: naming things and cache invalidation.".

Here's why. A cache remembers an answer. But the real world keeps changing. Imagine you cache a product's price at $20. Then the shop updates it to $25. Your cache doesn't know. For a while, some customers still see $20.

That's stale data: a remembered answer that stopped being true. And deciding when to forget is genuinely tricky, because you're balancing two things that pull in opposite directions:.

Industry observers note that there's no perfect answer. There are only sensible strategies. Here are the main ones, in plain language.

According to recent reports, give every cached item a countdown. After 5 minutes, it's discarded and gets fetched fresh next time. Simple, predictable, and good enough for most things. A trending list that's 2 minutes out of date hurts nobody.

When someone updates a product, your code also removes the cached version. Next request, the cache misses, and the fresh data gets loaded. This keeps things much more accurate, but you have to remember to do it everywhere data changes. Forget one spot, and you've got a sneaky bug.

In a recent development, called write-through. Every change goes to both places together. The cache is always current, at the cost of slightly slower writes.

It has been revealed that called write-behind. Super fast for writes, but risky: if the cache dies before it saves to the database, you can lose data. Use it carefully, and not for anything like payments.

Industry observers note that called stale-while-revalidate. The user instantly gets the old answer, while the app fetches a fresh one in the background for the next person. Nobody waits, and the cache heals itself.

A good rule of thumb: match the freshness to the stakes. A "like" count being a few seconds behind? Nobody cares. An account balance or a stock level? Be much more careful, or don't cache it at all.

According to recent reports, if you build with caching long enough, you'll meet these. Better to meet them here first.

Caching things that are personal. If you cache a page that includes one user's data and then serve it to everyone, Alice sees Bob's account. It's a real, embarrassing, sometimes serious bug. Be careful about what goes into a shared cache.

Cache avalanche ("everything expired at once"). Say you load a thousand items into the cache at the same moment, all with a 10-minute TTL. Ten minutes later, they all vanish together, and your database suddenly gets hit by a thousand requests at once. Picture a whole crowd leaning on a door that was holding them back. The classic fix: add a little random wiggle to your expiry times (say 10 minutes, plus or minus a bit) so they don't all disappear in the same second.

Cache stampede, also called "thundering herd" ("one popular thing just vanished"). This is the avalanche's close cousin, but about a single item. Imagine your homepage data is cached and thousands of people are asking for it every second. The moment it expires, every one of those requests sees a miss at the same time, and every one of them rushes to the database to rebuild the same answer. Thousands of identical, expensive queries, all at once, for something only one of them needed to do. This is how a fast site suddenly falls over.

Cache penetration ("asking for things that don't exist"). Someone (or some bot) keeps requesting items that aren't real, like user ID 99999999. The cache never has them, so every request misses and goes to the database, which finds nothing. Since there's nothing to cache, it happens again and again. A simple fix: cache the "not found" answer too, for a short time. Fancier fixes exist, but that one handles most cases.

In a recent development, never expiring anything. "I'll just cache it forever" is how you end up debugging at midnight, wondering why an old value won't go away.

Caching without measuring. If you don't know your hit rate (what percentage of requests are answered from cache), you don't know if your cache is helping. A cache with a 5% hit rate is mostly just extra complexity.

Industry observers note that okay, so how do you actually proposal one, rather than just sprinkling it everywhere and hoping? Here's the order I'd think through it. Each step is just a question.

Industry observers note that 1. What am I caching, and is it worth it? Pick the things that are read often, change rarely, and are expensive to produce. Look for the slow spots first, then cache those. If you can't point to something slow, you don't need a cache yet.

Recent findings suggest that 2. What should the key look like? The key is the label on the sticky note. It has to be unique and predictable, or you'll pull out the wrong note. A good habit is a clear pattern like user:42:profile or product:991:v2.

Recent findings suggest that the most important part: include everything that changes the answer in the key. If the page looks different per language, put the language in the key (home:en, home:sw). If you forget, a Swahili reader gets the English page, and you spend an evening confused. Adding a version (v2) also lets you "invalidate" everything at once by simply changing the version number.

It has been revealed that 3. How long should it live? Pick a TTL based on how bad it would be to show old data. Seconds for fast-moving things, minutes or hours for slow-moving ones. When in doubt, start short and lengthen it once you trust it. And remember the wiggle: add a little randomness so things don't all expire together.

4. What happens when it fills up? Memory is limited, so eventually the cache is full and something has to go. That's called eviction, and the rule for choosing what to throw out is called an eviction policy. The common ones:.

You don't need to memorize the details. Just know that "LRU" is the answer you'll see most often, and that your cache will need a rule.

In a recent development, 5. How major should it be? Here's the happy surprise: a cache usually doesn't need to hold everything. In most apps, a small slice of the data gets most of the requests (people tend to ask for the same popular things). So a modest cache can give you a high hit rate. Start small, watch the hit rate, and grow only if it helps.

Sources indicate that 6. What if the cache disappears? Design for it. Your app should still work if the cache is empty or down, just slower, by falling back to the database. And since an empty cache means a flood of misses, make sure your database (and the stampede protections above) can survive the "cold start" moment.

7. How will I know it's working? Track your hit rate, how much memory you're using, how many items are being evicted, and how fast reads are. If the hit rate is low, the cache isn't earning its keep. If evictions are constant, it's probably too small. Numbers beat guessing every time.

Sources indicate that that's the whole checklist: what, key, how long, eviction, size, fallback, measure. Walk through those seven questions and you've designed a cache.

Sources indicate that no. And this might be the most useful sentence in this whole post.

In a recent development, caching adds a second place where data lives, and any time the same fact lives in two places, they can disagree. That's a real cost.

A good habit: don't cache first, measure first. Find what's actually slow or expensive. Then cache that. Good candidates:.

Poor candidates: things that change constantly, things that must always be exact, and anything you haven't proven is slow.

Look at how far we've come, and notice how every part is really the same instinct wearing different clothes:.

Underneath it all is one simple belief: the fastest request is the one that never has to travel far, or never has to be computed twice.

It has been revealed that the next time an app feels instant, even though it must be handling millions of people, you'll know part of the secret: it's not working that hard. It's just remembering really well.

Next in this series: rate limiting, or how apps say "slow down, friend" without ever being rude about it.

According to recent reports, what's the strangest stale-cache bug you've ever debugged? I'd love to hear it in the comments. Everyone has one.

→ Read original article