If you have worked with backends of any sort, you might be familiar with the word caching, at its core, caching is the process of storing a copy of data in a temporary, high-speed storage so that future requests for that same data can be served much faster.
Redis is an in-memory database, meaning it stores data on the server’s RAM, since reading from RAM is much faster than reading from a hard disk. Redis can perform operations in a fraction of a millisecond.
If you are not familiar with Fast API, I recommend reading: Getting Started with FastAPI in 2025: A Beginner’s Guide | by Anandhu AS | Python in Plain English
I am running Redis on Docker inside a Windows machine. If your machine has Docker installed, you can follow along (Things are much easier in MAC and Linux).
Step 1 => open CMD and run (Pull the Redis image)
docker pull redis:7
Step 2 => Run Redis, name the container redis, and expose it on port 6379
docker run -d --name redis -p 6379:6379 redis:7
Step 3 => Verify it is running
docker ps
If everything works, you will see something like container ID, Image name, and exposed port.
Step 1: Once the Fast API app is created, install these dependencies
pip install redis httpxp
Step 2: Here Redis is initialized on app start, endpoint (“/entries”) is fetching a public API, if entire exist in Redis it is served right away, if not data is fetched, cached in Redis and served.
//main.py
from contextlib import asynccontextmanager
from fastapi import FastAPI
from redis.asyncio import Redis
import httpx
import json
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.redis = Redis(host="localhost", port=6379)
app.state.http_client = httpx.AsyncClient()
yield
await app.state.http_client.aclose()
await app.state.redis.aclose()
app = FastAPI(lifespan=lifespan)
@app.get('/entries')
async def read_items():
value = await app.state.redis.get('entries')
if value is None:
response = await app.state.http_client.get
('https://jsonplaceholder.typicode.com/posts')
value = response.json()
data_str = json.dumps(value)
await app.state.redis.set("entries", data_str)
return json.loads(value)
Step 3 => Testing the API, use (/docs) to open Fast API’s built-in API documentation.
Here we can see the first call took 343ms, once the data is cached, the consecutive calls are lightning fast, taking only less than 12ms.
I hope you got to learn something new. Thanks for reading.
Before you go
- Please take a moment to like the post and follow the writer!
- Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute here
Further Reading
Discover more articles on similar topics across our network
Comments
Loading comments…