Spring Boot vs LoopBack – Node.js for developing Microservices


In this post, we will see comparison between Spring Boot and LoopBack – Node.js for implementing Microservices.

SpringBoot

Spring Boot is an open source Java-based framework used to create Microservices. It is developed by Pivotal Team and is used to build stand-alone and production ready spring applications.

Microservices architecture using Java Spring Boot

LoopBack – Node.js

Events and event-driven programming

Events are actions generated by the user or the system, like a click, a completed file download, or a hardware or software error.

Event-driven programming is a programming paradigm in which the flow of the program is determined by events. An event-driven program performs actions in response to events. When an event occurs it triggers a callback function.

Node.js is a platform that executes server-side JavaScript programs that can communicate with I/O sources like file systems and networks.

LoopBack

LoopBack is a highly extensible, open-source Node.js and TypeScript framework based on Express that enables you to quickly create APIs and microservices composed from backend systems such as databases and SOAP or REST services.

The diagram below demonstrates how LoopBack serves as a composition bridge between incoming requests and outgoing integrations. It also shows the different personas who are interested in various capabilities provided by LoopBack.

Advantages of LoopBack – Node.js and Spring Boot

LoopBack – Node.js Spring Boot
Lightweight, fast – loosely typed Java is statically-typed (type safety)
Javascript Community: growing rapidly Java Community: mature and thriving
Great for I/O tasks. Example: file writing and reading, network calls, Streaming Long-term support and maintainability for memory intensive applications
Single-threaded – low memory utilization Support for multi-threading
npm is constantly growing Many easily usable dependencies using Maven, Gradle

Disadvantages of LoopBack – Node.js and Spring Boot

LoopBack – Node.js

  • Doesn’t support multi-threading
  • Lack of strict type checking can lead to runtime problems
  • Not great for heavy computing – performance bottlenecks

Spring Boot

  • High memory utilization
  • Java is verbose
  • Contains lots of boilerplate code which makes debugging tough
  • May include unused dependencies – huge deployment binary file size.

Industry Usage of these technologies

Companies using Spring Boot

  • Amazon
  • Intuit
  • JP Morgan Chase & Co.
  • Capital One
  • Google
  • Microsoft

Companies using Node.js

  • FlightOffice
  • Symantec
  • Pen Systems
  • GoDaddy.com
  • Sapient

LoopBack vs SpringBoot on various parameters

Criteria / Parameter SpringBoot LoopBack
Performance Long-term support and maintainability for memory intensive applications Great for I/O tasks. Example: file writing and reading, network calls, Streaming
Circuit Breaker Resilience4j Opossum
Hystrix Levee
Soap Client Apache CXF, Camel, Spring WebServiceTemplate loopback-connector-soap
JSON Manipulation/Validation Jackson, Spring Validator payload-validator
Orchestration and Routing support Apache CXF, Camel, Spring WebServiceTemplate, RestTemplate loopback-connector-soap, loopback-connector-rest
Caching support Spring Cache, external cache support Interception – CachingService, external cache support
Open API Contract first, API first both are supported Contract first, API first both are supported
Recommended For Building applications which consists of Memory intensive tasks Building applications which consists of I/O intensive tasks

References:

Node JS experienced interview questions


Is Node.js Single-threaded? Why it is required?

Yes, Node Js is single threaded to perform asynchronous processing.
All Node JS applications uses “Single Threaded Event Loop Model” architecture to handle multiple concurrent clients. Doing async processing on a single thread could provide more performance and scalability under typical web loads than the typical thread-based implementation.

What are events in Node Js?

An event is an action or occurrence recognized by software/app that is handled by event handler by writing a code that will be executed when the event fired.
Mouse move, Click, file copied or deleted are some examples of events.
In Node Js there are two types of events.
1)System Events: The event that comes from the C++ side.
2)Custom Events: Custom events are user-defined events.

What is an event loop in Node Js?

In Node Js processes are single threaded, to supports concurrency it uses events and callbacks. An event loop is a mechanism that allows Node.js to perform non-blocking I/O operations.

What is Express JS?

Express JS is an application framework which is light-weighted node JS. A number of flexible, useful and important features are provided by this JavaScript framework for the development of mobile as well as web applications with the help of node JS.

List some features of Express JS.

Some of the main features of Express JS are listed below: –

  • It is used for setting up middlewares so as to provide a response to the HTTP or RESTful requests.
  • With the help of express JS, the routing table can be defined for performing various HTTP operations.
  • It is also used for dynamically rendering HTML pages which are based on passing arguments to the templates.
  • It provides each and every feature which is provided by core Node JS.
  • The performance of Express JS is adequate due to the presence of a thin layer prepared by the Express JS.
  • It is used for organizing the web applications into the MVC architecture.
  • Everything from routes to rendering view and performing HTTP requests can be managed by Express JS.

Why we need to use Express.js in a node application?

Below are the few reasons why to use Express with Node.js

  • Express js is built on top of Node.js. It is the perfect framework for ultra-fast Input / Output.
  • Cross Platform
  • Support MVC Design pattern
  • Support of NoSQL databases out of the box.
  • Multiple templating engine support i.e. Jade or EJS which reduces the amount of HTML code you have to write for a page.
  • Support Middleware, basic web-server creation, and easy routing tools.

What are the differences between readFile and createReadStream in Node.js?

  • readFile load the whole file which you had marked to read whereas createReadStream reads the complete file in the parts of the size you have declared.
  • The client will receive the data faster in the case of createReadStream in contrast with readFile.
  • In readFile, a file will first completely read by memory and then transfers to a client but in later option, a file will be read by memory in a part which is sent to clients and the process continue until all the parts finish.

Show example for asynchronously/blocking and asynchronously/non-blocking

Normally NodeJs reads the content of a file in non-blocking, asynchronous way. Node Js uses its fs core API to deal with files. The easiest way to read the entire content of a file in nodeJs is with fs.readFile method. Below is sample code to read a file in NodeJs asynchronously and synchronously.

Reading a file in node asynchronously/ non-blocking

var fs = require('fs');  
fs.readFile('DATA', 'utf8', function(err, contents) { console.log(contents);
});
console.log('after calling readFile');

Reading a file in node asynchronously/blocking

var fs = require('fs'); 
var contents = fs.readFileSync('DATA', 'utf8'); console.log(contents);

What are Streams? List types of streams available in Node Js?

Streams are special types of objects in Node that allow us to read data from a source or write data to a destination continuously. There are 4 types of streams available in Node Js, they are

  • Readable − For reading operation.
  • Writable − For writing operation.
  • Duplex − Used for both read and write operation.
  • Transform − A type of duplex stream where the output is computed based on the input.

How to generate unique UUIDs/ guid in Node Js

Use node-uuid package to generate unique UUIDs/ guid in Node Js. Below code demonstrates how to generate it.

var uuid = require('node-uuid'); 
// Generate a v1 (time-based) id
uuid.v1();
// Generate a v4 (random) id
uuid.v4();

Rewrite the code sample without try/catch block:

Source: medium.com

Consider the code:

async function check(req, res) {
  try {
    const a = await someOtherFunction();
    const b = await somethingElseFunction();
    res.send("result")
  } catch (error) {
    res.send(error.stack);
  }
}

Rewrite the code sample without try/catch block.

Answer:

async function getData(){
  const a = await someFunction().catch((error)=>console.log(error));
  const b = await someOtherFunction().catch((error)=>console.log(error));
  if (a && b) console.log("some result")
}

or if you wish to know which specific function caused error:

async function loginController() {
  try {
    const a = await loginService().
    catch((error) => {
      throw new CustomErrorHandler({
        code: 101,
        message: "a failed",
        error: error
      })
    });
    const b = await someUtil().
    catch((error) => {
      throw new CustomErrorHandler({
        code: 102,
        message: "b failed",
        error: error
      })
    });
    //someoeeoe
    if (a && b) console.log("no one failed")
  } catch (error) {
    if (!(error instanceof CustomErrorHandler)) {
      console.log("gen error", error)
    }
  }
}