Skip to content
intermediate Phase 68 · Cache System

Cache Tags — Tag-Based Invalidation and Cache Identity

Understanding cache tags in Magento 2: tag-based invalidation, cache identity, tag implementation, and tag-based cache management

45m
1 problems
Topic Progress 0%

Cache Tags Fundamentals

What Are Cache Tags?

Cache tags allow you to invalidate specific cache entries by label rather than by key.

// Save cache with tags
$cache->save(
    $data,
    'my_cache_key',
    ['catalog_product_123', 'category_45'],
    3600
);

// Invalidate all entries with tag
$cache->clean('tags', ['catalog_product_123']);

Tag Format

// Standard Magento tag format
'catalog_product_' . $productId    // Product-specific
'catalog_category_' . $categoryId  // Category-specific
'config'                           // Configuration
'block_html'                       // Block HTML cache

Cache Identity

Cache identity is the combination of cache key + tags that uniquely identifies what the cached data represents.

public function getCacheIdentity(): string
{
    return 'product_list_category_' . $this->getCategoryId();
}

Implementing Cache Tags

Block Cache Tags

namespace Vendor\Module\Block;

class ProductList extends \Magento\Framework\View\Element\Template
{
    public function getCacheKey(): string
    {
        return 'product_list_' . $this->getCategoryId();
    }

    public function getCacheTags(): array
    {
        return [
            'catalog_category_' . $this->getCategoryId(),
            'catalog_product_list'
        ];
    }

    public function getCacheLifetime(): int
    {
        return 3600;
    }
}

Custom Cache Tags

namespace Vendor\Module\Service;

class DataCache
{
    public function saveWithTags(string $key, string $data, array $tags): void
    {
        $this->cache->save(
            $data,
            'vendor_module_' . $key,
            $tags,
            3600
        );
    }

    public function invalidateByTag(string $tag): void
    {
        $this->cache->clean('tags', [$tag]);
    }

    public function invalidateByTags(array $tags): void
    {
        $this->cache->clean('tags', $tags);
    }
}

Tag-Based Invalidation in Observer

namespace Vendor\Module\Observer;

class ProductSaveObserver implements ObserverInterface
{
    public function execute(Observer $observer)
    {
        $product = $observer->getEvent()->getProduct();
        
        // Invalidate product-specific cache
        $this->cache->clean('tags', [
            'catalog_product_' . $product->getId(),
            'product_list'
        ]);
    }
}

Tags with Redis and Varnish

Redis Tag Storage

Redis stores tags as sets:

# Check tags for a key
redis-cli smembers magento_cache:tags:key123

# Check entries for a tag
redis-cli smembers magento_cache:tag:catalog_product_123

Varnish Tags

Magento sends tags via X-Magento-Tags header:

X-Magento-Tags: catalog_product_123,catalog_category_45

Varnish Ban by Tag

sub vcl_recv {
    if (req.method == "BAN") {
        if (!client.ip ~ purge_acl) {
            return (synth(403, "Forbidden"));
        }
        ban("req.http.X-Magento-Tags ~ " + req.http.Tag-To-Invalidate);
        return (synth(200, "Banned"));
    }
}

Tag Hierarchy

// Product tags
catalog_product_123       // Specific product
catalog_product_all       // All products
product_list              // Product listings

// Category tags
catalog_category_45       // Specific category
catalog_category_all      // All categories

// Page tags
page_home                 // Home page
page_category_45          // Category page
page_product_123          // Product page

Tagging Strategies

Fine-Grained Tagging

// Tag per entity
tags: ['catalog_product_' . $id]

// Invalidate per entity
$cache->clean('tags', ['catalog_product_123']);

Pros: Precise invalidation
Cons: Many tags, higher memory

Coarse-Grained Tagging

// Tag per entity type
tags: ['catalog_products']

// Invalidate all products
$cache->clean('tags', ['catalog_products']);

Pros: Simple, low overhead
Cons: Over-invalidation

Hybrid Tagging

// Both specific and general tags
tags: [
    'catalog_product_' . $id,   // Specific
    'catalog_products'           // General
]

// Invalidate specific product
$cache->clean('tags', ['catalog_product_123']);

// Invalidate all products
$cache->clean('tags', ['catalog_products']);

Best Practices

  1. Use entity-specific tags for precise invalidation
  2. Add general tags for bulk operations
  3. Keep tag strings short
  4. Limit tags per cache entry (< 10)
  5. Use consistent naming conventions

Practice Problems

0 / 1 solved
Tag Strategy Design

Design a cache tagging strategy for a product catalog with categories, attributes, and custom blocks.

Quiz

1. What is the purpose of cache tags?

Question 1 options

2. How does Varnish receive cache tags?

Question 2 options

3. What is the standard Magento tag format for products?

Question 3 options

4. What is the trade-off between fine-grained and coarse-grained tagging?

Question 4 options

Flashcards

Question

What is the Magento product tag format?

Answer

catalog_product_{entity_id}

Question

How does Varnish receive cache tags?

Answer

Via X-Magento-Tags HTTP header

Question

How to invalidate cache by tag?

Answer

$cache->clean('tags', ['tag_name'])

Question

What is cache identity?

Answer

The combination of cache key + tags that uniquely identifies cached data

Question

How many tags should a cache entry have?

Answer

Less than 10 for optimal performance

Revision Notes

Key Takeaways

  • 1. Cache tags enable targeted invalidation of specific cache entries
  • 2. Magento uses catalog_product_{id} and catalog_category_{id} tag formats
  • 3. Varnish receives tags via X-Magento-Tags header for ban-based invalidation
  • 4. Redis stores tags as sets linking keys to tags
  • 5. Balance fine-grained (precise) vs coarse-grained (simple) tagging
  • 6. Keep tag strings short and limit tags per entry

Interview Tips

  • Explain how cache tags enable targeted invalidation
  • Describe the tag format used by Magento
  • Discuss fine-grained vs coarse-grained tagging trade-offs
  • Know how tags work with Redis and Varnish

Cheat Sheet

Cache Tags Cheat Sheet

Tag format:
catalog_product_{id}
catalog_category_{id}

Save with tags:

$cache->save($data, $key, ['tag1', 'tag2'], $ttl);

Invalidate by tag:

$cache->clean('tags', ['tag1']);

Redis:
smembers magento_cache:tag:tag_name

Varnish:
X-Magento-Tags header -> ban() in VCL

Strategy:

  • Fine-grained: precise, more overhead
  • Coarse: simple, over-invalidates
  • Hybrid: both specific and general tags