Supervisors
Supervisors[edit]
A supervisor is a behavior in Elixir that helps in building fault-tolerant systems. It is responsible for starting, monitoring, and restarting child processes, ensuring the stability and resiliency of the system.
Role of Supervisors[edit]
Supervisors use a "let-it-crash" philosophy to handle faults. When a child process crashes, the supervisor is notified, and depending on the restart strategy, it can decide how to handle the failure.
In Elixir, supervisors are implemented using the `Supervisor` module. They are defined as part of a supervision tree, which is a hierarchical structure that organizes the processes of an application. Each supervisor can have multiple child processes.
Starting Child Processes[edit]
Supervisors start child processes using the `start_child` function, specifying the child specification. A child specification describes how a child process is started and how it should be supervised.
Restart Strategies[edit]
Elixir provides different restart strategies that supervisors can use when a child process crashes:
- `:one_for_one`: This strategy restarts only the failed child process. - `:one_for_all`: This strategy restarts all child processes. - `:rest_for_one`: This strategy restarts the failed child process and all the ones that were started after it.
Handling Faults[edit]
When a child process crashes, the supervisor is notified and can take further action. Supervisors can choose if they want to restart the failed child process immediately or have a delay before attempting a restart.
Supervisors can also define a maximum number of restart attempts within a given time period. If a child process fails too many times within this limit, the supervisor can take other actions, like shutting down the entire application.
Linking to Other Articles[edit]
Visit the following articles to learn more about supervisors and related topics:
- Processes: Explains the basics of processes in Elixir. - OTP Behaviors: Discusses different OTP behaviors, including supervisors. - Supervisor Strategies: Provides in-depth explanations of the available restart strategies. - Supervision Trees: Details how supervision trees are structured and how supervisors are organized within them.
By employing supervisors in your Elixir applications, you can enhance fault tolerance and build robust systems.