DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • What Are the 7 Rs of Cloud Migration Strategy?
  • From Architecture to an AWS Serverless POC: Architect's Journey
  • The Future of Rollouts: From Big Bang to Smart and Secure Approach to Web Application Deployments
  • Performance Optimization for Multi-Layered Cloud Native AWS Application

Trending

  • Rethinking Recruitment: A Journey Through Hiring Practices
  • From Zero to Production: Best Practices for Scaling LLMs in the Enterprise
  • AI’s Role in Everyday Development
  • Concourse CI/CD Pipeline: Webhook Triggers
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. Microservices Aggregator Design Pattern Using AWS Lambda

Microservices Aggregator Design Pattern Using AWS Lambda

This article explores the possibilities of implementing an aggregator service for microservices using AWS Lambda.

By 
Satrajit Basu user avatar
Satrajit Basu
DZone Core CORE ·
Sep. 07, 18 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
18.0K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

The aggregator design pattern is probably the most commonly used design pattern in microservices implementation. This design pattern can be thought of as a web page invoking multiple services and displaying the results on the same page. In another form, the design pattern can be implemented as an aggregator service that invokes multiple services, collates the results, optionally applies business logic, and returns a consolidated response to the client. In this article, I’ll explore the implementation of an aggregator service using AWS Lambda.

An Example

To explain this better, I’ll need the help of an example. Suppose I’m designing a ticketing application. This application can be used to view details and book tickets for various activities like sports, movies, and other events. Users can search for either of these individually on the application. Subsequently, they could select an activity of their choice and book tickets. When registered users visit their home page, they would expect to see a consolidated view of everything that is happening around them, based on their individual preferences. This is the use case that will be implemented using the aggregator design pattern.

The Architecture

There will be three services: one each for sports, movies, and events. These services will be exposed individually over REST endpoints. Each of these services will be implemented on AWS Lambda. Then, there will be another Lambda service that invokes the other services. These invocations will be private and will not be routed over the internet. The details will be outlined in the implementation section below. This is essentially a composite service that will be exposed over a REST endpoint as well. An HTTP request from the client will be routed via an API Gateway to this Lambda service.

I would also like to make the following assumptions about the application:

  • The providers will push the details of their events to our application.
  • The microservices will store this information in their individual data stores. 
  • During the actual booking flow, the services will connect the booking server of the individual providers to manage inventory and get bookings confirmed. 

Following is an illustration of the architecture:

Image title

Performance

Generally, the primary risk of this type of implementation is performance. My aggregator service will invoke multiple services. This would definitely have a serious impact on the performance of my application. To minimize this risk, I’ll invoke all the services from my aggregator service asynchronously. This would mean that all the invocations will run in parallel and inform back to the aggregator service individually once complete. This will ensure that one invocation is not waiting for another to complete, and thus eliminates the risk of performance bottlenecks.

Implementation

Let’s look at the implementation now. I’ll use Java 8 as the coding language. Let’s also assume that the individual services are deployed as Lambdas – I’ll not go into the details of that. As discussed above, I’ll invoke the services asynchronously. To do that, I’ll write a handler class for each service to handle the asynchronous invocation and response processing.

public class EventClientAsyncHandler implements
AsyncHandler < InvokeRequest, InvokeResult > {

 private EventSearchResponse eventResponse;

 public EventSearchResponse getEvents() {
  return eventResponse;
 }

 public Future < InvokeResult > invoke(String input) {
  String event_function_name = "EventSearchFunction";
  AWSLambdaAsync eventClient = AWSLambdaAsyncClientBuilder.defaultClient();
  InvokeRequest req = new InvokeRequest().withFunctionName(
   event_function_name).withPayload(
   ByteBuffer.wrap(input.getBytes()));

  return eventClient.invokeAsync(req, this);
 }

 @Override
 public void onError(Exception e) {
  /*Populate error response*/
 }

 @Override
 public void onSuccess(InvokeRequest req, InvokeResult res) {
  ByteBuffer response_payload = res.getPayload();
  try {
   JsonbConfig nillableConfig = new JsonbConfig().withNullValues(true);
   Jsonb jsonb = JsonbBuilder.create(nillableConfig);
   this.eventResponse = jsonb.fromJson(
    new String(response_payload.array()), EventSearchResponse.class);
  } catch (JsonbException e) {
   /*Handle exception*/
  } catch (Exception e) {
   /*Handle exception*/
  }
 }
}

