Introduction to Light 4J Microservices Framework

  •        0

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.

Light 4j is fast, lightweight, secure and cloud native microservices platform written in Java 8. It is based on pure HTTP server without Java EE platform. It is hosted by server UnderTow. Light-4j and related frameworks are released under the Apache 2.0 license.

Why Light 4J?

To start a Rest API microservices application it just takes milliseconds when compared to other microservices like spring boot (takes around 8 seconds). Detailed benchmark available here.

Spring Boot Startup Log
class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@4eabe900]
2019-02-28 20:53:05.109 INFO 10004 --- [ main] c.s.tutorial.controller.Application : Started Application in 8.299 seconds (JVM running for 9.175)

It can serve upto 3 million requests per second on commodity hardware with lesser memory footprint compared to typical java ee platform. Thereby reducing production operation cost.

All microservices cross cutting concerns like auditing, security, cluster support, logging and registry discovery are pre-built in to the framework which can be added on demand by configuring the scaffold project.

Architecture & Design

Principal of microservices is to break down the entire framework into smaller pieces, so customization and replacement will be done as necessary. Light 4J also uses the same microservice principal and have plugins implemented for different phases like route, middleware, startup, shutdown hooks. All the plugins are wired in request/response chain for best performance.

Light4j handler chain

All the handlers are registered to the undertow http server based on composition / aggregation based architecture. It has built in OAuth2 security feature with maximum security and flexibilty.

Cloud native applications requires safe and reliable delivery of messages between microservice to another services. Communication between services can be done by dedicated infrastructure layer called service mesh. Light4j has light-eventuate-4j which manages the complexity of services by techniques like latency aware load balancing, eventual consistency, service discovery, retries, distributed transaction and deadlines. Transaction management done by JTA couldn't scale much because of synchronous communication and chance of partial failures. So event based framework(light-eventuate-4j) will provide eventual consistency.

In Distributed environment, logging will be complex which can be managed by centralized logging with tracing and correlation feature. It can be configured to open source ELK stack, where logs will be collected by Logstash, indexed by Elastic search and visually shown by Kibana reporting tool.

To read more about features in terms of design and architecture refer to Light 4J documentation.

Let's see the steps to start Rest service and enable security in it.

Setup and Start Rest Service

Light 4J works by design first approach, where developers work on only functional design and all non functional requirements provided by the framework. Framework has scaffolding code generation project which generates the basic Light 4J Rest project.

So let's clone the scaffolding code generation tool like below.

  mkdir networknt
cd networknt
git clone

Then the configuration project for code generation tool can be downloaded

git clone

Now build the code generation tool through maven to generate Light 4J cli tool.

  cd ~/networknt/light-codegen
mvn install -DskipTests

Then execute the cli tool and it generates sample PetStore REST API project based on OpenAPI3.0 specification. Generated project has configuration file for stage of the request-response chain.

cd ~/networknt
java -jar light-codegen/codegen-cli/target/codegen-cli.jar -f openAPI -o light-example-4j/Rest/openAPI/petstore -m model-config/Rest/openAPI/petstore/1.0.0/openAPI.json -c model-config/Rest/openAPI/petstore/1.0.0/config.json

 Passed parameter details:

 -f   - Whether it is OpenAPI 3.0 specification or swagger?
 -o  - Project target directory.
 -m - IDL spec where each Rest API is defined with request and response format
 -c  - config file to provide package, project name and other details

Now execute the project to access the Rest API. It starts the server as https at port 8443

 cd ~/networknt/light-example-4j/Rest/openAPI/petstore 
 mvn install exec:exec

Test whether Rest service is up with following url

/*which will print all the pets */


We can also access single pet with "". If it is not accesible, just modify the ip address "ip:" in server.yml file available in petstore project.


Enable JWT

By default, the generated API has security turned off. Turn on the JWT verification by updating src/main/resources/config/openAPI-security.yml in petstore project as below.

# Enable JWT verification flag.
enableVerifyJwt: true

# If OAuth2 provider support http2 protocol. If using light-oauth2, set this to true.
oauthHttp2Support: true

Then restart the server for the configuration to take effect.

mvn clean install exec:exec 

Now if we try the same url in browser [], the following exception will be shown

  "description":"No Authorization header or the token is not bearer type",

So we need to access the Rest API with bearer JWT token in header which is available in Then the list of pets will be displayed. To check on logs, check target/test.log file in petstore project folder.

Authorization: Bearer <<token>>

Create Hello World Rest API

Now lets try to create a sample Rest API in the generated petstore project. First we need to create a handler,  which gets the name from the url and print in the string template. This handler will be present in the petstore project inside the source folder under the package com.networknt.petstore.handler.

 package com.networknt.petstore.handler;

 import com.networknt.handler.LightHttpHandler;
 import io.undertow.server.HttpServerExchange;
 import io.undertow.util.HttpString;

 public class HelloWorldHandler implements LightHttpHandler {

    public void handleRequest(HttpServerExchange exchange) throws Exception {
        String name = exchange.getQueryParameters().get("name").peek();
        exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/text");
        exchange.getResponseSender().send("hello " + name + "! welcome to Light 4J!!!");

Then we need to map the handler to the Rest API url with http method. This configuration needs to be done in handler.yml file which is present in src/main/resources/config folder.

  - path: 'v1/pets/helloworld' 
    method: 'GET'
        - default
        - com.networknt.petstore.handler.HelloWorldHandler

Handler should also be added to the list of business handlers in the same file as shown below.

  # Business Handlers
   - com.networknt.petstore.handler.PetsGetHandler
   - com.networknt.petstore.handler.HelloWorldHandler
   - com.networknt.petstore.handler.PetsPostHandler
   - com.networknt.petstore.handler.PetsPetIdGetHandler
   - com.networknt.petstore.handler.PetsPetIdDeleteHandler

 Now using Postman or Curl, Hit the following URL with get request. Add authorization header,  if JWT token is enabled.

Output as shown below will appear as response.

      hello nagappan! welcome to Light 4J!!!





Nagappan is a techie-geek and a full-stack senior developer having 10+ years of experience in both front-end and back-end. He has experience on front-end web technologies like HTML, CSS, JAVASCRIPT, Angular and expert in Java and related frameworks like Spring, Struts, EJB and RESTEasy framework. He hold bachelors degree in computer science and he is very passionate in learning new technologies.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter

Related Articles

Light4j Cookbook - Rest API, CORS and RDBMS

  • light4j sql cors rest-api

Light 4j is a fast, lightweight and cloud-native microservices framework. In this article, we will see what and how hybrid framework works and integrate with RDMS databases like MySQL, also built in option of CORS handler for in-flight request.

Read More

Exonum Blockchain Framework by the Bitfury Group

  • blockchain bitcoin hyperledger blockchain-framework

Exonum is an extensible open source blockchain framework for building private blockchains which offers outstanding performance, data security, as well as fault tolerance. The framework does not include any business logic, instead, you can develop and add the services that meet your specific needs. Exonum can be used to build various solutions from a document registry to a DevOps facilitation system.

Read More

8 Reasons Why Python Scores Over PHP for Web Development

  • python php web-development

PHP, the general-purpose scripting language has been used since decades for socket programming and web development. But in recent times, Python has become the most sought after programming language. This all-purpose programming language is attracting more developers in the industry owing to its highly dynamic and extensible nature. Let's see how Python is winning over age-old PHP.

Read More

Best open source Text Editors

  • text-editor editor tools dev-tools

Text editors are mainly used by programmers and developers for manipulating plain text source code, editing configuration files or preparing documentation and even viewing error logs. Text editors is a piece of software which enables to create, modify and delete files that a programmer is using while creating website or mobile app.In this article, we will discuss about top 7 all-round performing text editors which is highly supportive for programmers.

Read More

Know everything about Dependency Injection in Magento 2

  • magento dependency-injection php

Magento 2 is no longer a buzzing term. Since Its inception one and a half years ago, developers are in love with its rich technology stack. The following post emphasizes on Dependency Injection (DI), one of the best design patterns that Magento 2 uses.

Read More

Top 10 AI development tools which you should know in 2020

  • artificial-Intelligence neural-networks frameworks ai machine-learning

It is a fact the 2020 is not going the way we expected to be but when it comes to technology breakthrough we can say 2020 will be the heir of greatness. <br />Speaking of technical breakthroughs we have got artificial intelligence which is known to be taking over the mankind like a wildfire. Everything around us is connected through AI be it shopping travelling or even reading. Every other activity of ours is transforming into a whole new extent.

Read More

WebSocket implementation with Spring Boot

  • websocket web-sockets spring-boot java

Spring Boot is a microservice-based Java framework used to create web application. WebSocket API is an advanced technology that provides full-duplex communication channels over a single TCP connection. This article explains about how to implement WebSocket using Spring Boot.

Read More

RESTEasy - A guide to implement CRUD Rest API

  • resteasy rest-api java framework

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol. It is licensed under the Apache 2.0 license.

Read More

COVID19 Stats using Angular Material Design

  • angular material-design covid covid-stats

Material design is inspired from the real world building architecture language. It is an adaptable system of guidelines, components, and tools that support the best practices of user interface design. Backed by open-source code, Material streamlines collaboration between designers and developers, and helps teams quickly build beautiful products. In this article, we will build COVID stats using Angular Material design.

Read More

Microsoft released F# under Open Source

  • fsharp opensource

F# is a functional programming language for the .NET Framework. It combines the succinct, expressive and compositional style of functional programming with the runtime, libraries, interoperability, and object model of .NET. Microsoft recently released its source code under Apache License.

Read More

An Introduction to the UnQLite Embedded NoSQL Database Engine

  • database nosql embedded key-value-store

UnQLite is an embedded NoSQL database engine. It's a standard Key/Value store similar to the more popular Berkeley DB and a document-store database similar to MongoDB with a built-in scripting language called Jx9 that looks like Javascript. Unlike most other NoSQL databases, UnQLite does not have a separate server process. UnQLite reads and writes directly to ordinary disk files. A complete database with multiple collections is contained in a single disk file. The database file format is cross-platform, you can freely copy a database between 32-bit and 64-bit systems or between big-endian and little-endian architectures.

Read More

ETag Easy With RESTEasy

  • resteasy etag http-header rest-api

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It comprises of frameworks for mock, embeddable server, rest client, proxy servers, logging and so on.In this article, we will walk-through ETag implementation and show the behaviour related to ETag done by rest easy framework. Example is developed using RESTEasy 3.7 and deployed in tomcat as RESTEasy framework is portable.

Read More

Push Notifications using Angular

  • angular push-notifications notifications

Notifications is a message pushed to user's device passively. Browser supports notifications and push API that allows to send message asynchronously to the user. Messages are sent with the help of service workers, it runs as background tasks to receive and relay the messages to the desktop if the application is not opened. It uses web push protocol to register the server and send message to the application. Once user opt-in for the updates, it is effective way of re-engaging users with customized content.

Read More

GreenMail - Email Test Framework in Java

  • email email-server test automation

In any project there will be a need to send mail out to users. It could be an alert mail, forget password or authentication related mail. Mail is the default communication between the software and the users. As a developer, we can write code, to send out a mail but we need to make sure whether it got successfully received and how the body of mail, Is it the same like what we have sent. GreenMail is a Email test framework which helps to send and receive mails. It is a test framework which supports SMTP, POP3, IMAP including SSL.

Read More

PySpark: Installation, RDDs, MLib, Broadcast and Accumulator

  • pyspark spark python rdd big-data

We knew that Apace Spark- the most famous parallel computing model or processing the massive data set is written in Scala programming language. The Apace foundation offered a tool to support the Python in Spark which was named PySpark. The PySpark allows us to use RDDs in Python programming language through a library called Py4j. This article provides basic introduction about PySpark, RDD, MLib, Broadcase and Accumulator.

Read More

Getting Started with Spring Batch

  • spring-batch spring-boot batch-processing

The best way to design a system for handling bulk workloads is to make it a batch system. If we are already using Spring, it will be easy to add a Spring Batch to the project. Spring batch provides a lot of boiler plate features required for batch processing like chunk based processing, transaction management and declarative input/output operations. It also provides job control for start, stop, restart, retry and skip processing also.

Read More

RESTEasy Advanced Guide - Filters and Interceptors

  • resteasy rest-api filters interceptors java

RESTEasy is JAX-RS 2.1 compliant framework for developing rest applications. It is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol.

Read More

Struts 1.x End Of Life. Whats alternative?

  • java eol struts

The Apache Struts Project Team announced End of Life (EOL) for Struts 1.x web framework. Struts was launched in the year 2000. It is only of the widely used web framework. It gave better control over writing UI and business logic code directly in to JSPs.

Read More

How to create SEO friendly url

  • seo url searchengine

SEO friendly URL is recommended for any website which wants to be indexed and wants its presence in search results. Searchengine mostly index the static URL. It will avoid the URL which has lot of query strings. Almost all websites generate content dynamically then how could the URL be static. That is the job of the programmer.

Read More

RESTEasy Advanced guide - File Upload

  • resteasy rest-api file-upload java

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol. It is licensed under the ASL 2.0.

Read More

We have large collection of open source products. Follow the tags from Tag Cloud >>

Open source products are scattered around the web. Please provide information about the open source projects you own / you use. Add Projects.