We use cookies to make your viewing experience better. By accepting you consent, you agree to our Cookie policy

Accept
Improve your Craft CMS skills

How To Clear Cache In Craft CMS

10 min read
How to Clear Cache in Craft CMS

Suffering site slowdowns after updating your Craft CMS site? Stale, outdated cached data could be the culprit. Clearing your Craft caches properly is crucial for optimal performance. This guide will provide CMS admins with best practices for effectively clearing all cache types in Craft CMS. Learn when and how to flush your caches, configure cache expiration, utilize cache tagging, plus avoid common cache clearing mistakes.

Clear Craft CMS caches after configuration changes, content updates, and when troubleshooting issues. Target data, template, and asset caches individually or clear all caches globally. Configure cache expiration rules for automatic clearing. Enable cache tagging to invalidate stale caches automatically when related content changes. Warm important caches after flushing to maintain speed.

When to Clear Cache in Craft CMS

After Making Configuration Changes

When working in Craft CMS, one of the most common times you'll want to clear the cache is after making any changes to the site's configuration or system settings. This includes things like updating Craft CMS or plugin versions, enabling or disabling plugins, modifying configuration files, or adjusting settings in the control panel.

Clearing the cache after configuration changes ensures Craft flushes any cached data, templates, or assets that relied on the previous config. For example, if you disable a plugin, pages using that plugin's output may still be cached and need invalidating. Or if you update your Craft version, the new code changes won't run until the cache clears.

Essentially, configuration changes often modify how Craft builds the frontend of your site. So clearing your caches gives Craft a fresh start with the updated settings. This prevents any conflicts with old cached data that's now invalid.

Some specific examples of configuration changes that warrant a cache clear include:

  • Updating Craft CMS to a newer version

  • Installing, updating plugins, or uninstalling plugins

  • Enabling or disabling plugins

  • Modifying plugin settings

  • Changing entries within the config/general.php file

  • Adjusting the System Settings in the control panel

  • Updating any .env environment variables

It's a good habit to clear your caches after any modifications like these, regardless of how big or small. Even tiny config tweaks can potentially cause conflicts with cached data. So it's better to be safe and give Craft a clean slate when working with new configurations.

After Content Updates

In addition to configuration changes, you'll also want to clear your Craft CMS cache whenever you update or publish new content. This includes things like:

  • Creating, editing, or deleting entries

  • Adding, modifying, or removing products

  • Updating navigation or categories

  • Publishing new assets or media

Whenever content changes like these occur, you'll want to purge any cached templates, pages, or data that could contain outdated content.

For example, your category archives may still show old products or entries until you invalidate the cache. Or a product page could display incorrect pricing or details prior to a cache clear.

Content updates happen frequently on most Craft sites. So it's a good practice to clear the cache after any significant content changes to keep things fresh. Some specific scenarios where a cache purge makes sense include:

  • Publishing a new blog post

  • Adding products to your ecommerce store

  • Archiving or deleting old entries

  • Changing the order of your navigation

  • Updating text content across the site

Essentially any content modifications that alter what visitors see on your frontend. You want Craft to rebuild those templates and pages from scratch, so they include the latest data.

Clearing your caches regularly after content updates also prevents your Craft data getting out of sync if you ever need to restore from a backup. So it's an important step in any standard content publishing workflow.

While Troubleshooting Issues

Finally, clearing your Craft CMS cache is also recommended when troubleshooting any potential errors, anomalies, or other frontend issues on your site.

If pages seem broken or you're seeing unexpected behavior, clearing your caches is one of the first troubleshooting steps to try.

This eliminates any corrupted cached data that could be causing the problems. Often times, these issues arise when cached templates or Twig code contain bugs. Purging the cache forces fresh page generation.

Some examples of common issues that cache clearing may fix include:

  • Incorrect or missing content

  • Server errors on certain pages

  • Problems with new elements not appearing

  • Conflicts after configuration changes

  • Stylesheets not updating properly

  • Strange Javascript behavior

Essentially any unexplained quirks, bugs, or frontend anomalies have a chance of being cache-related. Flushing your caches removes stale data as a potential cause.

