V
V
verycooldev2018-07-01 13:35:42
MongoDB
verycooldev, 2018-07-01 13:35:42

How to make a simple hit counter?

There is a simple API server for a SPA application. Stack: Node, Express, Mongo.
Task: a simple counter of the number of requests on a certain route (since the front itself is separated from the API) of non-unique users and saving this data. Those. count each hit, even if the user refreshes the page (just like on the Toaster).
And then the question arises how to implement it correctly?
1. If you change the field in Monge for the requested article everycount time you access data , it looks somehow too busy on the server
2. What will happen if 100, 500, 1000 people request a page at the same time (that is, the route from which the page pulls data)? 1000 write operations to the database at the same time? How does this work in practice with Monga? I believe the data will either be lost or everything will die. Or will they queue up and there will be a wild delay?
3. Can you somehow store the counter in memory and then periodically save it in the database to the desired article?
In general, despite the simplicity of the task, there is no answer yet on how to effectively accomplish it. Yesterday I googled for half an evening and did not find answers. I ask for help from more experienced comrades.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Shashenkov, 2018-07-01
@verycooldev

If a large load is expected, then you can shard the database or use databases that are ready for large recording volumes (clickhouse).
You can also use buffers, for example, after filling, more than 1000 records, immediately write the entire pack to the database. But writing on the 1st line to the main database is very expensive in terms of resource costs

F
frees2, 2018-07-01
@frees2

If there are more than 10 events, the user clicked, viewed 10 times, for example, then we send it to the server, but all sorts of robots are in flight.

var i = 0;(function(history){ var pushState = history.pushState;
history.pushState = function(state) { if (typeof history.onpushstate == "function")
{history.onpushstate({state: state});} 
return pushState.apply(history, arguments); }})(window.history);
window.onpopstate = history.onpushstate = function(e){ i++; test=JSON.stringify(e.state);  


if (localStorage.getItem('history666') === null) { document.getElementById("moo").innerHTML ='Нет в памяти!' ;   }

Or through localStorage, JSON data goes somewhere in the storage.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question