💧 Elixir Advanced

What is Elixir's GenServer deep internals and message queue management?

Answer

Understanding GenServer internals reveals how to build reliable production systems. Mailbox: each process has a message mailbox (queue). GenServer's receive loop processes messages in FIFO order. Selective receive: handle_info receives non-call/cast messages — timer expiries, monitor notifications, linked process exits. Hibernation: {:noreply, state, :hibernate} forces GC and minimal memory mode — ideal for long-lived processes with infrequent messages. Timeout: {:noreply, state, 5000} sends a :timeout message if no message arrives within 5 seconds. Continuing: {:continue, action} schedules handle_continue immediately after the current callback — for breaking long init work into steps without blocking the mailbox. Backpressure: GenServer mailbox can fill up under load — use Process.info(pid, :message_queue_len) to monitor. Dead letter: unexpected messages pile up in the mailbox if handle_info doesn't match — always add a catch-all clause.