Erlang OTP: Distributed & Fault-Tolerant Systems Programming · Lección

Intercambio de código en caliente y actualizaciones en vivo

Aprenda cómo Erlang actualiza el código en ejecución sin detener el sistema y cómo los comportamientos de OTP permiten realizar actualizaciones en vivo conservando el estado.

Lección 4 de 413 pasos

Intercambio de código en caliente y actualizaciones en vivo es una lección gratuita de Erlang OTP: Distributed & Fault-Tolerant Systems Programming en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Erlang OTP: Distributed & Fault-Tolerant Systems Programming, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Erlang OTP: Distributed & Fault-Tolerant Systems Programming incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Zero-Downtime Upgrades

One of Erlang's signature features is hot code swapping: replacing a module's code while the system keeps running, with no restart and no dropped connections.

Two Code Versions

The VM keeps up to two versions of each module: current and old. Loading a third version purges the oldest.

Local vs External Calls

A local call (foo()) stays in the running version. An external/qualified call (?MODULE:foo()) jumps to the newest loaded version. This distinction drives upgrades.

loop(State) ->
    receive
      Msg ->
        NewState = handle(Msg, State),
        ?MODULE:loop(NewState)  % picks up new code
    end.

Loading New Code

You compile and load the new version with the code module or via the shell.

c(my_module).
code:load_file(my_module).

The code_change Callback

Stateful OTP behaviors like GenServer support a code_change/3 callback. OTP calls it during an upgrade so you can transform old state into the new format.

code_change(_OldVsn, State, _Extra) ->
    {ok, migrate_state(State)}.

Why State Migration Matters

If your new version stores state differently (say a tuple becomes a map), code_change bridges the gap so live processes do not crash on the new code.

migrate_state({old, A, B}) ->
    #{a => A, b => B}.

Release Upgrades

For whole-system upgrades, OTP uses appup and relup files that describe the steps to move from one release version to the next.

{"1.1.0",
 [{"1.0.0", [{update, my_server, {advanced, []}}]}],
 [{"1.0.0", [{update, my_server, {advanced, []}}]}]}.

Suspending Processes

During an advanced upgrade, OTP suspends the affected processes, applies code_change, then resumes them, ensuring no message is handled with mismatched state.

Purging Old Code

After an upgrade, processes still running old code can be checked and the old version purged once safe.

code:soft_purge(my_module).
% returns false if any process still runs old code

When to Use It

Hot upgrades shine for telecom-grade always-on systems. For many apps, a rolling restart of nodes is simpler. Choose based on your uptime requirements.

Best Practices

Key rules:

  • Always make the recursive loop call qualified (?MODULE:loop)
  • Implement code_change for any stateful behavior
  • Test upgrades in staging before production

Quick Check

Test your hot-swap knowledge.

Recap

You learned Erlang's live upgrade model.

  • The VM keeps two code versions
  • Qualified calls adopt new code
  • code_change/3 migrates state during OTP upgrades
  • appup/relup drive full release upgrades
Gratis para empezar

Aprende Erlang con un tutor de IA — gratis

Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.

Cursos
12
Lecciones
48

Preguntas frecuentes

¿La lección «Intercambio de código en caliente y actualizaciones en vivo» es gratis?

Sí — el texto completo de «Intercambio de código en caliente y actualizaciones en vivo» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Erlang OTP: Distributed & Fault-Tolerant Systems Programming, actualiza a CoddyKit PRO. El curso de Erlang OTP: Distributed & Fault-Tolerant Systems Programming incluye 4 lecciones en total.

¿Qué aprenderé en «Intercambio de código en caliente y actualizaciones en vivo»?

Aprenda cómo Erlang actualiza el código en ejecución sin detener el sistema y cómo los comportamientos de OTP permiten realizar actualizaciones en vivo conservando el estado. Practicas Erlang OTP: Distributed & Fault-Tolerant Systems Programming con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Erlang OTP: Distributed & Fault-Tolerant Systems Programming?

No se requiere experiencia previa. Erlang OTP: Distributed & Fault-Tolerant Systems Programming en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Intercambio de código en caliente y actualizaciones en vivo»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Erlang OTP: Distributed & Fault-Tolerant Systems Programming?

Sí. Cada lección de Erlang OTP: Distributed & Fault-Tolerant Systems Programming incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. GenStatem para la gestión del estado
  2. GenEvent para la gestión de eventos
  3. Behaviors OTP personalizados
  4. Intercambio de código en caliente y actualizaciones en vivo
← Volver a Erlang OTP: Distributed & Fault-Tolerant Systems Programming