If I have a cache (IMemoryCache) Dictionary<string, List>. At some point in my app, I have get the List for some Id from Cache, then I use this List to insert it in the DB. Sometimes this List could be changed by other task prior to inserting - that's throwing an exception. To avoid this as soon as I get the list from Cache, I'm making a copy of this. But sometimes the object in the List can be changed by other task prior to inserting - that's throwing exception. To avoid this I could create a copy for each object in the list and the creating a new list from copied objects, but that's kind of unappealing.
Maybe other solution would be to get the List from cache and create a lock and then inside the lock finish the inserting to DB flow. Are there any other solutions, or best approaches to this kind of issues?
Some explanation: Well this is a long-chain problem. I’m using Cassandra DB for storage. The Cache from above as well as Table in DB is related to message queue. If I'm removing a lot from DB (Cassandra) it generates a lot of tombstones in a table, and at some point if I pass the threshold it fails to query the table. I solved this by changing the structure of my table from 1 row per unread message to 1 row per user with a column list. But that's now creating problems with the Cache. Why using Cache? Well because Cassandra is really fast on write operations, but not really for read operations (if I have 10.000 opened web sockets to 2 server instances and 1 cassandra node, read/write just hangs and my servers goes into thread pool starvation continuously getting more threads but not doing any job), so I read once on startup and then only write data to Cassandra using the Lists from Cache rather than those from DB to avoid rereading them from DB. And by doing all this I run in problems with consistency, weird cache layer & async mutations. Any advice will be helpful.