ARTICLE

Magento 2 Cache Types and Cache Tags: cache:clean vs cache:flush and Building a Custom Cache Type

Magento 2 Cache Types and Cache Tags: cache:clean vs cache:flush and Building a Custom Cache Type

Magento 2 splits its cache into named cache types, such as config, layout, block_html, and full_page. Each entry is stored with tags. cache:clean deletes entries by Magento’s tags for enabled types only. cache:flush wipes the whole cache storage, including anything else sharing that Redis database or directory. Clean first, flush only when needed.

That one distinction prevents a surprising number of outages, especially on stores where sessions, cache, and other apps share a Redis instance. But most teams stop there and never use the cache system the way it was built: targeted invalidation through tags, and custom cache types for expensive data that should not hit the database or an API on every request. This guide covers what each core type holds, how tags work, which command to run when, and how to build your own cache type properly.

What the core cache types store

Adobe’s Cache Management guide lists every type and what it holds. These are the ones developers touch most:

Cache type Code What it holds When you clean it
Configuration config Merged XML config from all modules plus store settings After changing config XML or core_config_data outside the Admin
Layouts layout Compiled page layouts After changing layout XML
Blocks HTML output block_html Rendered HTML fragments per block After template or view-layer changes
Collections Data collections Results of database queries Rarely; Magento usually cleans it automatically
Reflections reflection API interface reflection data After changing web API interfaces
Database DDL operations db_ddl Database schema information After schema changes made outside Magento
Compiled Config compiled_config Results of code compilation After compilation changes
EAV types and attributes eav Attribute metadata such as labels and settings Rarely
GraphQL Query Resolver Results graphql_query_resolver_result Resolver results for customers, CMS pages and blocks, product media galleries Keep enabled; cleaned by tags
Page Cache full_page Full rendered storefront pages Cleaned by tags on entity save
Translations translate Translation dictionaries After changing translation CSVs

Core declares the base set in Magento_Store’s cache.xml: config, layout, block_html, collections, reflection, db_ddl, and compiled_config. Other modules add their own the same way, which is exactly how you add a custom type.

If you run Varnish, the full_page entry in Magento’s list is the switch that tells Magento to send purge requests, while the pages themselves live in Varnish. Our guide to Magento full page cache and Varnish on Hyva covers that layer in depth. This article is about the application cache underneath it.

Cache tags: how Magento invalidates precisely

Every entry Magento writes to the cache can carry one or more tags. Cleaning a tag removes every entry carrying it, without touching the rest. Two kinds of tag do most of the work.

Type tags. Each cache type has a tag that scopes all its entries, such as TRANSLATE for translations. Cleaning a type means cleaning that tag.

Entity tags. Models that implement Magento\Framework\DataObject\IdentityInterface expose getIdentities(), which returns tags built from a prefix and an ID. In core, the product model’s CACHE_TAG is cat_p and the category model’s is cat_c, so product 42 is tagged cat_p_42. Blocks and pages that render that product collect those identities, and the rendered output is stored with them.

When the product is saved, Magento cleans cat_p_42. Every block, page, and GraphQL result carrying that tag is dropped, and nothing else is. That is why a well-built store never needs a full cache clean after a catalog edit.

The practical lesson for custom code: if your block or resolver output depends on an entity, return that entity’s identities. If you skip it, your output will either never refresh, or someone will “fix” it by disabling the cache type.

cache:clean vs cache:flush

Adobe’s cache management CLI reference defines the two commands precisely:

  • cache:clean deletes all items from enabled Magento cache types only. It does not affect other processes or applications, and it leaves disabled types alone.
  • cache:flush purges the cache storage itself, which may affect other processes or applications using the same storage.

The Admin buttons map the same way. Flush Magento Cache is cache:clean. It removes items from Magento’s cache by their Magento tags. Flush Cache Storage is cache:flush. It removes everything regardless of tag, including files other applications keep in the same location.

cache:clean cache:flush
Admin equivalent Flush Magento Cache Flush Cache Storage
How it removes data By Magento cache tags Empties the storage backend
Disabled cache types Left alone Removed with everything else
Other apps on the same Redis DB or directory Unaffected Wiped
Safe to run on a busy production store Yes, with a temporary load increase as caches rebuild Only if the storage is dedicated to this Magento cache
Typical use After deploys, config changes, module installs When clean did not fix a problem you cannot isolate

Adobe’s own recommendation is to always clean the cache after upgrading, installing B2B, or installing any module, and to flush only when cleaning has not resolved an issue.

Why the storage question matters

The dangerous case is shared storage. If Magento’s cache and sessions point at the same Redis database, cache:flush logs every customer out and empties every cart held in sessions. If two Magento instances share one Redis database, flushing one wipes the other. Keep cache, full page cache, and sessions in separate Redis databases or instances, and cache:flush becomes much less risky. We cover that layout, and the move many teams are making from Redis to Valkey, in our guide to the Redis to Valkey migration for Magento.

Target the type, not everything

Both commands accept type codes. After a layout change, bin/magento cache:clean layout block_html full_page rebuilds less than a full clean. After a config change, cache:clean config is usually enough. On a large store, warming everything after a blanket clean is a measurable load spike, so targeted cleans keep deploy windows calmer.

Enabling, disabling, and the INVALIDATED status

bin/magento cache:status shows each type and whether it is enabled. cache:enable and cache:disable take type codes too, and enabling a type automatically cleans it. Adobe notes that since 2.2, changing cache types from the command line in production mode is the supported path, and in developer mode the file system owner must be able to write app/etc/env.php.

Leaving types disabled in production is a common cause of slow stores. Teams disable block_html or full_page while debugging, then forget. Check cache:status on every environment after a release.

In the Admin, a type marked invalidated has stale entries, usually because a configuration or catalog change touched it. That status is set through Magento\Framework\App\Cache\TypeListInterface::invalidate(). Refreshing the type, or running cache:clean with its code, clears the flag.

Building a custom cache type

A custom cache type is the right tool when your module computes something expensive that many requests need. Think of a pricing matrix from an ERP, a shipping rate table, a store locator dataset, or a navigation tree you assemble from several sources. It gives merchants a named row on the Cache Management page and gives you clean invalidation.

Adobe documents the pattern in Create a cache type. There are two parts.

1. Declare it in cache.xml

<!-- app/code/Vendor/Erp/etc/cache.xml -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Cache/etc/cache.xsd">
    <type name="vendor_erp_pricing" translate="label,description"
          instance="Vendor\Erp\Model\Cache\Type\ErpPricing">
        <label>ERP Pricing</label>
        <description>Customer group price matrices imported from the ERP</description>
    </type>
</config>

name is the unique type ID, instance is the model class, and label and description appear on System, Tools, Cache Management.

2. Create the type class

The class extends Magento\Framework\Cache\Frontend\Decorator\TagScope, which wraps a cache frontend and adds the type’s tag to every entry it saves:

namespace Vendor\Erp\Model\Cache\Type;

use Magento\Framework\App\Cache\Type\FrontendPool;
use Magento\Framework\Cache\Frontend\Decorator\TagScope;

class ErpPricing extends TagScope
{
    public const TYPE_IDENTIFIER = 'vendor_erp_pricing';
    public const CACHE_TAG = 'VENDOR_ERP_PRICING';

    public function __construct(FrontendPool $cacheFrontendPool)
    {
        parent::__construct($cacheFrontendPool->get(self::TYPE_IDENTIFIER), self::CACHE_TAG);
    }
}

Core’s translation cache is built exactly this way: Magento\Framework\App\Cache\Type\Translate uses the identifier translate and the tag TRANSLATE.

3. Read and write through it

Adobe’s example saves through the generic CacheInterface with the type’s tag. A pattern that holds up better in production injects the type class directly and checks whether merchants have disabled it:

public function __construct(
    private ErpPricing $cache,
    private StateInterface $cacheState,
    private SerializerInterface $serializer,
    private ErpClient $erp
) {}

public function getMatrix(int $groupId): array
{
    $key = 'erp_pricing_' . $groupId;
    $enabled = $this->cacheState->isEnabled(ErpPricing::TYPE_IDENTIFIER);

    if ($enabled && ($hit = $this->cache->load($key)) !== false) {
        return $this->serializer->unserialize($hit);
    }

    $matrix = $this->erp->fetchMatrix($groupId);

    if ($enabled) {
        $this->cache->save(
            $this->serializer->serialize($matrix),
            $key,
            ['erp_group_' . $groupId],
            86400
        );
    }
    return $matrix;
}

Three choices in that code are deliberate:

  • One key per variant. Do not cache everything under the type identifier, as the minimal doc example does. Key by whatever changes the result, here the customer group, and add the store or website ID if prices vary by scope.
  • Extra tags for partial invalidation. The erp_group_<id> tag lets you clean one customer group’s matrix after an ERP sync without wiping the rest. The type tag is added automatically by TagScope.
  • Respect the enabled state. Magento\Framework\App\Cache\StateInterface::isEnabled() reports whether the type is switched on. Checking it means a merchant who disables “ERP Pricing” on Cache Management actually gets live data.

