Authentication Queues in Elixir


I need to make an “authentication queue”, what I need to achieve is a synchronously autentication, this in order to avoid multiple same account sessions in my app.

What is the best way to achieve this on Elixir?


Are you using Phoenix? If so, the session plug will take care of sessions for you.

If you are writing your own code, I’d fire a new GenServer inside a supervision tree to hold the state of this session, naming it so you could find it by the account ID plus the “device” id. I’d also add some mechanism to handle user inactivity.

You could also use ETS to keep track the pool of logged accounts, then you’d have one service to check if the account is logged or not.

1 Like

Thanks for answer ^^/, I have some questions

Just one GenServer that handle all account states or one GenServer for every account? My app is run by sockets so two request make at the same time will would not cross?

It’s up to you. But remember that processes are cheap in Elixir/Erlang. Not only that, you are encouraged to use processes. You can have one GenServer which its state is a map of agents or you can spawn one per account.

_If you have one GenServer and many websocket connection_s: since each process has a “mailbox” of messages and reads it in the order it received, if in one call you already have an successfull account authentication then in the next you’ll have the session. It’s simpler BUT having only one process to do that could be a possible bottleneck in your application - imagine hundreds of connections accessing just this one process.

Having many gen servers or agents: in this scenario you’d have to do a process lookup. I’d use Registry for this. Each process would have an unique name (using the account id, for instance) and then you’d just look for it. If the process exists, then you have a session. If not, just spawn a new one.

1 Like

So many thanks!

Is a lot more easy to do on Elixir than another languages :smiley: