Introduce the Supervisor's Behavior

Let's introduce the supervisor's behavior.

Customize supervisor processes

Process supervision begins with the supervisor Behaviour. We’ll get an overview of it in this section. Over the next few sections, we’ll learn to customize supervisor processes. Then we’ll build a supervisor to monitor all the game processes in Islands.

Like GenServer, supervisor is an Elixir Behaviour that wraps an OTP Behaviour. In this case, that is :supervisor. Like GenServer, we can also spawn new processes from supervisor modules. These supervisor processes start, monitor, restart, and stop other processes within an application.

We call any process under supervision a child process of the supervisor. Child processes can be workers, like GenServer processes, or other supervisor processes.

Since supervisors can supervise other supervisors, we can build tree structures of the supervised processes. These supervision trees allow us to be specific about how we supervise processes. We can tailor the way a supervisor behaves for a given type of process by specifying different startup options.

When we define a new supervisor module, we describe how we want it to supervise its child processes and what restart strategy to use. We also specify the circumstances under which the supervisor should restart the process.

We can also define some circumstances under which the supervisor itself should terminate and restart. Consider the case of a process that crashes continually and doesn’t successfully restart. There’s clearly something wrong that restarts aren’t fixing, and we wouldn’t want those restarts to continue indefinitely.

Supervisors allow us to configure the maximum allowable number of restarts over a given period of time with the :max_restarts and :max_seconds options. The default value for :max_restarts is 3, and the default value for :max_seconds is 5.

Restart strategies are a little more involved than restart thresholds. Let’s take a closer look at those next.

Supervision strategies

Processes often depend on one another to do their work. If a child process crashes, restarting just that process might not stabilize the application. In the event of a crash, a supervisor needs to decide whether to restart just the one crashed process or other processes as well. If it needs to restart others, it must decide which ones. Supervisors depend on restart strategies to make those decisions.

We’re going to look at all the available strategies, see how they work, and learn how to choose the right one for a given situation.

Each supervisor process can supervise a number of child processes. Those child processes might have different types of relationships with one another.

Sometimes all the child processes depend on one another, so if one of them crashes, the others will be invalid. Sometimes they are all completely independent. Therefore, if one crashes, the others will be fine.

Get hands-on with 1200+ tech skills courses.