Adding a Redis cache to an Express app

const express = require('express')
const app = express()
const port = 3000
const wait = ms => new Promise(resolve => setTimeout(resolve, ms))function greet(req, res) {
const between1and3seconds =
1000 + Math.floor(Math.random() * Math.floor(2000))
wait(between1and3seconds).then(() =>
res.send(`Hello, I just waited ${between1and3seconds} ms`),
)
}
app.get('/', greet)
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
$ brew install redis
!#/bin/zsh
redis-server /usr/local/Homebrew/etc/redis.conf
version: '3'
services:
redis:
container_name: redis-cache
image: redis
ports:
- '6379:6379'
$ npm install express-redis-cache
const ExpressRedisCache = require('express-redis-cache')
const cache = ExpressRedisCache({
expire: 10, // optional: expire every 10 seconds
})
app.get('/cached', cache.route(), greet)
  • The data returned by a service does not change very frequently
  • A particular route is slowed down by multiple services
  • An API called from the Express application is rate limited: call it once and retrieve from cache subsequent times
  • A service uses cookies/headers as parameters, since by default the URL is cache. However it is possible to cache per user session and to cache conditionally. This comes in handy to cache GraphQL queries.
  • The data changes faster than the cache expires.

Full code

--

--

--

Previously Paris and Geneva, currently New York. Can also be found at https://dev.to/arnaud

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Arnaud Dostes

Arnaud Dostes

Previously Paris and Geneva, currently New York. Can also be found at https://dev.to/arnaud

More from Medium

Connect MongoDB to Your React Project

SE3050 -Application Frameworks Blog — 05

Basics of Node JS

Introduction to NodeJS