How to prevent caching of field element data in custom field formatter?
For anonymous traffic in general there are probably better solutions client-side. If you want to build this server-side in Drupal then better use a session, this will pass the built in page cache for anonymous traffic.

If you want to handle your own cookies you have to uninstall the Internal Page Cache and cache the pages only in the Internal Dynamic Page Cache. Then for better caching performance set a cache context for the cookie instead of max-age:

  $elements['#cache']['contexts'][] = 'cookies:Drupal_visitor_resource_gate';