0Pricing
Erlang OTP: Distributed & Fault-Tolerant Systems Programming · 강의

핫 코드 로딩 및 업그레이드

Erlang 고유의 핫 코드 로딩 기능을 살펴보고 실행 중인 시스템을 중단하지 않고 소프트웨어를 실시간으로 업그레이드합니다.

핫 코드 로딩 및 업그레이드은(는) CoddyKit의 무료 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What is Hot Code Loading?

Erlang's hot code loading is a standout feature! It lets you update a running application's code without stopping it. Imagine changing parts of a website's backend while it's actively serving users, without any downtime!

This capability is crucial for systems that need to run continuously, like telecommunications switches or large-scale distributed services. It ensures maximum uptime and service availability.

How Erlang Manages Code

The Erlang Virtual Machine (BEAM) manages code modules in a unique way. For each module, it can keep two versions loaded in memory: an 'old' version and a 'new' version.

  • When a process starts, it runs the 'new' version of the code.
  • If you reload a module, new calls to its functions will use the very latest 'new' version.
  • However, existing processes continue to execute the code they were loaded with until they make a call to a function in the *reloaded* module or are explicitly told to change.

Simple Module Reloading

You can interactively reload a module in the Erlang shell. The l(Module) function (short for 'load') compiles and loads the latest version of a module from the code path.

Let's see a quick example. We'll define a simple math module, then change a function and reload it.

Module Reload Demo

First, create my_math.erl:

Then, in the Erlang shell, compile it with c(my_math). Call my_math:add(1, 2). Now, *change* the add/2 function in the file to X + Y + 10. Save. Run l(my_math) and call my_math:add(1, 2) again. Notice the new result!

-module(my_math).
-export([add/2]).

add(X, Y) -> X + Y.

State Migration Challenge

Simple reloading works for purely functional changes (like our my_math example). But what if a running process, especially an OTP behavior like a GenServer, holds internal state that changes its structure?

If you just reload the code, the running GenServer still holds its old state format. The new code won't know how to interpret it, leading to crashes. We need a way to 'transform' the old state into the new state.

Introducing `code_change/3`

OTP behaviors provide a special callback function called code_change/3. This function is designed precisely for handling state migration during a hot code upgrade.

When you tell a running OTP process to upgrade its code, Erlang will call this function in the *new* version of the module. It's your chance to convert the process's old internal state to the new format.

The `code_change/3` Callback

The signature for code_change in a GenServer looks like this:

code_change(OldVsn, State, Extra) -> {ok, NewState}

  • OldVsn: The version of the code *being upgraded from*.
  • State: The current internal state of the process (in the old format).
  • Extra: Additional arguments, often unused.
  • You must return {ok, NewState}, where NewState is the transformed state in the new format.

GenServer Upgrade: State Transformation

Let's imagine a GenServer that stores a simple counter as an integer. We want to upgrade it to store the counter as a map #{value => integer()}.

The code_change/3 function will receive the old integer state and return a new map state. This ensures the GenServer continues running smoothly with the updated code and state structure.

GenServer `code_change/3` Example

Here's a simplified example of how code_change/3 would look in my_counter_v2. If our old state was just an integer (e.g., 10), and our new state needs to be #{value => 10}, the conversion is straightforward:

This transformation is key to seamless upgrades.

-module(my_counter_v2).
-behaviour(gen_server).

-export([start_link/0, get_count/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, 
         terminate/2, code_change/3]).

start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

get_count() -> gen_server:call(?MODULE, get_count).

init([]) -> {ok, #{value => 0}}.

handle_call(get_count, _From, State) -> 
    {reply, maps:get(value, State), State};
handle_call(_Request, _From, State) -> 
    {reply, not_understood, State}.

handle_cast(_Msg, State) -> {noreply, State}.

handle_info(_Info, State) -> {noreply, State}.

terminate(_Reason, _State) -> ok.

code_change(_OldVsn, OldState, _Extra) when is_integer(OldState) -> 
    io:format("~p: Upgrading state from ~p~n", [?MODULE, OldState]),
    {ok, #{value => OldState}};
code_change(_OldVsn, State, _Extra) -> 
    io:format("~p: No upgrade needed for state ~p~n", [?MODULE, State]),
    {ok, State}.

Upgrade Best Practices

Hot code loading is powerful, but requires careful planning:

  • Test Thoroughly: Always test your upgrade paths in a staging environment before deploying to production.
  • Backward Compatibility: Design code_change/3 to handle multiple previous versions if necessary.
  • Small, Incremental Changes: Avoid massive changes in state structure in a single upgrade. Break them into smaller, manageable steps.
  • Release Handling: In production, hot code upgrades are typically managed by 'release handlers' (like release_handler in OTP applications), which automate the process of loading new code and coordinating state changes across multiple processes and nodes.

Quick Check: Hot Code Loading

You've learned about Erlang's hot code loading and how it handles state changes. Which of the following statements about Erlang's code_change/3 callback are TRUE?

Recap: Live Upgrades

In this lesson, we explored Erlang's powerful hot code loading feature, which allows applications to be upgraded without downtime. We learned:

  • Erlang can keep 'old' and 'new' versions of modules loaded.
  • Simple code changes can be reloaded with l(Module).
  • For stateful processes like GenServers, the code_change/3 callback is essential for transforming a process's internal state when the code structure changes.
  • Careful planning and testing are vital for successful hot code upgrades.

This unique capability is a cornerstone of Erlang's fault-tolerant and highly available systems!

자주 묻는 질문

“핫 코드 로딩 및 업그레이드” 강의는 무료인가요?

네 — “핫 코드 로딩 및 업그레이드” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의 전체를 잠금 해제할 수 있습니다. Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.

“핫 코드 로딩 및 업그레이드”에서 뭘 배우나요?

Erlang 고유의 핫 코드 로딩 기능을 살펴보고 실행 중인 시스템을 중단하지 않고 소프트웨어를 실시간으로 업그레이드합니다. 브라우저에서 직접 실행하는 실습 코드로 Erlang OTP: Distributed & Fault-Tolerant Systems Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Erlang OTP: Distributed & Fault-Tolerant Systems Programming을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Erlang OTP: Distributed & Fault-Tolerant Systems Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“핫 코드 로딩 및 업그레이드” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Erlang 릴리스 만들기
  2. 핫 코드 로딩 및 업그레이드
  3. 릴리스 버전 관리 및 배포
  4. 릴리스 구성과 부팅 스크립트
← Erlang OTP: Distributed & Fault-Tolerant Systems Programming(으)로 돌아가기