Complete guide to Magento 2 performance optimization. Steps, codes, tips.

Complete guide to Magento 2 performance optimization. Steps, codes, tips.

Boosting website speed is always good practice. Have you ever thought how critical a site speed improves performance? How one single factor can make a big difference in your site's user experience.  

Performance matters. It's hardly a secret that high-performing sites result in a better conversion rate. Sure you wish your store to provide the best ever website speed to your clients' advantages. Everyone wants to get a perfect 100% score on Google PageSpeed.

For this reason, we offer many opportunities for Magento 2 performance improvement. Read the guide to website performance optimization. Here you can see many techniques that could affect your site.

What does page speed rank take into account?

You do need to understand the purpose of website performance optimization. Speed or Score?

In fact, the most important metric for your site performance is the page load time. It is a full-page load time that takes to render the content on a page. It is also the time to first byte (TTFB) what means time spent waiting for the initial response from the webserver.

Quick page loading for your visitors is when speed is measured in seconds. Yes, Google estimates the entire website speed as a ranking factor. Even so, you still have to focus on those first seconds.

TTFB is directly related to that. Thus we recommend you consider it like the very first of many tasks you are gonna do to get a high page speed score in the end.

Some other performance enhancements will be significant after optimizing those first bytes. So you need to take TTFB as a part of your Magento 2 website optimization task.

We can then ask,

What would be the next step for speeding up TTFB? How to ensure a faster server response time?

Choosing fast hosting

In fact, the reduced server response time correlates with enhanced hosting speed.

The good news is the web host is a thing you can control over. You are able to choose the right hosting server with the best-expected speed and proper solutions that help reduce TTFB.

Well, Google says your server response time should be under 200ms. Let’s see what hosts offer the fastest TTFB. We will also check what else must-have services the web hosting company should offer you.

We recommend using the Magento Commerce Cloud hosting platform. It offers a well-organized infrastructure with a bunch of built-in high availability features.

See why we choose it:

  • built-in Varnish caching for enhanced performance
  • accommodated workflow
  • includes all required PHP extensions, and, of course, is PHP 7 ready
  • correct domain configuration or domain settings
  • optimized PHP accelerator to help fasten the hosting plan
  • fast CDN to help users get a lightning-fast site
  • fully managed services like MySQL, Elasticsearch, Redis, RabbitMQ, without requiring external plugins

With an automated hosting platform, you also get a great feature - New Relic APM (Performance Monitoring). It allows monitoring your sites' performance.

Due to this hosting solution, you can also be certain your website is always updated on time. With all possible changes made by Magento.

Well,

Besides, whatever host you want to select, try to avoid using shared hosting. It doesn't support the memory limits required by Magento. Yet, if the server sizes meet the needs of your store, for instance, it is enough for many daily visitors, go on to use it.

We also suggest considering the host with a data center closest to the majority of your clients. Focus on your country-based Magento web hosting provider. It will definitely make your store faster for your local visitors.

Let us briefly summarize the main requirements for hosting solutions. You’d better focus on host:

  • with servers that are PHP 7 ready
  • that includes an optimized stack with Linux-based OS, Nginx, PHP-FPM
  • that works best with built-in Magento cache as Varnish or other caching solutions such as Redis, or ElasticCache
  • that include features such as SSL certificate, SSD-based storage, CDN
  • that provides PHP acceleration
  • with the available option to enable GZIP compression
  • that supports HTTP/2

One more important thing is a web server that the hosting company uses. Most of the best hosts use Apache and NGINX servers. They are both engineered for optimal performance. But, but they still differ in speed, scalability, technical knowledge rule, and configuration.

Later we’re gonna talk about the page speed optimization solutions. Separately for Apache and Nginx. Keep reading.

Optimizing web server

After we moved step-by-step through a variety of hosting, let's focus on the other priority. These are the web servers that follow the Magento 2 system requirements. Magento best runs on Apache 2.2-2.4 and Nginx 1.8 (and later).

