antoine

antoine

Resilient and battle tested event store with PostgreSQL

  1. We need to store a lot of events in a PostgreSQL database.
    We can be spikes sometimes, so the rate of inserts can overload the database (2000/sec).

Those inserts are made in many places in our codebase, during important tasks, so an insert request should not be blocking.
I mean an EventStore.add(...) should not hang and lead to a Genserver timeout on the caller side.

defmodule Work do
  use GenServer

  def handle_call(...) do
     ...
     EventStore.add(...)
     ...
  end
end

Of course, we can not afford losing inserts, but we can trade by having a delay (being not realtime).
According to you, what is the best architecture for this?

  1. We also need to handle the case of the database crashing or not responding. Maybe by enqueuing inserts in RAM/disk and dequeue when database in up again.
    According to you, what is the best solution for this?

Most Liked

slashdotdash

slashdotdash

Have you considered using a purpose built event store, such as Greg Young’s Event Store?

“Store at around 15,000 writes per second and 50,000 reads per second!”
https://eventstore.org/

I’ve written an Elixir Event Store using Postgres for persistence. The performance when running the benchmark suite on my laptop is 4,929 events/sec for a single writer and 8,586 events/sec for 50 concurrent writers.

To persist events without blocking you could do:

Task.start(fn ->
  EventStore.append_to_stream(stream_uuid, :any_version, events, :infinity)
end)

Alternatively you could send the GenServer process a message to store the events outside of the request:

defmodule Work do
  use GenServer

  def handle_call(...) do
    send(self(), {:persist_events, events})
    # ...
  end

  def handle_info({:persist_events, events}, state) do
    EventStore.append_to_stream(stream_uuid, :any_version, events, :infinity)
    # ...
  end
end

You could even use an approach with two GenServers. One to accept requests (e.g. store these events) which forwards the request to a second process to actually persist them to the event store. This allows the first GenServer to immediately reply without any blocking as it is offloading the work to another process.

How do you deal with storing events when the database is inaccessible? You could push them onto a queue and have one or more consumers taking events from the queue and writing them to the event store. However the same problem applies when the queue is unavailable.

alvises

alvises

If you can’t loose any event (but you don’t need realtime) and the spikes can cause timeouts, I would put something like RabbitMQ or Kafka between the application and the database.

appevent–> kafka/rabbit —> event importer --> postgres

Rabbit/Kafka should handle much better the spikes and they could act as a durable buffer. If the importer (which takes the events from rabbit/kafka and stores them into postgres) has any timeout and crashes, or even if postgres locks, the event is not lost and will be reprocessed once the importer or postgres is healthy again.

Fl4m3Ph03n1x

Fl4m3Ph03n1x

Communication with DB

Batching

I understand that your main objective is not to lose information. So, IMO, the best way to do this is do send the information to the DB in batches. You would have a queue that would save data in RAM and every X seconds, write it to the DB.

This approach has the benefit that it will be harder to overload the DB with a billion petitions per minute, but it means that if your machine crashes, you lose the data in the queue (because it is in RAM). A possible solution would be to use DETS for this (write changes to disk) and clean the DETS table once the writes are done.

Pooling

Another approach would be to have a pool of workers which can write into the DB. If a process wants to write and there are no workers, it has to wait. The danger here is: what happens if I can’t wait indefnetly? That depends on your application.

Personal opinion

I would likely use a combination of the previous 2 approaches, having an infinite wait time for the process needing a worker to write to the DB but making sure that processes waiting are added to a queue. HTTPoison, an HTTP library, uses this algorithm with hackney.

What if the DB crashes?

DB crashes are hell. The only way to make sure your data is safe is to store it into disk. However, the longer the DB is down, the less space on your production machines you will have, which means they will eventually break down due to lack of space (it also happens with RAM). To avoid this I recommend a cleaner process, that deletes data older than X (seconds/minutes/etc) that runs permanently to clean your DETS, or files.

Other than that there is really nothing you can do, unless you are willing to streamline data into your DB via queues (Apache Kafka, RabbitMQ, etc).


Hope it helps!

slashdotdash

slashdotdash

Depends whether it’s better to have thousands of processes doing one thing, or one process with a mailbox containing thousands of messages. The only way to reliably answer that question is to try both and benchmark the performance.

Where Next?

Popular in Questions Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
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
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
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
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
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

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
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
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

We're in Beta

About us Mission Statement