benbonnet

benbonnet

Trying to understand Genserver memory leak

Getting started with otp; having a sample app which main purpose is to ingest data.

A genserver is subscribed to a given channel and receives load of data passed aroudn through pubsub. Its single purpose is tostore this data in the db (using ecto). It does not store any state.

  def init(_args) do
    Phoenix.PubSub.subscribe(PubSub, "CHANNEL_NAME")
    {:ok, []}
  end

  def handle_info({:matcher, data}, state) do
    upsert(data)
    {:noreply, state} # , :hibernate} added, solved memory leak, but ¯\_(⊙︿⊙)_/¯ 
  end

  defp upsert(klines) do
    Repo.insert_all(
      ModuleName,
      data, # array of struct
      on_conflict: :replace_all,
      conflict_target: [:key1, :key2, :key3]
     )
  end

Its memory invariably increase to some 100Mb, and never lowers. Googling around, found out about {:noreply, state, :hibernate}, and it solved my issue.

But no clue why this memory increase ended up to be permanent. Is it because of Ecto ? About the way the data is passed around (pubsub) ?
Hope the question is somehow relevant; would like to get a better understanding

regards

Most Liked

trisolaran

trisolaran

Sounds like this could be a plausible explanation: Extremely high memory usage in GenServers - #23 by sasajuric

karlosmid

karlosmid

Hi! What helped in my team was to run function as a async Task:

Task.async(__MODULE__, : upsert, [klines])
    |> Task.await(:infinity)

In that case, when Task is done, gen server memory related to it is released immediately.

Heads up: this was in combination with when the gen server did repetitive tasks triggered by the timer.

ityonemo

ityonemo

I believe hibernate triggers a GC event.

You can also trigger GC manually using :erlang.garbage_collect/0

ityonemo

ityonemo

It’s not required. but sorry, I don’t have answers for you on when the GenServer gets gc’d. Are maybe your messages coming in more rapidly than you can dispatch them to the database? (Aka do you always have a message in the message queue?). This is just a guess but I think if all of the messages are dispatched, the process goes into a tail call that calls GC, but if there are messages in the queue, the process is only put on ice by the scheduler.

Could also be some weird things with binary references, which are handled differently and have different lifetimes.

Here is specific data how the Erlang GC works, but that is not just for GenServers. Erlang -- Erlang Garbage Collector. If you’re curious you can always check out the source code for the gen module: otp/gen.erl at master · erlang/otp · GitHub + gen_server module otp/gen_server.erl at master · erlang/otp · GitHub

hst337

hst337

First of all, unused data will always be garbage collected. The question here is at which point it’ll be garbage collected
Second, here klines get copied into Task process you’ve created. So it might trigger gc in GenServer. But this klines will be in the Task until it dies.

But this is a bad solution, because you don’t need a process here, you don’t need to copy this data. You just need to call the Repo.all and then trigger minor gc

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
Mooodi
Given a string, how can I get access to its character by index? Enum.at("my_string", 2) doesn't work. Or rather, not char, but a substr...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New

We're in Beta

About us Mission Statement