While not a magic fix-all, clearing your caches when issues arise is a fast and easy way to troubleshoot. It costs nothing to try, often only takes a few seconds, and can end up resolving the problem quickly.

So whenever you run into any weird errors or behavior after changes, your first debugging step should be to clear your Craft CMS caches. At minimum it eliminates one potential culprit, and best case may fix the problem entirely.

Cache Types in Craft CMS

Data Cache

One of the core caching systems in Craft CMS is the data cache, which stores the results of database queries. When the same query needs to be executed multiple times, such as on high traffic pages, Craft can pull the results from a cached copy rather than hitting the database directly each time.

This provides a significant performance boost and faster page loads by avoiding redundant queries. However, the data cache does need to be cleared occasionally when data changes in the database. Otherwise, the cached query results would become stale.

For example, if you create a new blog post, the homepage would still show old posts on the first hit until the posts query cache clears. The data cache has no way of knowing your data changed until it's purged.

Some common cases where clearing the data cache in Craft makes sense:

  • After publishing/updating content

  • When new entries, products, categories are added

  • After users, tags, assets, etc. are modified

  • When troubleshooting content not updating

Essentially any data changes in Craft's database have the potential to cause conflicts in the query cache. So it's generally a good idea to clear after significant mutations to keep things in sync.

The data cache also supports caching individual queries specifically. So developers can have fine-grained control over which queries are cached versus which run fresh each request.

Overall, the data cache provides huge performance benefits for reads at the cost of some extra cache management when data changes. A smart invalidation strategy is key to getting the best of both worlds.

Template Cache

In addition to the database query cache, Craft CMS also caches the HTML output of rendered Twig templates and components. This is known as the template cache.

When a Twig template is rendered, Craft will store the entire HTML output in cache rather than re-rendering on every page load. This saves a ton of redundant rendering that would otherwise occur.

However, just like the data cache, the template cache does need to be cleared any time the output of a template changes. Otherwise, it would continue showing outdated HTML.

Some examples of when to clear the template cache:

  • After updating a shared layout or base template

  • When global include files like headers/footers are modified

  • After changing any templates affecting the frontend

  • If new templates are added, renamed, or deleted

  • When updating template logic that alters output

Essentially any changes that could modify the rendered HTML of your Twig templates warrant flushing the cache. This forces Craft to re-render using the latest templates and code.

The template cache is especially important for sites using complex, shared Twig components across pages. Without proper cache management, you may notice one part of the site updates while others remain stale. Clearing template caches avoids this scenario.

Developers can also cache specific blocks or templates manually for more fine-grained control over cache lifetimes. But in general, remembering to flush caches after template changes is crucial.

Asset Caches

In addition to data and templates, Craft CMS also caches many aspects of your assets and media for performance. This includes things like image transform caches, SVG sprite sheets, and preview image generations.

Clearing Craft's asset caches can be important when new images, SVGs, or other files are added to the system. Otherwise, the caches may not be aware new media exists.

For example, your image transform outputs could continue cropping old files until the transform cache is cleared after uploading new ones. Or the SVG sprite sheet generator won't see new SVGs to consolidate until its cache is busted.

Here are some common cases where clearing asset caches makes sense:

  • After uploading any new media to Craft

  • When transforming images or SVGs

  • If asset previews seem outdated or incorrect

  • When troubleshooting asset-related issues

In general, if assets ever seem "out of sync" or aren't reflecting recently uploaded files, try flushing your asset caches. This eliminates any outdated cache data and forces Craft to refresh its indices.

The good news is that in Craft 3.7+, asset caches will clear automatically whenever you update the "Asset Indexes" control panel setting. But on earlier versions, and for SVG sprites, manual cache busting is required.

Overall, remember to clear asset caches periodically, especially after uploading new files or performing asset indexing. This ensures Craft incorporates your latest media changes across all asset caching layers.

Clearing Specific Cache Segments in Craft CMS

Clearing the Data Cache

When it comes time to clear caches in Craft CMS, you have the ability to precisely target just the data cache if needed. This allows you to invalidate any stale query results from the database, without wiping out other cached elements like templates, assets, and more.

To accomplish this focused data cache clearing, simply log into your Craft control panel, navigate to Settings → Utilities → Clear Caches, check the box next to craft/storage/runtime/cache, and leave the other cache type boxes unchecked. Then click "Clear selected cache storage folders". Craft will now purge only the data query cache while leaving template, asset, and other caches intact.

Some good cases where clearing only the data cache makes sense include after publishing or editing content, when troubleshooting stale data issues, if templates seem fine but queries are outdated, or when assets don't need to be flushed yet. Essentially any scenario where cached database queries become suspect due to new or altered data, but other caches remain valid. Deleting just the outdated data cache entries allows for a more surgical, targeted approach versus nuking every single cache unnecessarily.

For an even deeper data cache clearing, the cache folder may contain additional sub-folders like arrays or level2 that you can also delete while leaving the templates folder and contents in place. Overall, precisely invalidating only the data cache gives you improved control over targeting the specific caches that need refreshing based on the changes at hand.

Clearing the Template Cache

Similar segmented cache clearing can be achieved for the template cache in Craft CMS as well. This allows you to discard any stale rendered HTML output from Twig templates and components, without affecting the data or asset caches.

To clear only the template cache, navigate to Settings → Utilities → Clear Caches in the Craft CP, check the box next to craft/storage/runtime/templates, leave other options untouched, and click the "Clear selected" button. Craft will purge the outdated template HTML while retaining all cached queries, assets, and more.

Some scenarios where flushing only the template cache makes sense include after updating shared Twig components, if global layout changes aren't reflecting properly when adding or removing templates, or if HTML seems stale but data queries remain fresh. Essentially any time the rendered frontend HTML is outdated, busting the template cache allows Craft to re-render affected templates while keeping the rest of the environment cached.

For bonus points, the templates folder may contain additional sub-folders that can be cleared out for an even deeper flush. But avoid the cache data cache folder to keep those query results intact. With this type of precise, segmented template cache deletion, you gain refined control over pinpointing exactly which caches need refreshing after specific changes.

Clearing Asset Caches

Finally, Craft also provides options for clearing just specific asset caching when required. This includes targeting image transform caches, SVG sprite generations, asset preview caches, and other media output.

Some ways to selectively invalidate only stale asset caches include:

  • Deleting all contents in craft/storage/runtime/transforms to clear image transform caches

  • Clearing generated sprite.svg files in web/dist folders to refresh SVG sprites

  • Removing old asset preview images in craft/storage/runtime/asset-previews

This allows you to refresh just the asset and media caches that have gone stale due to new uploads or changes, while keeping all other caching intact. Some examples of when to leverage targeted asset cache clearing include after uploading new media, if transforms or previews seem outdated, or if regeneration bugs occur on recently changed assets.

Essentially, anything that seems "off" with your asset generation can likely be fixed by surgically deleting the related cache remnants. Craft's flexible options for precise, segmented cache invalidation provide optimized control over managing cache performance. With some forethought, you can refresh exactly the caches needing updates after specific changes, rather than taking a sledgehammer approach.

Clearing All Caches in Craft CMS

Using Cache Flag Plugin

One easy way to flush all of your Craft CMS caches globally is by using the Cache Flag plugin. This provides a simple "Clear All Caches" button that deletes the contents of every cache folder with one click.

To set this up:

  1. Install and enable the Cache Flag plugin.

  2. Navigate to Settings → Cache Flag in the control panel.

  3. Check the box for "Clear all cache files and folders" under Clear Cache Options.

  4. Save the settings.

You will now have a handy "Clear All Caches" button available in the main toolbar. Clicking this instantly flushes the data cache, template cache, asset caches, and any other cached data throughout the system.

This is perfect when you need to completely invalidate all cached elements after major changes. For example, use it after updating Craft CMS versions, installing new plugins, modifying templates globally, or when troubleshooting cache-related issues.

Since it clears every cache universally, be aware it may have a slight performance hit on the next page load as all new queries run and templates re-render. But it quickly recovers, and is often necessary after substantial updates.

Overall, the Cache Flag plugin provides the ultimate "big red button" for effortless total cache clearing in Craft. One click to rule them all!

Using Cache Tool Plugin

An alternative plugin for globally flushing all caches in Craft CMS is Cache Tool. This also provides a one-stop cache clearing solution.

