How memory is managed in Elixir/Erlang

TL;DR #

Stack vs Heap #

Each Erlang process has its own stack and heap which are allocated in the same memory block and grow towards each other. When the stack and the heap meet, the garbage collector is triggered and memory is reclaimed. If not enough memory was reclaimed, the heap will grow.

Generational garbage collection #

Memory in erlang/elixir #

Loss of sharing #

BEAM does not expect you to send messages with shared sub terms (like nested repeated struct)

Memory leaks #

ETS and DETS #

How ETS manages its own memory? #

  1. Separate from Process Heaps: ETS tables are not part of the normal Erlang process heaps. Instead, they are allocated outside the process heaps in a separate memory area. This allows ETS tables to store large volumes of data without affecting the garbage collection of Erlang processes.
  2. Fixed and Dynamic Allocation: ETS allocates memory in blocks. It starts with a fixed block size, but as the table grows, new blocks are allocated dynamically. This enables efficient growth of tables and avoids frequent memory reallocation.
  3. Table Types: ETS supports several table types such as setordered_setbag, and duplicate_bag. Each type influences how memory is organized and accessed.
  4. Garbage Collection: ETS tables do not undergo the same garbage collection as Erlang processes. Since ETS tables are independent, memory usage must be managed explicitly by creating and deleting tables as needed.
  5. Ownership and Concurrency: An ETS table is owned by a process, and when this owning process terminates, the ETS table is automatically deleted, freeing up its memory. ETS provides concurrency controls allowing multiple processes to read from a table, with configurable options for write concurrency.

How (and when) ETS frees its memory #

  1. Table Deletion
  2. Owner Process Termination
  3. Manual Cleanup

Sources #

Memory leaks in Elixir
Erlang Garbage Collector — erts v15.1.2


Since you've made it this far, sharing this article on your favorite social media network would be highly appreciated 💖! For feedback, please ping me on Twitter.

Published