Loading..
Processing... Please wait...

Product was successfully added to your shopping cart.



Speed Up Magento 2 - The Ultimate Guide (35 Working Tips)

Speed Up Magento 2 with 35 tips

Do you want to speed up Magento?

Of course you do! And you are not alone. Magento, one of the most popular eCommerce platforms, might be slow. Its poor performance might come from an excessive use of various customizations.

Here are the 35 field-proven steps that will help you optimize Magento 2 performance:

35 Magento Speed Optimization Techniques:

  1. Optimize TTFB
  2. Cut Latency
  3. Magento Server Configuration
  4. Choose Fast Hosting
  5. Optimize VPS for Magento
  6. Audit Magento code
  7. Optimize Start Render Time
  8. GZIP Compression
  9. Use a Cache Warmer Script
  10. Use The Power of HTTP/2
  11. Leverage Browser Caching
  12. Focus on Above-the-Fold Content
  13. Remove Render-Blocking CSS and Javascript
  14. Reduce the Size of Visible Content
  15. Put Above-the-Fold Content First
  16. Optimize Document Complete Time
  17. Magento Image Optimization
  18. Sign up for CDN
  19. Optimize Fully Loaded Time
  20. Don't Abuse jquery.ready
  21. The Less Third-Party JS the Better
  22. Never Use JS bundling
  23. Run Store in Production Mode
  24. Use a PHP Profiler
  25. Enable ElasticSearch Query Cache
  26. Prevent Full Page Cache Automatic Clearing
  27. Turn PHP OpCache On
  28. Move JavaScript to the Page Bottom
  29. Use WebP and AVIF Image Formats
  30. Save Sessions in Redis
  31. Upgrade to PHP 8
  32. Make Varnish Your Caching Application
  33. MySQL Tuning
  34. Perform 3rd-party Extensions Audit
  35. Inline Critical CSS

Let us first define what we will use to measure site speed.

How to Measure Magento Speed

When a browser loads a web page it does certain actions:

  • It receives html data from a server.
  • It analyzes data and loads external files you might have on the page (CSS/JS/images/fonts etc).
  • It builds what is called a DOM (Document Object Map).
  • It renders the page (puts elements on the screen).

We can define 3 time periods that measure how quickly a webpage loads:

  • Time to first byte (TTFB) or server response time: the time from when a user clicked on a link or typed in a site URL until the first bit of information from the server arrived.
  • Start render time: the first point in time that something was displayed to the screen. Before this, a user was looking at a blank page.
  • DOM complete or document complete time: the point in time when the browser considered the page loaded (onLoad javascript event fired). All the content has been loaded except content that is triggered by javascript execution.
  • Fully loaded time: a webpage is loaded and no network activity is performed by a web browser.

TTFB < Start render < DOM complete < Fully loaded

The waterfall chart The Waterfall Chart

The most important time in my opinion is the start render time. The quicker you show a user that something is happening after he requests a webpage, the faster the site will appear to the user.. There are 3 main time limits that describe user perception of how quick a web application is [study]:

  • 0.1 second response time – a user feels that a system is reacting instantaneously.
  • 1.0 second response time – a user notices the delay, but it doesn't bother him.
  • 10 second response time – the limit for keeping the user's attention focused. For longer delays, a user will want to perform other tasks while waiting for the computer to finish.

We want to keep start render time around 1 second to make a user feel a website is fast. Alright, enough theory. Here are the 35 tips to fix slow Magento websites:

1. Optimize Time to First Byte

Server response time, or time to first byte (TTFB), consists of the time a browser's request goes to the server and the server response goes back to a browser (latency) and the time a server generates HTML.

Google recommends having TTFB around 200ms. 1s TTFB is considered bad.

To reduce server response time Magento codebase needs to be inspected. Here are my in-depth tutorials on how to optimize TTFB for Magento 1 and Magento 2.

2. Cut Latency

Host your website as close to your main audience as possible.

If you sell shoes in London, do not sign up for hosting in Japan. Common sense.

Do not think that SSL will impact your TTFB much. SSL negotiation time is negligible but the SEO benefit is obvious.

3. Magento Server Configuration

Optimizing server configuration includes choosing the right hosting and setting up server software. Magento 1 and Magento 2 performance optimization starts with following the hardware requirements:

  • Do not pick a cheap option here. It is the basis of your online store.
  • Secure as many resources as you can afford and a bit more.

You might want to get more CPU and RAM if you come to Magento 2 from Magento 1. 2.x needs more of it.

4. Choose Fast Hosting

A Magento site can't run on $5/mo shared hosting. If you want good TTFB and start render times, sign up for VPS or Magento-optimized hosting. Personally, I'd recommend Lexiconn, check them out.

5. Optimizing VPS for Magento

If you plan on running VPS or a dedicated server, you need to optimize server software and a database.

Options for your server setup are endless and depend on your expertise. You can configure NGINX, Apache, Varnish, HHVM, php-fpm, Redis, memcache.

Here are possible solutions for magento performance tuning:

  1. Varnish + NGINX + PHP-FPM + Redis
  2. Varnish + NGINX + HHVM + Redis
  3. Use PHP 8 with Magento 2
  4. Host webserver and database on different servers
  5. Use MySQL master-slave replication for separate reads and writes

5.1 Server Performance Hogs

Here are common server misconfigurations that slow Magento sites:

  • Disabled MySQL query cache. Modern MySQL servers come with query cache disabled by default. Enable it. By the way, it is one of the first things to check on my magento performance optimization checklist.
  • Slow disk I/O. Make sure your host provides you with SSD (solid state disk) storage.
  • RAM shortage. When the system runs out of RAM, it puts data on disk (swap), making things slow.

6. Audit Magento Code

PHP code and template files are the main reason for poor server response time.

To help optimize Magento websites, you need to profile the code and identify parts that slow the site down. Magento comes with a built-in profiler. You can also use the third-party extension Aoe Profiler or sign up for the NewRelic application performance management tool.

6.1 Magento Code Performance Hogs

  • Observers that run on every page request
  • Poorly written template files
  • A slow MySQL query(s) somewhere

Here is a detailed tutorial on how to optimize TTFB with Magento profiler.

6.2 Poorly-written Magento Code

Here’s an example of bad Magento code that I encounter often:

Loading Magento models inside a loop. That happens in product list templates; people iterate over product collection and load the product model every time:

foreach($collection as $product){
  $product = $obj->create('Magento\Catalog\Model\Product')
->($product->getId());

Don't do that. It’s better to construct your collection to have all the data you need. Magento model loads are expensive.

7. Optimize Start Render Time

Start render time (SRT) is the first time when a user sees the content after requesting the webpage.

It could be a background image or some text blocks, but from that time on the user knows something is happening.

In my opinion, start render time is one of the main factors by which a user judges how fast the site is.

According to the 3 main time limits [study] I mentioned earlier, we need to keep the start render time to around 1 second.

SRT consists of:

  • Time to first byte (TTFB)
  • Time it takes to download a page HTML
  • <head> section parsing and downloading resources (JS/CSS external files) a browser finds there
  • Initial layout calculation

After we understand what start render time is, we have options to optimize it. This will help us speed up Magento and have a better website.

8. GZIP Compression to Shrink Page Size

Compress your html page so that a browser has fewer kilobytes to download.

Enable gzip compression on the server side – see instructions for your web server. Confirm you have gzip enabled.

8.1 NGINX GZIP Compression

NGINX example configuration to enable gzip:

http {
        gzip on; 
        gzip_disable "msie6";

        gzip_vary on; 
        gzip_proxied any;
        gzip_comp_level 6;
        gzip_buffers 16 8k; 
        gzip_http_version 1.1;
        gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript;

You need to restart NGINX for the changes to take effect.

8.2 Apache GZIP Compression

When running Apache you can enable gzip by changing .htaccess file inside your Magento root folder:

<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4.0[678] no-gzip
  BrowserMatch bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent
</IfModule>

9. Use a Cache Warmer Script

Magento relies on Full Page Cache (FPC) to be extra fast.

FPC stores page content in cache on first request. That one request might be slow.

The cache warmer script does all those first requests. All the next page visits will be fast.

Here is a simple PHP script I use. It iterates over all categories.

You can also download top 1000 popular pages from Google Analytics. Make the script iterate over it to cut time to the first byte.

warm.php:

ini_set('memory_limit','12000M');
use Magento\Framework\App\Bootstrap;
require __DIR__.'/app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP,$params);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$categories = $obj->create('Magento\Catalog\Model\ResourceModel\Category\Collection');
$categories->addIsActiveFilter()
           ->joinUrlRewrite();

foreach($categories as $cat){
   $st = microtime(true);
   $dd = file_get_contents_ssl($cat->getUrl());
   $fn = microtime(true);
   if(($fn - $st) > 0.9)
    echo $cat->getUrl()." : time: ".($fn - $st)."\n";
   sleep(8);
}

$open = fopen("Pages.csv","r");
while(($data = fgetcsv($open,4000,",")) !== FALSE){
    if(filter_var($data[0],FILTER_VALIDATE_URL) !== FALSE && strpos($data[0],".pdf") === FALSE && strpos($data[0],"/blog/") === FALSE){
      $st = microtime(true);
      $dd = file_get_contents_ssl($data[0]);
      $fn = microtime(true);
      if(($fn - $st) > 0.9)
       echo $data[0]." : time: ".($fn - $st)."\n";
      sleep(8); 
    }
}
fclose($open);

function file_get_contents_ssl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3000); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 10000); 
    $result = curl_exec($ch);
    if($result === FALSE)
       $result = curl_error($ch);
    curl_close($ch);
    return $result;
}

10. Use the power of HTTP/2

HTTP/2 is the new generation of Hypertext transfer protocol. It has many performance improvements that allow a browser to load a webpage faster and be less resource-intensive.

Here are the key differences to HTTP/1.x:

  • HTTP2 is binary, instead of textual.
  • It is fully multiplexed ( can send multiple requests over the same connection ).
  • It can use one connection for parallelism ( meaning it can load resources considerably faster).
  • It uses header compression to reduce overhead.
  • It allows servers to "push" responses proactively into client’s browser caches.

All major web servers (Apache, Nginx, IIS) support HTTP2 out of the box. Here are the examples of configuration:

10.1 Enable HTTP/2 for Apache

Apache can use the latest HTTP protocol from version 2.4.17 up. First install mod_http2 module. Next enable it:

LoadModule http2_module modules/mod_http2.so

And modify Protocol directive:

Protocols h2 h2c http/1.1

10.2 Enable HTTP/2 for Nginx

You will need Nginx 1.9.5 up. All you will have to do is to add http2 parameter in listen directive.

server {
                 listen 443 https;

.....

You can use Google Chrome Developer Tools to verify the correct installation (if you are using chrome browser).

Open it up, go to Network tab and check for Protocol column - it should say h2. (To view Protocol column right click on any column and select it):

HTTP/2 Verification HTTP/2 Verification

11. Leverage Browser Caching

A browser can cache files for faster access. You can take advantage of this to lower the start render time. Configuration depends on your server:

11.1 Leverage Browser Caching for NGINX

Add this inside server directive:

  server{
       .....      
        location ~* .(js|css|png|jpg|jpeg|ico|gif|pdf)$ {
              expires 300d;
              add_header Pragma public;
              add_header Cache-Control "public";
        }

11.2 Leverage Browser Caching for Apache

Add this into your .htaccess file:

## EXPIRES CACHING ##
<IfModule mod_expires.c>
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"
</IfModule>
## EXPIRES CACHING ##

as taken from Gtmetrix.

12. Focus on Above-the-Fold Content

Above-the-fold content is the part of a page that you see before you scroll down. It is also called the visible content.

Read more about above-the-fold content optimization in my in-depth tutorial How to Optimize Magento 2 Core Web Vitals

Prioritize visible content – load and display it as quickly as possible.

How do I optimize above-the-fold content? Here are some tips:

13. Remove Render-Blocking CSS and Javascript

The less time a browser spends parsing <head> section of your webpage the better. Ideally, only JS and CSS need to display above-the-fold content which should be put in between head tags.

Go through your css files and identify rules that are applicable to visible content. Inline the rules and do the same for javascript.

Here is an extension to defer Javascript parsing (remove render-block Javascript).

14. Reduce the Size of Visible Content

The less visible content a browser has to download the better. Make sure images are optimized. Remove any content that is not needed.

15. Put the Above-the-Fold Content First

Analyze the page HTML and make sure visible content goes first.

You might need to restructure .phtml templates and .xml layouts.

16. Optimize Document Complete Time

Besides start render time and first byte time improvements, there are a few things you can do to decrease document complete time:

17. Magento Image Optimization

In my practice I use 3 techniques to reduce image size:

  1. Command-line Tools
  2. PageSpeed Server Module
  3. Google PageSpeed Insights

Let’s go over each of them in details

1. Command-line Tools

If you are familiar with Linux and Bash this tip will work for you.

I use:

  1. Gifsicle to compress GIFs
  2. Jpegtran to handle JPEGs
  3. Optipng to take care of PNGs

Here is a simple script to help you optimize images in bulk:

#!/bin/bash
find ./media -iname '*.gif' -exec sh -c ‘gifsicle -b -O3 -o "{}.out" "{}"; mv "{}.out" "{}"' ;
find ./media -iname '*.png' -exec optipng -o5 -keep -preserve '{}' ;
find ./media -type f -iname '*jpg' -exec sh -c 'jpegtran -outfile "{}.out" -optimize "{}"; mv "{}.out" "{}"' ;

2. PageSpeed Server Module

In an attempt to make internet faster, Google created PageSpeed Extension.

This is special software you plug into your server.

It compresses images on the fly, as well as other things needed to speed up a site.

3. Google PageSpeed Insights

Setting up the PageSpeed module sounds too techy for you?

No problem....

Google has a solution: Insights.

What are the insights?

It is a free magento speed test tool.

At the bottom you will see a link to download optimized images for the page tested.

Google Pagespeed Insights Google Pagespeed Insights

It is a tedious task to compress images for all the page using Insights.

But…

Done once, it could make a huge difference in how fast your site loads.

PS: There are various Magento image compression extensions available on the market.

Some free, some cost, but…

They all require professional installation.

If you want to try some of them, make sure it is installed by an expert.

18. Sign up for CDN

Content Delivery Network (CDN) is a web service to host your Magento site external resources likeCSS/JS files, images, fonts, etc.

It aims to serve those files a lot faster than you can with your own server.

I think that CDN is better than any magento image optimization extension.

Magento supports CDN by default, no extensions needed. Go to Stores > Configuration > General > Web and set secure/unsecure URLs for media and static files.

There are many CDN providers to choose from: Cloudflare, Amazon Cloud Service and others.

19. Optimize Fully Loaded Time

If you have done start render, first byte, and document complete times optimization, there is a final step – fully loaded time improvements.

What to do?..

First, keep the number of 3rd-party JS scripts to a minimum.

Second, do not rely too much on jquery.ready.

20. Don't Abuse jquery(document).ready

Choose onLoad events carefully. Don't put CPU intensive tasks in jquery.ready – it slows down page loading.

21. The Less Third-party Javascript the Better

Examine what third-party javascript files you add to your Magento store.

Do you really need them?

Well-known JS code like Google Analytics and Facebook are all optimized and performance impact is negligible.

Others – use with caution and always test.

22. Never Use JavaScript Bundling

Magento 2 can group JavaScript files to lower HTTP requests a browser needs to make to load a page. This is supposed to make a site faster.

Let me first say that JS Bundling is useless if HTTP/2 is enabled.

Second, it does more harm than good. The bundled JS file is huge in size (5-13Mb), which makes mobile speed suffer significantly (here is a bug report).

I advise to keep JS bundling off. Go to backend dashboard > Stores > Configuration > Advanced > Developer > Javascript Settings and set Enable Javascript Bundling to No:

Turn off JS Bundling Turn off JS Bundling

BTW, are you still running Magento 1? Transition to Magento 2 right now. My guide will help.

23. Run Store in Production Mode

I would list Run Store in Production Mode as a priority on any Magento speed optimization checklist.

M2 has three running modes: default, developer, and production. Production mode is the fastest one.

Make sure you always put your store in production mode. It will speed up Magento 2 significantly.

You will need to obtain SSH (Secure Shell) credentials to change running modes.

Here’s the command to find out what's the current mode:

php bin/magento deploy:mode:show

To switch to production:

php bin/magento deploy:mode:set production

24. Use a PHP Profiler

Online code profilers help to find slow function calls. You can then optimize certain files to speed up a website.

Magento 2 can be hooked up to New Relic. Go to Stores > Configuration > General > New Relic Reporting and enter Account IDs and API Keys:

Magento 2 New Relic Reporting

Let it run for a few days and then analyze graphs.

Tideways is another popular PHP profiler. It shows code bottlenecks and slow Mysql queries.

Slow Query Trace

25. Enable ElasticSearch Query Cache

The latest Magento versions need ElasticSearch (ES) to function properly.

ES stores a catalog index. With many product attributes and huge inventory it might be slow to deliver results.

I would turn the query cache on. Magento 2 ES library doesn’t use that feature.

Find the file vendor/elasticsearch/elasticsearch/src/Elasticsearch/Connections/Connection.php and make the following change around line 365:

+++ b/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Connections/Connection.php
@@ -365,6 +365,9 @@ class Connection implements ConnectionInterface
                 $params
             );
 
+            if(strpos($uri,'search') !== FALSE){
+             $params['request_cache'] = 'true';
+            }
             $uri .= '?' . http_build_query($params);
         }

Now every time Magento makes an ES request, it passes request_cache=true parameter. This forces Elastic to store results in cache.

26. Prevent Full Page Cache Automatic Clearing

Magento 2 flushes full page cache entries automatically. Various events could trigger cleaning: content changes, inventory changes etc.

It increases the average TTFB across the website. The page loading might feel slow to users.

I fix it by turning off automatic cache clearing.

Here is how to do it for disk storage. If you store FPC in Redis the logic is the same.

Find the file vendor/colinmollenhour/cache-backend-file/File.php. Add return to all clean functions:

 public function remove($id)
{     
     return;
     …

public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{  
     return;
     …

protected function _clean($dir, $mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{                                         
     return;
     …

protected function _cleanNew($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{                                         
     return;
     …

public function ___expire($id)
{                                         
     return;
     …

You can then set up cron to clean the FPC every week. Follow it with the cache warmer script to have the lowest average time to first byte.

10 15 * *  0 /usr/bin/rm -rf /path/to/magento/root/var/page_cache/* &&
 cd /path/to/magento/root && /usr/bin/php warmFPC.php

27. Turn PHP OpCache on

PHP opcache helps a webserver run Magento faster. Make sure you have that setting on.

php.ini:

php.opcache_enable=1

Ask your hosting provider to set it on.

Opcache has a revalidate_freq parameter. It tells the webserver how often to check code files for updates.

Ask the support team what your revalidate_freq is. If it’s 2 seconds (the default) you only need to wait 2 seconds before php picks up your file changes.

Some hosting providers set it to 30 seconds or longer. Then you need to wait half a minute for changes to be reflected online. Keep that in mind.

28. Move JavaScript to the Page Bottom

Keeping all JavaScript at the bottom improves start render time. The website feels faster to users and customers.

The latest versions of Magento 2 can defer JS parsing out of box. Switch the store to developer mode:

php bin/magento deploy:mode:set developer

And go to Stores > Configuration > Advanced > Developer > Javascript Settings:

Move Javascript To the Page Bottom

Set Move Js code to the bottom of the page to Yes and recompile:

php bin/magento deploy:mode:set production

Make sure you test the website and attempt to checkout. Deferring JS parsing might cause errors for some custom themes.

29. Use WebP and AVIF image formats instead of PNGs and JPEGs

WebP images are a lot smaller than PNGs and JPEGs. Serving images in the newest formats could speed up the site for slower networks.

There are extensions on Adobe Commerce Marketplace that do WebP compression automatically.

You can always perform manual converting. Use cwebp command line tool:

cwebp image.png -o image.webp

Some browsers still don’t support WebP so you will need to add a fallback. Picture HTML5 tag could help with that:

<picture>
   <source type=”image/webp” srcset=”/image.webp”/>
   <source type=”image/jpg” srcset=”/image.jpeg”/>
   <img src=”/image.jpeg”/>
</picture>

30. Save Sessions in Redis

Magento stores session data on disk. It might slow down the site when the customer base expands.

Redis comes to help. It’s an in-RAM data engine. Adobe Commerce and Magento supports Redis for session and cache storage.

Most hosting providers have Redis pre-installed.

Configuration is simple. Replace session settings in app/etc/env.php file:

-    'session' => [
-        'save' => 'files'
-    ],
+    'session' => [
+        'save' => 'redis',
+        'redis' => [
+           'host' => '127.0.0.1',
+           'port' => '6379',
+           'password' => '',
+           'timeout' => '5',
+           'persistent_identifier' => '',
+           'database' => '0',
+           'compression_threshold' => '2048',
+           'compression_library' => 'gzip',
+           'log_level' => '3',
+           'max_concurrency' => '24',
+           'break_after_frontend' => '5',
+           'break_after_adminhtml' => '30',
+           'first_lifetime' => '600',
+           'bot_first_lifetime' => '60',
+           'bot_lifetime' => '7200',
+           'disable_locking' => '0',
+           'min_lifetime' => '60',
+           'max_lifetime' => '2592000'
+       ]
+   ],

Pay attention to disable_locking. It has to be set to 'disable_locking' => 0 for stability reasons.

Setting to 1 might slightly improve performance but could seriously cripple the checkout process. Be careful.

31. Upgrade to PHP 8

Magento is powered by an interpreter engine called PHP.

PHP had a major upgrade not so long ago - the version 8.

PHP 8 runs faster than the previous PHP 5 and even PHP 7.

Ask your system administrator if you are using the latest release.

If not, upgrade to give your online shop a performance boost.

32. Make Varnish Your Caching Application

Varnish is a special server software that can cache and serve content super fast.

It is placed between users and a Magento site as shown below:

How Magento works with Varnish

Official documentation on how to setup Magento and Varnish

Magento 2 can use Varnish natively.

But…

You still have to install it on your server.

After you do that, enter host/port and other parameters at M2 Stores > Configuration > Advanced > System > Full Page Cache:

M2 Varnish Configuration M2 Varnish Configuration

On that page at the bottom you will see Export Configuration buttons.

M2 Varnish Export Configuration File M2 Varnish Export Configuration File

Export VLC file for your version of Varnish and ask your system administrator to upload it to the server.

You are almost done...

Now go and browse your website to see if it is fast enough.

33. Magento MySQL Optimization

This tip only makes sense if you are managing your own server.

If you are on a managed hosting plan (as you should be),go over to the next section.

First, collect DB statistic using this little perl script - mysqltuner.

It will tell you what needs to be done, right at the bottom:

Mysqltuner Recommendations Mysqltuner Recommendations

Go over to “Variables to adjust” part and set my.cnf configuration variables accordingly.

Where do you find my.cnf? It is usually at /etc/my.cnf.

34. Perform 3rd-party Extensions Audit

Well, it is the last step but it should have been the first one.

If you want to know how to increase Magento speed, this is what you should start with - a 3rd-party plugins audit.

It’s no surprise that custom extensions make Magento slower.

Not all of them but some and here is why…

On the one hand, Magento core was written by programming experts. There is little to no room for performance improvement in a stock installation.

On the other hand, various 3rd-party plugins are written by average coders at mostith no appreciation for performance benchmarks.

The rule of thumb here is to have as less custom modules as possible.

The ones you do have have to be inspected thoroughly.

Here is what I usually do:

  1. Disable extensions one by one
  2. Benchmark speed with and without an extension
  3. Find those that take most time to run
  4. Contact its vendor and let them patch
  5. If there is no patch, find an alternative or simple remove it

When my clients ask me, “how would I quickly make my Magento site faster?”

I always answer, “just remove all custom extensions.”

35. Use CSS Critical Path

That’s a feature of the latest Magento releases.

It inlines the critical CSS file and defers loading of all the other style files. It reduces the start render time.

Critical CSS styles the above-the-fold content.

You will need to compose critical.css and place it at app/design/frontend/Your_Theme/Your_Theme_Name/web/css/critical.css.

Then switch to developer mode and go to Stores > Configuration > Advanced > Developer > CSS Settings:

Critical CSS Path

Set Use CSS critical path to Yes and recompile.

Bonus: Implement a Magento Speed Test

Include performance benchmarks into your workflow. Every time you add an extension from Magento, connect or roll out a new feature, see what impact it has on site speed. Does it slow Magento? Debug or go for another module.

A few tools that will help you answer the question “how to speed up Magento's page load time?” (free to use):

1. webpagetest.org – provides you with page-loading waterfall charts and tons of other useful information. Supports mobile browsers.

2. Google Chrome Timeline – helps you analyze frontend performance. Takes a little time to get use to, but once you are familiar with it, it gives you valuable insights into why your Magento is slow.

3. Google PageSpeed Insights – an online tool that tells you what to do to boost site performance. Work on suggestions by Google and improve Magento speed.

Does all these 35 tips seem too complex for you?

Try my magento speed optimization service.

I have experience. I have references.

  

If you find this post interesting do not hesitate to sign up for our newsletter and join the 1433 people who receive Magento news, tips and tricks regularly.

Thank You!

 

32 thoughts on “Speed Up Magento 2 - The Ultimate Guide (35 Working Tips)”
  • Aman Pote December 6, 2024 at 6:16 am

    This article offers valuable insights into speeding up Magento, which is crucial for enhancing the user experience and improving SEO rankings. I particularly appreciate the practical tips on optimizing images, enabling full-page caching, and minimizing JavaScript. The advice on choosing the right hosting and utilizing a content delivery network (CDN) is also key to improving site performance. It would be great to see a section on how to monitor site speed post-optimization to ensure continuous improvement. Overall, the article provides actionable steps that will help Magento store owners improve performance and deliver a faster, smoother shopping experience.

  • ruhi sharma November 22, 2024 at 7:07 am

    I agree with your points on VPS hosting.

  • AbdurRahman November 23, 2022 at 5:50 am

    Your article is really helpful in optimizing the Magento store. Just 1 query related to hosting:
    Since I am not a much technical person so I guess an optimized managed Magento hosting solution may work for me but Lexiconn is charging $399 and Cloudways is charging $160. So which solution should I prefer?

  • Franc October 15, 2020 at 6:20 am

    Hello, it seems to me a very complete article. On the other hand, I usually use plugins to generate the file cache, but they end up generating a very large cache size.
    Do you know how to clear cache automatically?

    a cordial greeting

  • xFyVyT@mailgator.org October 14, 2020 at 1:49 am

    The recommendations are like "If you want to live, you should it".
    The main problem in Magento is the configuration caching, it collects everything from all sources - XML, DB and pushes it to Redis and fetches it from it the whole chunk on every request instead of storing only the config needed at the specific time.
    Off-topic: If you want a performant site, implement it without Magento (more precisely Magento 2, Magento 1 was okay-ish), rather use a framework.
    Cheers.

  • Alexpaul July 31, 2020 at 4:53 am

    Thanks for sharing the great guide on speed up the magento website. These tips were really helpful.

  • GSPANN December 19, 2019 at 11:54 pm

    Wow, great article for any magento user.

  • satish December 13, 2019 at 11:41 pm

    Very good article.

    Please advice on following :
    1. Use of async for JS.
    2. Rmove unused JS
    3. Remove unused CSS


    Thanks,
    Satish Mantri

  • Joash September 5, 2019 at 2:51 am

    I always look for best Magento guides and happy to see this one :)

    You have covered all the tips to improve the speed of Magento store.

    Thanks!!.

  • Akshara Malhotra July 9, 2019 at 10:19 am

    No doubt, the page loading time is significantly essential for any website/blog and as because of the slow rendering websites lose almost everything. For any internet site, the loading time is a major factor in developing now. I'm usually busy on one side trying my best to optimize the overall loading speed of my blog. The clean & near coding of HTML can help you to cut off a couple of seconds on your blog. One point I want to tell you that after I moved to Genesis or magazine framework, my blog loading speed has decreased by over 2.2s. Possibly that’s because it has a plain and lightweight structure and it even corrected me to remove unwanted and heavy plugins.

    About the images, not so many users are well aware of Photoshop, so for the alternative to optimize graphics there are lots of websites to help you to compress image size that matter greatly on the entire size of your HTML page rendering on the user side. Also, I switched to a dedicated server and the faster CDN (Content Delivery Network) that not only work for WordPress for the Blogger as well. The use of CDN and can cause a significant difference in site loading time. I used to make changes to HTML and keep an eye on site loading. A dedicated hosting including regular tweaking can make a difference.

    The slow loading causing the two most valuable things to stay away from your website that matter is "Google" and "Visitor." So it really matters to work hard on optimizing the loading speed of the site and each page.

  • Five Tips to Speed Up Magento Websites | MageWorx Magento Blog June 11, 2019 at 6:08 am

    [...] a comprehensive Magento extension audit to figure out how many extensions you have and find out how each one affects your loading time. [...]

  • Magento Installation – Fresh Start | Chris' Laboratory May 21, 2019 at 6:42 pm

    [...] https://www.goivvy.com/blog/speed-up-magento [...]

  • Noviemcom March 1, 2019 at 12:36 pm

    We could use a guide to optimize Magento 2 local dev env, as with "developer" mode on it takes ages to develop something on it.

  • Magento vs Shopify: Which Platform Is Best For Enterprises? - Trellis February 7, 2019 at 11:00 am

    [...] basics are rock-solid. It’s simply up to you to determine the best way to host and optimize it (you can find myriad tips here). At no point will you be left to feel that the state of your store is out of your hands. It’ll [...]

  • 11 Magento Best Practices in 2019 - Tillison Consulting January 28, 2019 at 4:33 am

    [...] Site speed [...]

  • Konstantin Gerasimov January 8, 2019 at 5:57 pm

    @Hristo one doesn't exclude another. You can use varnish with google pagespeed module without any specific modifications.

  • Hristo Hristov January 8, 2019 at 4:10 pm

    Hello Sir,

    Could you tell me how to use Varnish and Google Pagespeed module together?
    Thank you!

  • Antonella Morales December 10, 2018 at 11:13 am

    @Hristo please submit a ticket and we'll go from there.

  • Hristo Hristov December 2, 2018 at 5:33 am

    Hello Sir,

    Our new Magento 2.2.3 project is almost ready.
    Nginx-Varnish-PHP-FMP-Redis on the server with Percona 5.7
    Our hosting is Managed Cloud VPS and we would like to know could you make all neccessary server setings and optimizations.

    Thanl you!
    Intro Light Ltd.

  • Lee November 24, 2018 at 8:03 pm

    We became quite proficient at speeding up mage1 by combining scripts. M2 now loads >150 JS files. Some sites it's over 200. Whilst I get they are Asynchronous, It still seems excessive to be making that many requests. The default bundling option includes the massive zxcvbn.js file which is almost 1Mb. Have you found a way to minimise the number of scripts?

  • Parels oorbellen November 20, 2018 at 3:08 am

    Hi there,

    An extensive read but totally worth it. Will try to implement as much as i can into my website. Great work, thank you

  • Cannabis Seeds Store November 17, 2018 at 12:31 pm

    Thanks a lot for this article about speeding magento. Very very useful, it help me a lot. Cheers

  • Danial Wilson October 15, 2018 at 10:22 am

    Thank you very much for sharing this wonderful content regarding Speed up Magento website.

  • Daria August 21, 2018 at 9:06 am

    Hi! Thank you for the useful information.

  • deep January 3, 2018 at 11:38 pm

    wow. awesome contents

  • Randy de Decker November 11, 2017 at 4:28 am

    Good article that I've bookmarked. I've implemented a lot of these actions above, but good to know there are still some improvement points left.
    I agree with Steve that HHVM should not be used with M1. And a good FPC decreases load times substantially, but offcourse does not improve the uncached pages loadtime.

  • Fayyaz Khattak September 28, 2017 at 11:40 am

    Well, I have used Cloudways Magento Full Page Extension powered by Amasty to speed up the Magento performance. I avoided using heave theme and used trusted extensions to accomplish some tasks on my ecommerce store. The store now loads within 2 seconds, and I am delighted with the reviews of my customers about the performance of the store.

  • Alexander July 27, 2017 at 3:32 am

    Magento is an ecommerce heavy open source platform. It is a big problem for you when your magento store runs slowly and at that time you have to setup it properly.

  • Tej singh May 30, 2017 at 4:35 am

    Tottaly agreed to all the above points foe increased magento page speed but one point we are forgetting is what happens if we clear cache in middle of the day when customers are actually hitting the site, best solution is to have cache warmer that quickly crawls and puts the page back under cache.

  • olivedev January 19, 2017 at 5:11 am

    Some great tips for optimizing Magento's speed. Few more things that you can do to tune the performance are: install Turpentine – Varnish Cache plugin and configure Memcached with Magento 2. You will notice a significant increase in speed.

  • Konstantin Gerasimov October 25, 2016 at 3:41 am

    @Steve - thank you for your comment

    what did you mean by " I’d take care with infrastructure suggestions that are outside Magento’s requirements ( so no HHVM, > 5.4/5/6 on Magento 1.x and so on ). Don’t want to get sued!"?

    I run HHVM with magento 1.x with no problems

    master-slave setup for magento is a great way to speed things up - master for writes, slave for reads - magento supports separate reads/writes databases.

  • Steve Holdoway October 25, 2016 at 1:20 am

    Great to see a well thought out list rather than the usual regurgitated posts from a decade ago! However, I do disagree with a few of these, and have a few suggestions ( well, what do you expect from a grumpy old bugger like me! )...

    - If you split database and web server then you've not only added a new point of failure ( and potential performance problems ), but you now have to build up / tear down TCP connectivity to extract data from the database, rather than ( with a properly configured server ) just pick it out from local memory.

    - it's very unlikely that your site will ever become busy enough to require a master / slave database setup. Also remember that this will slow things down if you're not very careful indeed.

    - there are many more file types that can take advantage of browser caching.

    - domain sharding is pointless with use of a CDN... just hand the heavy lifting over to them and let them sort it out.


    Also...

    - what about http2?

    - I'd take care with infrastructure suggestions that are outside Magento's requirements ( so no HHVM, > 5.4/5/6 on Magento 1.x and so on ). Don't want to get sued!

    - tuning of the OS?

    - and finally what about caching!