Need ideas for preventing race conditions in my stock trading app

I am building a matching engine for stock trading. When a user place a buy/sell order, the engine will pull a list of available orders from the db whose price is equal to the placed order and is sorted by inserted_at. So basically FIFO.

So far, my code works fine but I know that it is prone to race condition because they run on different process(process started by the browser when visiting the buy/sell page).

Since I want to process the orders sequentially, I have thought of creating a genserver for each stock price for eg TSLA-200, TSLA-210 that will hold %{buyers: [], sellers []} in its state.
When someone makes a buy req for TSLA at 200 then it will be stored in the TSLA-200 genserver.

But it will create a host of other prbls like what if TSLA-200 cant keep up with the inflow of msgs, i can exhaust the process limit of my BEAM VM, etc.

So, how would you tackle this issue?

You can do it in an ecto transaction.


I’m no Elixir guru but how about using fixed amount of genservers and consistent hashing? You select genserver that handles stock based on consistent hash from stock’s unique identifier what ever that might be. This is one that Discord uses GitHub - discord/ex_hash_ring: A fast consistent hash ring implementation in Elixir.


yea i did it like that.