Is it worth trying not to hit database as much as possible?

Viewed 41

The data in db changes every 14 seconds but there may be many calls from clients to fetch same data in that duration. So, in Servlet I implemented a logic like

if(fetchedDataMoreThan3SecondsAgo) 
 /*a servlet field */ lastFetchedData=fetchData();

return  lastFetchedData;     

But when I measured, fetching data from db only takes few milliseconds. So the thing I did is probably already done by MySql. Is this an unnecasary optimization? Because with my "optimazation",in some rare cases a client may recieve data 2-3 seconds longer than it should.

1 Answers

From architecture point of view in your case caching is good idea - you have data which is not changing constantly, does not make sense to bother the DB - is expensive resource so caching makes a lot of sense. This is very important regarding scalability - if you have hundreds requests is OK, but what if your app gets millions of requests, this could lead to many problems without caching.

Implementing cache properly is good question, the code which you provided is the simplest, I would probably implement separate caching mechanism which will take care about updating in separate thread and share it on application level - servlets dont need to care about update period.

Actually you can determine in your app when the changing happened - first compare new data and old data with cache turned off, and when you see change you can start waiting for 13 seconds, then turn cache off until you see data change again. In this case you wouldnt have wrong data.

Related