• Docs
  • Talk to an expert
Blog
Blog
BlogProductCase studiesNewsInsights
Blog

What is caching? Redis explained for beginners

RedisperformancePython
Share

TL;DR

  • Caching means keeping a copy of data that's slow to get, such as the result of a database query, somewhere fast, so the next request can use the copy.
  • When the copy is there, it's a cache hit and the request is fast. When it isn't, it's a cache miss, and the app fetches the data and stores a copy for next time.
  • Caching happens at many levels: in the browser, in a CDN, in front of your app, and inside your app.
  • Redis is a popular in-memory data store used as an app cache, and also for sessions, queues, and rate limiting.
  • The hard part is keeping cached data fresh. Expiry times and clearing the cache when data changes are the usual tools.
  • On Upsun Cloud, you add Redis as a service in a few lines of configuration, as either a temporary cache or persistent storage.

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.

How caching works

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:

  1. A request needs some data, such as a product page's details.
  2. The app checks the cache for it.
  3. If it's there, a cache hit, the app uses it straight away.
  4. If it's not, a cache miss, the app gets the data from the database, stores a copy in the cache, and uses it.

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.

Where caching happens

Key takeaway: caching happens at several layers, each closer to the visitor than the last.

LayerWhat it cachesExample
BrowserImages, styles, and scripts it has already downloadedA returning visitor loads a site's logo from their own computer
CDNPages and files, stored in many locations worldwideA visitor in Tokyo gets a copy from a nearby server
Reverse proxyWhole pages, in front of your appRepeat requests are answered without reaching the app
Application cacheQuery results, computed values, fragments of pagesRedis or Memcached storing a product's details
DatabaseRecently used data, kept in memoryThe 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.

What is Redis?

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 typeWhat it holdsTypical use
StringsA single valueCached pages or query results
HashesA set of named fieldsA user's profile or session
ListsAn ordered listA simple job queue
SetsUnique itemsTags, or who's online
Sorted setsItems with a scoreLeaderboards 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.

Keeping cached data fresh

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:

ApproachHow it worksBest for
Expiry timeEach cached item disappears after a set time, such as five minutesData where being slightly out of date is fine
Clear on changeWhen the original data changes, the app deletes or updates the cached copyData 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.

Common caching mistakes

Key takeaway: many caching bugs come from caching the wrong thing, for the wrong person, for too long.

MistakeWhat happensHow to avoid it
Caching personal data under a shared keyOne user sees another user's detailsInclude the user in the key, or don't cache personal data
No expiry timeStale data lives forever, and memory fills upGive every cached item an expiry
Treating the cache as the only copyData is lost when the cache restarts or evicts itKeep the real data in a database. A cache can always be rebuilt
Many requests rebuilding the same item at onceWhen a popular item expires, every request hits the database togetherLet one request rebuild it while others wait, or refresh popular items before they expire
Caching everythingMemory fills with data that's rarely reusedCache what's slow to get and often requested

Redis on Upsun Cloud

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:

TypeHow it stores dataUse it for
redis (the default)In memory only. Data can be lost when the container restarts or movesCaching, where data can always be rebuilt
redis-persistentIn memory, and saved to disk so it survives restartsSessions, 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:

  • With persistent Redis, Upsun Cloud sets how much memory Redis can use for data automatically, based on the service's memory and disk, and it can't be changed by hand. To give Redis more room, give the service more resources.
  • To switch between persistent and temporary Redis, you create a new service with a different name.
  • Valkey is also available as a service, if you prefer it.

You can deploy on Upsun Cloud free for 15 days, with no card needed, or see how scaling and performance work on Upsun Cloud.

Frequently asked questions

What is a cache in simple terms?

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.

What is Redis used for?

Mainly caching, plus login sessions, job queues, rate limiting, and leaderboards. Anything that benefits from very fast reads and writes.

Is Redis a database?

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.

What is the difference between Redis and Memcached?

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.

What is a cache hit and a cache miss?

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.

How long should data stay in a cache?

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.

Stay updated

Subscribe to our monthly newsletter for the latest updates and news.

Deploy possibility.
Try Upsun for free.

Build with DispatchDeploy on Cloud