Detect pid reuse

Jesper Louis Andersen jesper.louis.andersen@REDACTED
Thu Jul 9 17:37:21 CEST 2020


On Mon, Jul 6, 2020 at 2:09 PM Dinislam Salikhov <
Dinislam.Salikhov@REDACTED> wrote:

>
> If I want to send a command to the database, I search for the pid of the
> corresponding connection (in supervisor's children list). And between the
> search and actual sending command (i.e. via gen_server:call(Pid,...)), the
> process may terminate and its pid will be reused by another connection (to
> different database). So I end up with sending a command to the wrong
> database (as gen_server:call/3 thinks that the pid is the correct one).
>
> Is there a way to detect that such restart has occurred?
>

I wouldn't worry about PID wraparound.

You have a small set of pids, and a lot of open slots in the PID table, so
in order to hit the same PID through wraparound, you need to spawn them
faster than is possible. The window is very small as well, so it is
unlikely to happen.

If you are still concerned, the trick is to have the calling process bear
some kind of witness term to the target. You can use the
erlang:unique_integer/0 call to obtain such a term which is unique over the
lifetime of the Erlang VM. If you don't provide the correct unique term to
the process, it responds with a retry message, and you try again. You can
place the unique term to supply either in ETS, persistent_term databases or
the like. If the process rolls around, it replaces that term, but if a
message comes in with a wrong term, you reject the message with an EAGAIN
type retry error back to the caller.

However, I'd like to see the problem happening before I would worry about
this for this case.

Also, I probably wouldn't search the supervisor, but rather use a dedicated
connection pool system.


-- 
J.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20200709/7cf3e36d/attachment.htm>


More information about the erlang-questions mailing list