A
A
Alexey2019-08-01 18:54:05
JavaScript
Alexey, 2019-08-01 18:54:05

Do-it-yourself limiting socket requests?

How much such an approach will be, not so much correct, but viable in terms of efficiency, in case the user starts spamming any button (on the site, just any action is reactive and the broadcast goes to all connected users)? Or is there another option to protect against a fool?

const reqLimit = 10;
webSocket.on('connection', (ws) => {
  ws.lastRequest = Date.now() - 1000; // от юзера считаем запросы в секунду, поэтому даем фору при коннекте
  ws.fastRequestsCount = 0;
  ws.on('message', (msg) => {
    ws.fastRequestsCount = (Date.now() - ws.lastRequest) > 1000 ? 0 : (ws.fastRequestsCount + 1);
    if (ws.fastRequestsCount > reqLimit) {
      return; 
    };
    ws.lastRequest = Date.now();
    // дальше идет какая-то логика, тоесть мы тупо игнорим юзера если от него было больше 10 запросов в секунду
  });
});

ps: debounce type conditions: not suitable, because sometimes you need a "burst" of 4-6 requests per second.
Date.now() - ws.lastRequest < 100;

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question