To use it:

  1. Install and enable the Cache Tool plugin.

  2. Go to Settings → Cache Tool in the control panel.

  3. Click the "Clear All Caches" button.

And done! This will rapidly purge the contents of every cache directory throughout Craft, including data, templates, assets, and more.

Like Cache Flag, Cache Tool is great when you need to invalidate all cached elements at once after major changes. Use it after Craft/plugin updates, global template edits, new module installs, or when troubleshooting weird caching behaviors.

Since it clears universally, expect a slight load spike on the next request as caches rebuild. But it's often a necessary step after substantial mutations.

Overall, Cache Tool provides another quick and simple path to flush all Craft CMS caches simultaneously. Combined with granular cache clearing options, it's a powerful cache management toolkit.

Manual Cache Deleting

Finally, the "nuclear option" for absolute total cache clearing in Craft is to manually delete the contents of all cache directories directly on the server. This flushes every last cached file.

Here are the key folders to empty out:

  • craft/storage/runtime/cache - Clears all data caches

  • craft/storage/runtime/templates - Purges template caches

  • craft/storage/runtime/transforms - Deletes asset transform caches

  • web/cpresources - Flushes control panel resources

Additional asset cache folders that may need clearing:

  • Generated SVG sprite files in web/dist

  • Asset preview images in craft/storage/runtime/asset-previews

Deleting all files in these cache folders represents the most thorough method of completely Flushing every cached byte throughout Craft CMS.

This approach requires FTP/SSH access and is overkill in many cases. But when absolutely all caches need purging, rolling up your sleeves for manual deletion can get the job done.

Consider it for major version updates, faulty cache behavior, or corrupted caches that plugins can't clear automatically. Just be sure not to delete the folders themselves, only the contents.

Overall, manual cache deletion gives you ultimate power over cache purging but requires more effort. Use it strategically when no stone can be left unturned in your caching purge. But for most needs, Cache Flag or Cache Tool plugins are faster and easier options.

Configuring Cache Expiration in Craft CMS

Global Cache Settings

Craft CMS provides several ways to configure cache expiration settings for automatically invalidating caches after a defined time period.

One option is to set global cache lifetimes that apply to all cache types universally. This is configured in Settings → General in the control panel.

The "Cache duration" setting specifies the max global cache lifetime, after which all cached data gets flushed. The default is 24 hours.

Some examples:

  • 1 = 1 second

  • 30 = 30 seconds

  • 1800 = 30 minutes

  • 86400 = 1 day

  • 604800 = 1 week

So setting this to 3600 would automatically clear all caches hourly.

The benefit of global expiration is set-and-forget cache flushing. You don't have to manually clear after changes—Craft handles it on a schedule.

The downside is less flexible control. You may clear caches more often than necessary if some need longer lifetimes.

Still, global expiry takes the effort out of remembering to manually purge caches regularly. For low-traffic sites where aggressive caching isn't as critical, it provides a hands-off approach.

Per-Cache Expiration Settings

For more control over cache lifetimes, Craft also allows defining custom expiration times for individual cache types:

  • Template caches

  • Data caches

  • Asset transform indexes

  • Asset preview images

These are configured under Settings → Assets for assets, and using {% cache %} tags or \craft\services\TemplateCaches::setDuration() for templates and data caching.

For example, you could set templates to expire after 1 hour, data after 24 hours, assets after 1 week, etc. This accounts for their different rates of change.

The benefit of per-cache expiry is tuning cache performance and clearing frequency for each unique case. Frequently changing templates can clear more aggressively than static asset indexes, for example.

The downside is added complexity. You'll need to analyze cache usage for each site to maximize performance.

Overall, per-cache expiration affords the ultimate flexibility when optimizing caching strategies. Set shorter lifetimes for volatile data, and longer expirations for static caches.

Cache Auto-Clearing Benefits

Configuring cache expiration in Craft CMS provides several benefits compared to relying solely on manual clearing:

  • Caches stay fresh automatically without constant manual intervention

  • Reduced risk of getting stale or outdated cached data

  • More hands-off caching without having to remember clearing

  • Ability to tune cache lifetimes based on frequency of changes

  • Caches clear "just in time" right before going stale

