Task.async code doesn't seem to be running completely when called from my Phoenix Context

I have a very simple use case: when someone does something on my app, I want to send the event to Posthog.

In my Context:

Posthog.send_event(
  "Some event",
  %{
    foobar: "Baz"
  },
  user.id
)

And my Posthog function:

defmodule App.Posthog do
  @moduledoc false

  def send_event(event_name, params, user_id \\ nil) do
    Task.async(fn ->
      # Do something prep for `body`
      Req.post(api_url, json: body)
    end)
  end
end

I want to do that Req.post in the background to not block my UI and I’m OK with a restart/deploy losing some events from being sent.

But when I use Task.async I notice that my events are no longer being sent to Posthog. If I remove the Task.async the event is sent normally.

Any ideas on how to accomplish this?

To fire and forget a background unsupervised task, I had to use Task.start

Task.start(fn ->
  do_something_beefy()
end)
2 Likes