Optimizing Magento Server Performance: Best Practices

Optimizing Magento Server Performance: Best Practices. The Magento server plays a crucial role in hosting your ecommerce store. By hosting the Magento application, it performs a wide range of tasks such as processing incoming requests from users, returning appropriate responses, storing and managing the application’s essential files and databases, and more. Basically, the Magento server is the backbone upon which the ecommerce store runs. 

Therefore, it’s crucial to optimize server performance, especially if you have huge traffic or during peak traffic times. A well optimized server handles traffic seamlessly and provide consistency and reliability to users. An optimized Magento server also efficiently handles spikes in traffic during peak shopping times without slowing down.

This article discusses Optimizing Magento Server Performance: Best Practices. Read on!

1. Enable Full Page Cache (FPC)

Full Page Cache is a cache management system in Magento that enhances the retrieval speed of your static pages. By enabling full page caching, you reduce the time it takes the server to render templates. This ultimately reduces the customer’s waiting time, as they read pages generated from the cache. FPC stores a snapshot of each page on the first visit, which is then served to subsequent users, saving on processing time.

Full Page Cache uses multiple caching techniques, including block caching, full page caching, and hole punching. Block caching caches specific elements within a page, while hole punching excludes dynamic content from the cache. All these techniques ensure proper handling of dynamic and personalized content.

There are three ways to enable Full Page Cache in Magento:

Configuring Full Page Cache via Magento Admin

To enable Full Page Cache in Magento, Login to your Magento Admin Panel. Navigate to Stores > Configuration. Under Advanced, select System. Expand the Full Page Cache section. Choose a Caching Application:

  • Built-in Application: Use Magento’s internal caching.
  • Varnish Caching: Use Varnish as the caching application.

For TTL for public content, set the desired time-out. Default is 86400 seconds. If using Varnish:

  • Set Access list with IPs separated by ‘,’.
  • Provide Backend host (default is localhost).
  • Set Backend port (typically 8080).
  • Click the Export VCL button for your Varnish version.

Click Save Config.

Config Full Page Cache via Command Line

To enable Full Page Cache in Magento via the command line, enter the following commands:

To enable cache:

				
					php bin/magento cache:enable
				
			

To disable cache:

				
					php bin/magento cache:disable
				
			

To flush the cache:

				
					php bin/magento cache:flush
				
			

To clean the cache:

				
					php bin/magento cache:clean
				
			

Through the above steps you are able to efficiently manage and optimize the Full Page Cache functionality and achieve optimal server performance and faster page load times.

2. Implement Advanced JavaScript Bundling

JavaScript bundling is a performance optimization technique that reduces the number of HTTP requests needed to load a page. It works by combining multiple JS files to reduce the number of server requests. Merging multiple Javascript files into one file forms bundles. Instead of loading lots of Javascript files for each page, the browser loads a few bundles.

Here is a step by step guide on how to implement Javascript bundling:

  • In developer mode, go to Stores > Configuration > Advanced > Developer > JS Settings and enable Minify JavaScript Files. Also, ensure you have the Magefan Rocket Javascript extension installed.
  • Compile a list of these crucial files from different pages using browser console commands. Inspect your homepage and run the provided script in the console to get a list of JavaScript files used. Repeat this process for different pages and compile common files.
  • Navigate to Stores > Configuration > Magefan Extensions > Rocket Javascript and enable JavaScript Bundling Optimization
  • Activate Magento JS Bundling: Return to Stores > Configuration > Advanced > Developer > JS Settings to enable both JavaScript Bundling and Merge JavaScript Files. Lastly, switch back to production mode.

3. Utilize Redis for Session Storage and Cache Backend

Redis is a key value store that stores data in memory and to provide fast read and write speeds. Using Redis for session storage and as a cache backend significantly improves your Magento store’s performance.

Redis improves performance by loading content from cache.to ensure faster webpage loading. Also, it caches database query results and uses this cached data for subsequent requests, reducing the need for actual database queries. With Redis, your Magento server becomes more efficient, as it minimizes memory usage through tag-based cache cleanup support. Also, it improves persistence and replication as it supports on disk save and master/slave replication.

Here is a step by step guide on how to implement Redis caching in Magento:

Step by Step Guide to Caching Magento Server with Redis

First, ensure that Redis is installed on your Magento server. Also, ensure this PHP Redis extension is installed.

Configure Redis default caching with this command:

				
					bin/magento setup:config:set --cache-backend=redis --cache-backend-redis-server=127.0.0.1 --cache-backend-redis-db=0
				
			

The –cache-backend=redis option enables Redis default caching while the –cache-backend-redis-server=127.0.0.1 option indicates that Redis is installed on the Magento server itself. The –cache-backend-redis-db=0 option sets the database number for default caching.

Configure Redis page caching with the command:

				
					bin/magento setup:config:set --page-cache=redis --page-cache-redis-server=127.0.0.1 --page-cache-redis-db=1
				
			

