socket.io icon indicating copy to clipboard operation
socket.io copied to clipboard

memory leak

Open bferreira opened this issue 14 years ago • 53 comments

Hi,

We are using 0.9.6,

We've been noticing memory usage increasing until the server stops responding. It usually would take a few days until this happened but now we increasing usage (about 220 peers) , the server stops responding in less than one day.

Should we be destroying some objects, releasing some connection? Anything we are not doing that we should do to stop this?

Our client setup:


var socket;
var subs = new pc.util.OrderedMap();

function addSubscription(subtopic, callback) {
    if(!PCAUser.loggedIn) return;
    subs.put(subtopic, callback);
    if(!socket) {
        initSockeIO();
    } else {
        socket.json.send({
            command : "subscribe",
            subscriptions: [subtopic]
        });
    }
}

function initSockeIO() {
    socket = io.connect(liveUpdateConfig.host,
        {port: liveUpdateConfig.port, rememberTransport: false});
    socket.on('message', function(obj) {
        if (obj.subtopic) {
            var key = obj.subtopic;
            if (subs.get(key)) {
                // execute callback
                window[subs.get(key)](obj); // FIXME bad approach
            }
        }
    });

    socket.on('connect', function subscribe(obj) {
        socket.json.send({
            command : "subscribe",
            subscriptions : subs.keys()
        });
    });

    socket.on('disconnect', function(obj) {
        setTimeout(function() {
            socket = io.connect(liveUpdateConfig.host,
                {port: liveUpdateConfig.port, rememberTransport: false});
        }, 1000);
    });
}

jQuery(document).unload(function() {
    if(socket) {
        socket.emit('disconnect');
    }
});

Our server setup:

//--------- Socket.IO server ---------


var socketio = io.listen(server, {
 transports: ['websocket','flashsocket','htmlfile','jsonp-polling']
});


