Most software developers encounter three main problems: naming things, caching, and off-by-one errors. 🤦🏻♂️
In this tutorial, we’ll deal with caching. We’ll walk through how to implement RESTful request caching with Redis. We’ll also set up and deploy this system easily with Heroku.
For this demo, we’ll build a Node.js application with the Fastify framework, and we’ll integrate caching with Redis to reduce certain types of latency.
Ready to dive in? Let’s go!
As I’m sure readers know, Node.js is a very popular platform for building web applications. With its support for JavaScript (or TypeScript, or both at the same time!), Node.js allows you to use the same language for both the frontend and the backend of your application. It also has a rich event loop that makes asynchronous request handling more intuitive.
The concurrency model in Node.js is very performant, able to
As you follow along, you can always browse the codebase for this mini demo at my
By using
After initializing a new project, we will install our Fastify-related dependencies.
~/project$ npm i fastify fastify-cli fastify-plugin |
---|
Then, we update our package.json file to add two scripts and turn on the ES module syntax.
We make sure to have the following lines:
"type": "module", |
---|
From there, we create our first file (routes.js) with an initial route:
// routes.js |
---|
Then, we create our app.js file that prepares a Fastify instance and registers the routes:
// app.js |
---|
These two simple files—our application and our route definitions—are all we need to get up and running with a small Fastify service that exposes one endpoint: /api/health. Our dev script in package.json is set to run the fastify-cli to start our server on localhost port 8000, which is good enough for now. We start up our server:
~/project$ npm run dev |
---|
Then, in another terminal window, we use
~$ curl http://localhost:8000/api/health |
---|
We’re off to a good start. Next, let’s add another route to simulate a long-running process. This will help us gather some latency data. In routes.js, we add another route handler within our exported default async function:
fastify.get("/api/user-data", async (_, reply) => { |
---|
This exposes another endpoint: /api/user-data. Here, we have a method to simulate reading a lot of data from a database (readData) and a long-running process (sleep). We define those methods in routes.js as well. They look like this:
import fs from "fs"; |
---|
With our new route in place, we restart our server (npm run dev).
How do we measure latency? The simplest way is to use curl. Curl captures various time profiling metrics when it makes requests. We just need to format curl’s output so that we can easily see the various latency values available. To do this, we define the output we want to see with a text file (curl-format.txt):
time_namelookup: %{time_namelookup} |
---|
With our output format defined, we can use it with our next curl call:
curl -w "@curl-format.txt" \ -o /dev/null -s \ "http://localhost:8000/api/user-data" |
---|
The response we receive looks like this:
time_namelookup: 0.000028s |
---|
Well, that’s not good. Over five seconds is way too long for a transfer time (the time it takes the server to actually handle the request). Imagine if this endpoint was being hit hundreds or thousands of times per second! Your users would be frustrated, and your server may crash under the weight of continually re-doing this work.
Caching your responses is the first line of defense to reduce your transfer time (assuming you’ve addressed any of the poor programming practices that might be causing the latency!). So, let’s assume we’ve done everything we can do to reduce latency, but our application still needs five seconds to put this complex data together and return it to the user.
In our scenario, because
~/project$ npm i @fastify/redis |
---|
We create a file, redis.js, which configures our Redis plugin and registers it with Fastify. Our file looks like this:
// redis.js |
---|
Most of the lines in this file are dedicated to parsing a REDIS_URL value into a host, port, and password. If we have REDIS_URL set properly at runtime as an environment variable, then registering Redis with Fastify is simple. After configuring our plugin, we just need to modify app.js to use it:
// app.js |
---|
Now we have access to our Redis instance by referencing fastify.redis anywhere within our app.
With Redis in the mix, let’s change our /api/user-data endpoint to use caching:
fastify.get("/api/user-data", async (_, reply) => { |
---|
Here, you see that we’ve hardcoded in Redis a single key, user-data, and stored our data under that key. Of course, our key could be a user ID or some other value that identifies a particular type of request or state. Also, we could
If there is data in the cache, then we’ll return it and skip all the time-consuming work. Otherwise, do the long-running computation, add the result to the cache, and then return it to the user.
What do our transfer times look like after hitting this endpoint two more times (the first one to add the data into the cache, and the second one to retrieve it)?
time_namelookup: 0.000023s |
---|
Much better! We’ve reduced our request times from several seconds to milliseconds. That’s a huge improvement in performance!
Redis has many more features that may be useful here, including having key/value pairs timeout after a certain amount of time; that’s a more common scenario in production environments.
Up to this point, we’ve only shown how this works in a local environment. Now, let’s go one step further and deploy it all to the cloud. Fortunately, Heroku provides many options for deploying web applications and working with Redis. Let’s walk through how to get set up there.
After
~/projects$ heroku login |
---|
When we create our Heroku app, we’ll get back our Heroku app URL. We take note of this because we’ll use it in our subsequent curl requests.
~/project$ heroku create -a fastify-with-caching |
---|
We need to set up a
~/project$ heroku addons:create heroku-redis:mini -a fastify-with-caching |
---|
Spinning up the Redis instance may take two or three minutes. We can check the status of our instance periodically:
~/project$ heroku addons:info redis-transparent-98258 |
---|
Not too long after, we see this:
State: created |
---|
We’re just about ready to go!
When Heroku spins up our Redis add-on, it also adds our Redis credentials as config variables attached to our Heroku app. We can run the following command to see these config variables:
~/project$ heroku config -a fastify-with-caching |
---|
(Your credentials, of course, will be unique and different from what you see above.)
Notice that we have a REDIS_URL variable all set up for us. It’s a good thing our redis.js file is coded to properly parse an environment variable called REDIS_URL.
Finally, we need to
~/project$ heroku git:remote -a fastify-with-caching |
---|
Now, when we push our branch to our Heroku remote, Heroku will build and deploy our application.
~/project$ git push heroku main |
---|
Our application is up and running. It’s time to test it.
We start with a basic curl request to our /api/health endpoint:
$ curl https://fastify-with-caching-3e247d11f4ad.herokuapp.com/api/health |
---|
Excellent. That looks promising.
Next, let’s send our first request to the long-running process and capture the latency metrics:
$ curl \ -w "@curl-format.txt" \ -o /dev/null -s \ https://fastify-with-caching-3e247d11f4ad.herokuapp.com/api/user-data |
---|
When we send the same request a second time, here’s the result:
$ curl \ -w "@curl-format.txt" \ -o /dev/null -s \ https://fastify-with-caching-3e247d11f4ad.herokuapp.com/api/user-data |
---|
Much better! Caching allows us to bypass the long-running processes. From here, we can build out a much more robust caching mechanism for our application across all our routes and processes. We can continue to lean on Heroku and Heroku’s Redis add-on when we need to deploy our application to the cloud.
By the way, if you want to test this more than once, then you may occasionally need to delete the user-data key/value pair in Redis. You can use the Heroku CLI to access the Redis CLI for your Redis instance:
~$ heroku redis:cli -a fastify-with-caching |
---|
In this tutorial, we explored how caching can greatly improve your web service's response time in cases where identical requests would produce identical responses. We looked at how to implement this with Redis, the industry-standard caching tool. We did this all with ease within a Node.js application that leverages the Fastify framework. Lastly, we deployed our demo application to Heroku, using their built-in Heroku Data for Redis instance management to cache in the cloud.