What is the point of passing an id option to a worker function

Hi Everyone. I am working on understanding supervisors and supervisor trees.

I understand that the worker function takes an optional Keyword List, where one of the keys can be the :id atom.

What is the point of passing this option to the worker function? There’s no way to use it, that I can see, to directly communicate with the the process.

1 Like

Could you point out the part of the docs that say that? I can’t really check right now but I believe it’s because the callbacks must return something like {:ok, pid}. Maybe that :id is supposed to be the pid?

1 Like

According to erlang documentation it is used internally only:

id is used to identify the child specification internally by the supervisor.

1 Like

Thank Nobbz. I’m not sure what is it for, but if it is used internally then it is probably not something a beginner to Elixir / Erlang should worry over.

I found that if I try to start two workers with the same name, I get the following error:

 ** (Mix) Could not start application <program_name>: <module_name>.start(:normal, []) returned an error: an exception was raised:
     ** (ArgumentError) duplicated id <worker_module_name> found in the supervisor specification, please explicitly pass the :id option when defining this worker/supervisor

Seeing how @NobbZ mentioned that it is used internally, I would guess that it’s used to distinguish workers of the same module.

@Olshansk that sounds right to me. Thanks for the post.

You can use the Supervisor method which_children which includes the id in the values returned. From this you could, for example, find a particular child process and send messages to that child.

The :id could be used when you’re adding/deleting workers or supervisors to/from a given supervisor (which is not :simple_one_for_one) dynamically using functions: start_child/2, terminate_child/2 and delete_child/2.

For example, you’re running your elixir server which connects to other servers dynamically. Let’s assume you don’t know the connection credentials of the other servers when starting the elixir server. Also, let’s say you need a gen_server to handle a connection to a server. Once you get connection credentials, you can add a gen_server to your supervisor. The :id would be a reference of that connection in case you want to remove it.