OTP Multiple Supervised Agent Workers

How to have multiple supervised agent processes of the same type in Elixir.


in the agent module:

def worker_spec(name) do
  id = "#{__MODULE__}.#{String.capitalize(name)}" |> String.to_atom()
  Supervisor.child_spec({__MODULE__, name: id}, id: id)
end

Important is line 2. This function can dynamically create specs for the supervisor by overriding the :id property. This way, you can have the same module/agent supervised multiple times.

Then use the agent in it’s supervisor module:

def init(_opts) do
  children = [
    MyModule.worker_spec("first"),
    MyModule.worker_spec("second")
  ]
  Supervisor.init(children, strategy: :one_for_one)
end

Important is line 3. This function can dynamically create specs for the supervisor by overriding the :id property. This way, you can have the same module/agent supervised multiple times.

Linked Technologies

What it's made of

illustration of Elixir
Elixir

Harness the power of concurrent, fault-tolerant programming for scalable, maintainable applications. Code that flows like water!

Linked Categories

Where it's useful

illustration of Software Architecture
Software Architecture

Dive into the world of Software Architecture where design meets functionality. Explore frameworks, patterns, and best practices that define the structure of software systems, making them robust, scalable, and maintainable.