Setting Up Custom Page Cache Magento 2 Tags in 4 Steps

Setting Up Custom Page Cache Magento 2 Tags in 4 Steps

Looking to improve your Magento 2 store's performance? Page cache Magento 2 aids with lightning-fast load times and improved user experience.

This article will cover everything about configuring, optimizing, and troubleshooting Magento 2 custom caching.

Best Magento Hosting now

Key Takeaways

  • Custom cache tags in Magento 2 give better cache control.

  • Built-in cache, Varnish, and Redis improve page load speeds.

  • Custom cache tags help clear specific data without full cache clearing.

  • Magento 2 cache management boosts store efficiency.

  • Full Page Cache reduces server load and improves user experience.

  • Varnish and Redis are ideal for high-traffic Magento stores.

  • Troubleshooting cache issues keeps your store running smoothly.

Magento 2 Built-in Cache vs. Varnish Cache vs. Redis Cache

Cache Type Built-in Magento 2 Cache Varnish Cache Redis Cache
Definition Magento 2's internal system stores a cached version of pages. External HTTP accelerator caching is for both static and dynamic content. In-memory data structure store. It caches pages and objects.
Configuration Enabled by default in Magento 2 settings. No external setup is required. Requires configuration through the Magento admin panel and server. Needs manual setup in Magento 2 and Redis server configuration.
How it Works Stores a cached page version every time it loads. Pages are served directly from the cache. No need to regenerate content. Acts as a reverse proxy. Caches HTTP responses and serves content without hitting the server. Caches page content and object data. Ideal for session storage and full-page caching.
Best Use Case Small to medium stores need simple caching with no extra setup. Larger stores with high traffic. Reduces load times and server strain. Ideal for fast session and object caching. Suited for enterprise-level sites.
Performance Impact Speeds up load times slightly. Server resources may become a bottleneck. Reduces server load significantly. Improves load times under heavy traffic. Provides fast read/write operations. Reduces I/O wait times.
Scalability Limited to server resources. Slows with increased traffic. Highly scalable. Handles many requests simultaneously during heavy traffic. Scales easily. Perfect for handling large data sets and high transaction volumes.
Cache Tags Tags help invalidate cache types when changes happen in the store. Uses cache tags to purge the expired cache. Improves content freshness. Handles object-based caching well. Allows selective cache invalidation.
Example Magento 2 stores with moderate traffic can use a built-in cache to reduce load time. A large e-commerce store can use Varnish to serve cached pages. It mainly helps during busy sales events. A Magento store can use Redis to cache full-page content and manage sessions. It reduces database queries.

4-Step Guide to Implement Custom Cache Tags in Magento 2

Step 1: Define Custom Cache Type

Custom cache tags allow for precise control over caching in Magento 2. To implement them:

  • Create a new XML file: app/code/Vendor/Module/etc/cache.xml

  • Define your custom cache type

  • Specify a unique identifier and label

  • Set the cache model class

Example:

<?xml version="1.0"?>  
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Cache/etc/cache.xsd">  
    <type name="custom_cache" translate="label,description" instance="VendorModuleModelCacheTypeCustom">  
        <label>Custom Cache</label>  
        <description>Custom cache for specific data</description>  
    </type>  
</config>  

Note: The above step establishes your custom cache type in Magento 2. It tells the system about your new cache and how to handle it.

Step 2: Create Cache Type Model

Next, create a PHP class for your custom cache type:

  • Create file: app/code/Vendor/Module/Model/Cache/Type/Custom.php

  • Extend MagentoFrameworkCacheFrontendDecoratorTagScope

  • Implement required methods

  • Set cache tag and identifier

Example:

<?php  
namespace VendorModuleModelCacheType;  
use MagentoFrameworkAppCacheTypeFrontendPool;  
use MagentoFrameworkCacheFrontendDecoratorTagScope;  
class Custom extends TagScope  
{  
    const TYPE_IDENTIFIER = 'custom_cache';  
    const CACHE_TAG = 'CUSTOM_CACHE';  
    public function __construct(FrontendPool $frontendPool)  
    {  
        parent::__construct($frontendPool->get(self::TYPE_IDENTIFIER), self::CACHE_TAG);  
    }  
}  

Note: The above class defines how your custom cache behaves. It sets up the identifier and tag for your cache type.

Step 3: Implement Cache Usage

Now, use your custom cache in your code:

  • Inject the cache type factory in your constructor

  • Create an instance of your custom cache type

  • Use load() and save() methods to interact with cache

  • Apply custom cache tags when saving data

Example:

use MagentoFrameworkAppCacheTypeListInterface;  
use MagentoFrameworkAppCacheFrontendPool;  
class YourClass  
{  
    protected $cacheTypeList;  
    protected $cacheFrontendPool;  
    public function __construct(TypeListInterface $cacheTypeList, Pool $cacheFrontendPool)  
    {  
        $this->cacheTypeList = $cacheTypeList;  
        $this->cacheFrontendPool = $cacheFrontendPool;  
    }  
    public function yourMethod()  
    {  
        $cacheType = $this->cacheFrontendPool->get('custom_cache');  
        $cacheKey = 'your_cache_key';  
          
        $cachedData = $cacheType->load($cacheKey);  
        if ($cachedData === false) {  
            $data = $this->getYourData();  
            $cacheType->save(serialize($data), $cacheKey, ['CUSTOM_CACHE']);  
        } else {  
            $data = unserialize($cachedData);  
        }  
          
        return $data;  
    }  
}  

Note: The above code shows how to use your custom cache to store and retrieve data. It checks for cached data before generating new data.

Step 4: Configure Cache Management

Configure Cache Management for Custom Cache Tag Implementation

Finally, set up cache management for your custom type:

  • Access the Magento 2 admin panel

  • Navigate to System > Tools > Cache Management

  • Find your custom cache type in the list

  • Enable or disable as needed

  • Use 'Flush Cache Storage' to clear all caches

Note: Custom cache tags provide granular control over caching. They allow you to invalidate specific data without clearing the entire cache.

Troubleshooting Common Magento 2 Full Page Cache Issues

1. Cache Not Updating

Configuring Magento 2 Full Page Cache to Resolve Cache Not Updating Issues

  • Clear cache manually in Magento admin. Mandatory for magento full page cache settings.

  • Check cache configuration settings. Configure the full page cache properly.

  • Verify that the cache storage backend is working. Confirm that the full-page cache magento 2 is operational.

  • Use proper cache tags. Essential for complete page cache management.

Cache updates may fail due to misconfiguration or storage issues. Always check your cache settings first. Magento must address these issues for optimal performance.

2. Slow Page Load Times

Managing Page Load Time Delays via Magento 2 Full Page Cache

  • Enable Varnish or Redis for better performance. Improves how magento 2 full-page cache works.

  • Optimize images and CSS/JS files. Enhances how every page is loaded.

  • Use CDN for static content delivery. Helps when a user requests a page.

  • Implement lazy loading for images. Affects how a page is loaded.

Slow load times often result from unoptimized content or inefficient caching strategies. Implement these optimizations to improve speed. Using the Magento cache effectively and critically.

3. Cached Pages Showing Outdated Content

  • Implement proper cache invalidation. Important for magento 2 fpc.

  • Use appropriate cache tags for dynamic content. Affects how a page in the cache is managed.

  • Set the correct TTL (Time To Live) for cached pages. Determines how long a version of the page exists.

  • Implement cache warming for frequently accessed pages. Helps generate the page efficiently.

Outdated content issues usually stem from improper cache invalidation. Your cache strategy should account for content updates. Essential for both Adobe Commerce and Magento Open Source.

4. Cache Conflicts with Extensions

  • Review extension compatibility with the Magento version. Affects the full-page cache in Magento.

  • Check for conflicting cache configurations. They shouldn't disrupt the list of cache items.

  • Disable problematic extensions temporarily. It can help isolate issues on a Magento 2 website.

  • Consult extension developers for support. They can help configure the full-page cache.

Extension conflicts can disrupt caching. Always test extensions thoroughly and keep them updated. Important for Commerce and Magento Open Source.

5. Full Page Cache Not Working for Logged-in Users

Resolving Magento 2 Full Page Cache Not Working for Logged-in Users Issue

  • Configure customer segment caching. Affects how the Magento 2 full-page cache works.

  • Implement hole punching for personalized content. Essential when a user requests the same page.

  • Use ESI (Edge Side Includes) for dynamic parts. Helps manage content on a page on a Magento 2 site.

  • Optimize session handling and storage. Affects how a page is generated.

Personalized content requires particular caching strategies. Implement these techniques to balance performance and personalization. The page should be optimized every time for each user.

Performance Benchmarks: Magento 2 with and without Full Page Cache

Enabling Full Page Cache in Magento 2 significantly improves performance. Benchmark differences typically vary as per below:

1. Page Load Time:

  • Without FPC: 2-3 seconds

  • With FPC: 0.5-1 second

2. Server Response Time:

  • Without FPC: 500-800 ms

  • With FPC: 100-200 ms

3. Requests per Second:

  • Without FPC: 10-20

  • With FPC: 50-100

