0Pricing
Elixir & Phoenix: Scalable Backend Development · บทเรียน

กลยุทธ์ซูเปอร์ไวเซอร์ขั้นสูง

สำรวจกลยุทธ์การควบคุมดูแลรูปแบบต่าง ๆ นอกเหนือจาก `:one_for_one` และออกแบบระบบที่ทนทานต่อความขัดข้อง

กลยุทธ์ซูเปอร์ไวเซอร์ขั้นสูง เป็นบทเรียน Elixir & Phoenix: Scalable Backend Development ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Elixir & Phoenix: Scalable Backend Development และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Elixir & Phoenix: Scalable Backend Development มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Beyond Basic Supervision

In Elixir, supervisors are key to building fault-tolerant applications. You've likely encountered the default :one_for_one strategy.

This strategy restarts only the crashing child process. But what if processes are tightly coupled or have dependencies?

Elixir offers more advanced supervision strategies to handle complex failure scenarios, ensuring your application remains robust.

Strategy: One For All

The :one_for_all strategy is powerful for tightly coupled processes.

  • What it does: If any child process dies, all other child processes are terminated and then all children are restarted.
  • When to use it: Ideal when child processes are interdependent and cannot function correctly if one of them fails. Think of a group of processes that must always be in a consistent state together.

It ensures the entire group is always fresh and consistent after a failure.

One For All in Action

Let's see :one_for_all with two workers. If Worker 1 crashes, both Worker 1 and Worker 2 will restart.

Notice the output showing both workers terminating and then starting again.

defmodule Main do
  defmodule MyWorker do
    use GenServer

    def start_link(name) do
      GenServer.start_link(__MODULE__, nil, name: name)
    end

    def init(_) do
      IO.puts("Worker #{inspect(self())} started!")
      {:ok, %{}}
    end

    def handle_call(:crash, _from, state) do
      IO.puts("Worker #{inspect(self())} crashing!")
      exit(:boom)
      {:reply, :crashed, state}
    end

    def handle_call(:status, _from, state) do
      {:reply, :ok, state}
    end

    def terminate(reason, _state) do
      IO.puts("Worker #{inspect(self())} terminating due to #{inspect(reason)}!")
    end
  end

  def main() do
    children = [
      {MyWorker, :worker1},
      {MyWorker, :worker2}
    ]

    opts = [strategy: :one_for_all, name: MyOFA_Supervisor]
    {:ok, _pid} = Supervisor.start_link(children, opts)

    Process.sleep(100)

    IO.puts("\n--- Initial state ---")
    GenServer.call(:worker1, :status, 100)
    GenServer.call(:worker2, :status, 100)

    IO.puts("\n--- Crashing Worker 1 ---")
    try do
      GenServer.call(:worker1, :crash, 100)
    rescue
      _ -> IO.puts("Worker 1 process exited.")
    end

    Process.sleep(500)

    IO.puts("\n--- After crash and restart ---")
    GenServer.call(:worker1, :status, 100)
    GenServer.call(:worker2, :status, 100)

    :ok
  end
end

Main.main()

Strategy: Rest For One

The :rest_for_one strategy is useful for processes with a linear dependency chain.

  • What it does: If a child process dies, it and all subsequent (later started) child processes are terminated and then restarted. Processes started before the crashing child are left untouched.
  • When to use it: Use this when processes have a cascading dependency. For example, if Process C depends on Process B, and Process B depends on Process A. If B crashes, C must also restart, but A is fine.

It's a more surgical restart than :one_for_all.

Rest For One in Action

Here, we have three workers. If Worker 2 crashes, Worker 2 and Worker 3 will restart, but Worker 1 will remain unaffected.

Observe how only the affected and dependent processes are restarted.

defmodule Main do
  defmodule MyWorker do
    use GenServer

    def start_link(name) do
      GenServer.start_link(__MODULE__, nil, name: name)
    end

    def init(_) do
      IO.puts("Worker #{inspect(self())} started!")
      {:ok, %{}}
    end

    def handle_call(:crash, _from, state) do
      IO.puts("Worker #{inspect(self())} crashing!")
      exit(:boom)
      {:reply, :crashed, state}
    end

    def handle_call(:status, _from, state) do
      {:reply, :ok, state}
    end

    def terminate(reason, _state) do
      IO.puts("Worker #{inspect(self())} terminating due to #{inspect(reason)}!")
    end
  end

  def main() do
    children = [
      {MyWorker, :worker1},
      {MyWorker, :worker2},
      {MyWorker, :worker3}
    ]

    opts = [strategy: :rest_for_one, name: MyRFO_Supervisor]
    {:ok, _pid} = Supervisor.start_link(children, opts)

    Process.sleep(100)

    IO.puts("\n--- Initial state ---")
    GenServer.call(:worker1, :status, 100)
    GenServer.call(:worker2, :status, 100)
    GenServer.call(:worker3, :status, 100)

    IO.puts("\n--- Crashing Worker 2 ---")
    try do
      GenServer.call(:worker2, :crash, 100)
    rescue
      _ -> IO.puts("Worker 2 process exited.")
    end

    Process.sleep(500)

    IO.puts("\n--- After crash and restart ---")
    GenServer.call(:worker1, :status, 100)
    GenServer.call(:worker2, :status, 100)
    GenServer.call(:worker3, :status, 100)

    :ok
  end
end

Main.main()

Supervisor Restart Intensity

Supervisors also come with options to prevent endless restart loops, which can consume system resources.

  • :max_restarts: The maximum number of times a child process (or group of processes, depending on strategy) can be restarted within a given time frame.
  • :max_seconds: The time frame (in seconds) during which :max_restarts is counted.

If the restart count exceeds :max_restarts within :max_seconds, the supervisor itself will terminate, potentially crashing its own supervisor.

Restart Intensity Example

Here, we set max_restarts: 2 and max_seconds: 5. If Worker 1 crashes more than twice within 5 seconds, the supervisor will give up and crash itself.

Run this code multiple times and observe the supervisor terminating.

defmodule Main do
  defmodule MyWorker do
    use GenServer

    def start_link(name) do
      GenServer.start_link(__MODULE__, nil, name: name)
    end

    def init(_) do
      IO.puts("Worker #{inspect(self())} started!")
      {:ok, %{}}
    end

    def handle_call(:crash, _from, state) do
      IO.puts("Worker #{inspect(self())} crashing!")
      exit(:boom)
      {:reply, :crashed, state}
    end

    def handle_call(:status, _from, state) do
      {:reply, :ok, state}
    end

    def terminate(reason, _state) do
      IO.puts("Worker #{inspect(self())} terminating due to #{inspect(reason)}!")
    end
  end

  def main() do
    children = [
      {MyWorker, :worker1}
    ]

    opts = [strategy: :one_for_one, name: MyIntensitySupervisor,
            max_restarts: 2, max_seconds: 5]
    {:ok, sup_pid} = Supervisor.start_link(children, opts)

    Process.sleep(100)

    IO.puts("\n--- Crashing Worker 1 repeatedly ---")
    Enum.each(1..3, fn i ->
      IO.puts("Attempt #{i}:")
      try do
        GenServer.call(:worker1, :crash, 100)
      rescue
        _ -> IO.puts("Worker 1 process exited.")
      end
      Process.sleep(100) # Short delay between crashes
    end)

    Process.sleep(1000) # Give supervisor time to react

    IO.puts("\n--- Supervisor status ---")
    if Process.is_alive(sup_pid) do
      IO.puts("Supervisor is still alive.")
    else
      IO.puts("Supervisor has terminated due to excessive restarts.")
    end

    :ok
  end
end

Main.main()

Custom Supervision Strategies

While :one_for_one, :one_for_all, and :rest_for_one cover most cases, Elixir allows for custom supervision strategies.

  • You can implement the Supervisor behaviour yourself.
  • This involves defining init/1 and handling restart logic based on the :which_child argument in handle_call/3.

This is an advanced topic, typically needed for highly specific and complex restart policies not covered by the built-in strategies.

When to Use Which Strategy?

Choosing the right strategy is crucial for your application's resilience.

  • :one_for_one: Default, independent processes. Most common.
  • :one_for_all: Tightly coupled processes where consistency is paramount.
  • :rest_for_one: Processes with linear, cascading dependencies.
  • Custom: Rare, for unique restart requirements.

Always consider the relationships and dependencies between your processes when designing your supervision tree.

Advanced Supervisor Quiz

A critical process P1 provides a service that P2 and P3 absolutely rely on. If P1 crashes, P2 and P3 cannot function correctly and also need to be restarted to ensure data consistency.

Which supervision strategy is best suited for a supervisor overseeing P1, P2, and P3 in this scenario?

Recap: Robust Supervision

You've now explored advanced Elixir supervision strategies that go beyond the default :one_for_one.

  • :one_for_all restarts all children if any child fails.
  • :rest_for_one restarts the failing child and all subsequent children.
  • You also learned about max_restarts and max_seconds to control restart intensity.

These tools allow you to design highly resilient, fault-tolerant applications by precisely controlling how your system reacts to process failures.

คำถามที่พบบ่อย

บทเรียน “กลยุทธ์ซูเปอร์ไวเซอร์ขั้นสูง” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “กลยุทธ์ซูเปอร์ไวเซอร์ขั้นสูง” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Elixir & Phoenix: Scalable Backend Development ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Elixir & Phoenix: Scalable Backend Development มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “กลยุทธ์ซูเปอร์ไวเซอร์ขั้นสูง”

สำรวจกลยุทธ์การควบคุมดูแลรูปแบบต่าง ๆ นอกเหนือจาก `:one_for_one` และออกแบบระบบที่ทนทานต่อความขัดข้อง คุณปฏิบัติ Elixir & Phoenix: Scalable Backend Development ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Elixir & Phoenix: Scalable Backend Development หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Elixir & Phoenix: Scalable Backend Development บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “กลยุทธ์ซูเปอร์ไวเซอร์ขั้นสูง” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Elixir & Phoenix: Scalable Backend Development นี้ได้ไหม

ได้ บทเรียน Elixir & Phoenix: Scalable Backend Development ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. Elixir แบบกระจายและการจัดกลุ่ม
  2. กลยุทธ์ซูเปอร์ไวเซอร์ขั้นสูง
  3. ซูเปอร์ไวเซอร์แบบไดนามิกและ Registry
  4. GenStage และสายการประมวลผลแบบควบคุมแรงดันย้อนกลับ
← กลับไปที่ Elixir & Phoenix: Scalable Backend Development