Establishing Supervision Strategies

Let's learn about some of the supervision strategies when we build a child spec.

As you’ll recall, when we build a child spec, we define the naming and lifecycle strategies our supervisors will apply to child processes. In general, this configuration code guides OTP in building the lifecycle.

Starting a worker

Let’s talk about what happens when we start a worker:

  • At startup, the worker will go down the list of child specs and start each of them using the child specs.

  • Some of those child specs will identify other supervisors or applications. Our application.ex child list has both.

  • Application.start then walks down a list of children and starts each one. Those children could be single processes, such as our QuizManager, or they could be applications in their own right.

Spinning up a child application means loading that application’s child list, and so on. That means our child list is a supervision tree.

Starting your application

Starting our application, then, is pretty straightforward:

  • The children will start in order, and each child will load its complete supervision tree before the next child starts.

  • Shutting down or restarting the application is another story altogether. We’ll need to evaluate dependencies between applications and specialized shutdown requirements carefully.

Here are some questions we might need to consider:

  • Do we need to wait for in-progress work to finish?

  • After a fixed period, should we abandon our attempts to shut down cleanly?

  • Are there dependencies between loading applications?

  • Do processes need to load in order?

OTP child specs

OTP child specs provide a good amount of detail when it’s time to configure the lifecycle policies for a given application. These are the options we have at our disposal as we’re making a child spec:

:id

The :id option lets OTP uniquely identify processes managed by supervisors.

:start

The :start tuple has the information the supervisor needs to start:

  • A worker.

  • A module.

  • A function name.

  • The argument list with the initial state of the server.

There’s no strategy here, only the description of a raw function invocation.

restart

This attribute defines policies for restart. This setting is a strategy:

:one_for_one

When a child fails, the supervisor will restart only that child. This strategy makes sense for long-running singletons or pools.

Get hands-on with 1200+ tech skills courses.