visionmedia/co — pull request #115 by gconaty (2014-04-26 17:37:38+00:00)
Title: setImmediate exhibits corrupt data when co is in KOA

I have an app whose middleware are basically koa_body->koa_pg->(mymethod that fetches from db and sets this.body=result).

With multiple simultaneous requests coming into Koa, I was having some responses 'hijack' the body from other responses. e.g. you'd expect

GET /route?id=1 -> 1
GET /route?id=2 -> 2
GET /route?id=3 -> 3
GET /route?id=4 -> 4

but what you'd get (totally non-determinstic) would be

GET /route?id=1 -> 1
GET /route?id=2 -> 2
GET /route?id=3 -> 3
GET /route?id=4 -> 2

After MUCH debugging (and with koa-compose debugging) literally I verified that this.body got set correctly, and yet before writing the response this.body would change to another.

If the setImmediate is removed (or changed to process.nextTick), there are NO issues. I verified this with 0.10.26 (gnode), 0.11.11, 0.11.12. Without debugging into libuv I wonder if this is as designed or a bug in node.js. Specifically from the node docs on setImmediate:

*While order is preserved for execution, other I/O events may fire between any two scheduled immediate callbacks.*

In any case using process.nextTick exhibits no issues (probably because maxDepth defaults to 1000 and I've got only 4 requests).