r/node•
abutterfly

What in the hell packages/architecture are you guys using for performant RESTful APIs?

Some background: the organization I work for has begun developing a RESTful API to replace our many Event Management Systems. Our initial prototype looked something like this:

  • Node.js
  • Express
  • Sequelize

This was pretty nice and got us a working prototype fairly quickly. However, we needed to do some authentication, and since we had an existing LDAP server, we chose to use that.

  • Node.js
  • Express (w/ express-sessions)
  • Passport (passport-ldapauth)
  • Sequelize

We weren't in love with this (but, in retrospect, I'm willing to reconsider it), so we tried something else. We used JWTs whose payload contained a document UUID in a Couchbase cluster. That document contained session information and user permissions.

  • Node.js
  • Express
  • Passport (jwt, passport-ldapauth)
  • Sequelize

It was at this point we finally started doing some load testing with wrk. The results were awful. Response times > 300ms, requests/s < 100 in some cases. We're now stuck and looking for answers:

  • Using WebStorm's debugger/spy-js, we saw a lot of CPU time being eaten up by Sequelize's deduplication (a result of the fact that it only wants to send one mega-query per request).
  • When we disabled the call to Couchbase, we saw a decent performance improvement, but not much.

We've begun looking into options to remedy this, but we're not sure how to proceed. We know we can't be the only organization in the world using node.js with N:M relations and token-based auth, yet we haven't heard a peep elsewhere about performance. Some options we looked into:

  • Abandoning the ORM for a DAO architecture
  • Using StrongLoop's Loopback
  • Trying a different ORM (Bookshelf, in this case, which somehow performed worse)

I would really like to hear from the node community about this project, common design patterns, and if there's something just patently obvious that we're missing.

Posted Jul 31, 2015, 1:17 PM UTC

1135
NippleNutz•

We just migrated away from strongloop to Hapi. Give hapi a look.

7
tylargh•

How is Hapi going to solve his ORM issues?

3
tuxedo25•

+1 to this. Been using hapi for a couple of months for a full rewrite of our API. SO happy with their approach to modules.

2
abutterflyOP•

I was eyeballing Hapi myself. Looked promising. Mind if I ask you what kind of data stores you're using and how you're interacting with them?

1
BeerinBiddo•

If you go the Hapi route, take a look at https://github.com/devinivy/dogwater, it should help a lot here.

2
Meneerdewit•

To the top. I ran into limitations when using Express, as soon as my application began to take shape and features were being added. So far I'm loving it. Configuration over convention, think of Ruby on Rails, but now it's Javascript with 100% code coverage and perfectly maintained core and plugins.

1
Heterogenic•

Raw node & felixge's MySQL client.

I'm not sure what value any additional packages offer, besides possibly Restify's debugging hooks (which I'd definitely consider, but in our specific environment don't help much).

6
abutterflyOP•

Interesting. I can't argue with the effectiveness of using node-mysql (though I think my team is writing that off as "unmaintainable", an analysis I'm not sure I agree with), but I'm curious as to hear about your decision not to use Express (or Restify).

Does your application do any auth/authz?

1
Heterogenic•

Anyone who thinks SQL is "unmaintainable" shouldn't be let near a relational database. :/

For our particular use, express failed because it uses a linear lookup on request matches. Routing is fast only until you have 1000+ routes. We needed that to be much better, and a hand-written lookup (nothing fancy!) ended up orders of magnitude faster in practice.

And it's not very hard to write a REST handler, just a few lines of code. Node is a fantastic routing system right out of the box.

We use Node.crypto (hardware accelerated) for auth. Auth is also just not very complicated, if you have a crypto library.

5
abutterflyOP•

Anyone who thinks SQL is "unmaintainable" shouldn't be let near a relational database. :/

10/10, strongly agree. However, I'm the junior intern and I can only sell so much.

Thanks a ton for your input, very valuable!

8
Heterogenic•

Recommend just doing it and showing them.

It's hard to argue with real results. Alternatively, if it's still slow, then you'll have way more visibility into what's going on.

2
tuxedo25•

Anyone who thinks SQL is "unmaintainable" shouldn't be let near a relational database. :/

Aren't they self-selecting?

3
Heterogenic•

Apparently not!

1
TheHeretic•

I agree, it shows complete ignorance and unwillingness to expand a developers abilities.

1
abutterflyOP•

I'm not saying one of the devs on the team is a sterotypical .NET developer, BUUUUT... ;)

0
chiminage•

Did you set it to Production?

5
torwori•

Agreed, NODE_ENV=production can do wonders.

2
TheHeretic•

There must be a multitude of factors at play here. I suspect everything has been written in a blocking fashion, but even that doesn't explain 300ms response times.

Are you generating the query in a loop?

Are you iterating over the result set in a blocking manner?

How large is the array of queries that sequelize is deduplicating, how large is your result set?

Express simply isn't that slow, and neither is sequelize if used properly.

4
abutterflyOP•

Hey, I appreciate you chiming in! I'll provide a little more detail for you.

Initially we were writing our Sequelize finders like this:

router.get('/:id/users', function(req, res, next) {
    models.user.scope(req.userScope).findAll({
        include: [{
            model: models.group,
            where: {id: req.params.id}
        }]
    }).then(function(result) {
        res.json(result);
    }).catch(function (err) {
        next(err);
    });
});

That was awful, so we tried this pattern and got some slightly better results, but still pretty miserable (the test I just ran showed 1s respond times and less than 100 req/s to a measly 96 concurrent connections):

models.group.findByPrimary(req.params.id)
        .then(function(g){
            g.getUsers({scope:req.userScope})
                 .then(function(result){...})

The example set shown here is a meager 45 users...Not that big at all.

There's no iterating over the results (at least explicitly). All queries go almost directly into res.json().

1
TheHeretic•

This appears to be okay, what is your Sequelize connection pool configured at (particularly max connections)?

I'm not sure if you want to do this, but to avoid Sequelize iterating over the queries (to batch them), try switching the query over to raw SQL i.e. http://docs.sequelizejs.com/en/latest/docs/raw-queries/

which will still allow you to use models

2
damnedmage•

I'm still just using express, but I wrote my own router layer on top of it to add easy, config-driven restful services. I'm getting 1ms/request response time, and handle a load of up to 10k reqs/s no problem.

3
_patientzero•

Sails.js!

2
DVWLD•

You forgot the /s

2
CarpetFibers•

Using Sails and loving it. No sarcasm needed.

2
jareddlc•

restify

2
[deleted]•

[deleted]

1
davesnx•

I'm trying to develop with restify and comming from a few experience on express, and with both mongoose.

But the packages that I can recomend:

  • lodash for managing js objects/arrays
  • nconf for manage a conf.json
  • mongoose-error-helper for manage errors with mongoose
  • mongoose-schema-extend for extend models like interfaces
  • winston for manage the logs
  • cuid for generate unik ids
  • cheerio for scrapp html with jqLite
  • passport/passport-http for autentificate
  • request for call other apis/web services
  • Q for using promises
  • mocha for testing
  • also json schema module for validate json objects

Not using all on each project, I don't feel awesome using a lot of dependencies... Just choose the correct for each project.

1
tuananh_org•

Dont use Q

1
davesnx•

Ok, thanks. why?

1
tuananh_org•

Super slow. Use sth like bluebird instead. They have benchmark there as well. Q is one of the worst

1
davesnx•

I will try it, for sure, Thanks (now yes :P)

1
chinkuSj•

Was looking for something like cuid. Thank you, Sir.

1
razvanzz•

You can try few optimizations, but they don't necessarily mean significant improvement.

  • I would first look at the business logic, and make sure blocking events are running in parallel if applicable. (I am personally a big fan of async and lodash which makes it readable and easy to code)
  • I haven't worked with sequelize, but generally, ORM's are quite performance heavy due to their abstraction layers. They also increase memory usage. Using the DAO architecture you can hard-code your application queries in each model and then use the basic driver for performing the queries.
  • If you're dealing with large datasets, consider processing them in a non-blocking manner.

I see that nobody said it before, you should keep in mind that node, while quite fast due to it's minimalist architecture, runs only in 1 process on 1 core. As much as you would try to optimize you would still be limited, and you will not use all the available power (considering that most of the servers have more than 1 core). Sometimes it's also preferable to sacrifice performance over maintainability and fast delivery with abstraction.

I don't know if it's applicable in your case, but you should consider horizontal scaling. pm2 is an example of a node process manager that makes it easy to spawn and load-balance few more instances of the same application, making use of all the server power.

1
abutterflyOP•

Well, the good news is that none of this is new to me. The very limited business logic that's getting done is using either async or lodash already. Datasets are very small, and we did use cluster.fork(). It looks to me that moving to the DAO pattern is the most logical way forward (indeed, I've already implemented some to show "it's not that scary"). Mostly my coworkers wanted to know if there was anything we were doing wrong that we didn't know about because of our collective lack of node experience.

1
nkomx•

Suaveio, f#, mono/.net

Loving it. Moved from node for better language and added performance.

1
runvnc•

I think instead of switching between 'best practices' recipes you should start with one that is working and do some profiling.

What does Couchbase have to do with sequelize?

If you are banging your head against a wall repeatedly then some of your assumptions are wrong.

I am looking for a Node.js job. I can profile this for you and then improve the performance of the bottlenecks. I would throw ideas out there like caching which might help, but really you just have to profile the actual code and go from there.

There is nothing about Node in general that is causing your performance problems.

-1