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?