Reputation: 27
I'm trying to process a stream of 300 million rows of data. Once I get to around 5 million rows I am getting a FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory. (The number varies by machine but is consistent happening).
You can run the code below to see this happening - I can't tell if the issue in the code of inherent to streams. I tried to dumb the process but I couldn't do that.
Is there a memory limit? I removed all other code and 'dumbed' the example down to make sure it wasn't some back pressure issue.
var Readable = require('stream').Readable;
var Writable = require('stream').Writable;
var util = require('util');
var tenMillion = 10000000;
//var tenMillion = 5000000; //THIS WORKS
var writeEvery = tenMillion / 10;
/*
* Create a really simple stream that will run 10 million times
*/
function Streamo(max) {
Readable.call(this, { objectMode: true });
this._currentIndex = -1;
this._maxIndex = max;
}
util.inherits(Streamo, Readable);
Streamo.prototype._read = function () {
this._currentIndex += 1;
if (this._currentIndex % writeEvery == 0) {
console.log(this._currentIndex + ' of ' + this._maxIndex)
};
if (this._currentIndex < 0 || this._currentIndex >= this._maxIndex) {
console.log("BOOM")
this.push(null);
return;
}
this.push(true);
};
/*
* Create a really simple Writable Stream to Count
*/
function Counta() {
Writable.call(this, { objectMode: true, highWaterMark: (200 * 1024) });
this._count = 0;
}
util.inherits(Counta, Writable);
Counta.prototype._write = function (chunk, enc, cb) {
this._count++;
if (this._count % writeEvery == 0) {
console.log('_______________________________' + this._count)
};
cb();
};
Counta.prototype.Count = function () {
return this._count;
}
/*
* Exercise It
*/
var s = new Streamo(tenMillion);
var c = new Counta();
s.pipe(c);
c.on('finish', function () {
console.log("BOOM BOOM BOOM BOOM BOOM BOOM BOOM BOOM BOOM ")
});
Upvotes: 1
Views: 2723
Reputation: 106696
This is a known issue with the current streams implementation.
In the streams documentation and code, there are multiple places where it is alluded to that _read()
should be asynchronous.
So if you're not actually performing (async) i/o of some kind in your _read()
implementation, then you may need to (at least occasionally) call setImmediate()
before push()
ing, to keep the call stack from getting too large. For example, this works without crashing:
Streamo.prototype._read = function (n) {
this._currentIndex += 1;
if (this._currentIndex % writeEvery == 0) {
console.log(this._currentIndex + ' of ' + this._maxIndex)
};
if (this._currentIndex < 0 || this._currentIndex >= this._maxIndex) {
console.log("BOOM")
this.push(null);
return;
}
var self = this;
if (this._currentIndex % writeEvery == 0) {
setImmediate(function() {
self.push(true);
});
} else
this.push(true);
};
Upvotes: 6