Which server is best? Let’s take it up briefly.

Magento itself suggests using the Nginx web server. They choose it because it contains settings for better performance. Hundreds of other web hosts are also offering Nginx - to serve both dynamic and static website content while handling a huge number of requests. Look at some fundamental characteristics:

  • Nginx serves static content about 2.5 times faster than Apache even dealing with the immense amounts of traffic.
  • NGINX got support for dynamic module loading.
  • NGINX supports FastCGI and SCGI handlers for serving dynamic content scripts such as PHP.

And, at the same time, lots of our clients still prefer Apache over Nginx. Customers like this web server for a big number of features such as:

  • A vast number of modules available to extend it.
  • Compatibility with far more third-party technologies.
  • Built-in PHP support.
  • Better supports loading various dynamic modules.

Magento 2 supports both Nginx and Apache web servers. So it’s up to you to select the right one for your eCommerce site. The only recommendation for you is to pay attention if the web hosting service helps you with a server configuration and setup.

3 must-haves for optimizing on server-side

Enabling browser caching

By enabling browser caching of static files or files you actually don’t change often, you speed up the secondary loads to these pages. It may increase the load time, so many users disable the option. But we recommend leveraging browser caching as a must for SEO purposes. You have to add Expires Headers to reduce the time the server requires to connect with the browser.

See the ways of adding Expires Headers for Nginx and Apache servers separately. You have to paste the next code on your site configuration file.

Nginx


#browser caching of static assets
location ~*  \.(jpg|jpeg|png|webp|gif|ico)$ {
  expires 31d;
}

#browser caching of css
location ~*  \.(css)$ {
  expires 6d;
}

#browser caching of js
location ~*  \.(js)$ {
  expires 31d;
}

Apache

Header set Connection keep-alive



    # Expires Headers - 2678400s = 31 days
    
      ExpiresActive On
      ExpiresDefault "access plus 1 seconds"
      ExpiresByType text/html "access plus 7200 seconds"
      ExpiresByType image/gif "access plus 2678400 seconds"
      ExpiresByType image/jpeg "access plus 2678400 seconds"
      ExpiresByType image/png "access plus 2678400 seconds"
      ExpiresByType text/css "access plus 518400 seconds"
      ExpiresByType text/javascript "access plus 2678400 seconds"
      ExpiresByType application/x-javascript "access plus 2678400 seconds"
    

    # Cache Headers
    
      # Cache specified files for 31 days
      
      Header set Cache-Control "max-age=2678400, public"
      
      # Cache HTML files for a couple hours
      
      Header set Cache-Control "max-age=7200, private, must-revalidate"
      
      # Cache PDFs for a day
      
      Header set Cache-Control "max-age=86400, public"
      
      # Cache Javascripts for 31 days
      
      Header set Cache-Control "max-age=2678400, private"
      

Gzip compression

This solution is a must-have for speeding up your site. It reduces the size of the files, and the server will need less time to process them. Gzip compression results in a significant reduction in the weight and speed of page loading.

To enable Gzip, please paste the following code to site configuration file.  

Nginx



gzip on;
gzip_disable "msie6";

gzip_comp_level 6;
gzip_min_length 1100;
gzip_buffers 16 8k;
gzip_proxied any;

gzip_types
  text/plain
  text/css
  text/js
  text/x-js
  text/xml
  text/html
  text/javascript
  image/svg
  image/svg+xml
  image/eps
  application/javascript
  application/x-javascript
  application/json
  application/xml
  application/rss+xml
  application/xml+rss;

gzip_vary on;

Apache


    
        ## enable resulting html compression
       php_flag zlib.output_compression on
    
        SetOutputFilter DEFLATE
        AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml application/x-javascript application/x-httpd-php
        BrowserMatch ^Mozilla/4 gzip-only-text/html
        BrowserMatch ^Mozilla/4\.0[678] no-gzip
        BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
        BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
        SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip
    

