Execute a piece of code also when the cached version of a page is served

You call it asynchronously via the REST API.

In a best case scenario, you want the entire HTML of a page cached (full page cache). Executing PHP inside that is not easily possible and that’s exactly the idea behind it

So what you want is some JavaScript that talks to the REST API. The JavaScript code (your “logic“) must be written in a way that it does not need to change, so it can be embedded within the cached HTML. Your data that comes from the endpoint can change, because the endpoint is not cached in the same way as a site is.