Multiple instances of a gen_server

I have a gen_server module, it does some periodic work: reads from the db, writes to another and sleeps. I want to scale it, and start multiple instances of the server. I do it in the following way:

def children_spec do
    0..@workers_number - 1
         fn (i) ->
           process_name = String.to_atom("#{__MODULE__}.#{i}")
           Supervisor.child_spec({__MODULE__, name: process_name}, id: {__MODULE__, i})

The module has that children_spec function, which returns list of the child specifications that will be added to the list of the top level application supervisor:

    children = children ++ MyWorkerModule.children_spec()
    Supervisor.init(children, strategy: :one_for_one)

Is there another way to do that? Also i thought about additional supervisor for the module with the :simple_one_for_one strategy

1 Like

yes what i exactly what i want to know this hope is there anyone who can help me out too. ?
with regards
mile smith

I would use :simple_one_for_one unless you absolutely need to send messages to a specific gen_server process.

I would recommend Dynamic Supervisor as a good replacement for :simple_one_for_one.

I wrote a series of blog posts about writing a pool supervisor with the dynamic supervisor. You may be interested in reading through it if you want to try using the dynamic supervisor (which is a good fit for your case). The series covers starting a variable number of worker processes which is what you want to achieve.