Remove the cache for a particular Twig file I'm showing the name of the currently logged-in user in header, using \Drupal::currentUser()-&gt;getUsername(), but it's showing an already cached  page. I know I can disable the cache for a particular page using \Drupal::service('page_cache_kill_switch')-&gt;trigger(), but this won't work with the header.html.twig file.

How can I achieve it without affecting the performance?
You need a cache context and a cache tag of the user:

$variables['username'] = [
  '#markup' =&gt; \Drupal::currentUser()-&gt;getUsername(),
  '#cache' =&gt; [
    'contexts' =&gt; [
      'user',
    ],
    'tags' =&gt; [
      'user:' . \Drupal::currentUser()-&gt;id(),
    ],
  ],
];


You can add this directly in a preprocess hook, but then the rendered output will vary for each user. For large numbers of users you might want to put this in a lazy builder callback, which will then match the auto-placeholder conditions and can be lazy-loaded through BigPipe without affecting page load performance.

See https://www.drupal.org/docs/8/api/render-api/auto-placeholdering