Task: Fire-and-Collect Concurrency
Task is the go-to abstraction whenever you need to run a one-off piece of work concurrently and, optionally, get its result back, without writing any GenServer boilerplate. Task.start/1 fires off work you don't care about waiting for, like sending a non-critical notification, while Task.start_link/1 does the same but links the task to the caller so a crash in the task also crashes the caller -- useful when the task's success is essential to the calling process's correctness.
Cricket analogy: Sending a twelfth man to fetch a replacement bat without needing him back in the field immediately is like Task.start -- nobody's waiting on the result, whereas sending a runner for an injured batsman whose return directly affects whether the innings can continue is like Task.start_link, since the runner's failure would abort the whole plan.
# Fire-and-forget, unlinked
Task.start(fn -> Logger.info("Sending analytics ping") end)
# Fire-and-forget, linked (crash propagates to caller)
Task.start_link(fn -> write_critical_cache() end)Task.async and Task.await
The more common pattern is Task.async/1 paired with Task.await/2: async immediately returns a Task struct while the work runs concurrently, and await blocks the caller until that specific task finishes or the timeout (5 seconds by default) expires, raising if the task crashed. For running many independent tasks in parallel, Task.async_stream/3 maps a collection concurrently with a bounded number of workers, which is the idiomatic way to, say, fetch ten URLs concurrently without spawning ten unmanaged processes.
Cricket analogy: Sending a scout to analyze the opposition's net session and asking for the report before the toss is like Task.async/await -- you carry on with other prep and only pause when you actually need that report; scouting five different opposition batsmen concurrently with only two analysts available is like Task.async_stream, bounding how many reports run in parallel.
task = Task.async(fn -> expensive_computation() end)
# ... do other work here ...
result = Task.await(task, 10_000)
urls = ["https://a.example", "https://b.example", "https://c.example"]
results =
urls
|> Task.async_stream(&HTTPClient.get/1, max_concurrency: 4, timeout: 5_000)
|> Enum.map(fn {:ok, response} -> response end)Agent: Simple Shared State
Agent wraps a GenServer-style process around nothing more than a piece of state, giving you Agent.get/2, Agent.update/2, and Agent.get_and_update/2 as simple functional accessors, so it's the right tool when a process's entire job is holding a value with no custom message protocol or business logic beyond reads and updates. Because Agent.update/2 takes a function that computes the new state from the old one, updates remain safe from race conditions the same way GenServer state does -- the function runs inside the Agent's own process, one update at a time.
Cricket analogy: A scoreboard operator whose only job is to hold the current run total and update it after each ball, taking no other responsibility, is like an Agent -- you just ask 'what's the score?' or tell them 'add four runs', and they process one ball at a time so the total is never corrupted.
{:ok, counter} = Agent.start_link(fn -> 0 end, name: :page_views)
Agent.update(:page_views, fn count -> count + 1 end)
current = Agent.get(:page_views, fn count -> count end)
Agent.get_and_update(:page_views, fn count -> {count, count + 1} end)Choosing Between Task, Agent, and GenServer
Reach for Task when you need one-off concurrent work with an optional result, reach for Agent when a process's job is purely holding and updating a simple value, and reach for a full GenServer when you need custom message handling, multiple distinct operations, or integration with handle_info for things like timers and monitors. In practice, many real systems start with an Agent for a small piece of shared state and later graduate to a GenServer once the logic around that state grows more complex than plain get/update.
Cricket analogy: Sending a single fielder to retrieve a ball hit into the crowd is like a Task -- one-off, done; keeping a scorer whose only job is the running total is like an Agent; but running the whole team's tactical operations including bowling changes, field settings, and reviews needs a full captain's decision-making, like a GenServer.
Task.await/2 defaults to a 5-second timeout just like GenServer.call/2, and it raises if the linked task crashes -- use Task.yield/2 instead of await if you want to poll without raising on timeout, or Task.Supervisor.async_nolink/2 if a failing task shouldn't crash the caller.
- Task is for one-off concurrent work, optionally with a result you retrieve via async/await.
- Task.start/1 is unlinked and unsupervised for fire-and-forget work; Task.start_link/1 links the task to its caller.
- Task.async_stream/3 runs a collection concurrently with a bounded max_concurrency, ideal for batch I/O.
- Agent wraps a GenServer around plain state, offering get/2, update/2, and get_and_update/2.
- Agent updates run one at a time inside the Agent's own process, avoiding race conditions.
- Choose GenServer over Task/Agent once you need custom message protocols, multiple operations, or handle_info.
- Task.await/2 and GenServer.call/2 share the same 5-second default timeout convention.
Practice what you learned
1. What is the main use case for Task.async/2 combined with Task.await/2?
2. What does Task.async_stream/3's max_concurrency option control?
3. What is Agent best suited for?
4. Why are Agent updates safe from race conditions even with concurrent callers?
5. When should you prefer a full GenServer over an Agent?
Was this page helpful?
You May Also Like
GenServer Explained
Understand how GenServer standardizes stateful server processes in Elixir with a clean client/callback API.
Processes in Elixir
Learn how Elixir's lightweight BEAM processes enable massive concurrency through isolation and message passing.
Supervisors and OTP
Learn how OTP supervisors monitor child processes and restart them automatically to build fault-tolerant systems.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics