Microservices architecture using Node.js and AWS Lambda
System engineering design based on microservices provides many advantages alongwith some complexity. This article defines an approach to reap maximum benefits and mimimize potential pain areas and other cons associated with microservices designs.
Most of the implementations get mislead by the term microservice resulting in countless services spread over the whole system architecture. The best approach is to have one microservice for one logical division. Lets say in object oriented programming a separate class is created for user and order, these classes encapsulate all functionality associated. If we translate into microservice, two microservices will be created namely user and order. These microservices will contain all public/private/internal functions associated and in order to interoperate between user and order we need to use a context.
AWS lambda is the first choice for developers writing microservices as it is very easy to scaffold and manage using AWS serverless application model. However most implementations get complex as the project grows.
AWS Serverless Application Model (SAM) cli provides a very comprehensive interface to write and test lambda functions on VS Code.
Lets get started with node packages.
- Develop and export your functions in node.js modules, your logical naming convention will help you save a lot of time in future.
- Do not bundle all functions in one module ie single .js or .ts file.
- Use typescript as preferred. (not absolute)
- Package your module and publish on NPM as private or public.
- You can publish single package or multiple packages depending upon your logical requirements.
AWS Lambda implementation.
- Install the package required in your lambda using npm install ‘package-name’.
- Lambda handler code will implement microservices router, all what it does is import dynamically the required module and execute the function.
- The module name and function name will be sent thru AWS API gateway as querystring parameters.
- A general implementation details on article Code splitting and dynamic function invocation Node js at https://asad-iqbal.medium.com/code-splitting-and-dynamic-function-invocation-node-js-9d1ebfbadb63
- Create separate lambda for separate package.
Advantages using this approach.
Improved fault isolation: Failure of a single module will not affect the service.
Migration : As functionality is composed in node.js packages and microservices router implementation reduced the number of lambdas, it makes it easier to migrate on other serverless providers.
Faster deployments & Updates: Node.js package can be updated using single comand ie. ‘yarn’ to update the associated node package.