liveBook · Manning

DynamicSupervisor.start_child/2

As explained in Elixir in Action, Third Edition

DynamicSupervisor.start_child/2 starts a new child process under a DynamicSupervisor and reports whether the start succeeded or conflicted with an already running child.

DynamicSupervisor.start_child/2 starts a child process on demand under a DynamicSupervisor when the required number of children is unknown in advance. The call sends a synchronous request to the supervisor, which starts the child and serializes concurrent start requests. section 9.2.2

Handle the returned result according to the child’s registration state:

  • Match {:ok, pid} when the child starts successfully. section 9.2.3
  • Match {:error, {:already_started, pid}} when registration finds an existing process, then reuse that pid. section 9.2.3
  • Recognize the efficiency boundary: repeated requests can briefly start and stop redundant children and make the supervisor a bottleneck. 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

Use the Todo.Cache implementation to see successful and already-started results mapped to the process returned to callers. section 9.2.3

How Elixir in Action, Third Edition covers it

How deep it goes
Explains invocation, synchronous serialization, result handling, and the supervisor-bottleneck trade-off.
Examples
Uses Todo.Cache to start Todo.Server processes for to-do lists and reuse already registered processes.
What you can do after
Operate DynamicSupervisor to start workers and handle successful or already-started results without race conditions.
How it connects
Connects DynamicSupervisor to Supervisor, child specifications, GenServer registration, and process lookup.

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.