supervisor(3erl)
๐ธ supervisor(3erl) โ Erlang Module Definition ๐ธ
okay so first thing, bestie: the manual name is supervisor, it lives in the Erlang Module Definition section, and it's literally the blueprint for one of the most iconic things in OTP. let's get into it ๐
โจ NAME โจ
supervisor โ the generic supervisor behavior. she supervises, that's the whole job ๐
๐ DESCRIPTION ๐
so this behavior module gives you a supervisor: a process whose entire personality is supervising other processes, which we call child processes. very main character energy, very "i don't do the work, i make sure the work gets done." ๐
now, each child process can be one of two things:
- another supervisor โ yes, supervisors supervising supervisors, it's giving supervision-ception ๐
- a worker process โ the ones actually out here doing stuff
worker processes are normally implemented using one of these behaviors:
gen_eventgen_servergen_statem
and a supervisor implemented using this module comes with a standard set of interface functions, plus functionality for tracing and error reporting. so you get the whole package, no cap. โจ
supervisors are how you build a hierarchical process structure called a supervision tree โ and ngl, it's genuinely a nice way to structure a fault-tolerant application. the tree is the vibe. the tree is the moment. ๐๐ณ
for more information, see Supervisor Behaviour in OTP Design Principles. (iykyk, go read it ๐ซถ)
another thing: a supervisor expects the definition of which child processes to supervise to be specified in a callback module that exports a predefined set of functions. so you don't just vibe your way into it โ you hand her a callback module and she takes it from there. ๐
โ ๏ธ and listen, unless otherwise stated, all functions in this module fail if the specified supervisor does not exist, or if bad arguments are specified. so likeโฆ don't do that. ๐
๐ SUPERVISION PRINCIPLES ๐
Okay so a supervisor is literally the main character of keeping its child processes alive: it starts them, stops them, monitors them, and restarts them when necessary. The basic idea? It must keep its child processes alive by restarting them when necessary. fr fr.
The children of a supervisor are defined as a list of child specifications. When the supervisor is started, the child processes are started in order from left to right according to this list. When the supervisor terminates, it first terminates its child processes in reversed start order, from right to left.
๐ Supervisor flags ๐
The supervisor properties are defined by the supervisor flags. The type definition for the supervisor flags is as follows:
sup_flags() = #{strategy => strategy(), % optional
intensity => non_neg_integer(), % optional
period => pos_integer(), % optional
auto_shutdown => auto_shutdown()} % optional
๐ฅ Restart Strategies ๐ฅ
A supervisor can have one of the following restart strategies specified with the strategy key in the above map:
one_for_oneโ If one child process terminates and is to be restarted, only that child process is affected. This is the default restart strategy. โจone_for_allโ If one child process terminates and is to be restarted, all other child processes are terminated and then all child processes are restarted.rest_for_oneโ If one child process terminates and is to be restarted, the 'rest' of the child processes (that is, the child processes after the terminated child process in the start order) are terminated. Then the terminated child process and all child processes after it are restarted. iykyk.simple_one_for_oneโ A simplifiedone_for_onesupervisor, where all child processes are dynamically added instances of the same process type, that is, running the same code.
Functions delete_child/2 and restart_child/2 are invalid for simple_one_for_one supervisors and return {error,simple_one_for_one} if the specified supervisor uses this restart strategy.
Function terminate_child/2 can be used for children under simple_one_for_one supervisors by specifying the child's pid() as the second argument. If instead the child specification identifier is used, terminate_child/2 return {error,simple_one_for_one}.
As a simple_one_for_one supervisor can have many children, it shuts them all down asynchronously. This means that the children do their cleanup in parallel, and therefore the order in which they are stopped is not defined. ๐
โฑ๏ธ Restart intensity and period โฑ๏ธ
To prevent a supervisor from getting into an infinite loop of child process terminations and restarts, a maximum restart intensity is defined using two integer values specified with keys intensity and period in the above map. Assuming the values MaxR for intensity and MaxT for period, then, if more than MaxR restarts occur within MaxT seconds, the supervisor terminates all child processes and then itself. The termination reason for the supervisor itself in that case will be shutdown. intensity defaults to 1 and period defaults to 5. ๐
๐ Automatic Shutdown ๐
A supervisor can be configured to automatically shut itself down with exit reason shutdown when significant children terminate with the auto_shutdown key in the above map:
neverโ Automatic shutdown is disabled. This is the default setting.
With auto_shutdown set to never, child specs with the significant flag set to true are considered invalid and will be rejected.
any_significantโ The supervisor will shut itself down when any significant child terminates, that is, when a transient significant child terminates normally or when a temporary significant child terminates normally or abnormally.all_significantโ The supervisor will shut itself down when all significant children have terminated, that is, when the last active significant child terminates. The same rules as forany_significantapply.
For more information, see the section Automatic Shutdown in Supervisor Behavior in OTP Design Principles.
โ ๏ธ Warning: The automatic shutdown feature appeared in OTP 24.0, but applications using this feature will also compile and run with older OTP versions. However, such applications, when compiled with an OTP version that predates the appearance of the automatic shutdown feature, will leak processes because the automatic shutdowns they rely on will not happen. It is up to implementors to take proper precautions if they expect that their applications may be compiled with older OTP versions.
๐งธ Child specification ๐งธ
The type definition of a child specification is as follows:
child_spec() = #{id => child_id(), % mandatory
start => mfargs(), % mandatory
restart => restart(), % optional
significant => significant(), % optional
shutdown => shutdown(), % optional
type => worker(), % optional
modules => modules()} % optional
The old tuple format is kept for backwards compatibility, see child_spec(), but the map is preferred. ๐ซถ
idโ is used to identify the child specification internally by the supervisor.
The id key is mandatory.
Notice that this identifier on occasions has been called "name". As far as possible, the terms "identifier" or "id" are now used but to keep backward compatibility, some occurrences of "name" can still be found, for example in error messages.
startโ defines the function call used to start the child process. It must be a module-function-arguments tuple{M,F,A}used asapply(M,F,A).
The start function must create and link to the child process, and must return {ok,Child} or {ok,Child,Info}, where Child is the pid of the child process and Info any term that is ignored by the supervisor.
The start function can also return ignore if the child process for some reason cannot be started, in which case the child specification is kept by the supervisor (unless it is a temporary child) but the non-existing child process is ignored.
If something goes wrong, the function can also return an error tuple {error,Error}.
Notice that the start_link functions of the different behavior modules fulfill the above requirements.
The start key is mandatory.
restartโ defines when a terminated child process must be restarted. Apermanentchild process is always restarted. Atemporarychild process is never restarted (even when the supervisor's restart strategy isrest_for_oneorone_for_alland a sibling's death causes the temporary process to be terminated). Atransientchild process is restarted only if it terminates abnormally, that is, with another exit reason thannormal,shutdown, or{shutdown,Term}.
The restart key is optional. If it is not specified, it defaults to permanent.
significantโ defines if a child is considered significant for automatic self-shutdown of the supervisor.
Setting this option to true when the restart type is permanent is invalid. Also, it is considered invalid to start children with this option set to true in a supervisor when the auto_shutdown supervisor flag is set to never.
The significant key is optional. If it is not specified, it defaults to false.
shutdownโ defines how a child process must be terminated.brutal_killmeans that the child process is unconditionally terminated usingexit(Child,kill). An integer time-out value means that the supervisor tells the child process to terminate by callingexit(Child,shutdown)and then wait for an exit signal with reasonshutdownback from the child process. If no exit signal is received within the specified number of milliseconds, the child process is unconditionally terminated usingexit(Child,kill).
If the child process is another supervisor, the shutdown time must be set to infinity to give the subtree ample time to shut down.
โ ๏ธ Warning: Setting the shutdown time to anything other thaninfinityfor a child of typesupervisorcan cause a race condition where the child in question unlinks its own children, but fails to terminate them before it is killed.
It is also allowed to set it to infinity, if the child process is a worker.
โ ๏ธ Warning: Be careful when setting the shutdown time to infinity when the child process is a worker. Because, in this situation, the termination of the supervision tree depends on the child process, it must be implemented in a safe way and its cleanup procedure must always return.
Notice that all child processes implemented using the standard OTP behavior modules automatically adhere to the shutdown protocol.
The shutdown key is optional. If it is not specified, it defaults to 5000 if the child is of type worker and it defaults to infinity if the child is of type supervisor.
typeโ specifies if the child process is a supervisor or a worker.
The type key is optional. If it is not specified, it defaults to worker.
modulesโ is used by the release handler during code replacement to determine which processes are using a certain module. As a rule of thumb, if the child process is a supervisor,gen_serverorgen_statem, this is to be a list with one element[Module], whereModuleis the callback module. If the child process is an event manager (gen_event) with a dynamic set of callback modules, valuedynamicmust be used. For more information about release handling, see Release Handling in OTP Design Principles.
The modules key is optional. If it is not specified, it defaults to [M], where M comes from the child's start {M,F,A}.
- Internally, the supervisor also keeps track of the pid
Childof the child process, orundefinedif no pid exists.
๐ฆ child_id() ๐ฆ
child_id() = term()
It's literally not a pid(), bestie. Do not come for me on that one.
๐ child_spec() ๐
#{id := child_id(),
start := mfargs(),
restart => restart(),
significant => significant(),
shutdown => shutdown(),
type => worker(),
modules => modules()} |
{Id :: child_id(),
StartFunc :: mfargs(),
Restart :: restart(),
Shutdown :: shutdown(),
Type :: worker(),
Modules :: modules()}
The tuple format is living here purely for backward compatibility โ it's giving legacy, ngl. The map form is what you actually want; more deets are up above. โจ
๐ธ mfargs() ๐ธ
{M :: module(), F :: atom(), A :: [term()] | undefined}
The undefined value for A (the argument list) is only for internal use inside supervisor โ don't be out here passing it yourself. If a child's restart type is temporary, that process is never getting restarted, so there's literally no point storing the real argument list. So undefined gets tucked in there instead. ๐
๐ฆ modules() ๐ฆ
modules() = [module()] | dynamic
๐ restart() ๐
restart() = permanent | transient | temporary
๐ง shutdown() ๐ง
shutdown() = brutal_kill | timeout()
โญ significant() โญ
significant() = boolean()
๐ startchild_err() ๐
already_present | {already_started, Child :: child()} | term()
๐ startchild_ret() ๐
{ok, Child :: child()} |
{ok, Child :: child(), Info :: term()} |
{error, startchild_err()}
๐ฅ startlink_err() ๐ฅ
{already_started, pid()} | {shutdown, term()} | term()
๐ฅ startlink_ret() ๐ฅ
{ok, pid()} | ignore | {error, startlink_err()}
๐ strategy() ๐
strategy() = one_for_all | one_for_one | rest_for_one | simple_one_for_one
๐ sup_flags() ๐
#{strategy => strategy(),
intensity => integer() >= 0,
period => integer() >= 1,
auto_shutdown => auto_shutdown()} |
{RestartStrategy :: strategy(),
Intensity :: integer() >= 0,
Period :: integer() >= 1}
Same story as child_spec() โ the tuple version is kept for backward compatibility only, map is the moment. Details are above. ๐ซถ
๐ sup_ref() ๐
(Name :: atom()) |
{Name :: atom(), Node :: node()} |
{global, Name :: term()} |
{via, Module :: module(), Name :: any()} |
pid()
๐ฆ worker() ๐ฆ
worker() = worker | supervisor
๐ EXPORTS ๐
โจ check_childspecs(ChildSpecs) -> Result โจ
โจ check_childspecs(ChildSpecs, AutoShutdown) -> Result โจ
Types:
ChildSpecs = [child_spec()]
AutoShutdown = undefined | auto_shutdown()
Result = ok | {error, Error :: term()}
You hand it a list of child specs as the argument, and it hits you back with ok if every single one of them is syntactically correct. If not? {error,Error}, obviously. ๐ญ
And if you pass that optional AutoShutdown argument and it's not undefined, it also checks whether the child specs are allowed for the given auto_shutdown option. Double-duty icon. ๐ฅ
โจ count_children(SupRef) -> PropListOfCounts โจ
Types:
SupRef = sup_ref()
PropListOfCounts = [Count]
Count =
{specs, ChildSpecCount :: integer() >= 0} |
{active, ActiveProcessCount :: integer() >= 0} |
{supervisors, ChildSupervisorCount :: integer() >= 0} |
{workers, ChildWorkerCount :: integer() >= 0}
Returns a property list (peep proplists) with the counts for each of these elements of the supervisor's child specifications and managed processes:
specsโ the total count of children, dead or alive. Everyone's invited.activeโ the count of all actively running child processes managed by this supervisor. Forsimple_one_for_onesupervisors, no check is done to make sure each child process is still alive โ although the result you get here is likely to be very accurate unless the supervisor is heavily overloaded. She's doing her best. ๐supervisorsโ the count of all children marked aschild_type = supervisorin the specification list, regardless of whether the child process is still alive.workersโ the count of all children marked aschild_type = workerin the specification list, regardless of whether the child process is still alive.
For a description of SupRef, see start_child/2. ๐
โจ delete_child(SupRef, Id) -> Result โจ
Types:
SupRef = sup_ref()
Id = child_id()
Result = ok | {error, Error}
Error = running | restarting | not_found | simple_one_for_one
Tells supervisor SupRef to delete the child specification identified by Id. Girlboss move, but โ the corresponding child process must not be running. Use terminate_child/2 to terminate it first, bestie. Don't skip that step. ๐
For a description of SupRef, see start_child/2.
If it works you get ok. If the child spec identified by Id exists but the corresponding child process is running, or is about to be restarted, you get {error,running} or {error,restarting} respectively. And if the child spec identified by Id doesn't exist at all? {error,not_found}. Slipped into the void. ๐ซ
โจ get_childspec(SupRef, Id) -> Result โจ
Types:
SupRef = sup_ref()
Id = pid() | child_id()
Result = {ok, child_spec()} | {error, Error}
Error = not_found
Returns the child specification map for the child identified by Id under supervisor SupRef. And the returned map contains all the keys โ mandatory and optional. Full transparency, no gatekeeping. โจ
For a description of SupRef, see start_child/2.
โจ restart_child(SupRef, Id) -> Result โจ
Types:
SupRef = sup_ref()
Id = child_id()
Result =
{ok, Child :: child()} |
{ok, Child :: child(), Info :: term()} |
{error, Error}
Error =
running | restarting | not_found | simple_one_for_one |
term()
Tells supervisor SupRef to restart a child process corresponding to the child specification identified by Id. The child spec has to exist, and the corresponding child process must not be running. No double-dipping. ๐ซ
โ ๏ธ Real talk: fortemporarychildren, the child specification gets automatically deleted the moment the child terminates. So it is not possible to restart those children. Ever. That's the whole vibe oftemporary. ๐ญ
For a description of SupRef, see start_child/2.
If the child spec identified by Id doesn't exist, you get {error,not_found}. If the spec exists but the corresponding process is already running, you get {error,running}.
If the child process start function returns {ok,Child} or {ok,Child,Info}, the pid gets added to the supervisor and the function returns that same value. Slay.
If the child process start function returns ignore, the pid stays set to undefined and the function returns {ok,undefined}. Iconic neutrality.
And if the child process start function returns an error tuple or an erroneous value, or if it fails? You get {error,Error}, where Error is a term containing info about the error. F in the chat. ๐ซก
โจ start_child(SupRef, ChildSpec) -> startchild_ret() โจ
Types:
SupRef = sup_ref()
ChildSpec = child_spec() | (List :: [term()])
startchild_ret() =
{ok, Child :: child()} |
{ok, Child :: child(), Info :: term()} |
{error, startchild_err()}
startchild_err() =
already_present | {already_started, Child :: child()} | term()
Dynamically adds a child specification to supervisor SupRef, which then starts the corresponding child process. Glow-up in real time. โจ
SupRef can be any of these cuties:
- The pid
Name, if the supervisor is locally registered{Name,Node}, if the supervisor is locally registered at another node{global,Name}, if the supervisor is globally registered{via,Module,Name}, if the supervisor is registered through an alternative process registry
ChildSpec must be a valid child specification (unless the supervisor is a simple_one_for_one supervisor โ see below ๐). The child process gets started by using the start function as defined in the child specification.
For a simple_one_for_one supervisor, the child specification defined in Module:init/1 is the one used, and ChildSpec must instead be an arbitrary list of terms List. The child process is then started by appending List to the existing start function arguments โ that is, by calling apply(M, F, A++List), where {M,F,A} is the start function defined in the child specification. Math. ๐งฎ
- If a child specification with the specified identifier already exists,
ChildSpecis discarded, and the function returns{error,already_present}or{error,{already_started,Child}}โ depending on whether the corresponding child process is running or not. - If the child process start function returns
{ok,Child}or{ok,Child,Info}, the child specification and pid are added to the supervisor and the function returns the same value. Periodt. - If the child process start function returns
ignore, the child specification is added to the supervisor (unless the supervisor is asimple_one_for_onesupervisor, see below), the pid is set toundefined, and the function returns{ok,undefined}.
For a simple_one_for_one supervisor, when a child process start function returns ignore, the function returns {ok,undefined} and no child gets added to the supervisor. Not one. Zero. ๐
If the child process start function returns an error tuple or an erroneous value, or if it fails, the child specification is discarded, and the function returns {error,Error}, where Error is a term containing information about the error and the child specification. Messy but honest. ๐ญ
โจ start_link(Module, Args) -> startlink_ret() โจ
โจ start_link(SupName, Module, Args) -> startlink_ret() โจ
Types:
Types, continued (we were literally mid-block, bestie):
SupName = sup_name()
Module = module()
Args = term()
startlink_ret() =
{ok, pid()} | ignore | {error, startlink_err()}
startlink_err() =
{already_started, pid()} | {shutdown, term()} | term()
sup_name() =
{local, Name :: atom()} |
{global, Name :: term()} |
{via, Module :: module(), Name :: any()}
Okay so start_link/2,3 creates a supervisor process as part of a supervision tree. For example, the function ensures that the supervisor is linked to the calling process (its supervisor). ๐
The created supervisor process calls Module:init/1 to find out about restart strategy, maximum restart intensity, and child processes. To ensure a synchronized startup procedure, start_link/2,3 does not return until Module:init/1 has returned and all child processes have been started. Slay, synchronized. โจ
- If
SupName={local,Name}, the supervisor is registered locally asNameusingregister/2. - If
SupName={global,Name}, the supervisor is registered globally asNameusingglobal:register_name/2. - If
SupName={via,Module,Name}, the supervisor is registered asNameusing the registry represented byModule. TheModulecallback must export the functionsregister_name/2,unregister_name/1, andsend/2, which must behave like the corresponding functions inglobal. Thus,{via,global,Name}is a valid reference.
If no name is provided, the supervisor is not registered. No cap.
Module is the name of the callback module.
Args is any term that is passed as the argument to Module:init/1.
- If the supervisor and its child processes are successfully created (that is, if all child process start functions return
{ok,Child},{ok,Child,Info}, orignore), the function returns{ok,Pid}, wherePidis the pid of the supervisor. - If there already exists a process with the specified
SupName, the function returns{error,{already_started,Pid}}, wherePidis the pid of that process. - If
Module:init/1returnsignore, this function returnsignoreas well, and the supervisor terminates with reasonnormal. - If
Module:init/1fails or returns an incorrect value, this function returns{error,Term}, whereTermis a term with information about the error, and the supervisor terminates with reasonTerm. - If any child process start function fails or returns an error tuple or an erroneous value, the supervisor first terminates all already started child processes with reason
shutdownand then terminate itself and returns{error, {shutdown, Reason}}.
terminate_child(SupRef, Id) -> Result
Types:
SupRef = sup_ref()
Id = pid() | child_id()
Result = ok | {error, Error}
Error = not_found | simple_one_for_one
Tells supervisor SupRef to terminate the specified child. Bye bestie, but make it supervised. ๐
If the supervisor is not simple_one_for_one, Id must be the child specification identifier. The process, if any, is terminated and, unless it is a temporary child, the child specification is kept by the supervisor. The child process can later be restarted by the supervisor. The child process can also be restarted explicitly by calling restart_child/2. Use delete_child/2 to remove the child specification.
If the child is temporary, the child specification is deleted as soon as the process terminates. This means that delete_child/2 has no meaning and restart_child/2 cannot be used for these children. ๐ซ
If the supervisor is simple_one_for_one, Id must be the pid() of the child process. If the specified process is alive, but is not a child of the specified supervisor, the function returns {error,not_found}. If the child specification identifier is specified instead of a pid(), the function returns {error,simple_one_for_one}.
If successful, the function returns ok. If there is no child specification with the specified Id, the function returns {error,not_found}.
For a description of SupRef, see start_child/2.
which_children(SupRef) -> [{Id, Child, Type, Modules}]
Types:
SupRef = sup_ref()
Id = child_id() | undefined
Child = child() | restarting
Type = worker()
Modules = modules()
Returns a newly created list with information about all child specifications and child processes belonging to supervisor SupRef. Itโs giving inventory, but make it supervisor. ๐ฅ
โ ๏ธ Notice that calling this function when supervising many children under low memory conditions can cause an out of memory exception. Lowkey important.
For a description of SupRef, see start_child/2.
Hereโs the tea for each child specification/process:
Idโ As defined in the child specification orundefinedfor asimple_one_for_onesupervisor.Childโ Thepid()of the corresponding child process, the atomrestartingif the process is about to be restarted, orundefinedif there is no such process.Typeโ As defined in the child specification.Modulesโ As defined in the child specification.
๐ CALLBACK FUNCTIONS ๐
The following function must be exported from a supervisor callback module. Periodt.
โจ EXPORTS โจ
Module:init(Args) -> Result
Types:
Args = term()
Result = {ok,{SupFlags,[ChildSpec]}} | ignore
SupFlags = sup_flags()
ChildSpec = child_spec()
Whenever a supervisor is started using start_link/2,3, this function is called by the new process to find out about restart strategy, maximum restart intensity, and child specifications. Bestie, this is the callback that spills the tea. ๐ซ
Args is the Args argument provided to the start function.
SupFlags is the supervisor flags defining the restart strategy and maximum restart intensity for the supervisor. [ChildSpec] is a list of valid child specifications defining which child processes the supervisor must start and monitor. See the discussion in section Supervision Principles earlier.
Notice that when the restart strategy is simple_one_for_one, the list of child specifications must be a list with one child specification only. (The child specification identifier is ignored.) No child process is then started during the initialization phase, but all children are assumed to be started dynamically using start_child/2.
The function can also return ignore.
๐ธ Notice that this function can also be called as a part of a code upgrade procedure. Therefore, the function is not to have any side effects. For more information about code upgrade of supervisors, see section Changing a Supervisor in OTP Design Principles.
๐ SEE ALSO ๐
Signed, sealed, and delivered with zero side effects ๐ โ Ericsson AB, stdlib 4.3.1.3, supervisor(3erl). Mwah! ๐
๐ฆ where this page comes from
- ubuntu noble: erlang-manpages 1:25.3.2.8+dfsg-1ubuntu4 ยท Apache-2.0
- ubuntu noble: erlang-manpages 1:25.3.2.8+dfsg-1ubuntu4.8 ยท Apache-2.0
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms