How to feed notifications in real time as a logged in user?

3

I'm wanting a system that keeps updating the logged in user to go showing the messages he receives. Taking into account that this system will have 250-500 concurrent users there, what is the best way to search the data in the database and update the user's mailbox? I thought about running a script every minute and updating everyone logged in but I do not know if this is the best way. I want to do this via Ajax with setInterval but I'm open to ideas since I've never done it and I do not know what the best implementation is.

What worries me is server overhead!

    
asked by anonymous 24.11.2016 / 18:05

1 answer

2

If dealing with an application developed for the web, there is no way to get away. The only ways to create updates for the client are:

Create business rules on the client's own computer (Solution in case the client will perform an activity on his own machine, such as being alerted after completing a form correctly or parsing a file via js).

Hitting the server via ajax, requesting and handling the incoming data. (I believe this should be your approach)

Okay, but what about "server grief"?

The purpose of ajax is to minimize the amount of data traffic, in order to make small requests to the server and take advantage of the data already provided. So the solution would be to create an endpoint to fetch only the required data. Example:

Client computer performs the request:

$.ajax({
    type: "POST",
    url: "/checkUpdates",
    data: {
        userId: 1,
        lastMessageId: 1
    },
    dataType: "json",
    success: function(response) {
        verifyAjaxReponse(response);
    }
});

You collect the data sent by the user, and compare them with the one received:

$data = json_decode($params); //dados vindos pelo ajax
$result = $db->exec('select lastMessageId where userId = "' . $data['userId'] . '"');

if ($data['lastMessageId'] == $result['lastMessageId']) { //Supondo que a request não passe por aqui, e exista um novo resultado
    $result == false;
}
$framework->disableLayout();
$framework->view = json_encode($result); // $result = ['message' => 'Você recebeu uma nova mensagem. Verifique sua caixa de entrada', 'id'];

After that, the data will be minified and returned to the client machine, where your javascript can check if the response has any updates and generate the alert.

success: function(response) {
    verifyAjaxReponse(response);
}
    
01.12.2016 / 14:58