Useful Tips for Magento 2 Performance Optimization

Useful Tips for Magento 2 Performance Optimization
COMMENTS ()
Tweet

The Need for Magento 2 Performance Optimization

E-commerce websites are a digital storefront that describes how a business is going to meet customer’s expectations. In this competitive era, a webpage that takes longer to load can result in higher abandonment rate, thereby leading to unsatisfied customers. Also, search engines take into account the page load time in their rankings, which means they’re more likely to guide shoppers to the websites that load quickly. Hence, page load time or speed is a direct component that reflects on the overall Magento 2 performance optimization. 

Magento 2 is one of the widely used e-commerce platforms that delivers great flexibility and control to its users. Although, it offers an extensive array of powerful tools for building and managing an online store, but its modular architecture is known to carry some performance challenges that can reduce its speed overtime and effect usability.

In this blog, I will be sharing few upgrades that can help greatly in the performance optimization of your Magento 2 store and help improve its speed, responsiveness and search engine rankings.

Upgrade to Latest Magento 2 Version

At first, ensure that you are upgraded to the latest version of Magento 2 as it releases new versions and security patches time to time, offering better performance, integrations with 3rd party services, improved security, fixed bugs, and other minor adjustments. Magento 2 notifies you each time there is an update so you don’t need to check it, on your own, again and again.

Here’s a sample snapshot of the notifications that you are expected to receive time-to-time:

Magento 2 customization

Hosting Environment

Hosting is the foundation of your e-commerce store. It is imperative for you to have a reliable and fast web host to improve Magento 2 performance. Use a server that is geographically located closer to your target audience for better results.

A good web host should be able to the deliver you the following:

  • High security standards
  • High speed connection
  • Quick support.

To make it easier for you, here is the list of some of the recommended servers for Magento 2:

  1. Nexcess
  2. Digital Ocean
  3. Rackspace
  4. Site Ground
  5. Blue Host
  6. In-Motion Hosting
  7. A2 Hosting
  8. HostGator
  9. iPage
  10. Cloudways

Code Optimization

Code optimization is one of the vital components in order to maintain Magento 2 performance. There are several performance optimization tips for Magento 2 that can help you achieve the desired results:

Use a PHP accelerator

Using a PHP accelerator is one form of code optimization. The accelerator is basically an extension that caches all PHP scripts used in the web page, thus doing away with the need to parse the scripts repeatedly when the visitors log into your page. Some of the popular PHP accelerators are listed below:

Don’t abuse jquery (document).ready

Putting CPU intensive tasks in jquery.ready slows down the page loading therefore, you must choose onLoad events very carefully in order to avoid such events.

Use less third-party JavaScript

Carefully examine the third-party JavaScript files you add to your Magento 2 store. Well known JS codes like Google Analytics and Facebook are well optimized. Always use alternative codes, other than the popular, with caution and ensure to run a test before processing any further.

You can also do the following for code optimization:

  • Identifying bottlenecks in the technology stack
  • Uninstalling the unwanted PHP modules to clean the space.

Database Optimization