Essentially, expiration settings ensure your caches flush right before their data gets outdated. This takes the effort out of having to manually clear on a regimented schedule.

For example, template caches can clear nightly or hourly automatically after template changes accumulate throughout the day.

The end result is consistently fresh caches, maximum caching performance, and less wasted manual cleansing of still-valid caches.

Configured intelligently, expiration rules can take the hassle out of cache management while keeping sites optimized. Set broad defaults globally, then tweak behavior for each unique caching scenario.

Cache Tag Invalidation in Craft CMS

Overview of Cache Tagging

Cache tagging is a powerful caching technique available in Craft CMS that creates dynamic relationships between cached data and the content powering it. It works by allowing developers to label specific caches with descriptive tags. These tags then get applied to related content elements as well.

When this tagged content gets modified or expired, Craft automatically invalidates any cached data also marked with the same tags. This elegantly eliminates the need for manually clearing caches associated with stale content whenever that content changes.

For example, a cached category page could be tagged with the IDs of all categories it displays. If any of those categories are then updated, Craft would automatically purge the category page cache thanks to their shared tag connection. This keeps things in sync without manual oversight.

Overall, cache tags allow cached data to intelligently refresh itself whenever its powering content changes just by linking them through shared tag identifiers.

Implementing Cache Tagging

To implement cache tagging, you first need to enable it globally in Craft under Settings → General by checking “Enable cache tagging”. This activates the tagging behavior.

Then when defining any cached elements like templates or data queries, you pass an array of descriptive cache tag strings:

{% cache using key, [‘tag1’, ‘tag2’] %}

This tags the cache for future invalidation.

Next, you apply those same cache tag identifiers to any related content that should trigger automatic clearing of the caches when changed:

craft.app.elements.tagElement(element, ‘tag1’)

Now whenever that element is saved, Craft invalidates all caches tagged with tag1, keeping them in sync.

Some common examples include tagging entry caches with entry IDs, product caches with product IDs, and category caches with category IDs. Essentially any content that powers a cache should be tagged for optimal automatic clearing.

You can also create services to programmatically tag both caches and content for more complex behavior. When tied together properly, any changes cascade automatically without manual cache cleansing.

Benefits of Cache Tagging

Intelligent cache tagging delivers a multitude of benefits for Craft CMS sites:

  • Greatly reduces manual cache clearing busywork whenever related content changes

  • Optimizes cache performance and lifetimes by only invalidating stale caches precisely when needed

  • Allows for cache invalidation at scale as data sets grow larger

  • Faster responses from hot caches without costly cache-busting logic

  • Improves content publishing workflows as changes cleanly propagate

Overall, cache tagging removes the inefficient human element of managing cache clearing by programmatically tying caches to their powering content. Changes in content automatically cascade out to any dependent cached data by virtue of their shared tag links.

This results in always-fresh caches tuned precisely to the content powering them, without costly premature busting of still valid caches. Manual oversight gives way to automated synchronization.

Cache Warming in Craft CMS

Pre-Caching Pages

Cache warming, also known as cache priming, is the process of proactively generating cached pages before they are requested by real visitors. This pre-caches and optimizes performance. In Craft CMS, deliberately warming caches helps offset the performance hit of necessary cache clearing.

By pre-building cached versions of key pages, a site can maintain speed and snap even after flushing caches. Some common approaches for cache warming include using scripts to programmatically crawl and request URLs to pre-cache them, leveraging plugin tasks and helpers designed for cache priming, or even manually visiting important pages yourself to trigger caching.

This effectively "repopulates" all caches with fresh data after a flush, avoiding the slow load times that would otherwise occur as live requests trickle in naturally. Some particularly important pages to focus cache warming on include the homepage, high-traffic landing pages, top product and category archives, popular blog articles, and other vital endpoints. Even warming a portion of key caches like this can restore baseline performance while allowing remaining caches to trickle back naturally.

Warming Specific Caches

In some cases beyond full pages, you may want to specifically target warming certain Craft CMS cache types like data or templates. For example, after flushing, only warming the entry query cache could optimize blog performance while skipping less important caches. Or only warming product caches may maintain catalog speed without incurring overhead across the board.

