josefrichter

josefrichter

Eventually persisting in-memory state?

Suppose I have a GenServer or Agent that holds some state and serves immediate responses.

What are some strategies to asynchronously persist this state in database, without slowing down the GenServer, but then also handling failures resulting in portion of state not written? In a way, this is sort-of “write cache” or buffer/queue for high-concurrency write situations…

My specific example: I have limited-capacity course with 30 seats, and I have 10000 within single second trying to enroll. I wanna put them in a queue, and give them immediate response whether or not they made it among the first 30, but then in the next step I also need to write it to db, so that the initial response is “set in stone” so to speak. It would be fine to send them kind-of “pre-approval” immediately in the first step, and then “full confirmation” a few seconds later once it’s written in the database.

I didn’t study computer science, so maybe this is a common problem with simple solution.

Thank you!

Most Liked

josefrichter

josefrichter

Thank you. I was thinking or Redis ordered sets (ordered by time of signing up) but was waiting whether someone will bring it up instead of (D)ETS and Mnesia - they do seem to offer similar features, but it feels like a few bits and pieces need to be added manually, while Redis is more up to date with today’s needs and has it all out of the box… So I would just ZADD everyone into ordered list, then save the first 30 in bulk to Postgres, but keep the list as a “waiting list” around, maybe just using Redis persistence options…

Then I was thinking also about not scaling prematurely because I believe Postgres is in fact much more powerful than most people realize :slight_smile: However, I am worried mostly about the atomicity - INSERT with RETURNING the “rank” in the table, which might be not so performant anymore…?

This is a university system and there’s gonna be dozens, maybe hundreds, of courses - I was thinking each having its own GenServer taking care of the queue. And they open the floodgates at the same moment for all the students, which is 40k people – so it’s huge sudden spike in traffic, but it’s also true that the atomic writes, which I’m afraid of the most, would likely be spread at least over several seconds, so probably not reach the rate of thousands per second.

I’m just trying to prevent the repeating scenario that the system always goes down within seconds of opening and then they’re putting out fires for the whole day while people at home are crazily hitting refresh button all day, desperately needing to enroll before it’s all full :smiley:

stefanchrobot

stefanchrobot

How many instances of web server are you going to have? Is it going to sustain the 10000 requests in a second?

If one server instance is fine, then a single GenServer per course sounds like a good solution. Looks like your constraint is just a counter (30 seats). Assuming you have a reasonable DB (INSERT is just a few milliseconds), you can just write the record immediately and have all the consistency guarantees. So the GenServer would be something like:

  1. Start the GenServer with course id,
  2. On init (or handle_continue) get the booked seats,
  3. On each “book a seat” message, check the counter, write to DB if seat available, return result.

Be sure to bump the timeout on the GenServer.call when sending the “book a seat” message. I think this should be good enough, but it’s hard to tell without real performance tests.

If it turns out that you need multiple instances of the web server, then things get a bit more hairy. You could go with Erlang distribution or use out-of-process cache like Redis.

lucaong

lucaong

Yep, I mostly agree with what @stefanchrobot said.

You could theoretically go with a singleton GenServer (a single global process), but that will make horizontally scaling your app to several instances and ensuring you don’t loose data in case of restarts a bit more difficult.

Honestly, I would rather:

  • Implement it efficiently with standard database queries. You can go a long way with a database like Postgres before you hit such a bottleneck. How likely it is that you would actually get 10.000 requests per second? Remember you can always optimize your solution when traffic actually grows to the point you start to see scalability problems.

  • If you need more performance, I would implement this with Redis rather than in a GenServer. You could use a simple integer counter, or even a set, so you can efficiently check if the course is full and only write to database if not (in cases when the sets are much bigger and one is fine with an approximated count Redis even provides HyperLogLog). With Redis you would get performance, but also durability if you use the WAL, so you don’t risk loosing bookings if your server crashes or restarts.

Of course, it is possible with Elixir to run a single global GenServer in your cluster taking care of each counter, but you would need to take special care in your logic to make it work properly in all cases (think about restarts, deployments, etc.).

Where Next?

Popular in Questions Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
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
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
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
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
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
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

yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
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
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
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
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

We're in Beta

About us Mission Statement