There's a Cache Bin for That!

Drupal 8 Cache System

Shawn Duncan, Technical Architect

Digital Pulp


Cache API

Cache API

How things get stored in cache

Cache services:


Cache API

  • A cache service in injected
  • A cache ID is created - 1:1 mapping between cid and data item
  • Before the data is obtained or calculated, check cache and use if found
  • Otherwise, generate and cache the data
  • Example:
// cacheDefault is injected cache.default service.
$cid = '' . $entity->id . ':' .  
if ($cache = $this->cacheDefault->get($cid) {
  $data = $cache->data;
else {
  $data = my_module_complicated_calculation();
  // optional $expire and $tags parameters omitted for clarity.
  $this->cacheDefault->set($cid, $data);

Cache API

  • If the core cache bins don't meet your needs you can define your own by appropriately defining a service. See Cache Bins for details or search through for cache.bin to see examples.
  • Both deletion and invalidation methods are available. Invalidation is better for performance and stability and should be use unless the data must be removed immediately.

Cache API

Cache Tags

  • Used to describe dependencies on data.
  • Optional argument when caching data. All data with the same tag can be invalidated as a group.
  • Convention is [prefix]:[suffix]
    • node:37
    • user:3
  • All core entities have built-in support for cache tags.
  • You can define your own.

Cache API

Cache Contexts

  • Used to describe dependencies on context, technically the request
  • Can define your own contexts.
  • Core contexts:
  • cookies
    • :name
  • headers
    • :name
  • ip
  • languages
    • :type
  • request_format
  • route
    • .book_navigation
    • .menu_active_trails
      • :menu_name
    • .name
  • session
    • .exists
  • theme
  • timezone
  • url
    • .host
    • .query_args
      • :key
      • .pagers
        • :pager_id
    • .path
      • .parent
    • .site
  • user
    • .is_super_user
    • .node_grants
      • :operation
    • .permissions
    • .roles
      • :role

Cache & Local Development

Cache &
Local Development

  • drupal site:mode dev will get you most of the way.
  • In the generated services.yml set http.response.debug_cacheability_headers to true
  • Can manually cache clear - important for seeing how your site interacts with cache
  • Cache backend is pluggable - plug it in to the Null Cache service when needed. Use a settings.local.php:
    $settings['container_yamls'][] = DRUPAL_ROOT . '/sites/';
    $settings['cache']['bins']['render'] = 'cache.backend.null';
    $settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

Render Cache

Render Arrays and Cache

$render_array = (
    '#cache => array(
        'max-age' => 0,
        'tags' => array(),
        'contexts' => array(),

Exempt a route from Cache

Blocking Cache



Open Q & A

“An infinite mystery is the Force.”

“The more we learn, the more we discover how much we do not know.”