<h3>Cache Creation</h3>

<p>The primary files to look at are <code>Cache_Node.php</code> in <code>app/etc/templating/twigextensions</code> and <code>TemplateCacheService.php</code> in <code>app/services</code>.</p>

<p>The Cache Node does some basic checking before deciding what content to output, and what to do with that content. It builds a cache key (either automatically, or uses the one defined), and then looks for an existing cached template. If a cache is found for that key, it is outputted and the template process moves on. If no cache is found for that key, the caching process begins.</p>

<p>If the cache node is not in a situation where caching is being ignored (either Live Preview or a config setting), then it starts caching with the Template Cache Service. That service has a method called <code>startTemplateCache</code>. This method creates an array of element queries and element IDs that are stored under the cache key.</p>

<p>The template within the cache node is then compiled with Twig's subcompile method. While this is happening, the element queries and resulting element IDs are stored in the previously created arrays. The compiled result is then placed in a variable and then given (along with the other cache parameters) to the <code>endTemplateCache</code> method.</p>

<p>The <code>endTemplateCache</code> method stores the cache in the <code>templatecaches</code> table. It also loops over the element criteria and element id arrays to tag the caches using the <code>templatecachecriteria</code> and <code>templatecacheelements</code> respectively.</p>

<p>Finally, the cache tag outputs the body (cached or otherwise).</p>

<h2>Cache Clearing</h2>

<p>When you make changes to elements in the control panel, the Template Cache Service does one or two things to clear caches:</p>

<ul>
<li><p>If the element was <strong>modified</strong> or <strong>deleted</strong>, it will check the <code>templatecacheelements</code> table to immediately clear any caches that it knows the element was involved in.</p></li>
<li><p>If the element was <strong>added</strong> or <strong>modified</strong>, it queues up a new “Delete Stale Template Caches” task, which cycles through the <code>templatecachecriteria</code> table to see if there are any cached element queries which (if not cached) would have started showing the just-saved element. If the query returns the element, its corresponding cache will be deleted.</p></li>
</ul>

CC BY-SA 3.0
2015-07-20T15:33:56.963Z
@BryanRedeagle re: to your comment about extending TemplateCacheService - I don't think that would work, because the BaseTemplate (which populates the Element IDs when the template is compiled) will call the load the default "templateCache" component, instead of a custom one (or is there a way to overwrite configuration so that your custom templateCache service in Craft is loaded instead of the default one?).
Christian P
CC BY-SA 3.0
2015-07-20T15:45:54.290Z
Really, both would end up being loaded. That's why you need to build a new Twig tag. The Twig tag is what's calling the Template Cache Service. You would also need to make sure you had the same hooks set up to clear your cache when changes are made.
Bryan Redeagle
CC BY-SA 3.0
2015-01-20T23:33:46.897Z
Thanks Bryan. I still dream of a Template Cache Service that does not only clear the caches but also updates them. :)
carlcs
CC BY-SA 3.0
2015-01-20T23:41:52.977Z
That would just be a matter of building a plugin that extends the Template Cache Service to include such a feature, and then building a new Twig extension to call that instead of the default. Personally that seems a tad resource intensive.
Bryan Redeagle
CC BY-SA 3.0
2015-01-25T05:00:00.947Z
Excellent, thanks Bryan for the detailed answer! And thanks Brandon for the additional notes on cache clearing!
Lindsey D
CC BY-SA 3.0
2015-01-20T22:39:29.643Z
2015-01-23T15:15:58.747Z
2015-01-23T15:15:58.747Z
Bryan Redeagle
<p>The <a href="http://buildwithcraft.com/docs/templating/cache"><code>{% cache %}</code></a> tag is quite powerful, and can be used to greatly increase the performance of templates.</p>

<p>But ultimately the whole thing is still pretty mysterious. I can see three tables in the database which seem to relate to caching:</p>

<ul>
<li><strong>craft_templatecachecriteria</strong></li>
<li><strong>craft_templatecacheelements</strong></li>
<li><strong>craft_templatecaches</strong></li>
</ul>

<p>I'm still trying to grasp how it all ties together... If I can get a better understanding of how it all works in the "big picture", it will help me to make better decisions as to when &amp; where to use caching.</p>

<p>I know the answer is probably complex, but I'd still love to know... <strong>How does caching work?</strong></p>

<templating><caching>
How does template caching work?
# How does template caching work?

(Asked by: username_0 on 2015-01-16)

The [`{% cache %}`](http://buildwithcraft.com/docs/templating/cache) tag is quite powerful, and can be used to greatly increase the performance of templates.

But ultimately the whole thing is still pretty mysterious. I can see three tables in the database which seem to relate to caching:

* **craft\_templatecachecriteria**
* **craft\_templatecacheelements**
* **craft\_templatecaches**

I'm still trying to grasp how it all ties together... If I can get a better understanding of how it all works in the "big picture", it will help me to make better decisions as to when & where to use caching.

I know the answer is probably complex, but I'd still love to know... **How does caching work?**

**Tags:** templating, caching

---

## 1 answers

### Answer by username_1 on 2015-01-20. Score: 14 | Accepted answer

### Cache Creation

The primary files to look at are `Cache_Node.php` in `app/etc/templating/twigextensions` and `TemplateCacheService.php` in `app/services`.

The Cache Node does some basic checking before deciding what content to output, and what to do with that content. It builds a cache key (either automatically, or uses the one defined), and then looks for an existing cached template. If a cache is found for that key, it is outputted and the template process moves on. If no cache is found for that key, the caching process begins.

If the cache node is not in a situation where caching is being ignored (either Live Preview or a config setting), then it starts caching with the Template Cache Service. That service has a method called `startTemplateCache`. This method creates an array of element queries and element IDs that are stored under the cache key.

The template within the cache node is then compiled with Twig's subcompile method. While this is happening, the element queries and resulting element IDs are stored in the previously created arrays. The compiled result is then placed in a variable and then given (along with the other cache parameters) to the `endTemplateCache` method.

The `endTemplateCache` method stores the cache in the `templatecaches` table. It also loops over the element criteria and element id arrays to tag the caches using the `templatecachecriteria` and `templatecacheelements` respectively.

Finally, the cache tag outputs the body (cached or otherwise).

## Cache Clearing

When you make changes to elements in the control panel, the Template Cache Service does one or two things to clear caches:

* If the element was **modified** or **deleted**, it will check the `templatecacheelements` table to immediately clear any caches that it knows the element was involved in.
* If the element was **added** or **modified**, it queues up a new “Delete Stale Template Caches” task, which cycles through the `templatecachecriteria` table to see if there are any cached element queries which (if not cached) would have started showing the just-saved element. If the query returns the element, its corresponding cache will be deleted.

> **Comments:**
> **username_3**: Thanks Bryan. I still dream of a Template Cache Service that does not only clear the caches but also updates them. :)  
> **username_1**: That would just be a matter of building a plugin that extends the Template Cache Service to include such a feature, and then building a new Twig extension to call that instead of the default. Personally that seems a tad resource intensive.  
> **username_0**: Excellent, thanks Bryan for the detailed answer! And thanks Brandon for the additional notes on cache clearing!  
> **username_2**: @BryanRedeagle re: to your comment about extending TemplateCacheService - I don't think that would work, because the BaseTemplate (which populates the Element IDs when the template is compiled) will call the load the default "templateCache" component, instead of a custom one (or is there a way to overwrite configuration so that your custom templateCache service in Craft is loaded instead of the default one?).  
> **username_1**: Really, both would end up being loaded. That's why you need to build a new Twig tag. The Twig tag is what's calling the Template Cache Service. You would also need to make sure you had the same hooks set up to clear your cache when changes are made.  

---