socketio.sockets.on('connection', function(client) {
    stats.peersCount ++;

    var msg = "Client connected: " + client.id + ", active peers count: " + stats.peersCount;
    logger.info(msg);
    socketio.sockets.send(msg);

    client.on('message', function(message) {
        var decodedMessage = util.inspect(message, true, 3);
        logger.info("\n\Client " + client.id + " Message received : " + decodedMessage);

        if( decodedMessage.indexOf('monitor') > -1) {
            logger.info('monitor enabled');
            if(!subscriptions[monitor_subscription]) {
                subscriptions[monitor_subscription] = [client];
            } else {
                subscriptions[monitor_subscription].push(client);
            }
            logger.info("Client " + client.id + " added as monitor");
            client.json.send({ subscriptions : [monitor_subscription] });

        } else
        if (typeof message.command != undefined) {
            try {
                switch (message.command) {
                    case "subscribe":
                        var incomingSubscriptions = message.subscriptions;
                        //if the subscriptions are in a string, split them into an array
                        if(message.subscriptions.replace) {
                            incomingSubscriptions = message.subscriptions.replace('[','').replace(']','').replace(/[\"\s]/g, '').split(',');
                        }
                        for (var i = 0; i < incomingSubscriptions.length; i++) {
                            var subtopic = incomingSubscriptions[i];
                            if (!subscriptions[subtopic]) {
                                subscriptions[subtopic] = [client];
                            } else if(subscriptions[subtopic].indexOf(client) < 0) {
                                subscriptions[subtopic].push(client);
                            }
                        }
                        logger.info("Client " + client.id + " subscribed");
                        client.json.send({ subscriptions : message.subscriptions });
                        break;
                    default:
                        logger.info("Undefined message: " + decodedMessage);
                }
            } catch (e) {
                logger.error('Error while handling message ' + decodedMessage + ", " + e.message);
            }
        }
    });

    client.on('disconnect', function() {
        stats.peersCount --;

        var msg = "Client " + client.id + " disconnected, active peers count: " + stats.peersCount;
        socketio.sockets.send(msg);
        logger.debug(msg);

        for (var subtopic in subscriptions) {
            if (subscriptions[subtopic].length > 0) {
                subscriptions[subtopic] = subscriptions[subtopic].filter(function(element) {
                    return element.id != client.id
                });
            }
        }
    });
});

Thanks, Barbara

bferreira avatar Sep 04 '12 14:09 bferreira

Hi, I had this issue long ago and spent a long time trying to figure it out. The closest I could get was to just disable "websockets" as a transport. Sad to do that, but that was the only thing keeping memory safe.

crickeys avatar Sep 06 '12 19:09 crickeys

Hi, Thank you. That is sad because that's the transport that we really would like to use, since our users will only use Chrome in the future. But we are now seen the socket.io stop responding without any high memory consumption. We are logging everything but nothing is tell us much.

bferreira avatar Sep 07 '12 06:09 bferreira

Same with me on Socket.io 0.9.10, NodeJS 0.8.10. Websocket is leaking memory with 600 concurrent connection, rss went up to around 900MB. I have to restart every hours or else, it will be really hard to connect to server after consume this much memory.

paiboonpa avatar Oct 03 '12 07:10 paiboonpa

Heha,

you can probably install nodetime and try to figure out if you have a leak https://nodetime.com/

We were having to many jsonp-polling requests. We were able to get down from 402 req/s to 42 req/s

And finnaly we got an error: local/nodejs/live-update-nodejs/node_modules/socket.io/lib/transports/jsonp-pol

 ling.js:88

this.response.writeHead(200, { ^ TypeError: Cannot call method 'writeHead' of undefined at JSONPPolling.doWrite (/local/nodejs/live-update-nodejs/node_modules/socke

 t.io/lib/transports/jsonp-polling.js:88:17)
at JSONPPolling.write (/local/nodejs/live-update-nodejs/node_modules/socket.                                            

 io/lib/transports/http-polling.js:132:8)
at JSONPPolling.packet (/local/nodejs/live-update-nodejs/node_modules/socket                                            

 .io/lib/transport.js:515:15)
at JSONPPolling.error (/local/nodejs/live-update-nodejs/node_modules/socket.                                            

 io/lib/transport.js:498:8)
at JSONPPolling.onData (/local/nodejs/live-update-nodejs/node_modules/socket                                            

 .io/lib/transports/jsonp-polling.js:69:10)
at IncomingMessage.<anonymous> (/local/nodejs/live-update-nodejs/node_module                                            

 s/socket.io/lib/transports/http.js:65:12)
at IncomingMessage.emit (events.js:64:17)
at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:130:23                                            

 )
at Socket.ondata (http.js:1506:22)
at TCP.onread (net.js:374:27)

So I guess our problem is with socket.io.

bferreira avatar Oct 03 '12 11:10 bferreira

I already got nodetime installed. I already used node-webkit-agent too. Nodetime cannot pinpoint the problem because sample object is quite random when use heap snapshot. For node-webkit-agent, it looks better, can drill down more but still, very hard to pinpoint a problem. There's no leak from one large object or else it would be caught very easy. I already tried using only xhr-polling and memory changed from 900MB/hour to 100 MB/hour but it's too slow for our real-time game. Not sure if jsonp is faster than xhr-polling or not.

paiboonpa avatar Oct 03 '12 11:10 paiboonpa

I can confirm. Our server will also eventually run out of memory and start to use swap during load when using socket.io and websockets.

I will try to do a baseline with only socket.io, without express or other requires.

I will run more tests but currently using:

node v0.8.9 socket.io v0.9.10 express v.3.0.0rc4

Disabling websockets significantly reduces memory load. I am currently using jsonp-polling and update this post with results at then end of the week.

nodenstuff avatar Oct 07 '12 16:10 nodenstuff

Real culprit is in https://github.com/einaros/ws/issues/43 Socket.io used this library as websocket transport. Short conclusion is Gabage Collector problem, v8 engine bug. Seem sockjs also has this issue with websocket: https://github.com/sockjs/sockjs-node/issues/62

One way to fix this problem is change node to version 0.4.12. Websocket will work smoothly with that version. However, lots of tools will be disable too like Nodetime, node-webkit-agent(can use node-inspector instead but I think it's harder to use.) including native cluster which introduced in Node 0.6 (may use other library instead). Another way is use XHR, JSON-P instead which is a lot slower. I heard that in NodeJS 0.9, there will be a re-write on Garbage Collector but sadly, after tested 0.9.2 with Socket.io, it failed since cannot find socket.io.js.

paiboonpa avatar Oct 08 '12 15:10 paiboonpa

Thanks. I will give 0.4.12 a try on our system this week. I'm also not sure that a lot of npm stuff will still work.

nodenstuff avatar Oct 08 '12 15:10 nodenstuff

Still, cannot rely on NodeJS 0.4 much because engine.io (new core for Socket.io 1.0) will support only NodeJS 0.6 or higher. Really make me a hard decision to stay on 0.4 or try restart node 0.8 every x hour instead. :(

paiboonpa avatar Oct 08 '12 15:10 paiboonpa

I agree but for my purposes I'd rather not have to restart the server consistently versus the usual weekly reboot. As it stands right now in any high use situations it's a choice between potential service interruptions or using an old version.

I plan on giving engine.io and socket.io 1.0 some time to stabilize before going into production.

I've been testing my current setup using 4GB of ram and I can only get to about 200-300 users before memory is sucked up in a few hours. I'm really not doing much other than some redis pubsub and relaying messages.

nodenstuff avatar Oct 08 '12 15:10 nodenstuff

Actually making engine.io work on 0.4 again wouldn't be that hard. It used to be compatible until a few weeks ago.

rauchg avatar Oct 08 '12 15:10 rauchg

@guille Wow. Great to hear! :)

paiboonpa avatar Oct 08 '12 16:10 paiboonpa

Dears, sorry my ignorance, but I have a very long message on my console finnish with this: info - socket.io started ...... ... .. ,"1048560":0,"1048561":0,"1048562":0,"1048563":0,"1048564":0,"1048565":0,"1048566":0,"1048567":0,"1048568":0,"1048569":0,"1048570":0,"1048571":0,"1048572":0,"1048573":0,"1048574":0,"1048575":0,"length":1048576},"offset":21456}]}

