Open menu
Magento 2 Speed Optimization – The Definitive Guide (Updated for 2020)

Magento 2 Speed Optimization – The Definitive Guide (Updated for 2020)

Magento 2 Speed Optimization – The Definitive Guide (Updated for 2020)
Updated April 13, 2020

Magento 2 is not a lightweight platform. It was built to serve thousands of users at once. But without proper optimization you can end up with a website that is a pain to use and an eyesore to look at.

Why a slow Magento store is bad? Well, you can say it’s because users hate to waste their time. Their frustration leads to fewer sales and bad experience. But that’s not all.

Google discriminates against slow websites, too – slow Magento is bad for SEO. If your store is taking its sweet time to load, Google will notice and rank you lower than your competition. This creates a dangerous slope. A slow website will sink lower and lower in Google results page which leads to fewer people finding your company online.

In this guide we will help you make your store fast and snappy to use.

A lot of Magento 2 optimization tools online focus on front-end performance. This is because they can’t measure much else. We offer a comprehensive approach where you can evaluate all aspects of your store performance and fix all the Magento issues. We’ve gathered insights from our in-house Magento optimization experts and focused on the actionable tips that work now and will work throughout 2019.

In this guide, we categorized all fixes into two lists. The first part has relatively easy tips to make your Magento 2 run faster. They are actionable, simple, and most of the time do not require a developer to implement. Ideal for the DIY-minded crowd or a team on a budget.

These steps allow you to see results within minutes from implementation. We recommend that everyone find the time and implement them.

All Magento 2 Speed Fixes You Need From Must-Haves to Optional

Assess Your Website Speed
1. Make Sure Magento Runs in Production Mode
2. Update Magento 2 to the latest stable version
3. Configure Redis or Memcached

Memcached vs Redis
How to Install Redis for Magento 2

4. Turn on Varnish Cache Tool
5. Remove Unnecessary Bloat
6. Profile and Review All Third-Party Extensions
7. Remove Unused Scripts and Move the Rest to the Bottom
8. Remove Unused Plugins and Event Observers
9. Stop Using Flat Catalogs
10. Install ElasticSearch to Speed up Search Results
11. Use Lazy Loading for Images
12. Use HTML <picture> Tag
13. Optimize Your Magento Theme and Media
14. Optimize CSS for Faster Load Times
15. Make Sure JS Settings Offer You the Best Performance
16. Enable HTML Minification
17. Use Magento Gzip Compression
18. Fix .htaccess Caching Options
19. Use HTTP/2 Instead of HTTP/1.x
20. Expires Headers or Cache-Control Headers
21. Get a CDN to Speed up Content Delivery
22. Upgrade Infrastructure to Improve Server Response
23. Replace Apache with Nginx
24. Optimize JavaScript
25. Review Page Performance With Magento Profiler
26. Use a Progressive Web App to Make Your Magento Website Faster
27. Clean Database Logs

Boost Your Magento Storefront Further

All Magento 2 Speed Issue Fixes You Need From Must-Haves to Optional

Fair warning! Even though these tips are sorted in the order from bearing most impact on performance to completely optional, some of these fixes will bring better results depending on your unique situation.

We have tried to make these Magento 2 speed steps as user-friendly as possible. And even though some of them are directed towards non-technical Magento users, please bear in mind you have to know how to use SSH and install or remove Magento extensions on your own.

On our part, we promise we will keep things as simple as possible. There will be lots Magento issues of explanations and step-by-step instructions so you don’t get lost in the technical jargon.

Assess Your Website Speed

Before we move on to the fixing part, you need to know where your website is today in terms of speed. There’s no point in conducting a Magento performance test subjectively although perceived performance is an important part of user experience. We need to get scientific!

What we are looking for is a better TTFB (time to first byte). This benchmark determines the time when the server sends your browser its very first byte. Google states this time should be 200 ms or less.

By the way, we went to to see how it’s doing. Turns out, even the e-commerce giant struggles a bit with TTFB.

amazon time to first byte chrome

You can easily measure your own TTFB using these simple techniques.

Method 1. Use this link – it’s easy but not too accurate. TTFB depends on the location of the hosting server and your customer’s location.

Method 2. Use Chrome developer console. This method is superior because you will test the Magento time to first byte from your actual location. The first method tests first byte load from the location where their server is.

