How To Make Your Site 25x Faster With A Few Lines Of Code

How To Make Your Site 25x Faster With A Few Lines Of Code

Reduce data load time insanely.

Organic traffic is a great way to get eyeballs on your website and Google is the most popular search engine of choice that you can use to get that organic traffic coming.

Although Google ranks your site based on a lot of metrics, how fast your website loads is one of the critical factors.

Websites that load quickly are not just great for rankings but also for the overall user experience.

Since most of us developers( especially indie developers) are using JavaScript frameworks, such as React and Angular, which probably do a client-side rendering of data, the speed at which data is fetched forms an important aspect of the development process.

There is a simple way of making your site load faster, and that is caching and CDN(Content Delivery Network).

Using a combination of both can lead to miraculous drops in time taken to load the first byte.

In this blog, I will demonstrate caching with an example using Redis and also explain what is CDN. Caching, in layman’s language, is storing data that you think might be used frequently into memory(called cache).

So the next time you need that data, you check whether it’s stored in the memory and if not, then you make a call to the database to fetch it and maybe store it into the cache for future use.

cache.png

Source: Author

As you can see from the image above, caching is simply a layer of a data structure containing frequently accessed data between your data source and the app.

Not all data needs to be cached. For example, a user’s personal setting or shouldn’t be cached on the server. However, you can always store them in the client’s local storage for faster access. Caching of data is one of the simplest ways to reduce the load time, at the same time, you have to be smart about how you cache your data.

What should you cache?

As stated before, frequently accessed data should be cached to provide a responsive and quick experience.

Different developers have different caching strategies depending on their preferences and needs. If you want me to cover various common caching strategies, then drop a response to this blog.

Below are some examples of items that you should cache:

  1. Authorization & Session Tokens
  2. Landing page data that doesn’t change often(such as recent projects in a portfolio site).
  3. Blog and post drafts can be stored in cache for a while and then inserted into the database after a fixed amount of time.
  4. Real-time comment streams & analytics.

Why Redis?

Although you are free to use whatever option you are comfortable with, I highly recommend at least checking Redis out.

Redis is an open-sourced in-memory data structure store that has familiar data types such as lists, dictionaries, strings, hashes, etc.

It is a key-value data store with extended abilities such as the ability to set expiry dates.

Redis is the most loved database as per the Stack Overflow 2021 survey.

Redis can be used for other purposes besides caching as well and Redis Enterprise, created by the makers of the open-source Redis, is a great starting for you to explore the robust and powerful nature of Redis. Redis Enterprise is an in-memory NoSQL platform with 99.999% uptime and offers several enterprise-grade capabilities.

AWS’s MemoryDB for Redis is also a great choice if you need a durable transactional log that stores data across multiple Availability Zones.

Installation

Installing Redis is incredibly straightforward if you are on Linux.

Head over to the Redis download page and download the latest stable version available or you can simply run the following command in your terminal:

sudo apt-get install redis

Once you are done installing Redis, simply type redis-server to spin up a Redis server. The default port of this server is port 6379.

However, if you are on Windows, there are two options.

You can either follow the simple guide on how to install an outdated Redis on your Windows machine or you can use Windows Subsystem for Linux(WSL) and get the latest Redis.

I personally went with the WSL way and it created an Ubuntu 20.04 system for me to install Redis and any other packages I might need in the future.

Usage

There are plenty of guides available online on how to get started with Redis, hence I will just be providing a demo of what Redis can do to speed up your website.

I will be creating a simple Node.js server that fetches some data from the web and then sends them to its clients and later we will be adding caching to it and see the massive difference.

Below is a server that simply fetches the data from a data source and then passes it along to the client.

You can see the response time in the image attached below:

image.png Source: Author. Time taken is 1301ms.

Now we will implement caching using Redis.

First of all, we need an npm package.

npm i --save redis

Once this is installed, we will import it into our server.js file & create a client.

const redis = require('redis');
const cacheClient = redis.createClient(); // => Redis client

We need to edit our app.get() function and add caching logic to it.

It’s simple if-else logic. We first check if the data is present in our Redis server or not by calling the Redis client and using the .get() to get data.

If the data is not present, then we make a call to our data source to get fresh data. We insert this data into our Redis store by calling the .setex() function on our Redis client.

cacheClient.setex('sample',60,JSON.stringify(json));

The first parameter is the name(key) of the data we want to store, followed by the time to expire, and then finally the actual data(value) goes in as the third parameter.

We are using JSON.stringify() method to convert our JSON data to a string data type. With the data stored in the Redis store, the next time the app.get(‘/’) function is called, the client will be able to fetch the data from the Redis server instead of fetching from our original data source.

image.png

With this implemented, we can instantly see amazing results as the time taken is just 52ms compared to 1301ms from before.

This was a very simplistic view of caching and Redis is capable of much more than caching and can even be used as a permanent storage option. Our final server.js file will look like this:

const express = require('express')
const app = express();
const redis = require('redis');
const fetch = require('cross-fetch');
const cacheClient = redis.createClient();
app.get('/', async (req, res, next) => {
await cacheClient.get('sample', async (err, data) => {
        if (err) console.error(err);
        if (data) {
            console.log('Data was cached before')
            return res.json({ data: JSON.parse(data) });
        }
        else
          await fetch('https://jsonplaceholder.typicode.com/photos')
                .then(response => response.json())
                .then(json => {
                    console.log('Newly fetched data')
                    cacheClient.setex('sample',
                        60,
                        JSON.stringify(json));
           return res.json({ data: json });
        })
})
});
app.listen(3000, () => console.log('listening on port 3000'));

Content Delivery Network(CDN)

Caching data on the server is surely a great improvement but what about caching large HTML, video & image files?

CDN provides a simple solution to this issue. It is important to know that CDN and caching are not the same.

While CDN does cache content, not everything that cache data can be called a CDN.

CDN refers to a geographically distributed group of servers that work together to provide fast delivery of sites & other assets(like image & video files).

Popular sites such as Netflix and Facebook leverage the benefits of the CDN and deliver content quickly to you using the nearest group of servers near you.

CDN stores a cached copy of your content in multiple locations throughout the world.

So if someone from Australia visits your UK-hosted site, they will instead visit the nearest CDN server available to Australia and get a cached copy of your UK-hosted site.

This also saves bandwidth costs and increases reliability & uptime.

In some platforms and hosts, a CDN is at your disposal by default, and generally, using it is as simple as adding a header to your HTML file.

Personally, in my experience, I have found Vercel’s CDN to be the simplest to use with a good, detailed guide with a useful feature that prevents your data from being stale(outdated).

In Vercel, you just need to add a header to inform the CDN that the site needs to be cached. An example header is given below: Cache-Control: s-maxage=1

It is worth noting that any data that you load client side will not be included in your site’s cached CDN copy.

This is because the data is loaded dynamically on the client-side and not server-rendered.

However, you can always cache the data that is being loaded on the client-side via Redis, CDN, or any other option available to make the dynamic loading faster.

Final thoughts…

Optimizing and reducing the time taken to load your site is a crucial step of the entire web development process.

As per Google,

As page load time goes from one second to 10 seconds, the probability of a mobile site visitor bouncing increases 123%.

Page load time can be reduced by implementing a few strategies to cache data and use the nearest server to the client.

Caching data also has economical benefits as you save on bandwidth costs as well as reduce read and write operations to your database.

A combination of CDN with a data caching strategy can lead to astoundingly low web load times, thereby also increasing your chances of getting ranked higher on Google.

Did you find this article valuable?

Support Anurag Kanoria by becoming a sponsor. Any amount is appreciated!