Set maximum / disable custom block cache for anonymous users I have a little issue regarding my custom block module. The module itself fetches weather data via json-request and the data is shown as a 4-day weather forecast to the user. As the weather should be actualized every day I want to set a "maximum cache time" or even disable caching for the whole block.
Right now I would have to flush the cash manually every day.

After a little bit of research to that topic I found out that using 'max-age' in the build() function would do the trick but it does not affect the caching for anonymous users at all.

Using \Drupal::service('page_cache_kill_switch')-&gt;trigger(); would disable the cache for a specific page or content-type but I don't want to disable the caching for a whole page at once.

So how can I trigger the caching for my custom-block? Or is there even a way to disable the caching for a certain part of the code e.g. the json-request in my case?
This is a known issue Bubbling of elements' max-age to the page's headers and the page cache.

The Internal Page Cache is designed for database content, which is handled by cache tags. So a workaround would be to add a custom cache tag to the block

$build['#cache']['tags'][] = 'weather_forecast';


which will bubble up to the page level and so you can invalidate both cached items, block and page, in a cron job:

/**
 * Implements hook_cron().
 */
function mymodule_cron() {
  \Drupal\Core\Cache\Cache::invalidateTags(['weather_forecast']);
}


All credit goes to @Berdir: Cache max-age and varnish ESI