Microservices using Flask(MUF): Redis Caching

Saurav Samantray
3 min readJan 5, 2021


Why caching?

Caching improves and speeds up service response and helps us avoid repeated computes.


What are we trying to achieve?

Explore how flask can connect and use redis as a caching layer. Once the integration is in place we will try to implement caching for simple REST api that accepts an integer, calculate the square of the number and returns the results in response.

Code Structure

flask-redis-service│ .env
│ .gitignore
│ docker-compose.yml
│ docker-compose-dev.yml
│ │ app.py
│ │ config.py
│ │ Dockerfile
│ │ requirements.txt

│ Dockerfile
│ nginx.conf



Flask and Gunicorn are the basic dependencies required to create and run our flask application. Flask-Caching and redis are additional ones needed for integrating redis as a caching layer for our application.


In config.py we will have to add below configuration details for flask to understand that cache type is redis and where & how to connect to it.

Let’s cache a REST API then!

from flask import Flask
from flask import request, jsonify
from config import BaseConfig
from flask_caching import Cache
app = Flask(__name__)
cache = Cache(app)@app.route('/square/<int:number>')
def square(number):
app.logger.info(f"Computing the square of {number}")
return jsonify({"computed":number*number})
if __name__ == '__main__':
  • The cache instance is created and managed using the Cache class defined in flask_caching. We can also create multiple cache instances with different types(simple, filesystem, memedcache etc.) if required.
  • We have defined a route /square/<int:number> that accepts an integer input as named parameter. Function square() evaluates the square of the input number and returns the computed result.
  • To cache this whole endpoint we have decorated it with @cache.cached(timeout=50)
  • The cached() decorator uses the request path by default as cache key.

Running the application

To run the application in development mode with hot reload, execute below command from root(flask-redis-service) of the application. It will start the application on 8000 port.

docker-compose -f docker-compose-dev.yml up –build

Testing :D

Access the end point http://localhost:8000/square/4 and you would get an expected 16 in the response. In the logs you can confirm the text “Computing the square of 4” which confirms it computed by the flask and not fetched from cache.

Access the same endpoint again and you would not get the log “Computing the square of 4” indicating a hit from cache and saving re-compute.

If you however wait for more than 30 seconds and try the same endpoint you will see a cache miss as we have configured cache timeout of 30 in the decorator.

You can get the complete code here.