Register process in Registry using :via with two keys

Currently, I register a GenServer process with a unique name in a local register when invoking a start_link/1 function part of it’s API as follows:

  def start_link(%{name: lobby_id, visibility: visibility}) do
    via_name = {
      :via,
      Registry,
      {LobbyRegistry, lobby_id}
    }
    GenServer.start_link(__MODULE__, %{name: lobby_id, visibility: visibility}, [name: via_name])
end

In some cases, I would like to register it both via its unique lobby_id as key, but also via another key used by the registry to identify a particular lobby process. It seems one possibility is to register it later on, e.g. in its init/1 callback using Registry.register/3, but I was wondering if its possible to register the process under both keys at the same time, in the above-mentioned start_link/1. If both are possible, is there any reason to prefer one over the other? Any other, better, solutions?

It is not possible to do two keys in the start_link call, you’ll need to do it inside init.

@benwilson512 If registered directly using Registry.register/3 will the key be removed when process is killed?

Yes. Keys of any registered processes are removed once the processes stop. That’s unrelated to how they became successfully registered.

1 Like