GenServer.cast - for what?

@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