Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does memory work across Heroku dynos?

Tags:

node.js

heroku

Let's say I have a dynamically created array in node, and I am running it on a heroku dyno:

var connections = [];
var wm = new WeakMap();

io.sockets.on('connection', function(socket) {

    socket.once('disconnect', function() {
        connections.splice(connections.indexOf(socket), 1);
        socket.disconnect();
        console.log("Disconnected: %s sockets remaining.", connections.length);
    });

    socket.on('idAndApi', (data) => {
        wm.set(socket, data);
    });

    connections.push(socket);
    console.log("Connected: %s sockets connected.", connections.length);
});

Now, it is possible the connections array and the wm weakmap could be created across other dynos.

Will heroku be able to span those variables across each dyno? Or do I need to use some other data-structure (such as a database) to hold the information?

like image 285
E.S. Avatar asked Oct 24 '25 08:10

E.S.


1 Answers

Dynos are independent, and node processes should be stateless (this is true in any environment, Heroku or otherwise).

Store state externally in a place that it can be managed and shared to best suit your app. Redis and Postgres are two of the most common systems for node.

Since you're using socket.io, you should be sure to follow their guide for spanning multiple nodes:

http://socket.io/docs/using-multiple-nodes/

like image 91
hunterloftis Avatar answered Oct 25 '25 21:10

hunterloftis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!