I have a Web API in C# that receives data from various clients, which needs to be saved to the database. Each client sends data approximately every 10 seconds. To save this data, I need to base it on some properties of the last record saved in the database. This means that each time I save a new record, I need to perform a query to fetch the last saved record.
The problem occurs when I receive multiple data points from the same client simultaneously. For example, sometimes I might receive 50 data points from the same client within the same second. When I perform the query to fetch the last record, that record might no longer be the last one since multiple data points are being inserted at the same time (the data is saved and retrieved asynchronously). When an invalid data point is saved, it compromises all subsequent records that are based on that invalid data.
My question is: what practice can I adopt to solve this problem? I thought about saving and retrieving all data synchronously, but I believe this would harm the performance of my application."