4. CPU Usage:

  • Without FPC: 60-80%

  • With FPC: 20-40%

5. Memory Usage:

  • Without FPC: High (varies)

  • With FPC: Moderate (reduced by 30-50%)

Analyzing Cache Hit Rates in Magento 2

Cache hit rates are essential for Magento 2 performance. A high cache hit rate (80%+) indicates efficient caching (faster page loads). Low hit rates may signal configuration issues or highly dynamic content.

1. Enable Cache Debugging

To start, enable cache debugging in Magento 2:

  • Open app/etc/env.php

  • Add 'cache_debug' => true to the configuration

  • Clear the cache using bin/magento cache:flush

The above setting allows you to see cache hit information.

2. Monitor X-Magento-Cache-Debug Headers

Check response headers for X-Magento-Cache-Debug:

  • MISS: Page generated from scratch

  • HIT: Page served from cache

Use browser developer tools to view these headers.

3. Using Magento's Built-in Profiler

Magento's profiler provides detailed cache information:

  • Enable profiler in app/etc/env.php

  • Add 'profiler' => ['enabled' => true]

  • View profiler output at the bottom of pages

The profiler shows cache operations and timings.

4. Analyze Cache Hit Patterns

Look for pages with low hit rates:

  • Identify frequently missed pages

  • Check for cache invalidation issues

  • Adjust TTL for dynamic content

Use this data to optimize your caching strategy.

5. Optimize Based on Analysis

Improve cache hit rates by:

  • Adjusting TTL for frequently changing content

  • Implementing more granular cache tags

  • Using cache warming for essential pages

Regularly review and adjust your caching setup.

FAQs

1. How does Magento Full Page Cache work?

Magento Full Page Cache (FPC) stores a cached version of a page. When the page is requested again, it’s loaded directly from the cache. It saves time by not regenerating the page. The cache system helps with faster page load times and improves overall performance.

2. How do I configure Magento 2 Full Page Cache?

To configure Magento 2 Full Page Cache, go to the Magento admin panel. Navigate to Cache Management settings and find the Full Page Cache section. You can choose either a built-in application or Varnish caching. After configuration, check if the page is served directly from the cache.

3. What is a Full Page Cache Warmer in Magento?

A Full Page Cache Warmer is an extension that preloads the cache content. It keeps a copy of the page ready before the user requests it. The cache warming queue helps regenerate the page, improving the user experience. The entire page can be read directly from the cache.

4. Why is my page cache not working in Magento 2?

If the page cache is not working, check if Full Page Cache is enabled in Magento. Confirm your cache system is functioning correctly. If issues persist, flush the cache to clear old data. Reload the version of the page to ensure the correct cached page is served.

5. What types of cache does Magento 2 support?

Magento 2 supports different cache types like Full Page Cache, specific cache, and object cache. These caches store various versions of a page to improve performance. For example, Full Page Cache works to speed up CMS pages. Specific cache types help reduce load times for dynamic content.

6. How does Varnish configuration help Magento 2?

Varnish configuration in Magento 2 allows faster delivery of cached content. Varnish acts as a caching application, storing a cached version of the page. When a page is requested, it’s served directly from the cache. Varnish can be configured in the Full Page Cache settings.

7. How do I manage the cache in Magento 2?

Managing the cache in Magento 2 involves the Cache Management system. Use it to check if a page is cached or needs regeneration. You can manage specific cache types and flush the cache when necessary. Learn how to configure Magento cache management to improve page load times.

CTA

Summary

Optimizing Magento 2 page cache decreases page loading times and enhances performance. Choose the right caching solution based on your store’s requirements. Here are the article’s key highlights:

  1. Select between built-in, Varnish, or Redis cache. Consider your traffic volume and infrastructure.
  2. Implement custom cache tags for granular control. It allows you to invalidate specific data without clearing the entire cache.
  3. Regularly troubleshoot and optimize your cache configuration. Address common issues like slow page loads and outdated content promptly.
  4. Monitor performance benchmarks with and without Full Page Cache. Use these metrics to justify and fine-tune your caching strategy.
  5. Analyze cache hit rates to identify areas for improvement. High hit rates indicate efficient caching, while low rates suggest optimization opportunities.
  6. Continuously refine your caching strategy as your store grows. Regularly review and adjust cache settings to maintain optimal performance.

Managed Magento hosting plans include automatic chaching assistance with 24/7 expert support.

Sayan Chakraborty
Sayan Chakraborty
Technical Writer

Sayan is a seasoned technical writer with over 4 years of expertise in SDLCs and Magento. His proficiency lies in simplifying complex Magento hosting concepts in clear, concise words.


Get the fastest Magento Hosting! Get Started