GenServer.cast - for what?

Hello!

Cannot understand for what is GenServer.cast? What’s the benefit’s of using it, over GenServer.call? What’s the use case?

As reading through tutorial: http://elixir-lang.org/getting-started/mix-otp/genserver.html#call-cast-or-info

handle_cast/2 must be used for asynchronous requests, when you don’t care about a reply. A cast does not even guarantee the server has received the message

I’m guessing that cast would be somehow faster than call? But still cannot come up with some use case - where guarantee that server has received the message is not needed

Thanks in advance!

@matDobek you use GenServer.cast when you want to notify GenServer about something, and continue your work immediately. For example, you could implement a logging mechanism where you log a lot of stuff from one process, have the logger running as GenServer, whenever something important happens you cast a message to your logger. But you don’t wait for your logger to save the message in file or in disk, this will happen with some delay.

Other use case would be sending transactional email. You could have a genserver running in background. Whenever you want to send email from your front-end, you cast a message to that genserver. You don’t really have to wait for the completion of sending emails (this can take X seconds) and immediately go on continuing sevring your request.

Please note a few things:

  1. If something goes wrong, you will not get notified back that processing of message you sent using cast failed. For example, you won’t know that sending email failed since you don’t wait for a reply
  2. GenServer still will handle all messages synchronously, one after another. There is no concurrency involved on GenServer side. GenServer is single Erlang process, it will only do one thing at a time, and then move to another one.
  3. Both logger and mailer examples above, might or might not need more robust implementations in real life. You may want to retry email sendout, or it can be perfectly okay if you miss some emails. Treat is as a stub for more robust solution I guess, not as pointers that you should really do it like that :wink:
3 Likes

You use asynchronous message passing (cast) when you dont right away need to know the result of what happened.

Synchronous message passing (call) makes the current process wait until the other process returns the result of the operation (or times out).

If you only ever use synchronous message passing in your application, it will not be concurrent, as only one person will perform some work, while all others are waiting for the result of this before they can continue.

1 Like

Thank you guys for responses - appreciated it!

1 Like