4. Invalidate and clean

Use TypeListInterface for the two operations merchants see:

$this->typeList->invalidate(ErpPricing::TYPE_IDENTIFIER); // marks it invalidated in the Admin
$this->typeList->cleanType(ErpPricing::TYPE_IDENTIFIER);  // removes all entries now

For targeted cleanup after a sync, clean by your own tags instead:

$this->cache->clean(\Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, ['erp_group_' . $groupId]);

On 2.4.7 and earlier, TagScope uses the \Zend_Cache constants shown here. The current 2.4 development branch has moved them to Magento\Framework\Cache\CacheConstants, so match whichever your installed version references.

Run that from the ERP import job, a message queue consumer, or a cron task, so stale prices disappear as soon as the source changes instead of waiting for the TTL. If those jobs are unreliable, invalidation will be too. Our guide to Magento message queue consumers covers keeping them running.

Custom cache types and Hyva

Hyva does not change the cache system, but it shifts where caching pays off. Hyva templates read data through PHP view models, and a slow view model on a category page or the header runs for every uncached render. Putting expensive lookups behind a custom cache type keeps those renders fast, and full page cache misses stay cheap.

If the data feeds a block, also give the block identities so block_html and full_page entries are dropped when the source changes. A cached view model that returns fresh data inside a stale cached page is still stale. The two layers have to be invalidated together.

Which cache to clear after which change

Change you made Run
Edited di.xml, plugins, or preferences setup:di:compile in production, then cache:clean config
Edited layout XML cache:clean layout block_html full_page
Edited a .phtml template cache:clean block_html full_page
Changed configuration in env.php, config.php, or by SQL cache:clean config
Changed translation CSVs cache:clean translate full_page
Installed or upgraded a module cache:clean (all types)
Clean did not fix it and storage is dedicated cache:flush

Changing generated code needs more than a cache clean. If plugins or extension attributes are involved, see our guide to Magento 2 deploy modes and setup:di:compile for when regeneration is required.

Work with a team that tunes this daily

Cache configuration sits under almost every Magento performance problem we look at: types left disabled after debugging, sessions sharing a Redis database with the cache, custom modules that cache under one key or never invalidate. Our Magento development services team audits and fixes this on Adobe Commerce stores of every size, and our Hyva development services make sure the storefront’s view models and blocks are cacheable from the start. Bemeir is a Brooklyn ecommerce agency built around Magento, Adobe Commerce, and Hyva. Learn more about Bemeir and the technology partners we work with. We also build on Shopify, Shopware, and BigCommerce.

FAQ

What is the difference between cache:clean and cache:flush in Magento 2?

cache:clean removes entries by Magento’s cache tags, for enabled cache types only, and leaves anything else in the storage alone. cache:flush empties the whole cache storage, including disabled types and data other applications keep in the same Redis database or directory. Use clean by default and flush only when clean has not fixed the issue.

Is it safe to run cache:flush on a production Magento store?

Only if the cache storage is dedicated to that Magento cache. If sessions or another application share the same Redis database or directory, a flush wipes them too, which can log customers out and empty carts. Separate cache, page cache, and sessions into their own Redis databases before relying on flush.

What are cache tags in Magento 2?

Cache tags are labels stored with each cache entry so related entries can be removed together. Each cache type has its own tag, and entities add tags through getIdentities(), such as cat_p_42 for product 42. Saving that product cleans every block, page, and resolver result tagged with it.

How do I create a custom cache type in Magento 2?

Declare the type in your module’s etc/cache.xml with a name, label, description, and model class. Create the class by extending Magento\Framework\Cache\Frontend\Decorator\TagScope with a unique type identifier and tag. Then save and load through it, and use TypeListInterface to invalidate or clean the type.

Which cache types should I clean after changing a template?

For a .phtml change, clean block_html and full_page, since the rendered block fragments and full pages contain the old output. Layout XML changes also need layout. In production mode, static assets referenced by the template may need a static content deploy as well.

Let us help you get started on a project with Magento 2 Cache Types and Cache Tags: cache:clean vs cache:flush and Building a Custom Cache Type and leverage our partnership to your fullest advantage. Fill out the contact form below to get started.

more articles about ecommerce

Read on the latest with Shopify, Magento, eCommerce topics and more.