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.

Architecture

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
│ README.md
├───app
│ │ app.py
│ │ config.py
│ │ Dockerfile
│ │ requirements.txt

└───nginx
│ Dockerfile
│ nginx.conf

Dependencies

Flask==1.0.2
gunicorn==19.9.0
Flask-Caching==1.9.0
redis==3.5.3

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.

Configurations

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__)
app.config.from_object(BaseConfig)
cache = Cache(app)@app.route('/square/<int:number>')
@cache.cached(timeout=50)
def square(number):
app.logger.info(f"Computing the square of {number}")
return jsonify({"computed":number*number})
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0',port=8000)
  • 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.

--

--