Elixir. Process Registry. Dynamic workers.

Dynamic workers

Give us a message if you’re interested in Blockchain and FinTech software development or just say Hi at Pharos Production Inc.

This is the second article about Process Registry. This time we will look at simple_one_for_one supervisor strategy and dynamic worker creation. If you have missed an article about “static” worker pool, find it here — Process Registry. One-node pool.

BRIEF

There is plenty of tasks which should start dynamically during application lifetime. That can be user’s session, shopping cart or image uploading task. There is a couple of straightforward abstractions like Agent and Task in Elixir but we should look at their core — gen_server behavior and simple_one_for_one supervisor strategy to understand how it works and to add more complex stuff into it when we need. All new functionality we will add on top of our already existed project.

APPLICATION

Application Module

Let’s add a new supervisor to application’s supervision tree. This time we will pass some initial values for the sake of clarity.

SUPERVISOR

Supervisor

Here we create a supervisor to handle future dynamic workers. Start_link takes arguments from Application Module and passing them into supervisor’s start_link function. A supervisor is defined in a local namespace.

Start_child is a starting point for every new worker. It takes the worker’s name — it should be unique until a worker is dead, and some initial value you want to pass into the worker. Start_child should be called while an application running and not on a start like in a “static” pool.

In init callback, we define worker signature and it’s restart strategy to temporary — that means if a worker is dead then it’s dead and doesn’t restart it, please.

WORKER-SERVER

Worker

Supervisor’s start_child instantiates start_link in a worker. Start_link has to parameters — initial arguments defined in application supervisor and arguments sent from start_child. Also, it is a POGS so it can use the same via_tuple as a static worker does. All other implementation is absolutely the same. It differs from a static worker by restart strategy and its behavior is the same as Elixir’s Agent.

DONE

Link to Github repo pharosproduction/process-registry

Thanks for reading!

--

--

Dmytro Nasyrov
Pharos Production

We build high-load software. Pharos Production founder and CTO.