Starting Per-User Processes with a Dynamic Supervisor

Let's learn how to use dynamic supervisors to handle variable processes and establish some policies using a child spec.

Now we need to start a process per user. There are two reasons for doing this:

  • We don’t have a fixed number of processes to start.

  • We’ll also need to be able to look them up based on a user’s attributes.

Hence, we will need a structure that is a little more sophisticated. We will use a dynamic supervisor.

Properties and requirements of dynamic supervisors

Most supervisors create processes when an application starts or restarts. That’s typically what you want, but not always. A dynamic supervisor is a supervisor that starts children dynamically. Since we have no way of knowing who will take quizzes and when, that sounds like exactly what we need. To use a dynamic supervisor, we need many of the same pieces of information:

  • We must provide a child spec, which describes how to start and restart processes.

  • The GenServer we’re starting must have a start_link.

  • We need a strategy for naming and accessing the process.

  • We must register our dynamic supervisor, perhaps in application.ex.

We’ll do each of these things in the sections to follow. Let’s start at the top with the child spec.

How to establish a Child Spec?

An OTP child spec is a policy. It defines how the lifecycle should work for a particular type of process. Remember, lifecycles define behaviors for the following:

  • Starts

  • Restarts

  • Shutdowns

Our child spec will need to identify the process by name, define exactly how to start the worker process, and determine a restart strategy. We’ll do those with keys:

  • :id

  • :start

  • :restart

We’ll add this child spec to /lib/mastery/boundary/quiz_session.ex, just below the module heading and aliases:

Get hands-on with 1200+ tech skills courses.