Magento speed optimization is a website performance enhancement process, aimed at improving loading times and responsiveness for a better user experience. When you speed up Magento 2, your store ranks better in SERP and has a reduced bounce rate.
If you've been wondering how to achieve these benefits through Magento performance optimization, this post will provide all the information you need. Below, we talk about Magento optimization best practices – both frontend and backend – and suggest helpful tools, pro tips, and easy-to-follow configuration guides.
Why You Need Magento 2 Performance Optimization: Statistics
According to Google, the chance of customers bouncing from your website increases by 32% when your page takes 3 seconds instead of 1 to load. An in-depth online performance study even shows that the optimal load times for the lowest bounce rate range from 700ms to 1.2s and load times for peak conversions range from 1.8 to 2.7 seconds.
Speaking of conversion, here are some more facts that tie the importance of Magento 2 speed optimization to your revenue:
- Almost 70% of consumers state that a website’s page speed affects their willingness to purchase from an e-commerce site.
- Each 100-millisecond delay in load time hurts your conversion rates by 7%.
- A website that loads in 1 second has a conversion rate 3x higher than a site that loads in 5 seconds and 5x higher than a site that loads in 10 seconds.
Frontend and Backend Magento 2 Optimization
First, test your current Magento 2 loading speed with one of the 5 tools we offer in our guide, or - in case you need expert help - request our performance audit service. If your results are alerting, you can address the issues by using a combination of frontend and backend Magento performance optimization techniques.
To succeed in making your Magento store faster, you can use several methods. All of them can be divided into two general categories:
Frontend speed optimization involves improving and adjusting Magento store elements visible to your users. This method may include:
- Image optimization
- JavaScript and CSS file minification
- Caching
- Lazyloading implementation
Backend speed optimization techniques focus on how to optimize Magento 2 website server and reduce the number of database queries. These are:
- Code optimization
- Server settings optimization
- Indexing configurations
- Extension management
Each of these variants has its pros and cons:
- Caching methods will accelerate many operations and speed up requests for static and dynamic pages. But unless your code and server are optimized, caching can only do so much.
Server optimization can boost a site’s performance in no time while requiring relatively low investments. However, you can't expect mind-blowing results if your website has code issues. Amasty experts have seen Magento stores where code issues repeatedly led to checkout failures while 3072MB were allocated for the memory_limit [sic]. In cases like these, server configurations will, at best, only postpone checkout failures for a few seconds.
Code optimization can help with the fundamental Magento performance issues. Yet its costs can be rather significant because the 'issues' here aren’t just 2 or 3 small coding bugs.
Now, let's take a look at all these and more speed optimization options in greater detail.
19 Proven Magento 2 Speed Optimization Techniques
You can optimize Magento for a satisfying customer experience and firm Google standing in multiple ways. In the next section, Amasty experts share the 19 most effective Magento 2 speed optimization steps.
1. Keep Your Magento Updated
One of the simplest and fastest methods of Magento 2 performance improvement is to stay on top of new Magento releases. Magento’s updates provide performance upgrades, patches, and other essential features and resources to keep Magento running smoothly and avoid slow loading times caused by out-of-date systems. If you’re using the latest version of the platform, you’re on the right track.
2. Delete All Unused Data
The Magento Datalog stores vital information about your products but it also stores unused data that can slow down your Magento loading time. For instance, you might have details on products you no longer sell that still take up disk space. Regularly deleting this data keeps your pages loading efficiently.
You can clean up your Magento Datalog in a few simple steps.
- From the Admin Panel.
- Select System > Configuration > Advanced > System.
- Expand the MySQL Message Queue Cleanup option and set values for the different attributes.
- Save the configuration once you’ve included all the required information.
3. Optimize Your Images
Image sizes play a big role in how fast your website is and weighty images can ruin your performance. One of the most popular Google tips is to use JPEG 2000, JPEG XR, and WebP formats to replace the images on your server and increase Magento 2 speed. With all images compressed into WebP Magento 2 stores are especially fast. As for the weight, an optimal value for a 400 px .jpeg photo is about 35 – 70 Kb.
At Amasty, we usually recommend clients have the image’s source file resized to the optimal size instead of relying on resizing by CSS to be 100% sure they won’t cause slowdowns. We also advise automating the optimization of all uploaded images, which is possible with Google Page Speed Optimizer.
To keep your images under control, you can analyze your Magento 2 with PageSpeed Insights and look at the detailed report that lists all the weightiest illustrations on your website. To make an even more comprehensive audit, use Screaming Frog's Spider. Download a complete list of all the images on your website with their addresses and weight values.
Images are integral to selling a product, so you should find a balance between image quality and size. You don’t want to lose customers by including only low-quality images, but you want everything to load quickly so customers can get a complete look at your catalog.
4. Use HTTP/2
HTTP/2 is a protocol for faster web page loading that reduces latency and improves efficiency via such features as server push, multiplexing, and header compression. It uses a single TCP (Transmission Control Protocol) connection to asynchronously send numerous requests for data to your server, allowing you to download multiple files from a server in ASync mode with no risks to site performance.
Switching to HTTP/2 can achieve even better Magento 2 optimization than reducing HTTP requests. What’s more, if your website uses HTTP/2 technology and loads in under 3 seconds (the current “golden rule”), you can expect Google to boost your Magento score as a best practice follower. The protocol is currently in use by 35.6% of all worldwide websites and the trend is still increasing.
To check if your Magento loads with HTTP/2, you can use the dev tool of your browser. Just press Ctrl + Shift + i and go to Network from the upper horizontal navigation menu. (If there’s no such a column, add it by right-clicking). If you see no HTTP/2 protocol in the column, this means it’s not there.
5. Set Up a Magento CDN
A content delivery network (CDN) will allow your Magento site to achieve faster speeds, essential to attracting and retaining customers. However, while a CDN is important to your Magento website, it doesn’t operate like your site’s cache. Instead, you’ll need to configure your CDN specifically because it isn’t already integrated into Magento. You can start the process by going to Admin > Stores > Settings > Configuration.
Once you reach this page, choose General > Web. Open the page’s Base URLs section, and enter the URL of the site location on the CDN in the Base URL for Static View Files option. Type in the URL for your JavaScript files in the Base URL for User Media Files option. Go to the Base URL (Secure) field and open it. Type the location URL on your CDN in the field Secure Base URL for Static View Files. Finally, type in the URL of the JavaScript files on your CDN in the Secure Base URL for User Media Files option and save the configuration.
Read More: How to Set Up Magento CDN
6. Enable Varnish Cache
Another way to speed up your Magento 2 site is to enable backend caching, particularly with Varnish Cache. Varnish is a powerful HTTP accelerator specifically designed to enhance the performance of dynamic, content-heavy websites like Magento stores. It works as a reverse proxy, which means it sits between the user's browser and your server.
When enabled, Varnish stores copies of your website's pages after they are generated by the backend. Instead of executing queries and regenerating the same content for every new request, Varnish serves the cached version of the page directly from memory. This reduces the load on your server, minimizes network bandwidth usage, and dramatically decreases response times for users.
To enable Varnish Cache in Magento 2, follow these steps:
- Go to Stores > Configuration > Advanced > System > Full Page Cache.
- Under the Caching Application section, select Varnish Caching.
To maintain optimal performance, you can also implement cache warming. Cache warming pre-loads frequently visited pages into the Varnish cache even before users request them. This way, when a user visits a page, it is already cached and ready to be served instantly. Magento supports cache warming through extensions like Full Page Cache Warmer or built-in mechanisms that automatically refresh and pre-populate the cache for key pages.
Make sure Varnish is properly configured on your server and works alongside your Magento setup for the best results. Cache warming helps keep your most critical pages always available at peak speed.
7. Use Full-Page Cache
In addition or as an alternative to Varnish, Magento 2 comes with its own built-in Full-Page Cache (FPC) system. FPC is designed to serve cached HTML versions of entire pages, reducing the time it takes for users to load content. It’s particularly effective for improving site speed because it eliminates the need for repeated database queries and complex PHP processing for each page load.
When a user requests a page, Magento checks whether a cached version of that page exists. If it does, the cached version is served instantly, significantly improving the loading speed. This is especially beneficial for pages that don’t change frequently, like category listings or product pages, as they can be served directly from the cache without additional server-side work.
Magento also supports block caching and object caching, which further optimize performance by caching individual page elements or data objects, reducing the workload on your server and database.
To enable Full-Page Cache in Magento 2:
- Navigate to Stores > Configuration > Advanced > System > Full Page Cache.
- Choose either Built-in Cache or Varnish Cache, depending on your server setup.
Using Full-Page Cache, combined with other caching layers, ensures your Magento store runs more efficiently, delivering faster page load times to your visitors.
8. Enable Expire Headers
Using expire headers in Magento helps optimize website speed by instructing the client's web browser to cache static resources such as images, CSS, and JavaScript files for a specified period. Once cached, these resources don't need to be re-downloaded on subsequent visits, reducing the number of HTTP requests and improving page load times.
Leveraging browser caching through expire headers not only enhances user experience but also reduces server load, resulting in faster and more responsive web pages. To enable expire headers, you can insert the following code into your server's configuration file, typically found in the Magento2 htaccess file for Apache servers:
ExpiresActive On ############################################ ## Add default Expires header ## http://developer.yahoo.com/performance/rules.html#expires <filesmatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$"=""> ExpiresDefault "access plus 1 year"
9. Optimizing Non-Cacheable Pages (Checkout, Cart)
While caching can significantly improve performance, certain pages in Magento 2, such as the checkout and cart pages, are non-cacheable by nature due to their dynamic content. These pages rely on real-time data and interactions, making them more challenging to optimize.
To improve the speed of these non-cacheable pages, you can focus on a few key areas:
-
Minimize server-side processing. Reduce the complexity of custom code and extensions running on these pages. Ensure your checkout process is streamlined and avoid unnecessary server calls or integrations that slow down the experience.
-
Use AJAX loading. For elements that don’t need to be loaded immediately, such as additional shipping options or promotions, consider using AJAX to load these components dynamically only when needed. This reduces the initial load time for the checkout and cart pages.
-
Optimize database queries. Ensure that the queries powering dynamic content are as efficient as possible. You can achieve this by indexing your database properly, cleaning up unused tables, and optimizing query logic.
Google Page Speed Optimizer for Magento 2 offers improvement of the speed on non-cacheable pages out-of-the-box using its built-in techniques.
10. Use “Update on Schedule”
Magento users have two options for scheduling their indexers: Update on Save or Update on Schedule. While it might seem like a small change, updating on schedule rather than on save will consume fewer resources and help your website run faster. When your indexers are set to Update on Save, specific indexes run every time you save a product, category, or attribute, which is time and resource-consuming and runs the risk of slowing down your servers.
By setting your indexers to Update on Schedule, you can have everything updated at a specific time, such as when traffic on your site is typically slow, rather than updating when more customers are using your site. To enable this Magento optimization technique, choose System > Index Management in the Admin and select all indexers. From the Actions dropdown menu, choose Update on Schedule.
11. Choose a Trusted Hosting Provider
A trustworthy hosting provider is a massive part of optimizing your Magento store. Magento has specific prerequisites to run efficiently and properly, and not every hosting provider has the features necessary to handle a Magento store. Technical requirements include Web Services, PHP, and related prerequisites to avoid slow response times and poor Magento performance.
Read More: Best Magento Hosting Providers
12. Implement Lazy Loading
Lazy Loading is an efficient technology for saving image-loading resources and enhancing page speed. With this technique, your Magento 2 site will load images only when they are needed - specifically when a user scrolls down to view them. Any elements not yet visible remain “untouched,” reducing the initial load time and bandwidth usage.
Implementing Lazy Loading ensures that unnecessary resources aren’t consumed on images that users might never view. This not only speeds up the perceived loading time but also reduces server strain. For example, using tools like Google Page Speed Optimizer, we easily applied Lazy Loading to our homepage. As a result, images like brand logos and social proof badges are loaded and displayed only when the user scrolls to their location. You can do the same for any or selected pages of your website.
13. Re-Index Your Products
Another indexing option that can optimize your Magento website is re-indexing your products. Products that aren’t properly indexed won’t appear correctly and can slow down your website. Re-indexing these products will bring scattered data into a single table, enhancing your Magento performance.
Re-indexing is a relatively simple process. Navigate to System in the main menu and select Index Management from the dropdown. You'll see a list of available indexers, where each indexer corresponds to a specific type of data in your store. Check the checkbox next to the indexers you want to re-index and then select Reindex Data from the Actions dropdown at the top right before clicking Submit.
Alternatively, you can run the following command in Magento CLI:
php bin/magento indexer:reindex
You can also set up automated re-indexing to ensure that your store's data stays up-to-date without manual intervention. You can achieve this through Magento cron jobs configured to run the re-indexing command at specified intervals.
14. Optimize Magento .htaccess
In Magento, the .htaccess file is a configuration file used on Apache web servers to control various settings for the specific directory. It is crucial for controlling URL rewriting, access restrictions, and other server-related configurations required for the proper functioning of the Magento website.
The first thing you can do to speed up Magento with .htaccess is to get rid of all the unnecessary customizations you added to the file or replace them. After that, proceed to more tasks:
- Protect your website's bandwidth by preventing other websites from directly linking to your images or files. Achieve this by adding specific directives to your .htaccess file:
# Prevent hotlinking of images RewriteEngine on RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourwebsite.com [NC] RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F]
- Secure sensitive directories and files by restricting access using appropriate directives in your .htaccess file.
<directorymatch "^var="" .*|^app="" etc="" .*"=""> Order deny,allow
This prevents unauthorized users from accessing critical parts of your website.
Deny from all - Periodically review and update your .htaccess file to ensure it remains optimized and aligned with the evolving needs of your website.
15. Minimize Your JS and CSS
Another way to achieve Magento speed optimization is to minimize your JavaScript and CSS files. There are 4 JS optimization techniques:
- Downloading each script separately
- Bundling
- Merging
- Bundling & merging
Bundling & merging is one of the most effective because all your separate JS/CSS files can be merged into a single file. This will help you with Magento performance tuning and significantly improve Magento 2 site speed. To merge files, follow these steps:
- Navigate to the Admin Panel, then select Stores > Configuration > Advanced.
- From the advanced tab, select Developer.
- Locate the JavaScript settings option, then change the values of the Merge JavaScript Files, Minify JavaScript Files, and Enable JavaScript Bundling to “Yes.”
- Under CSS settings, change the values of the Merge CSS Files and Minify CSS Files to “Yes.”
- After setting this up, click on Save Config.
If you want to take a more comprehensive approach to the task and ensure the best results, start with our free Magento Google Page Speed Optimizer. With this extension, you’ll minify HTML, CSS and JS, merge CSS and JS, move JS to the page bottom, and enable all-in-one Magento performance optimization to reduce the number of HTTP queries and their processing time.
16. Moving JS and CSS to the Footer
Another effective optimization technique for Magento 2 is moving JavaScript (JS) and CSS code to the footer of your pages. By default, JS and CSS files are often loaded in the header, which can block the rendering of other crucial page content, causing delays in page load time.
Moving these files to the footer ensures that the main content of your page, such as text and images, is loaded first. The browser can then load JS and CSS files after the user begins interacting with the page. This improves the First Contentful Paint (FCP) and reduces the perceived loading time for users. Implementing this technique can be done through Magento’s developer settings or with the help of performance optimization extensions.
To move JS and CSS to the footer in Magento 2, you can:
- Go to Stores > Configuration > Developer > JavaScript Settings.
- Enable the option to move JS files to the bottom.
- In the CSS Settings, optimize the loading sequence by reducing unused CSS and deferring non-critical styles to be loaded later.
As you might've guessed, this is also something that Google Page Speed Optimizer does for you. With this optimization step, your Magento store will prioritize content that users care about first, leading to faster load times and a better user experience.
17. Improve Magento TTFB
Magento time to first byte (TTFB) shows you how much time your Magento 2 needs to generate an HTML page. It is one of the main metrics of your Magento performance as it directly affects your position on SERP and is also the one that usually needs a professional optimization approach. To analyze the most time-consuming process and reduce your Magento 2 TTFB, you need to run a TTFB audit with a Magento profiler and perform a Magento TTFB optimization.
Step 1: TTFB Audit
To reduce server response time with the Magento 2 profiler, you can set up the profiler in one of two ways: using a command or by configuring the MAGE_PROFILER environment variable.
1. Using a Command
bin/magento dev:profiler:enable [--html] [--file]
After enabling the profiler, visit your Magento storefront or perform actions in the admin panel to trigger the profiler. Once you've captured the data you need, disable the profiler using the following command:bin/magento dev:profiler:disable
2. Using the MAGE_PROFILER
To enable the profiler, set the MAGE_PROFILER variable to "html" or "file" depending on your preference: export MAGE_PROFILER=html / =file
After setting the environment variable, trigger the profiler by visiting your Magento storefront or performing actions in the admin panel. Remember to unset the variable after you've captured the necessary profiling data to avoid unnecessary overhead on subsequent requests:unset MAGE_PROFILER
Step 2: Results and TTFB optimization
Here’s the information contained in different columns of the TTFB audit report:
- Timer ID – a unique identifier applied in the profiler function call. To identify a Timer id nested level, count the dots on the left.
- Time / Avg – time/an average time that the Timer ID needs to pass from the profiler start call to the stop call (in seconds).
- Cnt – identifies the number of times the block of code was run.
- Emalloc – memory consumed by PHP to execute the block of code (in bytes).
- RealMem – all memory taken by the system to run PHP processes. It includes unused pages as well.
Pay special attention to Time and Cnt to identify the Timer ID with the most time spent and the largest number of code running. Once you’ve defined it, inspect Magento files to understand where these blocks are placed. Also, when looking for the most time-consuming Timer IDs, pay attention to those with children, as profile entries are nested and one entry’s time includes all of its children’s.
18. Optimize PHP Server Configuration
Your Magento performance depends not only on the version but also on the PHP configuration of the domain. Adjust server parameters such as memory_limit, max_execution_time, and upload_max_filesize or switch off the session.auto_start or mods. To do this, add the next patch of code in your .htaccess file :
php_value memory_limit 2GB
php_value max_execution_time 18000
php_flag magic_quotes_gpc off
php_flag session.auto_start off
php_flag suhosin.session.cryptua off
php_flag zend.ze1_compatibility_mode Off
If you run Magento 2, don’t forget about OPcache, which is bundled with PHP 5.5.0 and later. The module uses shared memory to keep precompiled script bytecode and speed up your website loading. Learn why and how to use OPcache from our partner’s blog post.
19. Enable gZip Compression
Magento gZip htaccess compression allows you to optimize the web pages and stylesheets before sending them to end-users. You can still easily restore the original data by unzipping the files you compressed.
To enable gZip compression, add this code to your Magento gZip .htaccess file:
# 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
# Remove browser bugs (only needed for really old browsers)
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
Additional 2 Solutions: Magento Speed Optimization Services and Extensions
Apart from the available optimization options from above, you have 2 additional solutions that involve financial investments.
Request Magento Speed Optimization Services
There are numerous optimization services available that can help you speed up your Magento e-commerce store. Amasty’s Magento Speed Optimization Services provide all-inclusive optimization processes, including:
- Magento performance audit
- Caching configuration
- Media compression
- Magento database and server optimization
- Code optimization
- Theme and style optimization
- Third-party Magento extension optimization
- SEO services and a UI/UX audit
You can not delegate most of these general speed optimization best practices to the ready-made solution and need to either hire an in-house specialist or outsource the task to a proficient team.
- Service can fix all the problems affecting Magento performance. You are not limited to any parameters of speed optimization.
- No need for deep technical knowledge. If you don’t know how to use extensions, it may be easier to entrust the whole process to professionals.
- High price. Services are usually quite expensive compared to extensions.
- Site maintenance is still on you. Although the service includes a 2-month warranty on all customizations made, you still need to check your website later.
Rely on A Magento Speed Optimization Extension
The main idea of using a performance optimization extension is to speed up your store with minimal manual and maximum automated efforts. For example, with such a tool you don’t need to manually convert all your images to the WebP and shrink them to fit different devices. The extension also handles CSS/JS file minimization and lazy load setup.
- Customizable. You can customize the extension to suit your needs.
- Low price. If you get the extension, advanced support subscription, and training service, you will have the extension installed and configured on your Magento.
- Built-in diagnostic. Our plugin comes with a built-in diagnostic tool that will help you monitor your website performance without any external help.
- The extension deals only with the main issues. It can not solve problems with, for example, your server capacity or other issues affecting your Magento speed.
Magento Extension vs. Magento Optimization Services: How to Choose
The 2 options we've just explained have a huge difference in price and impact on your website. Let’s consider their best cases and try to understand when it is better to use the service and the module.
When to Go for a Magento Speed Plugin
To understand if the extension is enough to help you with speed optimization, you can go to Google PageSpeed Insights and test your website. You will get a list of parameters that Google recommends you to tune for better speed and SEO performance. Google Page Speed Optimizer can address the following warnings:
- Optimize images automatically.
- Minify HTML, CSS, JS, and merge CSS and JS.
- Save and index order data asynchronously.
- Sign static files to make your customers see the freshest version of your styles.
- Move JS to the footer.
- Enable lazy load to save resources on loading off-screen images.
From our experience, these issues are the most common among new websites and stores with little to no customizations.
When to Go for a Magento Performance Service?
An optimization service is usually more suitable for larger stores, websites with a lot of customizations, and sites that need improvements on the server side, like the caching settings. Here are the typical warnings from the Google PageSpeed Insights report that can be solved as a part of the optimization service:
- Reduce initial server response time
- Remove unused CSS
- Enable text compression
- Use video formats for animated content
- Preload key requests
- Preconnect to required origins
- Avoids an excessive DOM size
- Eliminate render-blocking resources
Most of these warnings require a lot of manual work and custom development.
Summing Up: Key Magento Performance Optimization Tips
Here's what we've discussed in the article and what you can do to accelerate the speed of your Magento:
- Enable browser, full-page, and Varnish caching.
- Optimize and compress images, implementing their lazy load.
- Delete unused data and minify CSS/JavaScript files.
- Leverage HTTP/2, use a reliable hosting provider, and set up a robust content delivery network (CDN) to deliver static assets faster.
- Optimize .htaccess file, PHP server configuration, and indexing settings.
- Consider benefiting from professional Magento performance optimization services or extensions.
Amasty provides advanced Magento services and solutions to ensure your Magento store runs smoothly! Check out our success stories of speeding up our own extension and a home decor website, achieving under 1-second load speed.