Implementing HTTP/2

The latest current versions of Apache and Nginx servers have added HTTP/2 support. You can also check the HTTP/2 browser support and availability by using an online tool.

Optimizing the PHP performance

The next point of significance for speeding up the Magento 2 site is PHP performance optimization.

The PHP code execution takes about 70% of the TTFB time. It is crucial to get it efficient.

Thus you have to use the fastest PHP interpreter and configure it well.

The next step is optimizing PHP code. To make it execute faster, and perform fewer input and output operations. Look at some tips on how to make PHP run efficiently:

First of all you have to set PHP options required by Magento 2:

  • Set the PHP memory limit.
  • Set the system time zone for PHP.
  • Activate the latest PHP version, that is required for Magento 2.3 and later.

Use the PHP accelerators for code optimization. It helps you to reduce server load and increase the speed of your PHP code. Magento 2 recommends activating the OpCache module to get the greatest speed. The core of the PHP accelerator is to improve the performance of PHP scripts by caching them. Please mention, in case you use Nginx, you must install PHP FPM because Nginx doesn’t include native PHP processing.

Disable the unwanted PHP modules. Magento 2 also recommends limiting the list of active PHP extensions. You have to select ones that are highly required for Magento functionality. By reducing the number of extensions you reduce the memory utilized and improve performance. You have also to keep track of what PHP modules conflict. For instance, some users don't disable xdebug on a production server. And hence, it skews the overall performance numbers.

See more about PHP performance optimization.

Then our conclusion is:

"Stores that run the latest supported version of PHP, result in a much faster website and run more efficiently".

For optimal performance, we recommend running Magento 2 with PHP 7.2 and later.

Tuning MySQL

As we know MySQL can run more than tens of thousands of simple queries per second. It makes it the most popular system for storing data.

As data volumes grow, your MySQL database might run slowly, and queries take longer to execute. Our common purpose is to increase Magento 2 site speed. So we suggest configuring MySQL settings correctly. It is gonna improve the overall speed of your database server.

Magento versions 2.1.2 and later are compatible with MySQL 5.7.x. Follow general Magento 2 recommendations on how to tune MySQL in order to optimize MySQL queries for faster database performance.

Optimizing Magento 2 speed settings

Time to optimize your website speed on Magento 2 side. The superbness of Magento 2 is a good list of possible optimizations obtained by default. We are gonna list them by way of explaining each one in short.

Caching

There is no reason to explain why the website caching is important. Faster server response time, better user experience, higher SEO ratings. The only question remaining is the caching solutions.

Well, the Magento 2 package comes with the built-in PageCache module as well as integrated Varnish Cache. The first solution is only for development purposes. The Varnish application is recommended to reduce the response time. We may see it as a much faster and flexible option. Furthermore, Magento 2 settings include Advanced Varnish configuration. If you are still hesitating which cache works better - Varnish or Built-in, have a look at some speed test results here.

Redis is also supported to cache data for production mode. We suppose it to be easier to use. The choice is yours.

Warming up the cache

We are talking about speedy browsing experience for every user, right? Then you also should provide the fastest page view for a first-time visitor. This is why we suggest you warm up the cache. You can add a full page warmer/crawler extension. It will cache all possible newly saved pages automatically.

Enabling merge CSS, JavaScript

The next possible Magento 2 speed optimization is minifying HTML, JS, and CSS files. It makes sense because a minified code is parsed, compiled, and loaded faster. It is also a way to improve the Google PageSpeed score.

By default, you can enable CSS/JS Minification in the Magento configuration. Sometimes big CSS files still take a long time to load. And a built-in Magento 2 CSS optimization strategy is not enough. To increase Magento 2 speed, you need to focus on setting critical CSS or in other words prioritizing visible content. That way you' ll reduce the size of the above-the-fold content within the HTML structure, and make it loaded first. Some  Magento 2 speed modules include the advanced CSS settings which allow you to set the generated critical CSS.

