liveBook · Manning

Supervisor.child_spec/2

As explained in Elixir in Action, Third Edition

Supervisor.child_spec/2 is an Elixir function that derives or modifies a child specification for a supervised process.

Supervisor.child_spec/2 derives a child specification from a worker tuple and modifies fields such as :id. This prevents duplicate child identifiers when several instances share one module. section 9.1.5

Assigning unique worker IDs

A database supervisor can build three worker specifications from {Todo.DatabaseWorker, {@db_folder, worker_id}}, then call Supervisor.child_spec(default_worker_spec, id: worker_id). Without the override, autogenerated specifications use Todo.DatabaseWorker as the ID for every worker and supervisor startup fails. section 9.1.5

Listing 9.6 Supervising workers (pool_supervision/lib/todo/database.ex)
defmodule Todo.Database do
 @pool_size 3
 @db_folder "./persist"

 def start_link do
   File.mkdir_p!(@db_folder)

   children = Enum.map(1..@pool_size, &worker_spec/1)
   Supervisor.start_link(children, strategy: :one_for_one)
 end

 defp worker_spec(worker_id) do
   default_worker_spec = {Todo.DatabaseWorker, {@db_folder, worker_id}}
   Supervisor.child_spec(default_worker_spec, id: worker_id)
 end

 ...
end

Shows the compact worker-specification function inside a supervisor that starts a pool with a :one_for_one strategy. section 9.1.5

How Elixir in Action, Third Edition covers it

How deep it goes
Explains default IDs, duplicate-ID failure, and the practical override, but does not detail the complete child-specification schema.
Examples
Demonstrates a three-worker database pool whose specifications receive distinct numeric IDs.
What it assumes
Assumes familiarity with supervisors, worker processes, and default child_spec/1 generation from use GenServer.
What you can do after
Apply it via Supervisor.child_spec/2 to customize child IDs when starting multiple instances of one worker module.
How it connects
Connects child specifications with supervisors, GenServer-generated child_spec/1 functions, worker processes, and supervision trees.

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.