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

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
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
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
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
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
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
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
_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
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
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
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 42633 214
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New

We're in Beta

About us Mission Statement