Have a look at some other tips on how to improve Magento 2 performance within its default functionality:

  • Check if you disabled a developer mode while already running store in production mode. It really matters for making your website faster.
  • Inspect every 3rd-party extension installed. Some of them lead to excessive load times. You can use web speed test tools to define which take the most time to execute.

Additional optimization with Magento 2 Page speed tool

Several times over the article we mentioned one solution. It is very powerful in features that expand the Magento 2 performance. We developed Magento 2 Page Speed extension to increase your web page speed. It comes with a bunch of practices proven to get your site at the top of Google search rating.

Have a look at numerous things that show why using the module is a must.

Advanced CSS settings

Merge / Minify CSS

Previously we talked about TTFB - faster starting load time. So, merging CSS files is an idea when it comes to the faster finishing load time.

M2 Page Speed module allows you to merge CSS styles, and not only minify them. This reduces code that should be loaded, thus the entire web page will be loaded faster.

Optimize CSS delivery

The module settings allow adding the inline CSS. This is necessary for faster display the above fold area of your page.

Enable critical CSS

The module allows for generating critical CSS. It will render above-the-fold content by including it in the HTML response. That way the page will load only the smallest amount of CSS required to render the top visible part of the page. Good idea to speed up your website.

Advanced JS settings

M2 Page Speed extension comes with lots of good practices to make JavaScript run faster. With the module you will be able to:

  • merge / minify JS files
  • deferred running all JS code on the page
  • enable using custom JS code unpacking
  • generate optimized JS bundle
  • use the advanced JavaScript bundling method

We'd like to focus on the last-mentioned option. Despite the many developers suggest disabling js. bundling, we still recommend using it for getting the faster server response time. We also offer to use the innovative bundling algorithm for better Magento 2 performance.

Innovative JS bundling method

M2 Page Speed extension enables the advanced js bundling. This allows you to build the separate bundles for each page of your site. The new algorithm combines the default Magento bundling and r.js optimizer methods and adds the default bundle.

As a result, you would add only the necessary JS files for a certain page. It can be a separate bundle-product.js for each page of your Magento 2 store. For instance, you can put all checkout-related stuff into one bundle and load it only on the checkout page. See more.

With the Page Speed module JS bundling method, we promise an increased Page Speed score.

 

Advanced image optimization settings

By speeding up image delivery you can also improve your page loading time.

To prevent images slow down your website, we recommend implementing some optimization techniques.

Lazy-loading for images

The feature helps browser load only pages which are in the browser's viewport. The module includes custom lazy loader configuration options. Such as auto specify image dimensions, offset, placeholder field, and offset for mobile devices.

WebP images support

WebP is Google's alternative image format that compresses your images to a smaller size than a JPG file. Smaller image files make your website load faster in times. The Page Speed extension supports WebP image detecting and generating in your Magento 2 site.

Summarizing the benefits of the Page Speed module, we’d like to mention one more option.

HTTP/2 push server preload feature

When a server HTTP/2 push enabled, the browser starts rendering the page much faster as it gets the js files, scripts, and fonts loaded via HTTP 2 protocol. It looks like you send content in advance that the visitor needs for the requested page.

The point is the Page Speed module contains so many techniques to help you significantly improve your Magento 2 site performance. Visit the module page or follow the user guide to learn more.

Conclusion

Getting your store close to 100/100 on Google Pagespeed tests is not an easy task. However, we’ ve got the best results possible for our SwissUpLabs website. We use different speed optimization practices and know how they work. And we are glad to share with you our positive experience.

We hope the guide adds value to your search queries on how to increase Magento 2 speed. In case you used to implement other techniques, please tell us about them in the comments. We love learning, too.

You can also review some more guides that will help you to improve your Magento website:

Popular Magento Themes & Extensions

Leave a Reply