So this is how you do it:

Go to
In Chrome, hit F12 to open developer console
Go to the Network tab
Sort by Waterfall and hover your mouse over the first entry

The TTFB you see in the popup is the one you are looking for. If it’s larger than 200 ms, things need to change.

How do you fix TTFB? We’ll give you more tips to lower your TTFB, but sometimes throwing money at the problem is the most efficient solution.

Ask your hosting provider if they have a better plan for Magento storefronts. Upgrade to more powerful hardware and feel the difference. As a bonus, you get better SEO rankings (Google loves fast websites) and more sales from improved user experience.

Bear in mind that more capable virtual / dedicated servers can be pricey. Shop around and find the price-to-performance ratio you are comfortable with or contact us, we’ll be happy to find an optimal hosting solution for your current needs.

1. Make Sure Magento Runs in Production Mode

You’ve heard this before but… Make sure Magento is in Production mode. You’ll be surprised how often people forget to switch modes after fixing something in Developer mode or after a new install.

When you install Magento for the first time it will run in Default mode. This mode is best used to configure and test your Magento store before you open it to customers.

Default mode lets you tinker with a few cool features but doesn’t offer the best performance.

Besides Default, there are two other Magento modes:

Developer mode – used for verbose logging, bug hunting, and more in-depth configuration of your Magento install.
Production mode – this mode is optimized for performance. It’s the one you want to use day-to-day since Production mode will get you the best user experience.

Default and Developer modes are slow. Make sure you switch to production before you open for business:

php bin/magento deploy:mode:set production

2. Update Magento 2 to the latest stable version

Keep in mind that Magento 2.0 isn’t the newest version of the platform. Magento keeps releasing new versions of the CMS almost every three months. At the time of this writing (April 2020), the latest and the most optimized version is 2.3.3 which leagues ahead of the previous ones.

They’ve made some performance improvements to several areas to make Magento 2 websites faster. Below are just some of them:

  • Non-critical CSS elements are moved to the bottom of the page. This update empowers the browser to speed up rendering and display the storefront page faster. The feature allows users to see the page sooner while non-critical elements remain passive. By default, this setting is disabled. In order to activate it, you need to go to Stores > Configuration > Advanced > Developer > CSS Settings > Use CSS critical path.
  • With the Magento 2.3.3 version, text content is displayed in readable system fonts while custom fonts are loading. This update is especially important for stores that implement many fonts and large CSS files. Consequently, it makes Magento 2 faster by improving page speed.
  • 2.3.3 has advanced the performance of resized image operations, and much more.

The Magento 2.3.4 release is expected on April 20th. It will bring even more performance advancements such as enhanced banner cache logic that helps to eliminate redundant non-cached requests to the server on catalog pages and the ability to disable statistics collecting for the Reports module by default.

In case the question of “why is Magento 2 so slow?” comes across, you must note that it is critical to upgrade your store to the latest version of the platform. Not only because you will get more features, bug- and security fixes, but also because with every update Magento performs better.

Besides, the platform does a great job by notifying its users of important updates within their messages inbox.

3. Configure Redis or Memcached

Redis is an in-memory distributed data structure store that is used as a key-value database to improve Magento performance. In layman’s terms, it’s a caching tool for the backend of Magento store.

This is a separate upgrade from a content delivery network or from Varnish since Redis optimizes Magento session storage, enables on-disk saves, and improves website stability making your store faster and more reliable.

To get acquainted with Redis better, here’s a nice interactive tutorial you can read.

Memcached vs Redis for Magento 2

Memcached is interchangeable with Redis. It allows the server to move the most frequently used page content from disk to RAM. This will increase the response rate when the user makes database and API calls or wants to load a webpage.

Please bear in mind that you should use either Memcached or Redis but not both. Memcached is a worse alternative to Redis, but we want to give you both options in case you have to use Memcached for some reason.

How to Install Redis for Magento 2

Most hosting providers can help you install Redis. After the installation, you’ll need to configure it, too. Default configuration settings for the server are fine most of the time, but for an in-depth Magento server optimization we recommend you take a look at the configuration manual.

There are very detailed, step-by-step installation from source files alongside the setup guides for the most popular operating systems: Ubuntu 16 and 18, CentOS 7, and Debian 9. That is if you’d like to install and configure everything by yourself.

