So I am trying to design a simple URL shortener application where every time a URL is queried, it is going to update the number of times it has been queried.
I'm thinking of using MongoDB and I am thinking of some sample schema like this
{
id : ...., //Mongo-generated ID
originalUrl: .... // The original URL
shortUrlKey: .... // The shortened URL key
createdAt: ....
updatedAt: .....
hitCount: ...... // Number of times the document has been queried.
}
I want to make sure that every time a particular URL is queried, the request increments the hitCount
field by one and then returns the entity.
Now I read somewhere that writes on MongoDB result in locking that particular document.
So I have the following questions:
Since every read here is going to update the document, how best can I design my application so that it can be scaled efficiently?
Also, I want to serve the URLs from Redis cache once the
hitCount
crosses a certain number. But while I'm serving the URL from the cache, I still want to update thehitCount
field. How do I do that?
It makes sense to have an asynchronous (fire and ignore the result) call to update the field once the URL starts getting served from cache because at that point keeping hitCount
synchronised doesn't matter, but until that point, how can I sync the document without degrading the performance or losing the chance of scalability?