...

/

Supervisors and Workers

Supervisors and Workers

Understand how the supervisor supervises and manages the processes' states.

Elixir doesn’t worry much about code that crashes. Instead, it makes sure the overall application keeps running. This might sound contradictory, but it isn’t. Think of a typical application. If an unhandled error causes an exception to be raised, the application stops. Nothing else gets done until it’s restarted. If it’s a server handling multiple requests, they all might be lost.

The issue here is that one error takes the whole application down. Now, imagine that our application consists of hundreds or thousands of processes, each handling just a small part of a request. If one of those crashes, everything else carries on. We might lose the work it’s doing, but we can design our applications to minimize even that risk. And when that process gets restarted, we’re back running at 100%.

In the Elixir and OTP worlds, supervisors perform all of this process monitoring and restarting.

Supervisor

An Elixir supervisor has just one purpose. It manages one or more processes. As we’ll discuss later, these processes can be workers or other supervisors.

At its simplest, a supervisor is a process that uses the OTP supervisor behavior. It’s given a list of processes to monitor and is told what to do if a process dies and how to prevent restart loops (when a process is restarted, dies, gets restarted, dies, and so on).

To do this, the supervisor ...