How to handle database updates?


Even if we have a simple application and we use a simple hashmap as a memory cache we still have to address this issue. When we update a database the cache should be updated with the new data or the old data should be removed from the cache.

Each time we update something in the database we have to remove the updated entities from the cache. We should take a special care because we our changes might affect other entities kept in cache:

update database  
invalidate saved and affected entities from cache

Memory Cache in Web Applications

As I said web applications are special applications. For each http request a thread will be created. In order to make sure that everything will work fine we must ensure that:

  • All the http request threads will access the same data in cache. There a many ways to achieve it, singletons can be taken into discussion.
  • The way the data is accessed is synchronized - one thread will not read the data while another one is updating it.

Distributed applications

The applications where memory cache is required are the applications with many users and usually they run in distributed environments. There are options here:

  • each server instance will have its own memory cache. If in one instance an entity is changed the affected entities should be invalidated in the cache on all the other server instances. The server instance changing the database will have to trigger the propagation the changes to other server instances.
  • the cache will run as a separate process and all the server instances will use it in common, connecting remotely to read/invalidate cached data.