ankane / ahoy

Simple, powerful, first-party analytics for Rails
MIT License
4.23k stars 377 forks source link

Race condition between visit and backend event after visit token expires #559

Open DamianPereira opened 3 months ago

DamianPereira commented 3 months ago

Hi,

We are having some issues when the visit token expires. We are using Ahoy.api = true and Ahoy.server_side_visits = :when_needed, and The situation is as follows:

  1. A user browses our store for a bit and leaves
  2. 4 hours later they come back, and first thing they do is add an item to cart
  3. This triggers both a post to /ahoy/visits from ahoy.js on our frontend, and a post to our controller for the cart (let's say /cart).
  4. The controller for the cart tries to do ahoy.track

When this happens, sometimes the post to /ahoy/visits finishes first, causing the event from the cart to fit into that visit (this is the expected scenario), when the cart route finishes first, 2 visits are created, one auto generated from the :when_needed parameter, and the other from the /post route.

This causes issues for parameters like landing_page as well, which is either nil or an api route a lot of the time.

Please tell me if you need any more information! I'd be happy to provide more context. I'm not sure what solution we might have, are we supposed to wait for visit post to finish in our own code? Or is there an option which might help that I'm missing?