We've started to add server side Mixpanel tracking, and official documentation recommends tracking asynchronously so it doesn't effect performance. The Mixpanel method involves writing events to a log file, and then consuming them later. I came up with a more streamlined method where you use Sidekiq to perform the tracking asynchronously with no need for a file.
This first step isn't absolutely required, but I created a singleton instance for my Mixpanel tracker so I don't have to create a new instance every time:
class MixpanelTracker
include Singleton
def initialize
@tracker = Mixpanel::Tracker.new(ENV['mixpanel_token'])
end
def track(user_id, event_key, properties)
@tracker.track(user_id, event_key, properties)
end
end
Then I created the Sidekiq worker:
class MixpanelWorker
include Sidekiq::Worker
def perform(user_id, event_key, properties)
tracker = MixpanelTracker.instance
tracker.track(user_id, event_key, properties)
end
end
And in my controller code, I call perform_async on the worker:
MixpanelWorker.perform_async(user.id, 'Created an account', {
'Name': user.name,
'Email': user.email
})
That's it! For some reason the tracking didn't work in my local development environment, but it worked fine once I pushed it to Heroku