감독자와 애플리케이션 구조
감독자로 프로세스를 모니터링하고 재시작해 장애 허용성을 확보하는 탄력적인 애플리케이션을 설계합니다.
감독자와 애플리케이션 구조은(는) CoddyKit의 무료 Elixir & Phoenix: Scalable Backend Development 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Elixir & Phoenix: Scalable Backend Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Elixir & Phoenix: Scalable Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Building Resilient Systems
In concurrent applications, things can go wrong. Processes might crash due to unexpected errors or external issues.
Fault tolerance is the ability of a system to continue operating even when components fail. Elixir embraces a "let it crash" philosophy, meaning instead of trying to prevent every single crash, it focuses on gracefully recovering from them.
Guardians of Processes
This is where Supervisors come in! A supervisor is a special kind of process designed to monitor other processes (its "children").
- If a child process crashes, the supervisor automatically restarts it.
- This ensures your application remains stable and available.
- Supervisors form the backbone of fault-tolerant Elixir applications.
Your First Supervisor
Let's define a simple supervisor module. It uses the Supervisor behavior, similar to how GenServer uses the GenServer behavior.
The init/1 callback is where you define the children it will supervise and its restart strategy.
defmodule MySupervisor do
use Supervisor
def start_link(init_arg) do
Supervisor.start_link(__MODULE__, init_arg, name: __MODULE__)
end
@impl true
def init(_init_arg) do
# No children yet, just the supervisor itself
children = []
Supervisor.init(children, strategy: :one_for_one)
end
end
# --- Main execution part ---
# This simulates starting the supervisor and checking its status.
# In a real app, this would be part of an Application's start/2.
IO.puts("Attempting to start MySupervisor...")
{:ok, supervisor_pid} = MySupervisor.start_link([])
IO.puts("MySupervisor started with PID: #{inspect(supervisor_pid)}")
# Check if the supervisor process is alive
if Process.alive?(supervisor_pid) do
IO.puts("Supervisor is alive!")
else
IO.puts("Supervisor is NOT alive!")
endUnderstanding Supervision Strategies
Supervisors have different strategies for handling child failures:
:one_for_one: Restarts only the child that crashed. This is the default and most common.:one_for_all: If any child crashes, all other children are terminated and then all children are restarted.:rest_for_one: If a child crashes, it and all children started *after* it are terminated and then restarted.
Choosing the right strategy depends on the dependencies between your processes.
Adding Supervised Children
To make a supervisor useful, it needs children! You define children using Supervisor.child_spec/2, which tells the supervisor how to start and manage a process.
Here, we define a simple MyWorker GenServer and add it as a child to our supervisor.
defmodule MyWorker do
use GenServer
def start_link(_opts) do
GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
end
@impl true
def init(:ok) do
IO.puts("MyWorker started!")
{:ok, %{}}
end
@impl true
def handle_call(:crash, _from, state) do
IO.puts("MyWorker is crashing!")
exit(:bad_state) # Simulate a crash
{:reply, :ok, state} # This line won't be reached
end
end
defmodule MySupervisorWithWorker do
use Supervisor
def start_link(init_arg) do
Supervisor.start_link(__MODULE__, init_arg, name: __MODULE__)
end
@impl true
def init(_init_arg) do
children = [
# Define our worker as a child process
Supervisor.child_spec(MyWorker, id: MyWorker)
]
Supervisor.init(children, strategy: :one_for_one)
end
end
# --- Main execution part ---
IO.puts("Starting supervisor with worker...")
{:ok, supervisor_pid} = MySupervisorWithWorker.start_link([])
IO.puts("Supervisor PID: #{inspect(supervisor_pid)}")
# Get the worker's PID
worker_pid = Process.whereis(MyWorker)
IO.puts("Initial MyWorker PID: #{inspect(worker_pid)}")
if Process.alive?(worker_pid) do
IO.puts("Worker is alive and supervised.")
else
IO.puts("Worker did not start correctly.")
endFault Tolerance in Action
Now, let's see the supervisor in action! We'll deliberately crash our MyWorker process, and the supervisor will automatically restart it.
Notice how the worker's Process ID (PID) changes, indicating a new process was spawned.
defmodule MyWorker do
use GenServer
def start_link(_opts) do
GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
end
@impl true
def init(:ok) do
IO.puts("MyWorker started!")
{:ok, %{}}
end
@impl true
def handle_call(:crash, _from, state) do
IO.puts("MyWorker is crashing!")
exit(:bad_state) # Simulate a crash
{:reply, :ok, state} # This line won't be reached
end
def crash_it do
GenServer.call(__MODULE__, :crash)
end
end
defmodule MySupervisorWithWorker do
use Supervisor
def start_link(init_arg) do
Supervisor.start_link(__MODULE__, init_arg, name: __MODULE__)
end
@impl true
def init(_init_arg) do
children = [
Supervisor.child_spec(MyWorker, id: MyWorker)
]
Supervisor.init(children, strategy: :one_for_one)
end
end
# --- Main execution part ---
IO.puts("Starting supervisor with worker...")
{:ok, _supervisor_pid} = MySupervisorWithWorker.start_link([])
worker_pid_before_crash = Process.whereis(MyWorker)
IO.puts("Worker PID before crash: #{inspect(worker_pid_before_crash)}")
# Crash the worker
IO.puts("Attempting to crash the worker...")
MyWorker.crash_it()
:timer.sleep(100) # Give supervisor a moment to restart
worker_pid_after_crash = Process.whereis(MyWorker)
IO.puts("Worker PID after crash: #{inspect(worker_pid_after_crash)}")
if worker_pid_before_crash != worker_pid_after_crash && Process.alive?(worker_pid_after_crash) do
IO.puts("Worker was restarted by the supervisor! New PID detected.")
else
IO.puts("Worker was NOT restarted, or PID remained the same (unexpected).")
endElixir Applications: The Top Level
While supervisors manage individual processes, an Elixir Application is the top-level unit of code and processes in an Elixir system.
It provides a structured way to:
- Group related modules and processes.
- Define how your system starts up and shuts down.
- Manage configuration and dependencies.
The `Application` Behavior
Every Elixir application typically has a main application module that use Application.
The most important callback is start/2, which is invoked when your application starts. This is where you typically start your top-level supervisor, which then recursively starts all other processes in your system.
defmodule MyApp.Application do
use Application
# This is the entry point for your application.
# It starts the top-level supervisor.
@impl true
def start(_type, _args) do
children = [
# In a real app, you'd start your main supervisor here.
# For example: Supervisor.child_spec(MySupervisorWithWorker, id: MySupervisorWithWorker)
]
# Start a supervisor that will supervise other processes/supervisors
opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)
end
end
# --- Main execution part ---
# This part simulates how an application would be started.
# In a real Mix project, 'mix run --no-halt' would call MyApp.Application.start/2
IO.puts("Simulating application start...")
{:ok, pid} = MyApp.Application.start(:normal, [])
IO.puts("Application top-level supervisor started with PID: #{inspect(pid)}")
if Process.alive?(pid) do
IO.puts("Application supervisor is active.")
else
IO.puts("Application supervisor failed to start.")
endHierarchical Supervision Trees
For complex applications, you often don't have just one supervisor. You create a supervision tree, where supervisors can supervise other supervisors.
- This allows you to organize your application into logical units.
- Different parts of your system can have different restart strategies.
- If a major component fails, its supervisor can restart it without affecting unrelated parts of the system.
Supervisor Check
Time for a quick check on your understanding of supervisor strategies!
Lesson Summary
Well done! You've learned how Elixir builds resilient applications:
- Supervisors monitor processes and restart them upon failure.
- Different supervision strategies (
:one_for_one,:one_for_all,:rest_for_one) dictate how failures are handled. - Elixir Applications provide the top-level structure, starting supervisors and forming supervision trees.
These concepts are fundamental to building robust, fault-tolerant systems in Elixir.
자주 묻는 질문
“감독자와 애플리케이션 구조” 강의는 무료인가요?
네 — “감독자와 애플리케이션 구조” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Elixir & Phoenix: Scalable Backend Development 강의 전체를 잠금 해제할 수 있습니다. Elixir & Phoenix: Scalable Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
“감독자와 애플리케이션 구조”에서 뭘 배우나요?
감독자로 프로세스를 모니터링하고 재시작해 장애 허용성을 확보하는 탄력적인 애플리케이션을 설계합니다. 브라우저에서 직접 실행하는 실습 코드로 Elixir & Phoenix: Scalable Backend Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Elixir & Phoenix: Scalable Backend Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Elixir & Phoenix: Scalable Backend Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“감독자와 애플리케이션 구조” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Elixir & Phoenix: Scalable Backend Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Elixir & Phoenix: Scalable Backend Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Elixir 프로세스와 메시지 전달
- GenServer 동작 구현
- 감독자와 애플리케이션 구조
- Task와 Agent를 사용한 동시 작업