Utilising a Content Delivery Network (CDN) is one way to enhance the performance of web applications.
A global network of geographically dispersed servers makes up a CDN. The server closest to the user is where CDNs serve static content like photos, videos, scripts, stylesheets, and more.
This strategy offloads the job of serving static assets off the web server, decreases the amount of time it takes for assets to load, and enhances the overall user experience. Additionally, we can lessen the workload on our web server and free up resources for other tasks.
We will look at using Amazon CloudFront as a CDN in our Rails app to speed up load times by shifting assets to the CDN in this blog article. We’ll go through the advantages of using a CDN, how to set it up, and why CloudFront is a well-liked option for CDNs.
Integration with CloudFront
CloudFront offers a wide range of features and advantages like High performances, Easy to use, Integration with other AWS services.
Sign up for Amazon CloudFront
Click on Create Distribution
- Fill the details about distribution with origin of our site domain
- Click on Create Behaviour
- Fill the details about behaviour with added origin
How to load assets using CDN in a Rails app
To load assets using a CDN in a Rails app, we will need to make a few changes to our application code. Here are the steps we need to follow:
- Update our Rails application to use the CDN. In our Rails application, update our asset_host configuration in our production.rb file to point to our CloudFront distribution. Here’s an example:
- It’s recommended to use an environment variable to set the asset host:
When we deploy our application to production, Rails will generate full CloudFront URLs for our assets. For example, in a Rails view, we might have:
When Rails renders the view, it should output something like:
- Precompile our assets. Before deploying our application to production, we will need to precompile our assets. But mostly its will e take care by the out deployment script. We can do this by running the following command:
- Size 1.7 MB and Time 1.1 min
without cache - Size 883 B and Time 196 MS
with cache - Size disk cached and Time 4 MS
Finally, CDNs offer further performance enhancements like HTTP/2 compatibility, SSL acceleration, and load balancing, which can help performance even more.