Berkeley Now
Berkeley Now

Reputation: 137

How does the performance work in a PHP websocket with a external DB connection?

CONTEXT. I have a web server on one side and the database (BD) on another server with another IP. I have a PHP websocket (WS) built with the Ratchet library. The idea is that the browser shows updated information second by second based on the existing data in the database. I configured the WS so that every second the client (through JS) sends a message to the server in order to retrieve the most recent data from the DB and display it in the browser:

let conn = new WebSocket("ws://localhost:8080/");
conn.onopen = function (e) {
    setInterval(function() {
        conn.send('myrequest');
    }, 1000);
};

Everything works perfectly in local development mode. But I suspect that I am not doing things well and that in production it will be a disaster with respect to performance, just because of the following.

PROBLEM. I place the DB connection in the constructor and inside the onOpen() method, with which I achieve that there is a single connection to the DB during the life of the WS. That's fine. The problem is that within the onMessage() event I make requests to the external DB:

$stmt = $this->pdo->prepare('SELECT ...');
if ($stmt->execute()) {
    if($stmt->rowCount()>0) {
        // ...
    }
}
$stmt->closeCursor();

I never get rid of multiple requests to the DB: $stmt->execute(), and like the DB is on another server, that makes me assume that the websocket is useless a lot when the web server is on one side and the DB server on the other, Is that so? If so, what would be the best way not to affect performance here?

Any comment is absolutely welcome!

Upvotes: 0

Views: 261

Answers (1)

Heinz
Heinz

Reputation: 399

As I am yet not allowed to comment I post here: I would not connect to a DB inside my web socket server.

Better have a standalone script connecting to the DB and the webs socket server. The script does the counting, sends a message with the data to the WS server, send sleeps for a second. The WS server receives the message and informs the client browser(s).

Upvotes: 1

Related Questions