The –page-cache=redis option enables Redis page caching while the –page-cache-redis-server=127.0.0.1 option indicates that Redis is installed on the Magento server. Similarly, the –page-cache-redis-db=1 option sets the database number for page caching

Finally, configure Redis for session storage with this command:

				
					bin/magento setup:config:set --session-save=redis --session-save-redis-host=127.0.0.1 --session-save-redis-db=2
				
			

–session-save=redis enables Redis for session storage, –session-save-redis-host=127.0.0.1 specifies the Redis server.
–session-save-redis-db=2 sets the database number for session storage.

After running the above commands, Magento updates your <Magento-install-dir>app/etc/env.php file. Check this file to confirm that the Redis configurations have been correctly updated. It should reflect the Redis configurations for cache and session storage as given in the commands. The new file would look something like:

				
					 [
        'frontName' =&gt; 'admin'
    ],
    'db' =&gt; [
        'table_prefix' =&gt; '',
        'connection' =&gt; [
            'default' =&gt; [
                'host' =&gt; 'localhost',
                'dbname' =&gt; 'magento_db',
                'username' =&gt; 'magento_user',
                'password' =&gt; 'password',
                'active' =&gt; '1'
            ]
        ]
    ],
    'crypt' =&gt; [
        'key' =&gt; 'your_encryption_key'
    ],
    'cache' =&gt; [
        'frontend' =&gt; [
            'default' =&gt; [
                'backend' =&gt; 'Magento\\Framework\\Cache\\Backend\\Redis',
                'backend_options' =&gt; [
                    'server' =&gt; '127.0.0.1',
                    'port' =&gt; '6379',
                    'database' =&gt; '0'
                ],
            ],
            'page_cache' =&gt; [
                'backend' =&gt; 'Magento\\Framework\\Cache\\Backend\\Redis',
                'backend_options' =&gt; [
                    'server' =&gt; '127.0.0.1',
                    'port' =&gt; '6379',
                    'database' =&gt; '1',
                    'compress_data' =&gt; '0'
                ]
            ]
        ]
    ],
    'session' =&gt; [
        'save' =&gt; 'redis',
        'redis' =&gt; [
            'host' =&gt; '127.0.0.1',
            'port' =&gt; '6379',
            'password' =&gt; '',
            'timeout' =&gt; '2.5',
            'persistent_identifier' =&gt; '',
            'database' =&gt; '2',
            'compression_threshold' =&gt; '2048',
            'compression_library' =&gt; 'gzip',
            'log_level' =&gt; '1',
            'max_concurrency' =&gt; '6',
            'break_after_frontend' =&gt; '5',
            'break_after_adminhtml' =&gt; '30',
            'first_lifetime' =&gt; '600',
            'bot_first_lifetime' =&gt; '60',
            'bot_lifetime' =&gt; '7200',
            'disable_locking' =&gt; '0',
            'min_lifetime' =&gt; '60',
            'max_lifetime' =&gt; '2592000'
        ]
    ],
    // ... other configurations
];

				
			

4. Clean Database Logs

As an ecommerce platform, Magento generates a significant amount of log data over time. They trace the user activity, and errors. But logs also contribute to a few performance issues. Large log tables consume more storage, potentially leading to disk space shortages. Also, larger tables slow down database queries, impacting the overall performance of the Magento application.

Here are some of the tables with logs to clear:

  • dataflow_batch_export
  • dataflow_batch_import
  • log_customer
  • index_eventlog_quote
  • log_summary
  • report_event
  • log_summary_type
  • log_url
  • log_url_info
  • report_compared_product_index
  • log_visitor;
  • log_visitor_info
  • report_viewed_product_index
  • log_visitor_online

For regular database log clearing automate the clean up process. However, Magento does not provide built-in cron jobs for log cleanup. Therefore, consider creating custom cron jobs or scheduled tasks at the server level to automate this process. Remember to backup your database before performing any clean up tasks to avoid data loss.

5. Optimize Images

Your store needs visual images for user interaction and to showcase products. But they need to be optimized images by being compressed without loosing on quality. Use tools like Optimizilla, WebP, JPEGmini, and TinyPNG

Besides compression implement responsive images. This ensures that images are served in appropriate sizes based on the user’s device. This practice improves loading times but also enhances the user experience for mobile visitors.

Employ lazy loading for images. In this case, images are loaded only as users scroll down the page, reducing the initial load time. However, ensure that lazy loading does not negatively impact the user experience.

6. Enable Flat Catalog

The Magento server has a default database model known as EAV (Entity-Attribute-Value). While EAV is flexible, it often leads to complex and long SQL queries, which slows down the site. To avoid them switch to the flat catalog. 

The flat catalog is a Magento server feature creates tables on the fly. It merges product data into one table, improving the performance of your Magento store. Basically, it takes all product attributes and stores them in a multicolumn table. This table updates automatically depending on your cron job settings. The flat catalog improves cart speed significantly, improving overall Magento performance.

