DEV Community

Cover image for Implementing Microservice Architecture In Node JS
server side digest
server side digest

Posted on

276 1

Implementing Microservice Architecture In Node JS

๐Ÿ“ Introduction

๐Ÿ™‚ As we have discussed in our previous blog "Monolithic vs Microservices: A Practical Approach". But today we're going to implement Microservices Architecture in NodeJS.

๐Ÿ‘‰ You can use any technology like Spring, Python, etc. But we are going to demonstrate using NodeJS.

NodeJS Meme

๐Ÿ“ Directory Structure

๐Ÿ™‚ You can find the GitHub Repo (Kindly run npm install in Order, Payment, and API-Gateway directories before running) Here. We have two services Order and Payment with API Gateway.

NodeJS_Microservices
|
---> Order
|
------> server.js (Running on PORT 8081)
|
---> Payment
|
------> server.js (Running on PORT 8082)
|
---> API-Gateway
|
------> server.js (Running on Port 9091)

๐Ÿ”ฅ The structure of our services looks like this:-

๐Ÿ“ Implementation

Microservices Architecture

๐Ÿ™‚ Whenever a client makes a request to the API-Gateway, We have defined some routes (Using prefixes) that redirect the request to the appropriate service (Depends which route is called). Payment and Order services are independent means If one fails other will not be affected.

๐Ÿ”ฅ Also we can add Auth or Middlewares so that no one can call the services directly or without Authentication. We have implemented a very basic architecture.

  • Order Server.js


const express = require("express");
const app = express();

const port = 8081;
app.get("/order-list", (req,res)=>{
    let response = {
        data: {
            item: [
                {
                    id: 1,
                    name: 'order-1'
                },
                {
                    id: 2,
                    name: 'order-2'
                }
            ]
        }
    };
    res.status(200).json(response);
});
app.get("/", (req,res)=>{
    res.send("Order called");
});

app.listen(port, ()=>{
    console.log("Listening at localhost "+ port);    
})


Enter fullscreen mode Exit fullscreen mode
  • Payment server.js


const express = require("express");
const app = express();

const port = 8082;
app.get("/payment-list", (req,res)=>{
    let response = {
        data: {
            item: [
                {
                    id: 1,
                    name: 'Payment-1'
                },
                {
                    id: 2,
                    name: 'Payment-2'
                }
            ]
        }
    };
    res.status(200).json(response);
});

app.get("/", (req,res)=>{
    res.send("Payment called");
});

app.listen(port, ()=>{
    console.log("Listening at localhost "+ port);    
})


Enter fullscreen mode Exit fullscreen mode
  • API-Gateway


const gateway = require("fast-gateway");

const port = 9001;
const server = gateway({
    routes: [
        {
            prefix: "/order",
            target: "http://localhost:8081/",
            hooks: {}
        },
        {
            prefix: "/payment",
            target: "http://localhost:8082/",
            hooks: {}
        }
    ]
});

server.get('/mytesting', (req,res)=> {
    res.send("Gateway Called");
})

server.start(port).then(server=>{
    console.log("Gateway is running "+port);
})



Enter fullscreen mode Exit fullscreen mode

๐Ÿ˜Œ Now, we can start the services including the gateway

Terminal running microservices

๐Ÿ“ And we can request http://localhost:9001/order Or http://localhost:9001/payment


๐Ÿ™‹ Follow for more in-depth tutorials. Right now, I am targeting beginners but soon more advanced things we'll discuss.

Drop your views in the Comment Box. Hope It helps.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (59)

Collapse
 
itsnitinn profile image
Nitin Sharma โ€ข

Crisp and nice.

Collapse
 
brense profile image
Rense Bakker โ€ข

Nice! I used node-http-proxy in the past to create a gateway, didn't realize that fast-gateway existed, it looks very clean ๐Ÿ‘

Collapse
 
ssd profile image
server side digest โ€ข

Thanks Rense. Highly appreciate ๐Ÿ˜Š

Collapse
 
adnanafzal565 profile image
Adnan Afzal โ€ข

You are using prefix as "/order" so I think your order server.js will have:

app.get("/order"

And not:

app.get("/order-list"

Kindly correct me if I am wrong.

Collapse
 
ssd profile image
server side digest โ€ข

You'll type localhost:9091/order and it will redirect you to the localhost:8081/

Collapse
 
pavanbelagatti profile image
Pavan Belagatti โ€ข

When I call localhost:9091/order on my local, it I am getting 'page canโ€™t be found' error. Am I doing something wrong?

Thread Thread
 
ssd profile image
server side digest โ€ข

Start all the services including order payment and gateway

Collapse
 
murilokaos profile image
Murilo Henrique โ€ข

Eu creio que nรฃo, ele vai ter as rotas com o /order como prefixo, ou seja:

/order e /order/order-list

Collapse
 
shifi profile image
Shifa Ur Rehman โ€ข

True

Collapse
 
snowowl profile image
Snow Owl โ€ข

This is very crisp and well done.

If you don't want to spend a lot of time doing config, we at Snow Owl have enabled request-level routing, monitoring, and transformations for microservices without using Kubernetes. This is done by creating a reverse proxy + API gateway + rules engine.

It's also SaaS, no-code, serverless, and sits on the edge. , we set up in 15 minutes and scale easily. DM me if you want to beta test! Snowowl.co

Collapse
 
ssd profile image
server side digest โ€ข

Ok.

Collapse
 
victorioberra profile image
Victorio Berra โ€ข

When will your site have docs, screenshots and info?

Collapse
 
snowowl profile image
Snow Owl โ€ข

You can check out docs.snowowl.co for docs, screenshots, and video. Also if you drop your email in the homepage I'll send you an email with beta login!

Collapse
 
akcgjc007 profile image
anupam โ€ข

what is the difference between let and const? ๐Ÿค”

Collapse
 
rxavio profile image
xavier Rucahobatinya โ€ข

const is a signal that the identifier won't be reassigned. let is a signal that the variable may be reassigned

Collapse
 
vaibhav68849256 profile image
Vaibhav Khandare โ€ข

Helpful

Collapse
 
tlylt profile image
Liu Yongliang โ€ข

Good demo! For simple routing/gateway it can also be done by setting up a reverse proxy with nginx.

Collapse
 
ssd profile image
server side digest โ€ข

Already done in the previous blog

Collapse
 
410nidhi profile image
Nidhi Upasani โ€ข

Great read

Collapse
 
arielro85 profile image
arielro85 โ€ข

Easy to Understand. Thanks for this

Collapse
 
ssd profile image
server side digest โ€ข

Thanks ๐Ÿ™‚

Collapse
 
latoadeoye profile image
latoadeoye โ€ข

Highly appreciated. Your posit is motivational. Thanks

Collapse
 
ssd profile image
server side digest โ€ข

Thanks man โ˜บ๐Ÿ˜Š

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools canโ€™t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay