Can a callback from a GenServer call another GenServer's API?

In a handle_call() for a Genserver, I need to send a message to another process. Should I just directly use “send(process, msg)” or should I call its external API? i.e. Server2.do_stuff(process, msg) which just is an API to call its own GenServer.call( msg ) ?

I did the latter initially, but it didn’t seem to actually call the code. So changing it to use ‘send’ seemed to actually get it to execute the callback on Server2.

If not our own API then it’s recommended to at least use GenServer.call(server, request) as it handles some low level stuff for us.

Also it seems like we don’t really care about the response of that Server2, so probably better use cast/handle_cast?

I did the latter initially, but it didn’t seem to actually call the code

I wonder why?

Thank you. Given your answer, I guess I need to devote more time to debug why it doesn’t call the API. I encountered a compile error before when calling an API from a server callback “server tried to call itself” when doing a Module.Name.api_func(self(), args) from a handle_call() so I thought that maybe there was a general rule that callbacks cannot call APIs (though maybe it just cannot call its own API on itself). I will have to dig more (I’m new so debugging is just IO.inspect lines within code to see where it got to – if there is any better way to debug would be happy to learn (I’m using VScode and jet brains IDEA)

Oh incidentally, I’m trying to call the Server2’s API from Server1’s handle_info() callback.

“Call” is implemented by sending a message then waiting for a response. A GenServer calling itself would just deadlock: it can’t process the message and reply to it, since it’s already blocked waiting for the reply.

1 Like

Changing it to cast did the trick. There was some other obscuring issue that made it so that the cast was not run, but it was.

I changed the code so that the handle_call() in server1 just calls GenServer.cast(server2, msg)

Thank you for the responses!