I am building an app where my database updates a new live stock price every second. A customer can choose to buy the stock, and this order will be saved to the database.
I am currently doing basic read/write operations using Sqlalchemy in a fastapi app, as shown in the example below. When i deploy the application, i tried triggering this function at the same time on 2 devices. (Click on buy stock at the same time) The result is that it will fail on one device, which is the behaviour that i desire, as for each timestamp, only 1 order should be allowed to occur.
I am curious as to whether this behaviour is due to the session by Sqlalchemy, and whether i am right in saying that when 1 session is occuring, another session cannot occur. I read online that it is still possible for postgres database to have race conditions if not handled correctly. Does using sessions automatically deal with race conditions?
with self.Session.begin() as session:
n_rows = session.query(Order).count()
if n_rows >= 1000:
oldest_data = session.query(Order).first()
session.delete(oldest_data)
order_model = Order(**order.__dict__)
session.add(order_model)
session.commit()