How to Build JavaScript Microservices with SenecaJS and Compose

Hemendra Singh
Hemendra Singh, Managing Director at The NineHertz
Published on Jun 12, 2019 in Cross Platform Developers Resources
How to Build JavaScript Microservices with SenecaJS and Compose

The first and foremost requirement to take any Microservices into production is to make sure it is ready to communicate securely and reliably. This article will show you how you can use SenecaJS, NodeJS and Compose databases to create a simple test application.

Microservices are much talked-about topics these days because of its growing popularity. Companies like Netflix, Walmart, and IBM use them to fuel their critical applications. This article also aims to be a quick guide to help you develop real-world microservices with Node.js.

Introduction to Microservices

A microservice can be defined as a single self-contained unit, which collectively with many others, makes an application. Splitting your app into smaller units gives the freedom to deploy each unit independently and in a scalable manner. All the units can be written by different teams and in different programming languages. They can even be tested individually for performance. 

Following a microservice architecture implies that your app is made up of several smaller, independent applications, each capable of running in their own memory space and have the capacity to scale independently from each other across potentially many separate machines.

Why Microservices?

In a typical scenario, a software application consists of a single process which contains all of the code-instructions needed to execute the application. This results in a monolithic architecture which allows a process to be extremely quick and simple to execute.

However, the biggest challenge comes in terms of scaling up functionality which requires executing multiple copies of the entire process. Unfortunately, this is true even when you only have to scale up one small piece of functionality. Consider this example for the sake of illustration where Netflix uses the streaming portion of its application far more than it uses the 'new user signup' portion. Understandably, it’s not the best use of the resource.

The problem comes because of the "all-in-one" approach of a typical application that literally makes it difficult to scale traditional application. By design, these monolithic applications are developed to be self-contained. This paves way for connecting multiple redundant copies of a monolithic process which is outright impractical or impossible. However, this issue can be bypassed by designing the application to accommodate such tandem scaling. The other big problem with monolithic applications is that they require a reboot of the entire application leading to downtime for end users. This could be a very unpleasant experience for the end users.

Take an example of a modern distributed software. In case of such large web applications, they need to be able to scale easily. They run processes on multiple machines in multiple locations at the same time. Microservices architectures follow similar behavior. Every microservice is designed to handle a small piece of functionality that contribute to a larger application. Multiple microservices connected together in a network, work together to form an application.

Applications designed as a "system of systems" makes it easy and uncomplicated to add new instances of a microservice to handle the extra load without impacting the existing system. Moreover, developers can also redirect the traffic to redundant copies running on different servers. Even in the event of server or application failure, the traffic can be redirected to a different server.

The benefits of Microservices

  • Microservices helps speed up development. Faster application development leads to enhanced developers productivity.
  • Microservices enables deployment of each service independent of other services. It is much easier to deploy new versions of services frequently or periodically.
  • Microservices provides a way to scale development. It also delivers a performance advantage.
  • Eradicates the need for long term commitment to a specific technology stack. Every time you develop a new service you are free to pick a new technology stack.
  • Since each of the microservices has a very specific job, therefore it can be organized in a much better way. There is no reliance on the jobs of other components.
  • Use of microservices also makes it easier for decoupled services to recompose and reconfigure to serve the purposes of entirely different apps. For example, it can be used to serve both the web clients and public API.

Even though Microservices comes with their own set of advantages, they have their fair share of problems too.

A single microservice might be a small and simple piece of software, but the way it interacts with the rest of the application components is more complex than a typical monolithic application. To overcome this issue SenecaJS (framework) provide tools to make these interactions easier.

Understanding SenecaJS application

SenecaJS is a NodeJS application framework. Its primary job is to help developers define microservices and connect them together to work in harmony. SenecaJS uses simple JSON message to communicate. A message is an object with at least 2 keys: a role and a cmd.

Here is a quick example that gives output: hello, world

{ "role": "hello", "cmd": "sayHello" }

SenecaJS compares the messages against the set of commands that have been registered with it. As soon as SenecaJS finds a matching command, it executes the function associated with that command.

Here is a basic SenecaJS application to understand how commands are registered. Create a new folder for your project on your system. Initialize a new Node module using npminit. You will get the prompt for your new module for options. Use the defaults and use npm install to install SenecaJS.

$ mkdirseneca-compose
$ cdseneca-compose
$ npminit
...
...
...
$ npm install --save seneca
We will now create a simple ping application. The application will respond with a message every time we call it to let us know that the application is online and working fine.
// Create a new SenecaJS application
varseneca = require('seneca')();

We will start by creating a new SenecaJS application by calling the "seneca()" function. This will make a place for us to register new commands and functionality.

seneca.add({"role": "compose", "cmd": "ping"}, (args, done) => {  
 console.log(args);
 done(null, {result: "Hi there"});
});

We'll call the Seneca.add a method to register a new command with the Seneca system. We will also define the function that will be executed each time that command is sent. This will require two arguments: a command pattern and a function that executes when the pattern is matched.

On the other hand, the function that executes also uses two arguments: an args object that contains the entire message and a done function that is executed once the service is ready to send a response. Again the done function also takes two arguments in typical Node.js fashion: an error as the first argument and the results as the second argument.

seneca.listen({"type": "http", "port": 8080});

Now we need an application to listen for connections using the Seneca.listen method. SenecaJS uses simple JSON messages, which means there are multiple ways to communicate between microservices. It is called transport. In our example, we are using HTTP which will also allow us to test our microservices using the curl utility.

To test the microservice, open two terminal windows. Run your SenecaJSmicroservice in the first window.

$ node service.js

Use the second window for curl utility to send a message to our running service.

$ curl -d '{"role":"compose","cmd":"ping"}' http://localhost:8080/act

If everything is fine you will see below output.

{result: "Hi there"}

Using Seneca Entities to store Data

We have just created a microservice in SenecaJS. This data can be saved in a database. SenecaJS is minimally functional. But the ecosystem of plugins extends its functionality, making SenecaJS far more powerful. You can use a plugin such as Seneca-entity that will help you store or retrieve data. If you have ever used ORM like ActiveRecord or an ODM like Mongoose, you will find Seneca entities familiar. To create a new Seneca-entity, you need to add the Seneca-entity and Seneca-basic plugins. With the help of .use command you can tell SenecaJS to use those plugins.

Storing Entities In Memory

SenecaJS comes packed with a memory store plugin that saves the entities using an in-memory database. This makes it easy to create some entities and test out operations on them during early development by Node js web development company. It is also extremely helpful in creating test drivers that can validate entity logic without connecting to a persistent database.

The plugin system allows Node js web development services providers to swap out the in-memory database with a plugin that adds a layer of persistent backing data store without requiring them to change any of their application or entity logic.

Takeaway

Building microservice applications in JavaScript shouldn't be an uphill battle for any Node js web development company. With the use of SenecaJS and Compose we can quickly develop server-side applications and swap out databases depending on their needs. Since SenecaJS allows you to use multiple transport mechanisms, you can use RabbitMQ and Redis on Compose to create stable and secure distributed microservices applications.

This article provided a quick overview to help impart a basic understanding of building JavaScript Microservices with SenecaJS and Compose. There is a lot more to learn and explore. We hope you get some interesting and useful things that you can use Microservices with SenecaJS and Compose in your workflow.

Find more top mobile app developers worldwide on AppFutura.

Looking for an app or software development company?

You can post a project on AppFutura for free and explain your needs for app or software development. You will receive quotes from qualified companies and will be able to hire the best candidate through a safe payment system.

Post a project

About the author
Hemendra SinghManaging Director at The NineHertz

Hemendra Singh is Managing Director and co-founder of The NineHertz, a Mobile App Development Company. Hemendra has a keen interest in the latest trends and technologies that are emerging in different domains. Being an entrepreneur in the field of IT...

Read more...
You might also like