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

고급 재시작 전략

one_for_one, one_for_all 및 rest_for_one 재시작 전략을 깊이 있게 살펴보고 내결함성에 미치는 영향을 이해합니다.

레슨 3/411개 단계

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

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

Intro to Restart Strategies

Welcome to a crucial topic in Erlang: restart strategies! These define how a supervisor reacts when one of its child processes crashes.

Understanding these strategies is key to building fault-tolerant and self-healing systems, which is a hallmark of Erlang/OTP.

Supervisors: The Fault Managers

Before diving in, let's quickly recap: a supervisor is a special process that monitors other processes (its children).

  • If a child process dies, the supervisor detects it.
  • Based on its configured restart strategy, the supervisor decides how to bring the system back to a healthy state.
  • This ensures your application can recover from individual process failures automatically.

`one_for_one`: Isolated Restarts

The one_for_one strategy is the simplest and most common. When a child process terminates:

  • Only the failing child process is restarted.
  • All other sibling processes remain unaffected and continue running.

This strategy is ideal for systems where child processes are largely independent of each other, such as individual client connections.

`one_for_one` in Action

Let's see one_for_one. We'll have a supervisor managing a single worker. When the worker crashes, only it restarts.

To run:
1. Compile: c(worker_gen). c(supervisor_one_for_one).
2. Start supervisor: supervisor_one_for_one:start_link().
3. Crash worker: worker_gen:crash(worker_1).
Observe the output in your Erlang shell.

-module(worker_gen).
-behaviour(gen_server).
-export([start_link/1, init/1, handle_call/3, terminate/2, crash/1]).

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

init(Id) ->
    io:format("Worker ~p (~p) started.~n", [Id, self()]),
    {ok, Id}.

handle_call(crash, _From, State) ->
    exit(i_crashed),
    {reply, ok, State};
handle_call(_Req, _From, State) ->
    {reply, ok, State}.

terminate(_Reason, Id) ->
    io:format("Worker ~p (~p) terminated.~n", [Id, self()]).

crash(Id) ->
    gen_server:call(Id, crash).

-module(supervisor_one_for_one).
-behaviour(supervisor).
-export([start_link/0, init/1]).

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

init([]) ->
    ChildSpec = #{
        id => worker_1,
        start => {worker_gen, start_link, [worker_1]},
        restart => permanent,
        shutdown => 5000,
        type => worker,
        modules => [worker_gen]
    },
    {ok, #{
        strategy => {one_for_one, 3, 5},
        children => [ChildSpec]
    }}.

`one_for_all`: All for One Failure

The one_for_all strategy takes a more drastic approach:

  • If any child process terminates, all other child processes are first terminated.
  • Then, all child processes (including the one that crashed) are restarted.

This is useful when your child processes are tightly coupled and require a consistent, synchronized state. A failure in one implies a need to reset the entire group.

`one_for_all` in Action

Here, a supervisor manages two workers. Crash one, and both will restart.

To run:
1. Compile: c(worker_gen). c(supervisor_one_for_all).
2. Start supervisor: supervisor_one_for_all:start_link().
3. Crash worker: worker_gen:crash(worker_A).
Notice how both worker_A and worker_B restart.

-module(worker_gen).
-behaviour(gen_server).
-export([start_link/1, init/1, handle_call/3, terminate/2, crash/1]).

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

init(Id) ->
    io:format("Worker ~p (~p) started.~n", [Id, self()]),
    {ok, Id}.

handle_call(crash, _From, State) ->
    exit(i_crashed),
    {reply, ok, State};
handle_call(_Req, _From, State) ->
    {reply, ok, State}.

terminate(_Reason, Id) ->
    io:format("Worker ~p (~p) terminated.~n", [Id, self()]).

crash(Id) ->
    gen_server:call(Id, crash).

-module(supervisor_one_for_all).
-behaviour(supervisor).
-export([start_link/0, init/1]).

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

init([]) ->
    Child1 = #{
        id => worker_A,
        start => {worker_gen, start_link, [worker_A]},
        restart => permanent, shutdown => 5000, type => worker, modules => [worker_gen]
    },
    Child2 = #{
        id => worker_B,
        start => {worker_gen, start_link, [worker_B]},
        restart => permanent, shutdown => 5000, type => worker, modules => [worker_gen]
    },
    {ok, #{
        strategy => {one_for_all, 3, 5},
        children => [Child1, Child2]
    }}.

`rest_for_one`: Cascade Restarts

The rest_for_one strategy offers a middle ground:

  • If a child process terminates, it and all subsequent children (those defined after it in the supervisor's child list) are terminated.
  • Then, the failed child and all subsequent children are restarted.
  • Children defined before the failed child are left untouched.

This is useful when processes have sequential dependencies, where a failure in an earlier stage might invalidate the state of later stages.

`rest_for_one` in Action

We have three workers: X, Y, Z. If Y crashes, Y and Z restart, but X remains active.

To run:
1. Compile: c(worker_gen). c(supervisor_rest_for_one).
2. Start supervisor: supervisor_rest_for_one:start_link().
3. Crash worker: worker_gen:crash(worker_Y).
See worker_X stay running, while worker_Y and worker_Z restart.

-module(worker_gen).
-behaviour(gen_server).
-export([start_link/1, init/1, handle_call/3, terminate/2, crash/1]).

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

init(Id) ->
    io:format("Worker ~p (~p) started.~n", [Id, self()]),
    {ok, Id}.

handle_call(crash, _From, State) ->
    exit(i_crashed),
    {reply, ok, State};
handle_call(_Req, _From, State) ->
    {reply, ok, State}.

terminate(_Reason, Id) ->
    io:format("Worker ~p (~p) terminated.~n", [Id, self()]).

crash(Id) ->
    gen_server:call(Id, crash).

-module(supervisor_rest_for_one).
-behaviour(supervisor).
-export([start_link/0, init/1]).

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

init([]) ->
    ChildA = #{
        id => worker_X,
        start => {worker_gen, start_link, [worker_X]},
        restart => permanent, shutdown => 5000, type => worker, modules => [worker_gen]
    },
    ChildB = #{
        id => worker_Y,
        start => {worker_gen, start_link, [worker_Y]},
        restart => permanent, shutdown => 5000, type => worker, modules => [worker_gen]
    },
    ChildC = #{
        id => worker_Z,
        start => {worker_gen, start_link, [worker_Z]},
        restart => permanent, shutdown => 5000, type => worker, modules => [worker_gen]
    },
    {ok, #{
        strategy => {rest_for_one, 3, 5},
        children => [ChildA, ChildB, ChildC]
    }}.

Selecting the Best Strategy

Choosing the right strategy depends on your application's architecture and process dependencies:

  • one_for_one: Use for independent processes, like individual client connections or request handlers.
  • one_for_all: Best for tightly coupled processes that must always be in a consistent state together (e.g., a group of processes managing a single resource).
  • rest_for_one: Suitable for sequential pipelines or layered systems where a failure in an earlier stage affects subsequent stages.

Test Your Knowledge

You are building a system where a primary worker fetches data, and two secondary workers process different aspects of that data. If the primary worker fails, the secondary workers cannot continue with stale data and must also restart. If a secondary worker fails, the others are unaffected. Which strategy is most appropriate for the primary worker and its dependent secondary workers?

Recap: Mastering Restarts

You've explored Erlang's powerful restart strategies:

  • one_for_one: Restarts only the failed child, keeping others running.
  • one_for_all: Restarts all children if any one fails, ensuring full consistency.
  • rest_for_one: Restarts the failed child and all subsequent children in the list.

These strategies are fundamental to building robust, self-healing applications in Erlang, allowing your system to recover from failures gracefully.

무료로 시작

AI 튜터와 함께 Erlang을(를) 배우세요 — 무료

브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.

코스
12
레슨
48

자주 묻는 질문

“고급 재시작 전략” 강의는 무료인가요?

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

“고급 재시작 전략”에서 뭘 배우나요?

one_for_one, one_for_all 및 rest_for_one 재시작 전략을 깊이 있게 살펴보고 내결함성에 미치는 영향을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 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개 중 3번째 강의입니다.

“고급 재시작 전략” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

  1. 복잡한 감독 트리
  2. 동적 프로세스 관리
  3. 고급 재시작 전략
  4. 감독자 브리지와 혼합 프로세스 계층 구조
← Erlang OTP: Distributed & Fault-Tolerant Systems Programming(으)로 돌아가기