Message Prioritization inside GenServer

You can use something called a selective receive. The basic idea is to just pattern match on the priority message first and the rest of them later. There are some drawbacks doing this especially for large mailboxes. Also note, that you must do this in your own processes and can’t use GenServer behaviour (as far as I know).

Some links I found.

If you google for selective receive you may found more information.

An example:


def check_important_messages_first() do
    receive do
        {:important, message} ->
           do_something_imporant(message)
    after 0 ->
        receive do
          {:important, message} ->
              do_something_important(message);
         {:normal, message} ->
              do_something_else(message)
      end
   end
end
4 Likes