So I created a custom block like this:

  public function build() {
    $output = [
      '#cache' => [
        'keys' => ['bix_salary_jobs'],
        'contexts' => ['url.path'],
        'tags' => ['bix_salary_jobs'],
        'max-age' => 60 * 60 * 24 * 7

    // expensive call comes here.
    $data = expensive_all();
    $output['data'] = $data;
    return $output;

From the browser, I can see this block is cached, because the same content has shown there. If cache is not enabled, i.e, if #cache is removed, the content will be different.

Now my question is since this block has been rendered using the cache, why this expensive call expensive_all(); is still running every time this page refreshes? I can see it runs because I put a var_dump("call runs") inside expensive_all();. This message always shows when page refreshes.

My assumption is since this block has been cached, those expensive call inside this block could be avoided, and that's the purpose of cache. If this expensive call still runs with cache, then this block cache becomes useless.

  • 1
    Are you sure you don't have disabled caching for debugging purpose? Other than that you don't need to build a cacheable render array with cache keys, because the block has one already, so it is enough to return the contexts/tags/max-age. But if you want to build such a cacheable element then put the expensive to calculate function in a #pre_render callback. See dev.acquia.com/blog/drupal-8-performance-render-caching – 4k4 Nov 7 '19 at 8:16
  • 1
    Sounds like you might be calling expensive_all() elsewhere in your code. Try putting a var_dump or something within the build() code you've provided. If thats not getting triggered then something else is calling your expensive_all function – Leigh Nov 7 '19 at 9:23
  • @Leigh, var_dump() is put inside build(), and it has been called too. – smiletrl Nov 7 '19 at 11:30
  • Then it sounds like you dont have block caching enabled and what you thought was drupal's caching may have just been your browser caching. Have you disabled caching via a settings.local.php? Or perhaps something within your code/a module thats disabling it. As if that block is actually getting cached you wouldnt be seeing your dump – Leigh Nov 7 '19 at 11:36
  • @Leigh, I had the same assumption with you. Not sure why it works like this. The cached content can be served as stated in the question body. – smiletrl Nov 7 '19 at 13:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.