But you can also install Redis in two commands:

sudo apt-get update
sudo apt-get install redis-server

You’ll need to manually navigate to env.php located in /app/etc/ folder and edit it with any text editor. We used Notepad++ to show you how it’s done.

Initially, the default env.php version will state that it either saves to files (for a local Magento install) or a database (for a live website). Our goal is to save to Redis. In order to do that we will add the following lines to env.php:

Now let’s find out how to setup and configure Redis session cache. By default, in Magento 2.x Redis needs to be installed and enabled in env.php for session caching:

magento 2 redis

Add to the code (line 31 and onward as shown in the screenshot) to look like this:

You’ll notice the code is not complete. You’ll need to find Redis IP and port settings to make it work for your specific setup. Our input is can serve as an example.

4. Turn on Varnish Cache Tool

Varnish is a caching tool that works as an additional layer between the web server and the user. It will cache frequently requested files into RAM giving priority to those files that are requested more often than others. RAM is way faster than any SSD and it will return cached files in a fraction of a second. So instead of a long wait, the user will see the page almost instantly.

Varnish will bring in even more benefits when combined with a CDN upgrade. Alongside an improving caching mechanism, cached images get placed into your CDN for an added performance boost.

Varnish is more flexible than the built-in full-page cache that Magento uses by default. But this flexibility comes at a price. If you configure Magento 2 Varnish incorrectly it will actually slow you down. Varnish also introduces a new point of failure which can in some cases compromise stability. So basically Varnish is a trade-off between speed and reliability.

Before implementing Varnish, you’ll need to take a closer look at the page code. Take into consideration:

  • the amount of cacheable=false blocks
  • content with undefined TTL

This kind of content will obviously work poorly with Varnish since it will not be cached and will still load from your web server. Take these challenges into account when you are planning an upgrade.

Varnish is one of the major upgrades to your store. That’s why we recommend you use a separate Magento instance to check for system stability and avoid downtime.

All in all, to understand whether it’s a worthwhile upgrade, you need to know how much faster Varnish can be. On average, we are talking about 50-100% improvement in speed.

In Magento, the default setting is a full-page cache. Let’s go ahead and switch to Varnish.

First, make sure your hosting provider supports Varnish. After you do that, go to

Stores > Configuration > Advanced > System > Full Page Cache.

varnish cache magento 2

Tick off “Use system value” and turn on Varnish. You can leave Varnish configuration options as they are.

And with this fix done we are finished with the Developer mode. Use the command to return to Production:

php bin/magento deploy:mode:set production

5. Profile and Review All Third-Party Extensions

Using multiple extensions from different vendors can significantly degrade website performance. They can affect Magento speed through a variety of means:

  1. Custom extensions can overload the server due to some critical issues overlooked by developers.
  2. Installing a great number of extensions that actually provide similar features overloads the system and makes Magento site loading slow down. As a result, these extensions perform the same operations, request the same data, and process it many times. Needless to say that these repeated actions affect speed negatively.
  3. Installing third-party extensions with many features most of which are never used. The unused features create an unobvious load on the system performance.

When it comes to third-party extensions, the only way to avoid the problems with them is to constantly review your website with Magento Profiler in order to check for possible performance killers.

6. Remove Unnecessary Bloat

This one is easy. Make sure you know what all extensions do in your website. Are they all necessary? Magento takes a slight hit to performance every time you install something new.

Shed the dead weight. Take a look at your Modules folder. It’s the one located at /app/etc/modules. Do you recognize everything you see there? Turn off or completely remove unnecessary extensions from your store to make your Magento website faster.

For Magento 2, use SSH with the following commands to disable and then delete the extension you don’t need anymore. We are using TestExtension here to give you an example:

For developer mode:

bin/magento module:disable TestExtension --clear-static-content
bin/magento setup:upgrade
cd app/code/TestExtension/
rm -rf TestExtension

For production mode:

bin/magento maintenance:enable
bin/magento module:disable TestExtension --clear-static-content
bin/magento setup:upgrade
bin/magento setup:di:compile
bin/magento setup:static-content:deploy en_US de_DE
bin/magento maintenance:disable
cd app/code/TestExtension/
rm -rf TestExtension

Be careful when you delete separate extensions that have a common extension that serves as a foundation for them. If all of them are located in the same folder, rm -rf TestExtension will delete everything, not just the one you were thinking about. Please consult the extension user manual for a correct uninstallation process.

Take a look at this part: static-content:deploy en_US de_DE. Here we specify the languages that your Magento stores are using. By default, Magento will deploy for en_US, but you’ll need to add more languages manually if you have them in your website.

7. Remove Unused Scripts and Move the Rest to the Bottom

Have you completed all PageSpeed Insights but still think your website is not quite there yet? Try a more thorough code audit. Remove unused scripts from your store and push the rest to the bottom of the page to optimize Magento.

During the page load process, your browser reads the page as a few separate parts – the head and the body.

The browser will read the code from top to bottom sometimes waiting to download specific JS files before going any further down the page.

This is, of course, an oversimplification. Your browser will try to optimize this process as much as possible downloading files in parallel and whatnot. But we don’t need to make its life any harder than it has to be. In fact, we can help.

First, identify whether there is JS code on the page that doesn’t need to be there and get rid of it. JS code that will never be executed simply has no place on your page.

Now we need to move the code that is actually useful to the bottom of the <body>. This way the code will stop blocking static content from loading. As a result, your users will see an improvement in page render speed.

Instead of staring at a blank page store visitors can now read the text and see the pictures of your products even before the rest of the page is rendered.

8. Remove Unused Plugins and Event Observers

Magento 2 is moving away from observers and encourages developers to use plugins instead. But for now both tools are present in the system. And both of them can slow it down. We need to fix that.

In Magento, event observers are attached to certain events and can dispatch them when needed with the help of the Event Manager. Although today observers are pretty limited in what they can do and are mostly present in M2 as a legacy tool, some extension developers use events and their observers to extend basic Magento 2 functionality with custom code.

By default, Magento loads a lot of event observers that might or might not be used for a specific page. Regardless of their usefulness, they still take up system resources.

You can see all core observers and their corresponding tags in the events.xml file located at /dev/tests/functional/etc/.

Disabling useless event observers will speed up all Magento pages. The performance boost will be most noticeable on AJAX-heavy web pages.

To disable an observer, add


to its code. The best way to do this is by creating a separate events.xml file inside a third-party module. Disabling an event observer in the custom .xml file will override the main events.xml value without compromising core Magento file structure.

Overriding plugins works in a similar manner. You’ll need to audit your Magento install to see which plugins are necessary and which you can safely override or turn off.

Bear in mind that for extension use, the general rule of thumb here is it’s better to use preferences if you need to completely overhaul Magento core functionality, and using a plugin is the second best option. Event observers still have a place in Magento 2 development but they should be your last choice.

9. Stop Using Flat Catalogs

For many years, one of the best practices for boosting Magento performance was to switch to a flat catalog. The setting that’s available in both Magento 1.x.x and Magento 2.x.x versions is designed to gather the applicable Product Attributes within your database and merge them into a more light-weight table. Flat catalogs are considered to lead to fewer database queries per action by consolidating data and keeping it together. 

However, this tip DOESN’T WORK any more! Magento 2.3.0 recommended disabling this function. You can find this warning on the official Magento website:

Magento warning

According to Magento, if you don’t stop using a flat catalog, you will face slow running, performance degradation, and other problems. 

To disable the function, go to Stores > Settings > Configuration

Next, choose Catalog in the left panel and expand the Storefront section.

Now, set No in both the Use Flat Category and the Use Flat Catalog Product fields. 

how to disable a flat catalog in Magento

When you finish, press the Save Configs button.

10. Install ElasticSearch to Speed up Search Results

Using ElasticSearch in Magento 2 is faster and more reliable than the default option. It offers multi-language support, advanced search and indexing functionality, and even features outside of search. ElasticSearch is scalable and will work well without additional configuration.

The exact installation process will depend on what setup you use. We would like to emphasize a few points:

  • Install ElasticSearch on a separate host
  • Use clustering for best performance and scalability

Please note that you will need root privileges and some additional software to complete the install. Full guide for CentOS and Ubuntu is available here.

After you install ElasticSearch, turn it on in Magento 2 Admin Panel.

Go to

Stores > Settings > Configuration > Catalog > Catalog > Catalog Search.

Find Search Engine and switch to Elasticsearch for better Magento site speed optimization.

11. Use Lazy Loading for Images

Selective approach to page loading order offers a significant performance boost without a lot of investment.

Lazy loading is a pattern that can help you load images, gifs, and other heavy media as they enter viewport. This means that the browser will not try to load the whole page at once, instead it will prioritize loading visible content first.

As the user scrolls to the bottom of the page, new content gets loaded on the go. First LazyLoad shows a lower-resolution image or a placeholder image, then it will switch on the fly to the high-quality source image.

For the user, the implementation of lazy loading will mean:

  • Smoother perceived performance especially on low-end machines and tight bandwidths
  • Faster image load for media that the user can already see (inside their viewport)

For a Magento 2 store lazy loading means:

  • Better perceived page load speed which is important for user experience
  • SEO friendly implementation (search engines will crawl images as usual)
  • Bandwidth savings – since not all users will scroll to the bottom of the page

12. Use HTML <picture> Tag

HTML <picture> tag is most useful for responsive designs and pages with lots of images. With this tag, you can define multiple image sources within a single <picture>. The correct image selection will depend on the viewport and the min-width parameter of the image.

This is useful when you want to offer the browser the ability to choose the best fitting image for a certain dimension. The most common example would be desktop vs mobile browsing experience where the viewport value will fluctuate quite a bit.

It can be time-intensive to implement <picture> tags from the ground-up for the entire website since you will need to teach other extensions on your store how to work properly with the <picture> tag.

But the result will be a faster, more responsive website on all devices. We think you should at least look into it.

13. Optimize Your Magento Theme and Media

A heavy Magento theme will make load times longer even for users who have a decent Internet connection. Another side effect of an unoptimized theme – it uses a lot of bandwidth. And if you have a metered hosting data plan you are paying for that.

There are two ways you can deal with a bad theme. The most obvious is changing it to something lighter – especially if your theme is old and the developers discontinued its updates.

But let’s say you really like your theme and aren’t in a hurry to change it. Your next best option is to make it lighter yourself.

How? You can optimize image sizes.

Media is a huge part of every e-commerce website so dealing with these files first will show immediate gains. You’ll have to be thorough in your approach, though:

  1. Upload files that don’t exceed image requirements for a specific field. No need to use a 500×500 photo where a 200×200 will do. Even though Magento 2 will resize images automatically when you save a product, preparing your images is a good idea.
  2. Minify large images before upload. TinyJPG,, and other services are your best friends here. You can also download your existing images, tinify them and upload to the store.
  3. Cloudflare CDN will help you a lot.

A fast website is a small website. Check out how your store is doing in Magento image optimization. Can you beat our score?

magento 2 image optimization

14. Optimize CSS for Faster Load Times

Most content that your browser has to download is photos and graphics elements. We’ve already shown you how to deal with large media. Let’s move on to other files. There a few tricks you can implement right from your Magento Admin panel.

Switch to Developer mode to access these settings. Fire up SSH and type:
php bin/magento deploy:mode:set developer

Now go to Stores > Configuration > Advanced > Developer (this is a new tab you can now see), find CSS Settings.

Set both to Yes. This tool will try to shorten and in other ways optimize existing CSS code to help the browser download it a bit faster.

Merge is also quite useful: browsers will maintain only a limited number of connections per server. A few big files will download faster than a dozen of small ones.

merge css magento 2

15. Make Sure JS Settings Offer You the Best Performance

Magento will try to combine all JS files into a few big bundles to improve loading procedures. But JS bundling prevents page load until the browser finishes downloading all JS bundles.

JS bundles can be 10+ MB large. They are way bigger than CSS so merging JS is not the best idea because Magento loads them every time your browser requests a new page. Imagine how much of a show stopper it can be for your customers.

First impressions matter. And the first visit to your store from a brand new customer can be painfully slow if they have to download a 10+ MB JS bundle in addition to whatever media your page has.

JS Bundling fix works great in conjunction with a CDN upgrade. Smaller JS files will make individual pages lighter and your CDN will take care of delivering these smaller files to your customers faster.

With the development of HTTP/2 (in 2015) and HTTP/3 (in November 2018) JS bundling will no longer be relevant anyway.

Remember we are still in Developer mode? Good. Let’s make sure your Magento JS settings are optimal.

