Remove the cache for a particular Twig file
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