liveBook · Manning

DynamicSupervisor

As explained in Elixir in Action, Third Edition

DynamicSupervisor is an OTP and Elixir supervisor implementation that starts and supervises child processes dynamically at runtime.

DynamicSupervisor starts and supervises child processes on demand when the required number of workers is unknown in advance. Unlike Supervisor, it starts without a predefined child list and accepts children through DynamicSupervisor.start_child/2. section 9.2.2

Use it to:

  • Register the supervisor locally so application code can request new supervised workers by name. section 9.2.2
  • Treat {:error, {:already_started, pid}} as success when a named worker already exists. section 9.2.3
  • Rely on serialized child-start requests to avoid races between concurrent callers, while recognizing the synchronous call cost. section 9.2.3

On-demand to-do servers

Todo.Cache runs as a named DynamicSupervisor. Its server_process/1 function starts a Todo.Server for a list and returns either the new PID or the PID of an already-registered server. section 9.2.2 section 9.2.3

Listing 9.11 Finding a to-do server (dynamic_workers/lib/todo/cache.ex)
defmodule Todo.Cache do
  ...
 
  def server_process(todo_list_name) do
    case start_child(todo_list_name) do
      {:ok, pid} -> pid                          #1
      {:error, {:already_started, pid}} -> pid   #2
    end
  end
 
  defp start_child(todo_list_name) do
    DynamicSupervisor.start_child(
      __MODULE__,
      {Todo.Server, todo_list_name}
    )
  end
end

Shows the concise lookup pattern that handles both newly started and already running workers. section 9.2.3

How Elixir in Action, Third Edition covers it

How deep it goes
Explains startup, child specifications, registration, duplicate starts, serialization, and synchronous-call costs without detailing supervisor internals.
Examples
Uses Todo.Cache to create named Todo.Server processes for individual to-do lists.
What it assumes
Assumes familiarity with Elixir processes, GenServer registration, child specifications, and basic supervision.
What you can do after
Operate dynamic workers through DynamicSupervisor.start_child/2 and handle concurrent or duplicate-start results.
How it connects
Connects DynamicSupervisor with Supervisor, GenServer, process registration, supervision trees, and process state.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.