Caching in Drupal 8
Blog

A beginners guide to caching in Drupal 8

Caching is a popular technique to optimize the performance of a website. It is a process that stores web data (HTML, CSS, Image) in some accessible space. Moreover, a cache is a detailed information of a validity of a resource. This information defines for how long the resource is valid and should not be considered stale. The information can be stored at every level right from the original server to intermediate proxies to the browser.

Here you will get to learn about what key/value pairs in the header mean and Cacheability metadata in Drupal 8.

Every request or response contains a HTTP header, which provides additional information about the request/response. This also contains information related to cache.

Typical HTTP Header Example :

HTTP Header Example

Let’s see what these key/value pairs in the header mean:

  • Expires: The Expires header sets a time in the future when the content will expire. This header is probably best used only as a fallback.
     
  • Etag: It is a unique hash identifier of the cacheable object that the browser caches. Whenever a cached response is requested repeatedly, browser checks with the server if the eTag of the response is modified. If the response is not modified, the server returns 304 not modified else 200 along with new response & new eTag.
     
  • Last-modified: This parameter specifies the date and time the resource was last modified. Last-modified is used as a fallback when Etag is not specified.

          Syntax : , :: GMT

  • Vary: Vary specifies the list of a parameter on which the response should vary. For example, Accept-Encoding specifies the format in which the browser expects the response such as gzip, sdch or simply text/html.

Similarly, User-Agent specifies the user-agent such as a mobile user or desktop user based on which the content should vary.

Another interesting Vary parameter is ‘cookie’ which specifies to vary content based on the user. For instance, the different version of same content for the anonymous user and logged-in user.

  • Cache-Control: Cache-Control specifies directives which instruct the browser / intermediate-proxies to who can cache the response, the conditions for caching the response and the maximum time for which the response can be cached. Some of Cache-Control directives are:
     
    • No-cache: Indicates that the response should be validated with the origin server before sending.
       
    • Public/private: "Public" marked responses indicates that the response can be cached by any cache, even if it has HTTP authentication associated with it. Private marked responses are intended for a single user and intermediate cache should not store the response, but private cache such as browser may store the response.
       
    • No-store: Shows that the response should not be cached by the browser or intermediate proxies.
       
    • Max-age: Indicates the maximum time in seconds for which the content can be cached before it must-revalidate. This replaces the Expires header for modern browsing. This option takes its value in seconds with a maximum valid freshness time of one year (31536000 seconds).
       
    • s-maxage: Similar to the max-age setting. The difference is that this option is used only for intermediary caches.

Now we have a basic understanding of caching, so let’s see how this works in Drupal 8.

Cacheability metadata in Drupal 8 :

All things that are either directly renderable or used to determine what to render, providing cacheability metadata.

Cacheability metadata consists of three properties:

  • Cache tags: If our renderable arrays depend on some data such as entity data or some configuration values we use cache tags to invalidate the data.

    Syntax : “Thing:identifier” 

    Example:

    node:5 // cache tag for node entity 5
    user:4 // cache tag for user entity 4
    node_list // list cache tag for node
    
    $tags = array('node:1', 'user:7');
    \Drupal::cache()->set($cid, $data, CacheBackendInterface::CACHE_PERMANENT, $tags);
    
    // Invalidate all cache items with certain tags.
    \Drupal\Core\Cache\Cache::invalidateTags($tags);
  • Cache contexts: Cache context is used when our renderable arrays depend on some context such as user role, theme or URL. This is similar to Drupal 7 block constants like DRUPAL_NO_CACHE / DRUPAL_CACHE_PER_ROLE / DRUPAL_CACHE_PER_PAGE, but with many more options.

    Example :

    // Setting Cache Context & Tag for a block.
    return array(
      '#markup' => $this->t('My custom block content'),
      '#cache' => array(
        'contexts' => ['url.path'], //setting cache contexts
        'tags' => ['node:1', 'node:2'] // setting cache tags
      ),
    );	 
  • Cache max-age: Cache controls how long an item may be cached by a number of seconds.

    0 means cacheable for zero seconds, i.e. not cacheable.

    \Drupal\Core\Cache\Cache::PERMANENT means cacheable forever, i.e. this will only ever be invalidated due to cache tags. (In other words: ∞, or infinite seconds.)

Here we have explored the basic of Caching in Drupal 8, what key/values pairs in the header mean and cacheability metadata. Caching allows retrieval without having to request the data from the original source. In case you have any questions, feel free to share in the comments below—we'll get back to you ASAP.

Below given is a presentation on Caching in Drupal 8.

Download the Drupal Guide
Enter your email address to receive the guide.
get in touch