Create a service class that is a singleton that keeps track of likes on posts, comments. Periodically flush the data to the database.
class LikeService {
// format: <pk, nlikes>
HashMap<Integer, Integer> cachePostLikes = new HashMap<Integer,Integer>();
HashMap<Integer, Integer> cacheCommentLikes = new HashMap<Integer,Integer>();
HashMap<Integer, Integer> dbPostLikes = new HashMap<Integer,Integer>();
HashMap<Integer, Integer> dbPostLikes = new HashMap<Integer,Integer>();
void incrementPostLikes() {}
void incrementCommentLikes() {}
Long getPostLikes(Integer postId) {
if(!cachePostLikes.containsKey(postId)) {
// load from db
}
return cachePostLikes.get(postId) + dbPostLikes.get(postId)
}
Long getCommentLikes(Integer commentId) {}
// Always reset counts in cache hashmaps to zero
void flushToDB() {}
}