Javier García
Javier García

Reputation: 1114

Adding in-memory state to a web API with genservers

I'm currently trying to build a small web API in Elixir which needs some in-memory state. In a nutshell, the first time a user uses the API he starts a certain business process which he can later continue with further API calls.

For this, I've seen that the best approach is to create a GenServer, store the state there and then have further API calls work with it through the PID.

While trying to search how to stringify the PID in order to return it in each API call I found this thread which said:

PIDs aren't guaranteed to be unique as they get recycled.

So my question is: what would be the best approach for this scenario? How is it typically solved?

Upvotes: 1

Views: 147

Answers (1)

7stud
7stud

Reputation: 48599

:erlang.make_ref() can be used to create a unique identifier:

iex(1)> :erlang.make_ref()
#Reference<0.3918424786.2664955905.32640>

iex(2)> 

(Is there a reason you don't want to use System.unique_integer/1 ?)

The Elixir docs mention the Reference, Pid, Port data types, but I can't find any info on the Reference type in Elixir, e.g. whether Elixir has a native function which creates references.

Response to comment:

Here's how you can convert a reference to a string* in Elixir:

iex(4)> make_ref() |> inspect()  
"#Reference<0.784388646.1821114370.207624>"

*Credit to Hauleth in the comments for finding Kernel.make_ref().

would that work?

According to the Kernel docs:

The returned reference will re-occur after approximately 2^82 calls; therefore it is unique enough for practical purposes.

Upvotes: 2

Related Questions