This type of targeted, surgical cache warming improves the performance of certain actions over others. Warming all page and block caches equally isn't always ideal. Some approaches for specific cache warming include directly executing Element queries to warm those caches, calling particular template rendering methods to warm template caches, or running key database queries to warm underlying data caches. Dedicated tools like Template Cacher for Craft can help automate and simplify these types of targeted cache warming workflows.

Overall, precision cache warming gives you granular control over exactly which cached elements get pre-cached and optimized after cache purging. No need to incur overhead for unimportant caches.

Automating Cache Warming

The downside of manual cache warming techniques is the repetitive effort and overhead required. This is where automation can help streamline the process considerably. Some ways to automate cache warming include leveraging plugin helpers designed to run on cache flush events, creating post-clear tasks and scripts to programmatically warm caches, and utilizing crawlers that continuously recache pages automatically in the background.

Automated workflows like these make performance self-healing and resilient when caches inevitably need to be flushed. There is no reliance on manual intervention or one-off cache warming each deploy. For example, a plugin like Cache Warmer could automatically crawl and warm key pages after clearing occurs. Or a custom script could re-cache top product queries on a schedule.

Additional benefits of automated cache warming include keeping caches continuously hot at all times, removing reliance on live traffic to gradually trigger caching, and ensuring predictable optimized performance around the clock through programmed cache priming. When combined with intelligent cache expiration rules, automated warming can keep sites performing at peak speed.

Common Cache Clearing Errors in Craft CMS

Permissions Issues

One of the most common issues that can prevent smoothly clearing caches in Craft CMS is running into permissions errors on the underlying cache folders. Craft needs proper write access to core cache folders like craft/storage/runtime/cache, templates, and transforms in order to successfully delete old cache files on clear.

However, if the permissions on these folders are too restrictive, you may encounter errors like:

Unable to clear caches: Failed to delete file

This occurs when the web server user lacks the proper delete access to manage clearing cache files. Some common cache folders that require sufficient write permissions include craft/storage/runtime/ (usually 755 or 775 recommended), craft/storage/rebooted/ (also typically 755 or 775), and then the actual cache type subfolders like cache, templates, etc. which should also be 755 or 775.

The owner of these cache folders should match the user identity running the web server, like www-data or apache. If ownership and permissions were set incorrectly during initial folder creation, it can lead to frustrating permissions-related errors when trying to clear caches down the road.

If you run into mysterious failures when clearing caches, double check write access on the key cache folders as restrictive permissions is a prime suspect.

Invalid Cache Type

Another potential error that can surface when trying to clear caches in Craft relates to targeting a cache type that doesn't actually exist. For example, if you try to delete something invalid like mycache that hasn't been defined:

{% cache using key %}

{% endcache %}

{{ craft.app.cache.delete('mycache') }}

This would result in a cache clearing error since mycache is an undefined cache type in Craft. Some common valid cache types that can be cleared include template for Twig template caches, data for database query caches, transform for generated asset transform caches, and so on.

The solution is to double check that you are targeting a cache type that matches your actual caching configuration and workflow. Referencing an invalid or non-existent cache type is a straightforward cause of cryptic caching errors. Defining your cache types clearly upfront prevents this.

Caching Disabled

Finally, another potential gotcha when trying to clear caches in Craft CMS is having caching disabled outright, either globally or for specific cache types. For example, if you have selectively disabled Twig template caching in your config/general.php:

// config/general.php

'enableTemplateCaching' => false,

Trying to clear the template cache would result in an error:

Template caching is disabled

It's important to verify caching is enabled both globally under Settings → General, and specifically for the cache type you want to clear. Caching sometimes gets disabled as part of troubleshooting, disabling certain plugins, or config optimizations. Confirm it's active before attempting to clear caches, or re-enable it to resolve any related errors.

Shape April 2022 HR 202
Andy Golpys
- Author

Andy has scaled multiple businesses and is a big believer in Craft CMS as a tool that benefits both Designer, Developer and Client. 

Share
Feedback
Show us some love
Email Us
We usually reply within 72 hours
Agency Directory
Submit your agency
Affiliate Partners
Let's chat