Skip to content

Instantly share code, notes, and snippets.

@gaurang847
Created December 4, 2022 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gaurang847/f1680c593ebe56bbd2fedf15468c5b51 to your computer and use it in GitHub Desktop.
Save gaurang847/f1680c593ebe56bbd2fedf15468c5b51 to your computer and use it in GitHub Desktop.
This script starts a barebones Node.js server that has three APIs.
'use strict';
const http = require('http');
const childProcess = require('child_process');
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
if (req.url === '/quick-api') {
return res.end('<h1>This API must return immediately.</h1>');
}
if (req.url === '/slow-sync-api') {
childProcess.execSync('sleep 30');
return res.end('<h1>This API performs a slow synchronous operation. '
+ 'It will block all other requests '
+ 'and bring down the performance of the entire application.</h1>');
}
if (req.url === '/slow-async-api') {
return childProcess.exec('sleep 30', () => {
return res.end('<h1>This API also performs a slow operation. '
+ 'But it does not block other requests. '
+ 'The performance of rest of the application is unaffected by such slow APIs</h1>');
})
}
})
server.listen(3000, () => {
console.log(`Server is listening`);
});
@gaurang847
Copy link
Author

gaurang847 commented Dec 4, 2022

To run this script, just run node index.js. There are no additional packages to be installed.

This script starts a barebones Node.js server that has three APIs.

  • GET /quick-api
  • GET /slow-sync-api
  • GET /slow-async-api

The quick-api API is supposed to return a response immediately.
But, if you call quick-api after slow-sync-api, it does not return until slow-sync-api returns. This is because Node.js is single-threaded. And slow-sync-api calls a synchronous method that does not let the main thread do anything else till its execution is complete. It blocks all other requests.
However, if you call quick-api after slow-async-api, the quick-api works as expected. This is because slow-async-api does not block the main thread till its execution is complete. The work of the asynchronous function is deferred to a worker thread and the main thread waits for the execution to complete. Meanwhile, the main thread is free to fulfill other requests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment