How to create a process with a given name if it doesn't exist?

I have a small caching subsystem in my app, which works more or less as following:

  • I have a collection of objects with attached resources identified by an ID
  • Whenever I want an actor for an object with a given ID I look up this ID in registry
  • If the ID does not exist I create a process and register it under that ID
  • That process on initialization fetches relevant data from DB and various other places
  • That process serves requests for the next 10 minutes
  • Once the process has not been requested for the next 10 minutes it persists its’ data and shuts down

Everything works quite well in this setup except for a weird feeling that the way I create a process doesn’t feel “right” - even though I’m not very experienced in Elixir it feels like the way I’m doing it is very unidiomatic and screams of code smell.

My code is basically as follows: try to send a message to that actor and wrap that in a try-catch block. If sending a message doesn’t succeed, create that actor and then send a message again.

I feel like it must be a pretty common problem so there must be a better solution to this problem.

You could have a get_pid function that gets the pid from the Registry and if not found, creates it.