How to Use Drupal #lazy_builder for Personalized Blocks Without Breaking Dynamic Page Cache

One of the most common performance killers on authenticated Drupal sites happens when a single personalized widget—such as a “Welcome back, Sarah” banner, a shopping cart count, or a live stock badge—bubbles max-age: 0 or user cache context up to the entire page. The moment that metadata bubbles to the root render array, Drupal’s Dynamic Page Cache marks the whole page UNCACHEABLE for logged-in users, forcing Drupal to rebuild the header, navigation, Views, and footer from scratch on every hit. Using #lazy_builder isolates that dynamic fragment into a placeholder so 95% of the page stays cached.

Editorial illustration of Drupal #lazy_builder placeholders with Dynamic Page Cache and BigPipe

Editorial illustration: #lazy_builder prevents per-user or max-age: 0 metadata from poisoning the outer page cache.

Summary

  • A #lazy_builder callback tells Drupal’s renderer to replace a dynamic element with a lightweight placeholder inside the outer cached page, evaluating only the small personalized callback at request time (and streaming it via BigPipe when enabled).
  • Per Drupal’s render callback security rules, any class providing a #lazy_builder callback must implement TrustedCallbackInterface (otherwise Drupal throws UntrustedCallbackException).
  • #lazy_builder callbacks accept only scalar arguments (string, int, float, bool, NULL)—never pass full $node or $user objects; pass IDs like $node->id() instead.
  • If a #lazy_builder element itself returns max-age: 0, that uncacheable setting stays isolated inside the placeholder—unless you omit placeholder generation (#create_placeholder / auto-placeholdering conditions).

Why dynamic blocks break Dynamic Page Cache without placeholders

Suppose a custom block renders an account greeting and sets '#cache' => ['contexts' => ['user'], 'max-age' => 0]. Because Drupal bubbles cacheability metadata upward from child elements to parent templates, the entire page inherits max-age: 0 and user. Dynamic Page Cache refuses to store the page, and your X-Drupal-Dynamic-Cache header drops to UNCACHEABLE.

With #lazy_builder, the block returns a placeholder first—with no user context or max-age: 0 on the outer shell. Dynamic Page Cache stores the outer page once across roles, and only the tiny lazy-builder callback runs per request.

Step-by-step: Build a safe #lazy_builder service in Drupal 10 and 11

1. Implement TrustedCallbackInterface on a dedicated service

As enforced since Drupal 9 and documented in Drupal’s BlockViewBuilder::lazyBuilder and change record #2966725, render callbacks must be explicitly trusted:

<?php

declare(strict_types=1);

namespace Drupal\my_module;

use Drupal\Core\Security\TrustedCallbackInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;

final class UserGreetingBuilder implements TrustedCallbackInterface {

  use StringTranslationTrait;

  public function __construct(
    private readonly AccountProxyInterface $currentUser,
  ) {}

  public static function trustedCallbacks(): array {
    return ['buildGreeting'];
  }

  public function buildGreeting(string $prefix): array {
    return [
      '#markup' => $this->t('@prefix @name', [
        '@prefix' => $prefix,
        '@name' => $this->currentUser->getDisplayName(),
      ]),
      '#cache' => [
        'contexts' => ['user'],
        'tags' => ['user:' . $this->currentUser->id()],
      ],
    ];
  }

}

Register my_module.user_greeting_builder in my_module.services.yml with @current_user injected.

2. Return the #lazy_builder render array (not the rendered HTML)

Inside your block plugin’s build() method, return only #lazy_builder (plus #create_placeholder => TRUE when you want to guarantee placeholdering even if the callback itself uses a context/max-age below auto-placeholdering thresholds):

public function build(): array {
  return [
    '#lazy_builder' => ['my_module.user_greeting_builder:buildGreeting', ['Hello']],
    '#create_placeholder' => TRUE,
  ];
}

Notice two strict rules of #lazy_builder render arrays:

  • No sibling render properties like #markup or #theme alongside #lazy_builder in the same array—the callback must return the actual render array.
  • Only scalar arguments (['Hello']) inside the second array element, because Drupal serializes those arguments into the placeholder string.

3. Verify X-Drupal-Dynamic-Cache: HIT on staging

Enable BigPipe (included in Drupal core) and inspect response headers while logged in. Confirm X-Drupal-Dynamic-Cache switches from UNCACHEABLE to HIT on the second page load, while the personalized greeting updates per user. For deeper header inspection, see our guide on debugging Drupal cache tags without clearing all caches and Drupal render cache metadata.

Common mistakes

  • Forgetting TrustedCallbackInterface. Calling a service method from #lazy_builder without trustedCallbacks() throws UntrustedCallbackException at runtime.
  • Passing $node or $account objects in #lazy_builder arguments. Drupal throws an exception if non-scalar arguments are passed—pass (int) $node->id() and load the entity inside the lazy builder if needed.
  • Putting #cache => ['max-age' => 0] outside the #lazy_builder on the parent block array. Putting max-age: 0 on the outer array defeats the placeholder completely and forces the whole page to uncacheable! Put cacheability metadata inside the render array returned by the lazy builder method.
  • Using #lazy_builder for content that is identical for all users. If a block only varies by node:42 and never by user or session, standard render caching with cache tags is simpler and faster without placeholder overhead—compare Drupal Views tag-based vs. time-based caching.

Why this matters

Authenticated Drupal traffic (member portals, intranets, e-commerce) cannot rely on anonymous page caching or Cloudflare HTML caching. Isolating per-user fragments with #lazy_builder and BigPipe keeps logged-in page loads fast without sacrificing personalization.

My Take

Whenever an authenticated Drupal page shows X-Drupal-Dynamic-Cache: UNCACHEABLE, inspect your custom blocks and Twig embeds first. Moving a single per-user greeting or cart counter behind a TrustedCallbackInterface #lazy_builder service with #create_placeholder => TRUE often cuts server response times in half.

Conclusion

Isolate per-user or high-churn Drupal render elements into a dedicated service implementing TrustedCallbackInterface, pass only scalar arguments to #lazy_builder, set #create_placeholder => TRUE, keep #cache metadata inside the callback’s return array, and verify X-Drupal-Dynamic-Cache: HIT on staging.

Sources