Magento Cache Management: Cache Types, Backend Options, and Setup Tips

Table of Content

Magento cache explained: a guide for store owners

Magento caching is a key mechanism for optimizing website performance and ensuring swift access to your store content. To help you rid your customer of the long loading times,  Magento 2 offers a range of cache management techniques. 

In this article, we explore the peculiarities of Magento cache types, backend store options (including Redis and Varnish), as well as tools for Magento cache management.  

What is Magento Cache?

Magento caching is the temporary storage of data that helps raise Magento store loading speed and enhance overall website performance. Cache stores frequently accessed information such as page elements, database queries, and other resources. When these elements are cached, Magento can serve them quickly to users upon request, reducing server load and improving site responsiveness

Magento 2 Cache Types 

Magento supports various cache types, each serving specific purposes in optimizing the platform's performance. Here are some of the main Magento 2 cache types:

  • Configuration Cache – Stores merged configuration data from XML files, improving the performance of configuration data load.
  • PHP Opcode Cache – Stores compiled PHP code, known as opcodes, to reduce the time needed for PHP interpretation and execution.
  • Database Query Cache – Caches database queries to reduce the load on the database server by serving cached query results.
  • Full Page Cache (FPC) – Caches the entire HTML of a page, including dynamic blocks, and serves it to subsequent visitors without generating it again.
  • Page Cache – Caches individual blocks of content, such as product lists, navigation menus, and other components of a page.
  • Browser cache – Information about your website that can be stored in a user's browser.

Now, let’s explore each type in more detail.

Configuration Cache

The Configuration Cache in Magento stores processed configurations, layouts, HTML blocks, and similar data. It stops repeating tasks, as long as nothing changes to affect these stored items.

It's best to use this type for Magento cache management in all scenarios except for staging projects or developer environments. There, its use can let irrelevant cached content affect development work.

Database Query Cache

Magento 2 stores frequently used database queries in a cache to reduce the load on the database server. This means it can quickly serve up cached results when needed, boosting performance, especially for apps that prioritize reading data. 

Tip: It's often recommended to increase the size of the database query cache but in Amasty’s experience, this is a bad practice. Increasing the size of the database cache does not align with the architecture of many modern servers.

Allocating more resources to the database cache can lead to inefficient use of memory or processing power and potentially slow down database performance instead of enhancing it.

PHP Opcode Cache

We have already mentioned this Magento cache type in one of our previous articles. PHP opcode cache enables you to decrease the time required by the PHP interpreter to conduct file searches, reading, and conversion to opcode, which is then executed directly by the PHP interpreter. Currently, the most commonly utilized tools include APC, Xcache, Zend Opcache, and eAccelerator.  

One crucial aspect to remember is to flush the opcode cache after modifying the server code. You can achieve this by simply rebooting the Apache web server (if mod_php is utilized) or via the Fast CGI manager. To manage APC, use the apc.php script provided in the APC distribution kit.

There are also scenarios where the application of the PHP opcode cache is ineffective. For example, when using SPHP, CGI or CLI. Why? Opcode cache generation occurs upon startup, but in these modes, the interpreter terminates the task after processing the query, resulting in the loss of cache state.

Full Page Cache (FPC)

One of the most critical caching mechanisms in Magento 2 is the Full Page Cache (FPC). FPC stores the entire HTML content of a page, including dynamic blocks, and delivers it to returning visitors without regenerating it. This caching mechanism significantly reduces query processing time to several dozen milliseconds, enhancing the overall performance of the website.

FPC is particularly beneficial for e-commerce websites with high traffic volumes and frequent page requests. It helps alleviate the strain on server resources by serving cached content to multiple users simultaneously and improves the site's performance under heavy loads.

Tip: While FPC optimizes the delivery of cached content, it does not directly speed up the server connection process. FPC also may face challenges with dynamic content, such as the shopping cart page needing updates when items are added or deleted, and the 'recently viewed' block adjusting as users navigate the shop.

To avoid this, leverage tools that insert special markers into HTML code, which are later replaced by appropriate dynamic block content.

Can FPC Speed Up Your Website?

If you want to see the difference that can be brought to your store by FPC, you need to measure the ‘time to first byte’ for your pages. Use webpagetest.org for that. Go to the tool, enter your page URL, choose the Test Location, and choose the Native Connection (No Traffic Shaping) variant for the Connection option. If your site is secured by HTTP authorization, go to the Auth tab and fill in the necessary info. Now, press START TEST.  After the test has been completed, you’ll see the results page.

To find the 'time to first-byte' number, check the Waterfall section for the First View in your testing tool. Look for the request that generates the page's HTML code. In our example, it's usually the first request shown. However, it might differ due to redirects like example.com → www.example.com.

TTFB for FPC Magento CacheIn our analysis, we see the full request time is 135 milliseconds, with 'time to first byte' at 89 milliseconds. The whole page loads in 1.212 seconds. Let's imagine if Full Page Caching (FPC) can make 'time to first byte' just 14 milliseconds, it would cut processing time by 75 milliseconds. This speeds up request handling, but overall page loading might improve by only around 7%.

Page Cache

While Full Page Cache specifically targets caching entire pages, Page Cache encompasses a broader spectrum by caching individual page components, blocks, or elements. By caching these individual components, Page Cache enhances the performance of Magento by reducing the need to regenerate or re-render these elements for each user request. This results in faster page load times and improved overall responsiveness of the application.

One significant advantage of Page Cache is its ability to intelligently cache dynamic content. While static content can be easily cached using traditional caching mechanisms, dynamic content requires a more nuanced approach. Page Cache intelligently identifies which components of a page are dynamic and need to be regenerated for each request, while caching the static elements to improve performance.

Browser Caching

Magento browser caching involves instructing web browsers to store certain pages or resources locally on a user's device for a specified time. This helps to reduce page load times for returning visitors by allowing the browser to retrieve cached resources instead of requesting them from the server again. Commonly cached resources include images, CSS files, JavaScript files, and other static assets.

When browser caching is leveraged effectively, Magento websites can improve performance and user experience, particularly for users who frequently visit the site or navigate between pages. 

Tip: Make sure to configure Magento browser caching policies carefully. To avoid showing outdated or irrelevant content to your visitors, balance performance benefits with the confidence in providing the latest version of your dynamic content.

Backend Options for Magento 2 Cache Management

In Magento 2, a cache backend is the storage mechanism used to store and retrieve cached data. It plays a crucial role in optimizing the performance of your online store. There are various backend options available, each with its advantages and considerations.

In this section, we'll delve into three popular backend options for Magento 2 cache management: File system, Redis, and Varnish.

Magento File System

Here, the cached data is stored in files on a disk along with your Magento installation. You can find them on a server in the magento_installation_folder/var/cache/ and magento_installation_folder/var/page_cache/ folders. The load speed depends on the disk reading/writing speed, so a proper file system and SSD storage can improve the results.

Pros:

  • This solution is readily available without the need for complex Magento 2 cache configuration or setup.
  • Cache flushing can be achieved solely with server access details by deleting all files from the var/cache/ and var/page_cache/ directories. No need to log into the Admin Panel.

Cons:

  • Disk reading/writing speed typically lags behind that of database or RAM operations.
  • On shared servers or servers hosting multiple stores, there's a risk of running out of inodes. Many hosting providers impose inode limits, restricting the creation or uploading of new files even if disk space is available.

Read More: Best Magento Hosting Providers

Redis for Magento 2

Redis stores cached page content in server memory. When a query is executed for the first time, its results are stored in Redis cache along with a unique identifier. Later executions of the same query can retrieve the results directly from the cache without accessing the database again, which leads to faster response times.

Magento Redis Pros:

  • Memory reading and writing speeds outperform those of disk or database operations.
  • Cached data is efficiently managed using cache tags and inner indexation, reducing the time needed to retrieve requested information.
  • The cache storage can be hosted on a separate server, preventing resource sharing with Magento. It offers vertical scalability to accommodate increased requests and data storage, as well as horizontal scalability to serve multiple replicated Magento installations on separate servers.
  • Configuration allows for cached data replication on other servers, ensuring data availability in case of connection loss with the main storage, known as Master/Slave replication for Magento.

Magento Redis Cons:

  • Cached data size is limited by the server RAM due to its reliance on server memory. Consider employing a separate server with adequate RAM for Redis cache storage.

While Redis can be used for caching pages or fragments of pages, it's more commonly used for caching data such as database query results, session data, or frequently accessed application data.

Varnish for Magento 2

Like Redis, Varnish cache stores cached data in server memory but operates by caching web server responses. Working alongside integration modules like Nexcess Turpentine, Varnish efficiently handles queries when dynamic blocks don't require updates, reducing the load on Magento. When dynamic blocks need updating, Varnish communicates with Magento to retrieve content or employs AJAX code to fetch required content from the browser's side. 

Varnish Pros:

  • Visitor requests to site pages bypass the web server and Magento, leading to swift retrieval of cached content when coupled with server memory usage.
  • Native support in Magento 2 removes the need for third-party extensions.
  • Varnish is highly efficient in handling high volumes of traffic, ensuring consistent performance even during peak periods.
  • Can be integrated with load balancers to distribute incoming traffic across multiple backend servers. 

Varnish Cons:

  • Varnish does not support HTTPS (SSL protocol) directly. A workaround involves configuring an SSL terminator or proxy to decrypt HTTPS traffic before reaching Varnish and encrypting the response.
  • Manual removal of all files from the var/cache folder requires restarting the Varnish service. 

Varnish is specifically designed for HTTP caching and is often employed as a full-page caching tool. Given its memory-intensive nature, you may need to opt for adequate server memory or relocate Varnish to a separate server. 

How to Enable or Disable Magento 2 Cache

Magento System Cache

To enable or disable the Magento configuration cache, navigate to the Admin Panel. From there, proceed to System > Cache Management. You'll see a list of cache types, look for the "File System" cache.

  • To enable the file system cache, select the checkbox next to "File System" and then click on the "Enable" button above the list of cache types.
  • To disable the file system cache, deselect the checkbox next to "File System" and then click on the "Disable" button above the list of cache types.

Redis Magento Caching

To enable or disable Redis cache in Magento 2, access the Admin Panel and navigate to Stores > Configuration > Advanced > System > Full Page Cache. From there, select "Redis" as the cache type and configure the necessary settings. 

Varnish Magento Caching

To enable or disable Varnish cache in Magento 2, access the Admin Panel and navigate to Stores > Configuration > Advanced > System > Full Page Cache. From there, select "Varnish" as the cache type and configure the necessary settings.  However, to achieve optimal configuration, you need specific skills and knowledge.

Browser Caching for NGINX

Step 1: Log in to the server via SSH to implement your Magento browser caching in NGINX. Then issue the following command: :

cd /etc/nginx/sites-available

nano YOUR_SITE.conf

Step 2: Paste the next code into the server block:

Step 3: Save the changes and exit. Then reload the NGINX configuration with the following command: service nginx reload

Step 4: Make sure that everything is ok by reloading the front end.

Also, you can customize these settings. In the example, we have a general seven-day cache for all assets. But you can set any other time or leave only some types of assets:

Browser Caching for Apache

You can add browser caching to your Magento 2 website with .htaccess in two different ways: via mod_expires or mod_headers. You need to set the date when the cache should be updated.

  1. Place this code in the .htaccess file, located in your public_html folder. Edit this file and save it.

With this code, your Magento store will update the information about your .jpg, .jpeg, .gif, and .png files every year, while .pdf and .js files will update monthly. You can change these settings and customize them to your store.

  1. If you have a shared server and no access to Mod_Expires, you can use Mod_headers to leverage browser caching. Please, apply this code:

How to Check Magento Cache Status

To check the cache status in Magento 2, you can use either the command line interface (CLI) or the Magento Admin Panel. Here are the steps for both methods:

Using Command Line Interface (CLI)

  1. Use SSH to access your server's command line interface.
  2. Use the cd command to navigate to your Magento 2 root directory.
  3. Run the cache status command: bin/magento cache:status.

This command will display the status of all cache types in your Magento 2 installation, including whether they are enabled or disabled.

Using Magento Admin Panel

  1. Enter your credentials to access the Admin Panel.
  2. Go to System > Tools > Cache Management.
  3. On the Cache Management page, you will see a list of cache types along with their statuses (Enabled or Disabled). You can also see when each cache was last refreshed.
  4. You can even refresh the cache by selecting the cache types and clicking on the "Refresh" button at the top right corner.

Using DevTools (Browser Caching)

To check if you already use browser cache in Google Chrome, follow these steps:

  1. Open your browser and go to your website, then press F12 (or Fn+F12 for laptops). Chrome DevTools will open on the right side of the page.
  2. Choose the Network tab and reload the page.
  3. Now you need to choose JS/CSS/jpg/jpeg/png/gif file. You will see a Response Headers section in the tab Headers.
  4. If you see the setting of a maximal age in the cache-control line and the expires line, this file will be stored in the cache.
  5. Alternatively, you can see the max-age line – the maximum amount of time in seconds that the cache can be used again from the last visit. For example, “max-age=315360000” indicates that the website advises remaining this JS file in a browser cache for the next 10 years. In that case, you need to review the browser caching setup.

Tools for Cache Management in Magento 2

If you are looking for a simple and effective Magento 2 cache management solution, we offer a package of 3 powerful extensions. Install them together or choose only one – and enjoy a speedy website, lucrative for both search engines and your users.

Full Page Cache Warmer

Cache warming is a proactive approach where site pages are pre-crawled to ensure they're cached. Amasty's Full Page Cache Warmer for Magento 2 extension simplifies this process by generating a queue of URLs and systematically visiting each of them. 

This tool will timely cache all the necessary pages and auto-update after changes. With its help, you can:

  • Prioritize pages for warming.
  • Generate queues based on customers' activities.
  • Specify the queue generation source.
  • Exclude pages.
  • Schedule a specific time for warming.

When genuine visitors arrive, they won't endure the delay of Magento generating pages from scratch. Instead, they'll enjoy swift loading from cached versions previously visited by our module. 

Back-Forward Cache

Back/forward cache (bfcache) enhances website performance and user experience by caching recently viewed pages for instant navigation. With Back/Forward Cache, previously loaded pages are stored in memory, enabling instant display without server requests, reducing server load. Amasty's Back/Forward Cache for Magento 2 extension brings this feature to your store and enables:

  • Automatic page caching to boost loading speed.
  • Page exclusion, ensuring dynamic pages like Shopping Cart or Checkout remain responsive.
  • Improved Core Web Vitals, including Largest Contentful Paint (LCP), First Input Delay (FID), and Cumulative Layout Shift (CLS), for better scores on Google PageSpeed Insights.
  • Compatibility with major browsers, including Chrome, Firefox, and Safari, across desktop and mobile platforms.

Google Page Speed Optimizer

This extension provides an overall optimization of your Magento performance. Its features include:

  • Image optimization to automatically decrease the size of all JPEG, PNG, and GIF images without losing the quality.
  • Minification of HTML, CSS, JS, and merging of CSS/JS files for even faster cache downloading.
  • Static file signature to always display the current version of your website design.
  • Flat tables to shorten the query in the database.
  • Asynchronous indexing to prevent conflicts between different operations.

Optimize your Magento 2 store with Back/Forward Cache to provide users with a seamless browsing experience and improve site performance.

These extensions work perfectly as standalone solutions but when together, they complement each other and help you reach effective Magento caching and high loading speed.

March 12, 2015
April 17, 2015
February 9, 2015
Comments
Alessandro
April 17, 2015
Thanks for this interesting article on an important topic. You mention Varnish as an example of server-side FPC. Is everything valid for Nginx too? About opcode caching, you mention CGI mode as possible source of problems. Is this valid also for FastCGI mode? Lastly, about Mysql query cache, you mention problems with multicore. Do you mean only hardware multicore, with physical CPUs, or also software multicore? Because all cloud servers are multicore by design, and you need quite a few cores to 'satisfy' Magento. So the query cache would become problematic in almost any cloud installation of Magento.
Reply
Ksenia Dobreva
April 22, 2015
Thanks for your questions, Alessandro! >You mention Varnish as an example of server-side FPC. Is everything valid for Nginx too? Nginx can perform caching in theory (if that's possible) but we have never met server-side caching for Magento and nginx so far. >About opcode caching, you mention CGI mode as possible source of problems. Is this valid also for FastCGI mode? Not exactly. Unlike with cgi, fastcgi runs several php processes which can work for a pretty long period of time and use opcache advantage. >Lastly, about Mysql query cache, you mention problems with multicore. Do you mean only hardware multicore, with physical CPUs, or also software multicore? Because all cloud servers are multicore by design, and you need quite a few cores to ‘satisfy’ Magento. So the query cache would become problematic in almost any cloud installation of Magento. In fact there is no difference in talking about a virtual or a physical multicore here. We are not saying that query cache is always bad, too. There are scenarios when it can be of help, but to state that it's always needed to test a specific installation. In fact, here we draw attention to this: turning query cache on _may_ limit performance of a powerful server. Hope that helps.
Alessandro
April 26, 2015
Thanks Ksenia. I cited Nginx as a FPC alternative to Varnish because it is included in Plesk, so we usually set it up with a few clicks and we're done, rather than taking the time and effort to install an additional component.
Ksenia Dobreva
April 27, 2015
Thanks for sharing your experience, Alessandro!
Leave your comment

Your email address will not be published

This blog was created with Amasty Blog Pro

This blog was created with Amasty Blog Pro