The code above demonstrates an asynchronous handler. The class EventClientAsyncHandler implements the interface AsyncHandler from AWS. It implements the invoke method, which is the entry point to the handler. From the invoke method, the corresponding Lambda service for an event search is called. It is interesting to note here that for the name of the Lambda function, I’ve used just the logical name and not the ARN (Amazon Resource Name). If the invocation is within the same account and region, the logical name is good enough. The method invokes the corresponding Lambda function and returns a Future object back to the caller. The caller then listens on this Future object to determine when the execution is complete.

The OnSuccess method is invoked when the EventSearchFunction completes successfully. This method will then parse the response payload and create an EventSearchResponse. Similarly, a SportsSearchResponse and a MoviesSearchResponse will be created by the corresponding handlers.

The OnError method, on the other hand, is invoked when the Lambda function doesn’t complete successfully and throws an exception. This method is used to construct an error response.

Now, let’s look at the caller method. The caller method will invoke all the handlers and get back the corresponding Future objects. It will then keep on checking the Future objects to see whether the executions are complete. If not, it will sleep for 100 milliseconds to avoid unnecessary polling and run the checks again. Finally, when all the executions are complete, the consolidated response is constructed and returned to the client.

EventClientAsyncHandler eventClient = new EventClientAsyncHandler();
Future<InvokeResult> event_future_res = eventClient.invoke(eventRequest);

SportsClientAsyncHandler sportsClient = new SportsClientAsyncHandler();
Future<InvokeResult> sports_future_res = sportsClient.invoke(sportsRequest);

MoviesClientAsyncHandler moviesClient = new MoviesClientAsyncHandler();
Future<InvokeResult> movies_future_res = moviesClient.invoke(moviesRequest);


boolean done = false;
boolean sportsPopulated = false;
boolean moviesPopulated = false;
boolean eventsPopulated = false;
boolean sportsDone = false;
boolean moviesDone = false;
boolean eventDone = false;
while (!done) {
 sportsDone = sports_future_res.isDone();
 moviesDone = movies_future_res.isDone();
 eventDone = event_future_res.isDone();
 if (sportsDone && !sportsPopulated) {
  result.setSports(sportsClient.getSports());
  sportsPopulated = true;
 }
 if (eventDone && !eventPopulated) {
  result.setEvents(eventClient.getEvents());
  eventPopulated = true;
 }
 if (moviesDone && !moviesPopulated) {
  result.setMovies(moviesClient.getMovies());
  moviesPopulated = true;
 }
 done = sportsDone && moviesDone && eventDone;
 if (!done) {
  try {
   Thread.sleep(100);
  } catch (InterruptedException e) {
   log.error("Thread.sleep() was interrupted!");
  }
 }
}

Conclusion

Lambda is a powerful serverless computing platform from AWS and is pretty straightforward to write microservices on. The ability to invoke a Lambda function from another Lambda function — asynchronously, if required — makes it easy to implement the microservices aggregator pattern.

AWS microservice Design Web Service AWS Lambda application

Opinions expressed by DZone contributors are their own.

Related

  • What Are the 7 Rs of Cloud Migration Strategy?
  • From Architecture to an AWS Serverless POC: Architect's Journey
  • The Future of Rollouts: From Big Bang to Smart and Secure Approach to Web Application Deployments
  • Performance Optimization for Multi-Layered Cloud Native AWS Application

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: