jaggard

jaggard

Design issue in Pooly example from The Little Elixir and OTP Guidebook

I am making my way through the Little Elixir & OTP book. I like the philosophy behind this book - it doesn’t mess about with lots of chapters teaching you about recursion and pattern matching for the nth time. Instead it jumps straight into the core principles of erlang/elixir i.e. achieving reliability with Processes and Supervisors.

By chapter 6 it is taking the reader through a complex example of creating a worker process pool. Now you start to see why most books opt for simpler examples as errors start to creep in to the text and the code. Viewing the errata on the Manning website is a must but it doesn’t cover all the issues.

I am digressing.. Anyway, by page 155 you have a supervision tree with a set of worker processes that are supervised by a Worker Supervisor that in turn is supervised by a pool supervisor. There is a pool_server at the same level as the Worker supervisor (<0.119.0> is the worker supervisor)

Here is the code for the Worker Supervisor:

def init([pool_server, {m, f, a}]) do  
    Process.link(pool_server)
    worker_opts =   [restart: :temporary,
                    shutdown: 5000,   
                    function: f]            

    children = [worker(m, a, worker_opts)] 
    
    opts = [strategy: :simple_one_for_one,  
            max_restarts: 5,
            max_seconds: 5]

    supervise(children, opts)               
end

As far as I can tell it doesn’t do anything! The restart option is set to temporary so it doesn’t restart any of the workers if they are killed.

The restart is actually handled by the Pool Server as this has been made into a system process to trap :EXIT signals and has a link to each of the worker process (as you can see in the diagram).

Why does the Worker Supervisor exist in this instance? Why not make the Pool server a real supervisor rather than using the manual method of trapping exit signals and restarting workers?

I don’t mean to sound disparaging about this book. It has obviously engaged me as I am spotting errors and questioning the code - some books are so dull that they go in one ear (eye?) and out the other…

Most Liked

sasajuric

sasajuric

Author of Elixir In Action

I can’t say exactly for this example (I’d have to reread it), but I can give a more general answer.

The essential roles of a supervisor process are starting and stopping process. In other words, a supervisor is a lifecycle manager. Having processes under a supervisor, ensures that a termination of the supervisor will also terminate its descendants recursively. So if some larger portion of the subtree is taken down, you can be sure that no dangling processes are left behind.

This is why I say that in most cases, workers should sit directly under the supervisor process. It’s not a strict rule, so it’s fine if you sometimes override it for some specific reasons, but it’s a good default which reduces the chances of leaving dangling processes. Therefore, I think that starting workers under some supervisor is never a bad practice.

That said, there are occasional cases where it makes more sense to bypass a supervisor and start workers directly under another worker. This is definitely possible (and sometimes done in practice), but you need to reinvent some parts of the Supervisor abstraction, so you need some tangible reasons for that. If you’re not really sure whether you want to start a child under a supervisor or not, I’d say that it’s better to choose a supervisor as the parent.

One special exceptions are one-off finite-time processes, such as tasks. We frequently start tasks directly under workers with Task.async. But this is usually fine, b/c tasks don’t run indefinitely, and they shouldn’t trap exits, so the problem of dangling processes should not bite us here. If the parent of task(s) terminates, they will be taken down as well, owing to the link mechanism.

dom

dom

Supervisors have a few other roles in the process lifecycle besides just start / stop:

  • Log progress and error reports to SASL
  • Kill children if they do not shutdown within the given timeout
  • Support code replacement (details in release handling and appup cookbook)

It’s safer not to mix these concerns with application logic, since bugs in a supervisor have a lot more impact than bugs in a worker.

I don’t have the book around, but I would think it’s using links to ensure the workers die if the server crashes and gets restarted. Otherwise when the server restarts its state would be out of sync with the pool’s real state; it has no way of knowing which workers are available and which are not.

This could be avoided by making the top supervisor a one_for_all, so that if the server crashes the pool is restarted as well. Then monitors would be enough.

kokolegorille

kokolegorille

I also started with this book, as it quickly shows the promise of concurrency, instead of focusing on what FP is.

For your question, I don’t think they share the same responsability, the worker supervisor is in charge of starting workers, while the pool server manages… the pool, and it ensures they are not more than x workers at a time.

Using a restart strategy will not work on low load, as there will be always the same number of workers, even if the load does not require them.

The pool server allows to check in/out workers on demand, provided they do not get over config limitation.

The worker supervisor role might look limited, as it only start temporary workers, but it is the place where You can get the list of running workers… with Supervisor.which_children/1

Also, it is based on a real library, poolboy. So the book explains how it was designed, as an example of supervision tree.

Also, it does not use the most recent version of Elixir.

But as with anything with OTP in the title, the book is good at showing You what You might expect working with Elixir/Erlang soft concurrency.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39467 209
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement