Supervised Fire-and-Forget Tasks in Elixir with Task.Supervisor
Replace unsupervised Task.async with Task.Supervisor.async_nolink to keep fire-and-forget work inside your OTP supervision tree, gain visibility via which_children, and ensure graceful shutdown on application stop.
07 Sept 2026, 11:31 UTC

Problem: Unsupervised Background Work Leaks Processes
Using Task.async/1 or Task.start/1 for fire-and-forget work creates processes outside your supervision tree. When the application stops, these tasks are killed abruptly—no cleanup, no graceful shutdown, and no visibility into what's still running. In production, this means lost work, connection leaks, and no way to inspect in-flight background jobs.
Solution: Task.Supervisor with async_nolink/3
Task.Supervisor keeps dynamically started tasks inside the OTP supervision tree. Tasks started with async_nolink/3 are not linked to the caller: a caller crash won't kill the task, and a task crash won't kill the caller. The supervisor tracks every task, supports graceful shutdown via the standard OTP termination sequence, and exposes which_children/0 for health checks.
Prerequisites
- Elixir 1.11+ (Task.Supervisor stabilized in 1.11;
async_nolink/3added in 1.13) - OTP 24+ recommended for consistent shutdown behavior
- A Mix project with an
Applicationmodule (standardmix new --suplayout)
Verify availability in your environment:
iex -S mix
# In the shell:
h Task.Supervisor
# Confirm async_nolink/3 appears in the function list
Add the Supervisor to Your Application Tree
Open lib/my_app/application.ex and add a Task.Supervisor child under the top-level supervisor. Use :one_for_one so a single task crash doesn't affect siblings.
defmodule MyApp.Application do
@moduledoc false
use Application
def start(_type, _args) do
children = [
# ... existing children ...
{Task.Supervisor, name: MyApp.TaskSupervisor, strategy: :one_for_one}
]
opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)
end
end
The name: option registers the supervisor locally so you can call MyApp.TaskSupervisor anywhere without passing a PID.
Start Fire-and-Forget Tasks
Replace raw Task.async/1 calls with Task.Supervisor.async_nolink/3. The third argument is the module-function-args tuple or an anonymous function.
# In a controller, channel, or GenServer callback:
Task.Supervisor.async_nolink(MyApp.TaskSupervisor, fn ->
# Background work: send email, call webhook, process upload
ExternalApi.notify_user(user_id, payload)
end)
Key behaviors:
- Returns
{:ok, pid}immediately; the caller continues without waiting. - No link is created—caller exit won't terminate the task.
- Task crashes are logged by the supervisor but don't propagate to the caller.
Inspect Running Tasks
Use Task.Supervisor.which_children/1 to list live tasks for health endpoints or debugging.
defmodule MyApp.HealthCheck do
def background_task_count do
children = Task.Supervisor.which_children(MyApp.TaskSupervisor)
# children = [{child_spec_id, pid, :worker, [module]} | ...]
Enum.count(children)
end
def task_details do
Task.Supervisor.which_children(MyApp.TaskSupervisor)
|> Enum.map(fn {id, pid, type, modules} ->
%{id: id, pid: pid, type: type, module: hd(modules)}
end)
end
end
This enables a /health/background endpoint that returns the number of in-flight jobs and their modules.
Graceful Shutdown Behavior
When the application stops (via System.stop/0, release shutdown, or Application.stop/1), the supervisor receives :shutdown and forwards it to each child task. Each task process gets a configurable shutdown timeout (default 5000 ms) to finish work before being killed with :kill.
To adjust the timeout per task, use the :shutdown option in the child spec. Since async_nolink creates a temporary child spec, you can't customize it directly. For tasks needing longer shutdown, start a dedicated Task.Supervisor with a custom :shutdown value in its own child spec:
# In application.ex children list:
{Task.Supervisor,
name: MyApp.LongRunningTaskSupervisor,
strategy: :one_for_one,
shutdown: 30_000} # 30 seconds for long jobs
Then route long-running work to that supervisor.
Concurrency Guard: Prevent Unbounded Task Spawning
Task.Supervisor imposes no limit. A traffic spike can spawn thousands of tasks, exhausting schedulers or memory. Add a simple semaphore using :erlang.system_info/1 or a lightweight pool.
Example: limit to 100 concurrent tasks using an ETS counter.
defmodule MyApp.ConcurrencyGuard do
@table :task_slots
@max 100
def init do
:ets.new(@table, [:named_table, :public, {:keypos, 1}])
:ets.insert(@table, {@table, 0})
end
def acquire do
case :ets.update_counter(@table, @table, {2, 1}, {@table, 0}) do
count when count =< @max -> :ok
_count ->
:ets.update_counter(@table, @table, {2, -1}, {@table, 0})
{:error, :busy}
end
end
def release do
:ets.update_counter(@table, @table, {2, -1}, {@table, 0})
end
end
Wrap your task start:
case MyApp.ConcurrencyGuard.acquire() do
:ok ->
Task.Supervisor.async_nolink(MyApp.TaskSupervisor, fn ->
try do
do_work()
after
MyApp.ConcurrencyGuard.release()
end
end)
{:error, :busy} ->
# Reject, queue, or apply backpressure
{:error, :overloaded}
end
For production workloads, consider Poolboy, Jobs, or Broadway instead of a hand-rolled guard.
Expected Checks After Deployment
- Task appears in supervisor: Call
Task.Supervisor.which_children(MyApp.TaskSupervisor)immediately after starting a task; the returned list should include a new{ref, pid, :worker, [Module]}tuple. - Caller crash isolation: Kill the caller process (e.g.,
Process.exit(caller_pid, :kill)) and verify the background task continues to completion. - Graceful shutdown: Stop the application (
Application.stop(:my_app)in a test ormix release+bin/my_app stop) and confirm tasks receive:shutdownand finish within the timeout (addProcess.sleep/1in test tasks to observe). - Health endpoint: Hit your
/health/backgroundroute; it should return a JSON count matchingwhich_children/1.
Recovery Options
Task Crashes Silently
Because async_nolink doesn't link or monitor, the caller never learns of a task crash. Add explicit monitoring if you need failure notification:
{:ok, pid} = Task.Supervisor.async_nolink(MyApp.TaskSupervisor, fn -> risky_work() end)
Process.monitor(pid)
# Caller will receive {:DOWN, ref, :process, pid, reason} on crash
Supervisor Restart Loops
With strategy: :one_for_one, a repeatedly crashing task restarts indefinitely. If the task function is deterministic and always fails, this wastes resources. Either fix the task or switch the supervisor to :rest_for_one (rarely appropriate) or use a circuit-breaker pattern around the work.
Application Upgrade (Hot Code Reload)
During a release upgrade, the supervisor and its children are suspended and restarted. In-flight tasks started with async_nolink are terminated with :shutdown per the OTP upgrade sequence. Design tasks to be idempotent or checkpoint progress externally (database, message queue) if they must survive upgrades.
Limitations
- No built-in result handling:
async_nolinkreturns{:ok, pid}, not aTaskstruct. You cannotTask.await/2the result. Use a reply channel (message queue, PubSub, database) if the caller needs the outcome. - Not a GenServer replacement: For stateful coordination, periodic work, or complex lifecycle, use a
GenServerorGenStageunder the supervisor instead. - Version dependency:
async_nolink/3requires Elixir 1.13+. On older versions, useTask.Supervisor.start_child/2with aTaskchild spec andTask.await/2on a monitor. - No backpressure: The concurrency guard above is advisory. Under sustained overload, the ETS counter becomes a bottleneck. A proper pool library handles queueing and rejection more robustly.
Verification Checklist
# 1. Confirm module exists
iex -S mix
h Task.Supervisor
# 2. Start a task and inspect
{:ok, pid} = Task.Supervisor.async_nolink(MyApp.TaskSupervisor, fn -> :timer.sleep(5000); IO.puts("done") end)
Task.Supervisor.which_children(MyApp.TaskSupervisor)
# Should list the new task
# 3. Kill caller, task survives
spawn(fn -> Process.exit(self(), :kill) end)
# Wait, then check which_children again — task still present
# 4. Stop app, watch shutdown
Application.stop(:my_app)
# Tasks get :shutdown, have 5s (default) to exit
Run these steps in a staging environment before promoting to production.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.