Problem/Motivation
I've debugged a problem on a Drupal Commerce project, where the add_to_cart Event was firing either not (or too much delayed) or multiple times on subsequent requests. "too much delayed" -> it hasn't fired on the product page reload after the product has been added to the cart, and it wouldn't do so as well, if you reload the page multiple times. Instead, it rendered on the page visited next, which in this case was often the cart page.
I tracked it down, that the product pages get a X-Drupal-Dynamic-Cache "HIT" on subsequent requests, so that hook_page_attachments() won't get called at all at these pages. This is good so for "normal" product page visits, but in case we have any delayed GTM event in the session, we'll want to render it immediately. Instead this only happens at the first response that doesn't hit the dynamic page cache.
Even worse: if you add a product to the cart, and then click a link to let's say another product. And this product isn't cached yet, but is added to the page cache on your request, then the add_to_cart event will fire on any subsequent HIT - so if you press F5 10 times, then 10 times the add_to_cart event will be fired to GTM
Steps to reproduce
dynamic_page_cache must be installed of course. And you have to make sure, that the dynamic page cache gets a HIT on subsequent visits on the product page (check the X-Drupal-Dynamic-Cache header)
Visit product XY, add the product to the cart and you'll see that the page iis shipped from dynamic page cache, no add_to_cart event data is present in the Drupal settings.
Now visit another product, which hasn't been cached yet. Now, the add_to_cart event data should be present in the Drupal settings of this page. Reload the page, and it will still be there.
Proposed resolution
Make sure, requests having delayed event data are not handled by dynamic page cache. In order to accomplish that, we should implement a request policy handling this