Devin Roché

Somewhat good Node APIs

It’s easy to make a node api, its less easy to make a good api.

Intro

When making an API its important to focus on scalability. Sure your API might work well when you and your two friends are playing with it, but can it hold 1000 users making calls all at once? What about 2000? Chances are it can’t, I know this because my API’s in the past couldn’t.

What can I do about it?

When you want to focus on scalability it’s helpful to implement some sort of caching system. I decided to work with Redis because why not? Redis was a little confusing at first, but if you just think of it as a key value storage method then it becomes a lot easier to work with.

Redis

When adding Redis to my API I cut the wait time from 2 seconds to 0.07 seconds with caching. Basically I set the key value after the user calls the endpoint and set it to expire after some time (in my case I had to use 15 seconds).

Cluster

Clustering helps with high traffic or since js is single threaded it provides backup in case our single thread dies for whatever which reason. This is a code snippet straight from nodejs docs.

const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  // Fork workers.
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log(`worker ${worker.process.pid} died`);
  });
} else {
  // Workers can share any TCP connection
  // In this case it is an HTTP server
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('hello world\n');
  }).listen(8000);

  console.log(`Worker ${process.pid} started`);
}

twitter |github