Erlang / Erlang Advanced Interview questions
What is the code_change/3 callback used for in gen_server?
code_change(OldVsn, State, Extra) is the hook OTP calls during a release upgrade or downgrade
so a gen_server can transform its existing in-memory state to match whatever shape the new code version
expects, instead of losing state by simply restarting.
code_change(OldVsn, State, _Extra) when OldVsn =:= "1.0" -> %% old state was a plain tuple {Count}, new state is a map NewState = #{count => element(1, State)}, {ok, NewState}; code_change(_OldVsn, State, _Extra) -> {ok, State}.
It's only invoked as part of the relup-driven upgrade machinery, not on a normal restart, and only makes sense when a release upgrade actually changes what a process's internal state looks like — adding a new field to a record, switching representations, or renaming keys. If the state shape hasn't changed between versions, the default identity implementation (returning the state unchanged) is all you need.
More Related questions...