Yuseferi
Yuseferi

Reputation: 8710

Server Send Event Issue on High traffic website

we have high traffic website, 2000 concurrent users and 250K unique users daily, our Back-End technology is PHP 5.6 ,we are going to implement Service Send Event on our website to get notification number form the server ( in other world send notification number to Browser ),I've seen some example of implement of SSE in PHP , as an example

ClientSide :

if (!!window.EventSource) 
{
    var source = new EventSource('task.php');

    source.addEventListener('message', function(e) 
    {
        console.log(e.data);
        //Do whatever with e.data
    }, false);
}

PHP:

<?php
/**
    EventSource is documented at 
    http://dev.w3.org/html5/eventsource/
*/

//a new content type. make sure apache does not gzip this type, else it would get buffered
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.

/**
    Constructs the SSE data format and flushes that data to the client.
*/
function send_message($id, $message, $progress) 
{
    $d = array('message' => $message , 'progress' => $progress);

    echo "id: $id" . PHP_EOL;
    echo "data: " . json_encode($d) . PHP_EOL;
    echo PHP_EOL;

    //PUSH THE data out by all FORCE POSSIBLE
    ob_flush();
    flush();
}

$serverTime = time();

//LONG RUNNING TASK
for($i = 0; $i < 10; $i++)
{
    send_message($serverTime, 'server time: ' . date("h:i:s", time()) , ($i+1)*10); 

    //Hard work!!
    sleep(1);
}

send_message($serverTime, 'TERMINATE'); 

(most of the solution are implement it by A unlimited (or long time) loop and sleep for a short time)this keep a thread per user live and in high traffic like us I though It could be a big problem, What is the good solution to implement Server Send Event with PHP Back-End in High traffic websites?

Note : I see this https://github.com/licson0729/libSSE-php but It seems it doesn't handle it with good performance solution.

Upvotes: 0

Views: 496

Answers (1)

rlanvin
rlanvin

Reputation: 6277

What is the good solution to implement Server Send Event with PHP Back-End in High traffic websites?

Easy: use a dedicated server (software) that can handle the load for your SSE connections.

It doesn't have to be written in PHP. For example, I have used Nginx modules that do the job very well, and the PHP backend pushes events to them using curl:

If you want a pure PHP solution, it's possible but you will need to implement a server yourself, and not rely on nginx/apache. Basically you will need an event loop, listening to sockets, http protocol, etc. A framework like ReactPHP should help get you started.

Upvotes: 1

Related Questions