Go to Stores > Configuration > Advanced > Developer > JS Settings.

js optimization magento 2

Set your JavaScript as shown in the image above. JS Merge and Bundling should be Off. JS minification should be set to On.

16. Enable HTML Minification

Minified HTML, CSS, and JS files will load faster and take up less space on the server. Minification will boost your load speeds even more. It will cut out developer comments, replace variable names with shorter versions, and generally tidy up your code and reduce clutter.

Minify HTML is only visible as an option in Developer mode.

Find Stores > Configuration > Advanced > Developer > Template Settings.

Tick off “Use system value” to access the Minify HTML option.

Set it to Yes.

minify html magento 2

17. Use Magento Gzip Compression

Gzip is the foundation of a performance-oriented store. It offers an interesting compromise between bandwidth reduction and Time to First Byte.

Gzip will compress every page that you request from the server. So, for example, a 64 KB file will be sent to your browser as a 10 KB gzip archive. Notice that compression takes up CPU time which means your web server will have to make a compromise between data savings and fetch time.

Gzip is an extremely commonplace module so most environments will support it from the get-go. All you need to do is make sure it’s running on your website. The easiest way to do that is to ask your hosting provider to turn it on for your Magento website.

18. Fix .htaccess Caching Options

The .htaccess file stores critical server instructions and we will need to change some of those to get the best performance out of Magento.

A clean Magento 2.2.x install on Apache will have an .htaccess file that looks something like this:

magetno 2 htaccess optimization

Mod_expires that you see in the screenshot determines how often your cache will be automatically discarded. But the problem is the defaults have only the bare minimum of what you would like to see here.

Let’s fix that.

Change the section between <IfModule mod_expires.c> and </IfModule> with the following data:

ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"

New rules will detail media expiration dates as well as CSS and JavaScript. Note that ExpiresDefault has been changed from “access plus 1 year” to “access plus 2 days”. This sets the expiration date to all document types we haven’t specifically mentioned above.

These values will make sense for most Magento stores but you will know your customers better than us. Feel free to experiment with different values for images, code, PDFs, and default content and find out what works for your update cycle best.

Here are a few tips to get you started.

Access times can be in seconds, minutes, hours, days, weeks, months, and years. You can also combine them together, for example:

ExpiresDefault "access plus 3 weeks 2 days"

Please bear in mind this .htaccess will be useful for Apache servers. We’ll post an optimized Nginx config as a separate guide.

19. Expires Headers or Cache-Control Headers

Downloading static resources all over again every time a user visits a page is monkey business. Due to the necessity to resend requests, speed may suffer. Besides, users have to waste a large amount of traffic. That is why reducing HTTP requests should be among your prime concerns when you are seeking ways to increase Magento site speed.

By using Cache-Control Headers, as well as Expire Headers, it is possible to condense the number of HTTP requests and its size to make the page load much faster.

Cache-control is an HTTP header that is used to specify browser caching policies in both server responses and user requests. Policies define how and where a website is cached, as well as specifies its maximum age before expiring. After expiring, a browser refreshes its version by sending another request to a server. It is a common practice for caching static resources.

For instance, cache-control: max-age=200 means that the browser has to request a new version of the returned resource after 200 seconds.

Static Magento components, like images, Javascript, and CSS files, should have far-future expiry headers (no less than 1 year). There will be no problem with clearing the browser cache so it can download the new version because Magento automatically changes the paths for static components with every deployment. This forces the browser to load the new version of the files.

By default, this feature is enabled. To find the configuration for this feature, go to Stores > Settings > Configuration > Advanced > Developer > Static Files Settings.

Static Files Settings

In order to learn more about Magento frontend optimization, you can read our Magento Optimization for Google page Speed Guide.

20. Use HTTP/2 Instead of HTTP/1.x

HTTP/2 is a relatively new protocol based on Google’s SPDY. It has implemented a few key optimizations to data transfer that makes HTTP/2 significantly faster.

For Magento we are most interested in its ability to compress headers, use multiple server requests at the same time, and work in parallel on a single connection.

We have included this tip more as due diligence than a practical advice since 99% of all web hosting Magento servers (Apache 2.4.17+, Nginx 1.9.5+, more here) will support HTTP/2 by default. The same goes for CDN providers (Cloudflare, MaxCDN, KeyCDN, etc.). But it never hurts to ask your hosting provider whether HTTP/2 is enabled in their server settings.

