tuananh
tuananh

Reputation: 755

Memory leak when running Nodejs socket.io on AWS EC2 t2.micro

I want to check the maximum number of connections for websockets that a t1.micro instance (1GB RAM) can handle.

So I made a simple example to check it with nodejs(v6.2.1) and [email protected].

Here is the code on server:

require("http").globalAgent.maxSockets = Infinity;
var http = require('http').createServer(function(req, res) {});
var io = require('socket.io')(http);
io.on('connection', function(socket){
    socket.on('echo me', function (data) { //receive msg from client
        var msg = {msg: data.msg};
        io.emit('echo me', msg);
        delete msg.msg;
    });
});

var clock = setInterval(function(){
    global.gc();
}, 2000);

http.listen(3000, function(){
    console.log('listening on *:3000');
});

And code on client:

<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script type="text/javascript">
var n = 20;
var socket = [], id = [];
for(var i = 0; i < n; ++i){
    socket[i] = io('http://aws_ip_address');
    socket[i].on('connect', function(){            
        id.push(this.io.engine.id);
        console.log('Connected to Server. My name is ');
    });
    socket[i].on('echo me', function(data){ //receive message from server
        console.log(data.msg);
    });
}
var inv = setInterval(function(){
    sendEchoToServer();
}, 1000); //1 second

function sendEchoToServer(){
    for(var i = 0; i < n; ++i){
        var msg = 'My name is ' + id[i] + ' with msg: ' + Math.random();
        socket[i].emit('echo me', {msg: msg});
    }
}
</script>

The problem is, when I open 10 tabs (200 connections) on clients, the memory increases minute by minute. And if I open 350 connections, the server can't handle it in 5 minutes (the OS kills it). The CPU usage is getting 100%.

How can I allow it to handle more than 500 connections?

Upvotes: 2

Views: 812

Answers (1)

You can change the memory handling in node to be more agressive.

More on the options available: https://gist.github.com/listochkin/10973974

node --expose-gc --optimize_for_size --max_old_space_size=460 --gc_interval=100 app.js

Upvotes: 1

Related Questions