MySQL has its own query cache, which it uses in Magento 2 to help generate dynamic pages and content whilst improving performance. Scripts like, “The Tuning Primer” (https://launchpad.net/mysql-tuning-primer/) and “MySQL Tuner” (https://github.com/major/MySQLTuner-perl) allow you to review and adjust the MySQL settings in order to increase Magento 2 database performance and stability. These scripts help in analyzing MySQL statistics and provides recommendations on how to fine-tune your MySQL server.

The following are some of the settings that you can adjust for better performance:

  • Slow Query Log
  • Max Connections
  • Worker Threads
  • Memory Usage
  • Key Buffer
  • Query Cache
  • Sort Buffer
  • Joins
  • Temp Tables
  • Table (Open & Definition) Cache
  • Table Scans (read buffer)
  • Table Locking
  • Innodb Status

Given below are some of the recommended settings for your my.cnf (mySQL configuration file):

  • query_cache_type = 1
  • query_cache_size = 32M
  • query_cache_limit=2M

Also, a recommended setting for your php.ini (PHP configuration file):

  • php_value memory limit 1024M

Minify, Merge & Bundle JavaScript and CSS files

Magento 2 can minify, merge & bundle CSS and JavaScript files. This reduces the number of HTTP requests to server and page, thereby saving bandwidth. You need to change the Magento’s running mode to “Production” in order to minify the said files.

  • To find out your current Magento store’s mode, issue this command from the command prompt

php bin/Magento deploy:mode:show

  • To change the mode to ‘Production’ run:

php bin/Magento deploy:mode:set production

  • To merge JS/CSS, follow this path in the Magento Admin panel:
  • On the Admin panel, navigate to Stores > Settings > Configuration
  • Click on Developer under the Advanced tab
  • In the JavaScript Settings change the fields Merge JavaScript Files, Enable JavaScript Bundling and Minify JavaScript Files to Yes
  • Now, go to the CSS Settings tab and change the fields of Merge CSS Files and Minify CSS Files to Yes
  • Clear cache

Magento 2 customization

 

Magento 2 customization

Clean Up Magento Database & Logs

Magento 2 saves the statistics by logging them into the database. This data is useful, however, over the course of time, the database table can grow to an unmanageable size hence forming a large log file that slows down the backup on the server. Also, it is difficult to look for a particular event if you have a million log entries to skim through. Therefore, you need to clean these logs periodically, in order to keep your Magento 2 store optimized.

Unfortunately, Magento 2 has not introduced any function, as yet, that can automatically clean logs from the admin panel as it was present in Magento 1.

(Reference: https://github.com/magento/magento2/issues/7512).

Some of the database log tables that need regular cleaning are:

  • customer_log
  • customer_visitor
  • report_compared_product_index
  • report_event
  • report_event_types
  • report_viewed_product_aggregated_daily
  • report_viewed_product_aggregated_monthly
  • report_viewed_product_aggregated_yearly
  • report_viewed_product_index

It is highly recommended that you setup log rotation to automatically purge old logs in order to improve site performance and speed.

Log rotation refers to:

  • Archiving an application’s current log,
  • Starting a fresh log,
  • Deleting older logs.

Magento logs are created in /magento_root/var/log/*.log. Some of them are:

  • debug.log
  • exception.log
  • install.log
  • magento.cron.log
  • setup.cron.log
  • system.log
  • update.cron.log
  • update.log

Implement Logrotate

To implement logrotate, you’ll first need to create a file in /etc/logrotate.d/ called magento2 and then add the following contents to it and save it.

/var/www/<magento_root>/var/log/*.log {
size 10M
missingok
rotate 50
compress
delaycompress
notifempty
dateext
dateformat -%Y-%m-%d-%s}

Explanation:

  • size – any of the *.log files that becomes larger than 10M are rotated.
  • missingok – if there are no logs, that’s ok.
  • rotate – number of rotations to keep.
  • compress + delaycompress – compress the log after rotation, but keep the most recent uncompressed.
  • notifempty – do not logrotate, if empty.
  • create – not needed as Magento handles the log creation on its own.
  • dateext – add a date extension to rotated files.
  • dateformat – sets the date format of the dateext.

Disable and Remove the Unused Modules

The more extensions you have installed in Magento 2, the more HTTP requests you get (along with additional CSS and JavaScript files), which has a negative impact on your Magento 2 site’s performance. It is therefore best to keep the number of extensions installed on Magento 2 to a minimum. An added benefit of this is that your site’s admins won’t be distracted or confused by the additional configuration options and features that are enabled/displayed on the admin panel by some of these extensions.

Since the ability to disable extensions/modules’ output from Admin panel has been removed from Magento 2.2 and later versions, you’ll need to this step manually from the command line tool.

First, to see a list of all your active and inactive Magento 2 extensions/modules, use the following command.

bin/Magento module:status

Then, specify the module name in command below in order to disable it.

bin/Magento module:disable Vendor_Module

OR

Use the below command to fully uninstall the module

bin/Magento module:uninstall Vendor_Module

(Please note: this command works only with modules installed via the composer)

Magento 2 Index Management

As you know, indexing helps optimize your Magento data such as Products, Categories, Inventory stock, Static blocks, etc. for quicker search and retrieval. Since data changes over time though, it needs to be re-indexed, otherwise it can increase page load times. That’s why its necessary to update your Magento 2 store’s indexes regularly.

For example, supposing there is a change in price for the majority of the products listed on your Magento 2 store. In this case, you’ll need to re-index your data so the correct price is quickly displayed on your store.

Indexing also helps speed up MySQL queries. Without indexing, Magento 2 will calculate the price of every product individually, taking into account other pricing factors such as discounts, bundle pricing, wholesales, price rules and etc. This greatly increases the loading time for the price to be displayed (for a particular product, which could potentially result in shopping cart abandonment or high bounce rates.

To manually index your data, just peform the following in the Magento Admin panel.

  1. Navigate to SystemIndex Management
  2. Select all of the indexes (or the ones you want to update), choose Reindex Data from the dropdown and click Submit

Magento 2 customization

Optimize Magento Website for Mobile

Another vital factor in Magento 2 performance optimization is optimizing your store for mobile devices. Since typically, most optimization efforts tend to focus only on the desktop while neglecting smartphones and tablets.

Magento 2 customization

Graphical representation of U.S. mobile retail commerce sales as percentage of retail e-commerce sales from 2017 to 2021
Source: https://www.statista.com/statistics/249863/us-mobile-retail-commerce-sales-as-percentage-of-e-commerce-sales/
It is therefore highly recommended that you invest in a responsive design for your Magento store, which can scale to fit different device screens.

 
Leverage Caching
Caching data in Magento 2 can also have a significant impact on the performance of your site. And there are multiple forms of caching that you can be implement in Magento 2.

Magento 2 provides integration with Redis and Varnish (a powerful HTTP accelerator and reverse proxy) out of the box, and you can leverage that to improve your store’s performance. In production mode, I recommend that you use Varnish Cache for for optimal performance on your Magento 2 store (as shown in the screenshot below).

Magento 2 customization

The following figure depicts a basic view of Varnish in your Magento topology:

Magento 2 customization

Source: http://devdocs.magento.com/guides/v2.0/config-guide/varnish/config-varnish.html

Magento 2 also comes with a built-in caching module, however its better to use third party caching solutions like Redis, Varnish, APC and Memcached, as they tend to deliver better results.

To enable all cache types, follow the steps below.

  • Navigate to SystemCache Management
  • Select All from the Mass Action Dropdown
  • Click Enable (as depicted in the below screenshot).

Magento 2 customization

Integrate Content Delivery Network (CDN)

For those of you don’t know, a Content Delivery Network (CDN) is basically a system of distributed servers that deliver web content from multiple locations. By doing so, it can serve up files at lot faster than you can with your own server. By implementing a Content Delivery Network (CDN) on your Magento 2 site, you can greatly improve your Magento 2 store’s user experience. It’s one of the easiest ways to decrease page load times.

A CDN is best implemented on stores that cater to global traffic. For such sites, copies of static assets like images, CSS style sheets, and JavaScript files are stored in different datacenters and spread out globally by the CDN. That provides users with higher availability and faster load times for all interactions the web store.

To configure a CDN on your Magento 2 site, follow the steps below.

  • Go to the Admin panel, click Stores.
  • In the Settings section, select Configuration.
  • Select Web under the General panel on the left.
  • Open the Base URLs section, and do the following:
    1. In the Base URL for Static View Files field, enter the URL of the location on the CDN, where static view files are stored.
    2. In the Base URL for User Media Files field, enter the URL of the JavaScript files on the CDN.

Magento 2 customization

  • Now, open the Base URLs (Secure) section, and follow the steps below.
    1. In the Secure Base URL for Static View Files field, enter the URL of the location on the CDN where static view files are stored.
    2. In the Secure Base URL for User Media Files field, enter the URL of the JavaScript files on the CDN.

Magento 2 customization

● Once done, click Save Config.

Gzip Compression & Enable Output Compression

By using Gzip, you can compress users’ requested pages before sending them to the browsers, thereby resulting in shorter page load times. You can enable Gzip on your Magento 2 store by using either mod_gzip or mod_deflate. Typically, the compression offered by mod_deflate (as depicted in the code snippet below) is recommended, as this has a better conversion algorithm, plus the module itself is compatible with higher versions of apache.

Gzip compression on Static Content

<IfModule mod_deflate.c>
############################################
## enable apache served files compression
## http://developer.yahoo.com/performance/rules.html#gzip

 # Insert filter on all content
 SetOutputFilter DEFLATE

 # Compress HTML, CSS, JavaScript, Text, XML and fonts
 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

# Netscape 4.x has some problems…

 BrowserMatch ^Mozilla/4 gzip-only-text/html

 # Netscape 4.06-4.08 have some more problems
 BrowserMatch ^Mozilla/4\.0[678] no-gzip

 # MSIE masquerades as Netscape, but it is fine
 BrowserMatch \bMSIE !no-gzip !gzip-only-text/html

 # Don't compress images
 SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary

 # Make sure proxies don't deliver the wrong content
 Header append Vary User-Agent env=!dont-vary

</IfModule>

 

Gzip compression on Dynamic Content

If your Magento 2 store relies more on dynamically generated content, then you must create a file, called .user.ini on your site’s document root folder with the following content, in order to apply gzip compression.

zlib.output_compression = on

Leverage Browser Caching and Expires Headers

To optimize the browser cache, you must direct the files you want to keep in the cache to the browser and specify the time period for their retention. For example, since JavaScript files tend to change less frequently than CSS files in the initial stages of your website, so once the site is running smoothly, you can enhance their browser cache expiration date.

You can set this expiration limit in headers using the .htaccess file. By doing so, you can enable your Magento 2 store to keep using the cached version of the files, it will not download new ones until the expiration duration mentioned in the headers is attained.

 

############################################
<IfModule mod_expires.c>
# First of all enable expirations
ExpiresActive On
# Default expiration
ExpiresDefault “access plus 1 month”
# For favicon
ExpiresByType image/x-icon “access plus 1 year”
# Set Images Expiry
ExpiresByType image/x-icon “access plus 1 year”
ExpiresByType image/gif “access plus 1 month”
ExpiresByType image/png “access plus 1 month”
ExpiresByType image/jpg “access plus 1 month”
ExpiresByType image/jpeg “access plus 1 month”
# Set CSS Expiry
ExpiresByType text/css “access 1 month”
# For JavaScript Expiry
ExpiresByType application/javascript “access plus 1 year”
</IfModule>
############################################

 

Disable ETags

This is another aspect of Magento 2 performance optimization. Since ETags allow browsers to validate cached page components from visit to visit, they can sometimes hamper websites hosted on server clusters, thereby having a negative impact on site performance. To avoid this situation, its’ better to disable ETags. Here’s how you can do so.

############################################
## If running in cluster environment, uncomment this
## http://developer.yahoo.com/performance/rules.html#etags
   FileETag none

 

Enable Flat Category and Product Hierarchy

As you know, ORM (Object-relational mapping) is a software development technique used for converting various data types into objects and vice versa. In Magento 2, ORM takes place via the following two configuration models.

  • Flat – flat table structure
  • EAV (Entity Attribute Value)

Magento 2, by default uses the EAV model to store your customer and product data, as it enables you to add attributes on the fly, without redesigning the database. Flat table structures on the other hand, have a limited number of columns (for e.g. innoDB can have at maximum 1000 columns) which in turn limits the maximum number of attributes. That is why, Magento 2 prefers EAV over the flat table structure.

However, in some cases having an EAV model is not the best or fastest option, because although it enables objects to be incredibly extensible, it can result in longer SQL queries and higher joins. Comparatively, by enabling a Flat Catalog for Categories and Products, you can merge product data into one table, thereby improving your store’s overall performance.

Keep in mind that you rebuild the flat index, single flat tables for each of the store’s views are generated. Ideally, all stores should enable the Flat Catalog for Categories.

To enable the flat catalog for categories, just follow the steps below.

  • Go to the Admin Panel, Navigate to Stores > Configurations
  • On the left panel, under Catalog, select Catalog
  • Open the Storefront section:
    1. Choose Yes in the Use Flat Catalog Category field
    2. Choose Yes in the Use Flat Catalog Product field

 

Magento 2 customization

 

  • Click Save Config to complete
  • Clear the cache

Bonus Tools

In addition to the Magento 2 perfomance optimization steps mentioned above, here are a few additional tools that you can use to help you speed up your Magento 2 store and evaluate its performance:

  • Kraken.io: This tool reviews the images on your site and suggest which ones you can optimize to enhance load times on your site.
  • Pingdom: This tool can help you assess calls to any related server, network or database
  • PageSpeed: This online tool tells what you can do to boost your site’s performance (by implementing suggestions provided by Google)
  • GT Metrix: GT Metrix provides a comprehensive overview of what you need to do on the site to optimize performance, and the results you can expect from it.
  • Webpagetest.org – provides you with page-loading waterfall charts and tons of other useful information. It also supports mobile browsers.
  • Google Chrome Timeline– helps you analyze your Magento 2 site’s frontend performance. It takes a little time to get used to, but once you are familiar with it, it can give you valuable insights into why your Magento 2 site is slow.

Hope you find this post useful. Feel free to comment or reach out if you have any questions.

Having trouble with the performance of your Magento/Magento 2 web store? Want to know more about our Magento & Magento 2 performance optimization services? Get in touchwith us.

CALL

USA408 365 4638

VISIT

1301 Shoreway Road, Suite 160,

Belmont, CA 94002

Contact us

Whether you are a large enterprise looking to augment your teams with experts resources or an SME looking to scale your business or a startup looking to build something.
We are your digital growth partner.

Tel: +1 408 365 4638
Support: +1 (408) 512 1812