Devin Roché

Somewhat good Node APIs

It’s easy to make a node API, it’s less easy to make a good API.


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 use 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.


When adding Redis to my API I cut the wait time from 2 seconds to 0.07 seconds with caching. 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).


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 ${} is running`);

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

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

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

twitter |github