TL;DR
|
Caching is a way to make apps faster by remembering answers. Instead of asking the database the same question a thousand times, the app asks once, keeps the answer in a fast store, and reuses it until it's out of date.
Redis is a popular choice for that fast store. This guide explains how caching works, where it happens, what Redis is and what else it's used for, and the mistakes that make caches serve the wrong data.
Key takeaway: the app checks the cache first, and only does the slow work when the answer isn't there.
A common pattern, often called cache-aside, works like this:
Here's what that looks like in Python, using the redis-py library. The db.fetch_product line stands in for your own database query.
import json
import redis
# Connect to Redis. On Upsun Cloud, the host and port come from environment variables.
cache = redis.Redis(host="localhost", port=6379, decode_responses=True)
def get_product(product_id):
key = f"product:{product_id}"
cached = cache.get(key) # Check the cache
if cached is not None: # Cache hit: use the copy
return json.loads(cached)
product = db.fetch_product(product_id) # Cache miss: ask the database
cache.set(key, json.dumps(product), ex=300) # Keep a copy for 5 minutes
return product
The next request for the same data is a hit. Because reading from memory is much faster than running a database query, pages load faster and the database does less work.
Key takeaway: caching happens at several layers, each closer to the visitor than the last.
| Layer | What it caches | Example |
|---|---|---|
| Browser | Images, styles, and scripts it has already downloaded | A returning visitor loads a site's logo from their own computer |
| CDN | Pages and files, stored in many locations worldwide | A visitor in Tokyo gets a copy from a nearby server |
| Reverse proxy | Whole pages, in front of your app | Repeat requests are answered without reaching the app |
| Application cache | Query results, computed values, fragments of pages | Redis or Memcached storing a product's details |
| Database | Recently used data, kept in memory | The database's own internal cache |
Our guide What is a reverse proxy? explains page caching in front of your app. The rest of this guide focuses on the application cache.
Key takeaway: Redis is an in-memory data store. It's fast because it keeps data in memory, and flexible because it understands more than simple key-value pairs.
Redis stores data in memory, under keys you choose, such as product:42. Reading from memory is very fast, which makes it a natural cache. It also understands several kinds of data, not just text:
| Data type | What it holds | Typical use |
|---|---|---|
| Strings | A single value | Cached pages or query results |
| Hashes | A set of named fields | A user's profile or session |
| Lists | An ordered list | A simple job queue |
| Sets | Unique items | Tags, or who's online |
| Sorted sets | Items with a score | Leaderboards and rankings |
Every key can have an expiry time, after which Redis deletes it automatically. That's what makes it practical as a cache.
Redis is also used for login sessions shared across several app servers, job queues for background work, and rate limiting, such as counting requests per user per minute. Memcached is an older, simpler alternative used purely for caching. Valkey is an open source fork of Redis, created in 2024 after Redis changed its license, and it works the same way for typical uses.
Key takeaway: a cache is only useful if it isn't wrong. Expire data, and clear it when the original changes.
The famous hard problem with caching is invalidation: knowing when a cached copy is out of date. Two approaches cover most cases:
| Approach | How it works | Best for |
|---|---|---|
| Expiry time | Each cached item disappears after a set time, such as five minutes | Data where being slightly out of date is fine |
| Clear on change | When the original data changes, the app deletes or updates the cached copy | Data that must be current, such as prices or stock levels |
Many apps use both: clear the cache when data changes, and set an expiry as a safety net in case something is missed.
Key takeaway: many caching bugs come from caching the wrong thing, for the wrong person, for too long.
| Mistake | What happens | How to avoid it |
|---|---|---|
| Caching personal data under a shared key | One user sees another user's details | Include the user in the key, or don't cache personal data |
| No expiry time | Stale data lives forever, and memory fills up | Give every cached item an expiry |
| Treating the cache as the only copy | Data is lost when the cache restarts or evicts it | Keep the real data in a database. A cache can always be rebuilt |
| Many requests rebuilding the same item at once | When a popular item expires, every request hits the database together | Let one request rebuild it while others wait, or refresh popular items before they expire |
| Caching everything | Memory fills with data that's rarely reused | Cache what's slow to get and often requested |
Key takeaway: on Upsun Cloud, Redis is a service you add in your configuration file, either as a temporary cache or as persistent storage.
According to the Upsun docs on Redis, there are two ways to run it:
| Type | How it stores data | Use it for |
|---|---|---|
redis (the default) | In memory only. Data can be lost when the container restarts or moves | Caching, where data can always be rebuilt |
redis-persistent | In memory, and saved to disk so it survives restarts | Sessions, queues, and anything you can't easily rebuild |
Adding a Redis cache takes a few lines in .upsun/config.yaml:
applications:
myapp:
type: "php:8.4"
relationships:
cache:
services:
cache:
type: "redis:8.0"
Your app receives the connection details as environment variables, so there's no address or password to hard-code. A few details from the docs:
You can deploy on Upsun Cloud free for 15 days, with no card needed, or see how scaling and performance work on Upsun Cloud.
A fast store that keeps copies of data that's slow to get, so the app can reuse them instead of fetching the original every time.
Mainly caching, plus login sessions, job queues, rate limiting, and leaderboards. Anything that benefits from very fast reads and writes.
It's often called an in-memory database or data store. It can save data to disk, but it's usually used alongside a main database, not instead of one.
Both are fast in-memory caches. Memcached only stores simple values. Redis supports more data types, can save data to disk, and has extra features such as queues.
A hit means the data was in the cache and could be used straight away. A miss means it wasn't, so the app fetched it from the original source.
As long as it can be out of date without causing problems. That might be seconds for prices or stock levels and hours for content that rarely changes.