After a very long time I have the result on my client. Is this the same issue?

anibalvy avatar Oct 15 '12 00:10 anibalvy

Whatever is causing this bug pretty much renders socket.io and websockets on node useless is a large scale production environment.

I have been trying to track this down but I am not sure where its leaking. Sockjs has the same issues so I think its the websocket library not doing something correctly with the new versions of node. {Edit Sockjs not using the same websocket library}

It's eating 3 gigs of ram on one server will under 100 people connected.

nodenstuff avatar Oct 16 '12 17:10 nodenstuff

Sockjs isn't using the same WebSocket library as Socket.IO does. So there is something else going on here.

3rd-Eden avatar Oct 16 '12 17:10 3rd-Eden

@nodenstuff did you try with socket.io master ? (uses ws)

rauchg avatar Oct 16 '12 17:10 rauchg

Thanks guys. I'll pull down the most recent from github and give it a try on node 0.8.12.

nodenstuff avatar Oct 16 '12 17:10 nodenstuff

Master still leaks.

Sent from my iPhone

On Oct 16, 2012, at 12:38 PM, Guillermo Rauch [email protected] wrote:

@nodenstuff https://github.com/nodenstuff did you try with socket.iomaster ? (uses ws)

— Reply to this email directly or view it on GitHubhttps://github.com/LearnBoost/socket.io/issues/1015#issuecomment-9499274.

crickeys avatar Oct 16 '12 17:10 crickeys

updated to node 0.8.14 - will update this post accordingly if issue is fixed

Not going to do any charts or anything - newest node is no longer crashing our server during peak load - I'd say thats an improvement

6 hours - ram usage has been stable but increasing VIRT 671M RES 37096 SHR 4820 10 hours - ram usage has been stable but increasing VIRT 670M RES 45104 SHR 4820

Oct 28 - sever started swapping and crashed - looks like issue is still there just not as bad :S

nodenstuff avatar Oct 26 '12 06:10 nodenstuff

After some configuration with mysql and dropping all but jsonp and websockets - we've managed to stay stable. There is still a very slow memory leak - and some reconnection issues here and there

trying to track it down

nodenstuff avatar Nov 06 '12 21:11 nodenstuff