How to enable the flat catalog feature within the Magento admin panel. 

  • Log into the admin panel, navigate to Stores > Settings > Configuration.
  • Under Catalog, select Catalog. Open the Storefront section, and choose Yes in the Use Flat Catalog Category field. Also, choose Yes in the Use Flat Catalog Product field and click Save Config.

Also ensure to re-index the data to reflect the updated data structure. And monitor your store’s performance after implementing the flat catalog.

7. Optimize the Database

Whether you are using MySQL, MariaDB, or Percona, you must ensure your Magento database handles queries efficiently. Therefore regularly clean and optimize your Magento database server.  This includes removing outdated or unnecessary data and improving memory and processing power. There are various ways to optimize the Magento database:

  • Update the database version
  • Add indexes to large tables
  • Use Elasticsearch for layered navigation
  • Optimize queries
  • Implement table fragmentation

Besides optimizing the database itself also implement database management tools to help you with efficient management. 

8. Enable GZIP Compression

GZIP compression is a server feature that enables users to compress large files, thus ensuring faster load times. Ideally, when a user visits a site, GZIP compresses requested files before they are sent to the browser. This minimizes delay caused by large file sizes, hence improving user experience.

To enable GZIP compression, ensure that Apache’s mod_deflate is enabled. Then, find the open .htaccess file in the root directory of your Magento server and add this code:

To test GZIP compression functionality use tools like GtMetrix. Alternatively, use curl –compressed to inspect the response headers for accepted encoding formats. Adjust and test different settings to find the optimal compression level that provides faster loading times without compromising performance.

9. Adjust Cron Jobs Settings

Cron jobs are scheduled tasks that run automatically via configuration scripts. They relieve admins from tedious manual processes and help with tasks such as re-indexing, catalog price rules, and more. Optimizing these jobs helps prevent server overload and improves overall Magento performance.

To automate tasks, you need to configure cron jobs properly. Configure cron jobs carefully to avoid overlapping or having concurrent running tasks that could strain server resources. Also, you should stagger cron jobs effectively to ensure smooth, uninterrupted performance.

Adjust Cron Jobs

To adjust Cron Jobs settings in Magento, follow the following steps:

  • Login to the Magento Admin Panel and navigate to Stores > Settings > Configuration. On the left sidebar, under the Advanced section, click on System.
  • Scroll down and find the Cron (Scheduled Tasks) section. Here, you configure cron jobs for: General Cron configuration, Indexer Cron configuration, and Default tasks configuration.
  • Expand the required section and make the necessary adjustments. Then click Save Config.

Afterwards, test cron jobs after adjusting them to ensure they work as expected. .

10. Utilize FastCGI

FastCGI is a protocol used to improve web server performance when serving content generated by applications written in various programming languages. In the Magento server utilize FastCGI to efficiently handle PHP requests. FastCGI maintains persistent process pools to handle PHP scripts. This way, it reduces the overhead associated with repeatedly starting and stopping PHP processes. This results in quicker responses.

Configure FastCGI settings properly to balance performance and resource usage. Incorrect configurations lead to server resource wastage or even create performance bottlenecks.

With PHP Process Manager (PHP-PFM), you significantly improve Magento performance. PHP-FPM is a FastCGI Process Manager that that enables you to execute scripts with a single thread. How to set up Magento with FastCGI and PHP-FPM:

Firstly you need an active Magento installation and a server running Nginx or Apache with mod_fastcgi. Then, install PHP-PFM:

				
					sudo apt-get update
sudo apt-get install php-fpm
				
			

Edit the PHP-FPM configuration file. The exact location might vary, but common paths include /etc/php/7.x/fpm/pool.d/www.conf or /etc/php-fpm.d/www.conf. Edit the following lines as per your needs (the following values are a good starting point):

				
					listen = /var/run/php/php7.x-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
				
			

Make sure you replace 7.x with your actual PHP version. In your Magento Nginx configuration file, include the following:

				
					location ~ \.php$ {
    try_files $uri =404;
    fastcgi_pass unix:/var/run/php/php7.x-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}
				
			

 For Apache, ensure you have mod_fastcgi installed and enabled and add the following code to your Magento .htaccess configuration file:

				
					
    SetHandler "proxy:unix:/var/run/php/php7.x-fpm.sock|fcgi://localhost"

				
			

Then, restart PHP-FPM and your web servers for the changes to take effect. Once done, your Magento runs on FastCGI through PHP-FPM, which provides a more scalability and better performance.

Thank you for following Optimizing Magento Server Performance: Best Practices to the end. 

Optimizing Magento Server Performance: Best Practices Conclusion

Running a high performance Magento server is mandatory for any e-commerce business that aims to provide an outstanding user experience and high availability. Since servers degrade performance over time, it’s essential to implement performance best practices to maintain fast loading times, user experience, and SEO rankings. The above practices help to optimize your server and increase your store’s loading times.

Avatar for Dennis Muvaa
Dennis Muvaa

Dennis is an expert content writer and SEO strategist in cloud technologies such as AWS, Azure, and GCP. He's also experienced in cybersecurity, big data, and AI.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x