Microservices Aggregator Design Pattern Using AWS Lambda
This article explores the possibilities of implementing an aggregator service for microservices using AWS Lambda.
Join the DZone community and get the full member experience.
Join For FreeIntroduction
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:
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.
Opinions expressed by DZone contributors are their own.
Comments