How to use GenServer to create something similar to Microsoft Orleans virtual actor?

I’ve used Microsoft Orleans before that has virtual actors called grains in Orleans. Anyway the idea is that you have an actor that is initialized when you call it and after certain amount of inactivity it dies. Then another call to initializes it again. I don’t need any distribution like in Orleans.

My problem is that I don’t have idea how to create & initialize GenServer on first call and shutdown it on timeout without race conditions. Direct help or pointing me to some examples would be greatly appreciated.

1 Like

You are not saying what’s your actual desired outcome here – is it for education or an actual project?

In any case, you can start off with DynamicSupervisor.

1 Like

Without distribution this can be accomplished with dynamic supervisor, registry (for names and handling duplicates / race conditions) and the hibernate feature on genservers.

1 Like

I want to have sessions that keep state in memory and die after a while when they are not used, to be in initialized again by loading state from database.

Looked into registry but could found a way to stop GenServer. Hibernate is of course an option but I would like to remove GenServer completely when it’s not needed.

If I where to use hibernate is there a way to empty GenServer state before going into hibernate and load the state once GenServer comes out of hibernation?

Ah sorry. You can use timeouts (got them mixed up with hibernate) to stop the genserver on inactivity.

1 Like

You may want to have a look at GitHub - erleans/erleans: Erlang Orleans

4 Likes

I don’t want to use external library I want to do this with GenServer myself. Also erleans is made with Erlang and I have hard time reading Erlang, but I’ll try :wink: I think I might get pointers from that project how to do it from the looks of it.