If you don’t feel like asking, use this Chrome extension to find out. It also supports QUIC, which is the next-gen protocol, HTTP/3.

21. Get a CDN to Speed up Content Delivery

CDN or Content Distribution Network helps you speed up content delivery by caching your files on remote servers and serving each user from the server that is nearest to them. CDN is a great way to increase website speed when you have a very diverse target audience. Literally customers from all over the world.

CDN will make sure all of them can access your store at the same high speed no matter where you are hosting your Magento store.

CDN is a nice alternative to physically moving your server. Just bear in mind that you’ll see the most benefits from a CDN if your Magento store is installed on-premise and not in the cloud.

For new users we recommend Cloudflare. It’s user-friendly and easy to install:

cloudflare account magento 2

  1. Register a new Cloudflare account
  2. Add your website when prompted.

a) You’ll have to know you registrar’s login+password since a part of the configuration process is done outside of Cloudflare, at your registrar’s admin panel. Login to your registrar’s account

b) Navigate to the nameserver configuration tab

c) Write down current name servers then change them to the ones Cloudflare has provided you with

d) Save changes

3. Check your domain using a Whois service to make sure Cloudflare nameservers are up and running. It might take a while until they update. Up to 72 hours in some cases.

You can download the extension here and see the speed difference for yourself.

Alternatively, if your customers base is not very diverse, rent your server in the same country most of your customers come from. The closer your servers are to the users, the faster your website will load for them.

Google takes your actual server location into account, too. Physical servers located near the user will rank higher in their personalized search results.

Latency depends a lot on distance and routing. As a cool example, this site helps you see how different Amazon Web Services locations range in latency.

cloudflare latency magento 2

22. Upgrade Infrastructure to Improve Server Response

Ever wondered whether your hosting is slowing you down? It does. If you use a cheap shared web hosting service you should know: your website can work faster. Magento consumes a lot of resources. Get better bandwidth and hardware to serve your customers and improve Magento server response time.

There is no way around it. Sometimes the only way to Magento server optimization is to pay more.

When you are looking for a hardware upgrade, emphasize CPU, RAM, and SSD availability. The more RAM and CPU you get, the better. We recommend 4 GB of RAM as the bare minimum and will work for sites with up to several hundreds of visitors and couple of dozens of orders per day.

On the software side, look for HTTP/2 (and soon HTTP/3) support, nginx 1.x, Apache 2.2+, MySQL 5.7, PHP 7.1.x+, PHP OPcache, Varnish, Redis or Memcached (Redis is preferred), PHPUnit.

To make your Magento future-proof, look up the freshly released Magento 2.3 system requirements and ensure your hosting provider complies with them as well.

In the meantime, keep an eye on your CPU and RAM use. The rule of thumb here is to be below 80% use rate. This 20% window will give you enough leeway to deal with the occasional spikes and at the same time will not strain your budget too much.

23. Replace Apache with Nginx 

After we went through a variety of hostings, it is high time to focus on the other important point – choosing the right web server that meets the Magento 2 system requirements. The fact is that sometimes the performance problem occurs on the webserver side. When there are too many requests, the webserver needs more time to process them. This may be the reason for significant downtime.

In order to make your Magento website load faster, you need to hunt up a web server that will be able to process the request faster and efficiently deliver both PHP and static content.

As we know from the above, Magento best runs on Nginx 1.x and Apache 2.2+.  So, which one is the best for Magento performance optimization?

We’ll start by saying that Magento itself recommends using Nginx rather than Apache as the first one contains settings for increasing website performance.

Magento software recommendations

Moreover, lots of web hosts suggest Nginx as an optimal solution to serve both static and dynamic content while handling an enormous number of requests. With this approach, it uses fewer resources to cope with more significant loads and responds with blazing speed.

24. Optimize JavaScript

As one such example, jquery.ready will load all its JavaScript functions as soon as the page DOM becomes safe to manipulate.

This means that instead of serving the user with meaningful content, the browser will wait for JS code to load, taking up valuable time and spoiling user experience. This is especially aggravating for CPU-heavy functions that can completely disrupt a smooth page loading process.

The solution here is to avoid CPU intensive non-critical JS code to run in .ready(). Instead of crowding all functions into this handler, use a more flexible approach.

As a valid middle ground where you have to balance both JS code load and content delivery times, we recommend using $(window).ready() and $(window).load().

Another way to optimize render speeds is by using intervals and timeouts. For example, a heavy JavaScript code can be divided into smaller bits with mini-intervals.

For added flexibility, you can measure how long it takes the browser to execute a CPU-heavy code and add or reduce the amount of work for the next batch.

For example, the first batch is always 100 lines but depending on the browser performance next time you can instruct to execute for this user a workload of either 50 or 200 lines.

For our purposes, setInterval(func, delay) and setTimeout(func, delay) are the main methods that can break down longer JS into smaller parts. And if you would also like your code to change the delay in a more flexible way, use recursive setTimeout instead of setInterval.

25. Review Page Performance With Magento Profiler

Magento Profiler is a built-in tool you can use to inspect DB calls upon page loads, study dependencies, collect event logs, etc.

To enable the Profiler, go to .htaccess and de-comment or add the following line:

SetEnv MAGE_PROFILER csvfile

This command turns Magento Profiler on and instructs Magento to log events into the profiler.csv file that you can find at /var/log/ folder.

If you want to read Profiler feedback on the same screen, use instead:


Now the bottom of your page will show a neat collection of operations and results in one table. Here you can see timers cache_frontend_create, cache_load, store_resolve, etc.

Magento Profiler is a great tool to find bottlenecks, slow-downs, and other hidden performance issues. If you are already familiar with Magento Profiler but want to do more with it, we recommend MGT Developer Toolbar. It’s free and adds to the mix better data representation, improvements in plugin and events/observers inspection, and other goodies. If you have never worked with Magento Profiler – get in touch with our developers and we will inspect your store with this powerful tool.

26. Use a Progressive Web App to Make Your Magento Website Faster

You must have heard about PWAs. The eCommerce world is buzzing with the technology currently.

Progressive Web Applications are designed to blur the gap between responsive websites and mobile apps keeping the best of each channel. With PWAs, Magento store owners can deliver an app-like experience to the customers while they are on the website. You can find many PWA examples in eCommerce here and read on how to make a Magento PWA here.

But how can a PWA improve Magento websites load speed?

PWAs relieve pages from the necessity to reload. Thus, when a user visits the website for the first time, JS and CSS files are rendered on PWA Storefront developed with React.js, while all the updates are executed on Magento backend. So, when the user goes to the other website page, it loads much faster as all JS and CSS files are already loaded. For instance, the browser doesn’t need to load the page header or footer whenever the user goes to another page as they are already loaded on the PWA Storefront. As a result, the site performs much faster.

27. Clean Database Logs

If your store is old enough, database logs can grow to hundreds of MBs with millions of data entries. This clutter will slow down Magento and can even create a space shortage if your disk is already full to the brim.

Magento 1 had a neat option to automatically clean up all entries older than, say, 1 month. No such luck for M2. The feature request is already 2 years old but we still haven’t heard anything about the feature from the developer team.

Magento 2 doesn’t have even a basic cron job task for that. This means we’ll have to get creative.

To start the cleanup you’ll need to have access to the PHPMyAdmin Panel in your hosting tools.

On second thought, you could just go to GitHub and download a nice module that does this for you. Automatically. Once a week. Via cron. Because this is how it should be.

Let’s go through the installation steps together:

  1. Download the module and put it in /app/code/ folder of your Magento install
  2. Execute via SSH the following command stack:

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy
php bin/magento cache:flush
php bin/magento cache:clean

3. Install the module with the command php bin/magento module:status

4. Run your commands via cron: php bin/magento cron:run

A new entry db_log_cleaning will appear in the table cron_schedule

Boost Your Magento Storefront Further

Magento is a complex solution that can work faster or slower depending on how well you optimize it.

We wanted to give you advice that is applicable for almost any Magento 2 setup. But Magento stores are so diverse. Magento runs on countless different configurations powering up stores all over the world.

If you want to speed up your store even further, let us know. We’ll look into your particular setup and make sure it runs flawlessly.

Related Articles

Magento tips from real projects
Magento tips from real projects
CALL US 24/7:
& asia
+61 (02) 8005-7494