aws-samples/reactive-refarch-cloudformation

Name: reactive-refarch-cloudformation

Owner: AWS Samples

Description: Reactive Microservices Architectures with Amazon ECS, AWS Lambda, Amazon Kinesis Streams, Amazon ElastiCache, and Amazon DynamoDB

Created: 2017-11-09 21:03:54.0

Updated: 2017-12-24 09:55:24.0

Pushed: 2018-01-08 11:15:42.0

Homepage: null

Size: 830

Language: Java

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

Reactive Microservices Architectures with Amazon ECS, AWS Lambda, Amazon Kinesis Streams, Amazon ElastiCache, and Amazon DynamoDB

This reference architecture provides a set of YAML templates for deploying a reactive microservices architecture based on Amazon EC2 Container Service (Amazon ECS), AWS Lambda, Amazon Kinesis Streams, Amazon ElastiCache, and Amazon DynamoDB using Amazon CloudFormation.

You can launch this CloudFormation stack in the EU West (Dublin) Region in your account:

cloudformation-launch-stack

The Amazon CloudFormation-template is based on the reference architecture for deploying containerized microservices with Amazon ECS and AWS CloudFormation (YAML).

Overview

infrastructure-overview

The repository consists of a set of nested templates that deploy the following:

Why use AWS CloudFormation?

Using CloudFormation to deploy and manage services with ECS or Lambda has a number of nice benefits over more traditional methods (AWS CLI, scripting, etc.).

Infrastructure-as-Code

A template can be used repeatedly to create identical copies of the same stack (or to use as a foundation to start a new stack). Templates are simple YAML- or JSON-formatted text files that can be placed under your normal source control mechanisms, stored in private or public locations such as Amazon S3, and exchanged via email. With CloudFormation, you can see exactly which AWS resources make up a stack. You retain full control and have the ability to modify any of the AWS resources created as part of a stack.

Self-documenting

Fed up with outdated documentation on your infrastructure or environments? Still keep manual documentation of IP ranges, security group rules, etc.?

With CloudFormation, your template becomes your documentation. Want to see exactly what you have deployed? Just look at your template. If you keep it in source control, then you can also look back at exactly which changes were made and by whom.

Intelligent updating & rollback

CloudFormation not only handles the initial deployment of your infrastructure and environments, but it can also manage the whole lifecycle, including future updates. During updates, you have fine-grained control and visibility over how changes are applied, using functionality such as change sets, rolling update policies and stack policies.

Template details

The templates below are included in this repository and reference architecture:

| Template | Description | | — | — | | master.yaml | This is the master template - deploy it to CloudFormation and it includes all of the others automatically. | | infrastructure/vpc.yaml | This template deploys a VPC with a pair of public and private subnets spread across two Availability Zones. It deploys an Internet gateway, with a default route on the public subnets. It deploys a pair of NAT gateways (one in each zone), and default routes for them in the private subnets. | | infrastructure/security-groups.yaml | This template contains the security groups required by the entire stack. They are created in a separate nested template, so that they can be referenced by all of the other nested templates. | | infrastructure/load-balancers.yaml | This template deploys an ALB to public subnets, which exposes the ECS service. It is created in in a separate nested template, so that it can be referenced by all of the other nested templates and so that the ECS service can register with it. | | infrastructure/ecs-cluster.yaml | This template deploys an ECS cluster to the private subnets using an Auto Scaling group. | | infrastructure/dynamodb.yaml | This template creates a DynamoDB table to persist event-data. | | infrastructure/elasticache | This template deploys an ElastiCache cluster with Redis 3-engine to the private subnets with a Replication Group for high availability. | | infrastructure/kinesis | This template deploys two Kinesis Streams to decouple services from each other and implement a buffer to temporarily store data. | | infrastructure/lambda | This template deploys two Lambda-functions with according EventSourceMapping to consume data from Kinesis Streams | | services/tracking-service/service.yaml | This is an example of a long-running ECS service that implements the basic logic for an AdTracking use-case. For the full source for the service, see services/tracking-service/src.|

After the CloudFormation templates have been deployed, the stack outputs contain a link to the load-balanced URL for the deployed microservice.

stack-outputs

How do I…?
Get started and deploy this into my AWS account

You can launch this CloudFormation stack in the EU West (Dublin) Region in your account:

cloudformation-launch-button

Test the application

After the application has been deployed correctly, you can load test data into Redis by calling the following URL using e.g. curl:

 http://<endpoint>/cache/fill

After the cache has been filled succesfully, you can call the tracking application with an existing program id e.g. 212313

 http://<endpoint>/event/212313

This HTTP call returns a response like

erAgent":"curl/7.54.0","programId":"212313","programName":"program2","checksum":"124","customerId":9124,"customerName":"Customer2","messageId":"06bc2944-886c-4e56-907c-fa248c8af023","valid":true"}
Customize the templates
  1. Fork this GitHub repository.
  2. Clone the forked GitHub repository to your local machine.
  3. Modify the templates.
  4. Upload them to an Amazon S3 bucket of your choice.
  5. Either create a new CloudFormation stack by deploying the master.yaml template, or update your existing stack with your version of the templates.
Build the microservices

All microservices a implemented using Java 8 and use Maven for dependency management.

Main application
  1. Change directory to services/tracking-service/reactive-vertx: cd services/tracking-service/reactive-vertx
  2. Build an Uber-JAR using Maven: mvn clean install -Dmaven.test.skip=true
  3. Build a Docker image: docker build . -t smoell/reactive-vertx
Redis Updater
  1. Change directory to services/redis-updater: cd services/redis-updater
  2. Build an Uber-JAR using Maven: mvn clean install -Dmaven.test.skip=true
Kinesis Consumer
  1. Change directory to services/redis-updater: cd services/redis-updater
  2. Build an Uber-JAR using Maven: mvn clean install -Dmaven.test.skip=true
Create a new ECS service
  1. Push your container to a registry somewhere (e.g., Amazon ECR).
  2. Copy one of the existing service templates in services/*.
  3. Update the ContainerName and Image parameters to point to your container image instead of the example container.
  4. Increment the ListenerRule priority number (no two services can have the same priority number - this is used to order the ALB path based routing rules).
  5. Copy one of the existing service definitions in master.yaml and point it at your new service template. Specify the HTTP Path at which you want the service exposed.
  6. Deploy the templates as a new stack, or as an update to an existing stack.
Setup centralized container logging

By default, the containers in your ECS tasks/services are already configured to send log information to CloudWatch Logs and retain them for 7 days. Within each service's template (in services/*), a LogGroup is created that is named after the CloudFormation stack. All container logs are sent to that CloudWatch Logs log group.

You can view the logs by looking in your CloudWatch Logs console (make sure you are in the correct AWS region).

ECS also supports other logging drivers, including syslog, journald, splunk, gelf, json-file, and fluentd. To configure those instead, adjust the service template to use the alternative LogDriver. You can also adjust the log retention period from the default 365 days by tweaking the RetentionInDays parameter.

For more information, see the LogConfiguration API operation.

Change the ECS host instance type

This is specified in the master.yaml template.

By default, t2.large instances are used, but you can change this by modifying the following section:


pe: AWS::CloudFormation::Stack
Properties:
  TemplateURL: ...
  Parameters:
    ... 
    InstanceType: t2.large
    InstanceCount: 4
    ... 
Adjust the Auto Scaling parameters for ECS hosts and services

The Auto Scaling group scaling policy provided by default launches and maintains a cluster of 4 ECS hosts distributed across two Availability Zones (min: 4, max: 4, desired: 4).

It is not set up to scale automatically based on any policies (CPU, network, time of day, etc.).

If you would like to configure policy or time-based automatic scaling, you can add the ScalingPolicy property to the AutoScalingGroup deployed in infrastructure/ecs-cluster.yaml.

As well as configuring Auto Scaling for the ECS hosts (your pool of compute), you can also configure scaling each individual ECS service. This can be useful if you want to run more instances of each container/task depending on the load or time of day (or a custom CloudWatch metric). In this case, the service scaling is based on the number of 500 errors, the ALB generates.

Deploy multiple environments (e.g., dev, test, pre-production)

Deploy another CloudFormation stack from the same set of templates to create a new environment. The stack name provided when deploying the stack is prefixed to all taggable resources (e.g., EC2 instances, VPCs, etc.) so you can distinguish the different environment resources in the AWS Management Console.

Change the VPC or subnet IP ranges

This set of templates deploys the following network design:

| Item | CIDR Range | Usable IPs | Description | | — | — | — | — | | VPC | 10.180.0.0/16 | 65,536 | The whole range used for the VPC and all subnets | | Public Subnet | 10.180.8.0/21 | 2,041 | The public subnet in the first Availability Zone | | Public Subnet | 10.180.16.0/21 | 2,041 | The public subnet in the second Availability Zone | | Private Subnet | 10.180.24.0/21 | 2,041 | The private subnet in the first Availability Zone | | Private Subnet | 10.180.32.0/21 | 2,041 | The private subnet in the second Availability Zone |

You can adjust the CIDR ranges used in this section of the master.yaml template:


pe: AWS::CloudFormation::Stack
Properties:
  TemplateURL: !Sub ${TemplateLocation}/infrastructure/vpc.yaml
  Parameters:
    EnvironmentName:    !Ref AWS::StackName
    VpcCIDR:            10.180.0.0/16
    PublicSubnet1CIDR:  10.180.8.0/21
    PublicSubnet2CIDR:  10.180.16.0/21
    PrivateSubnet1CIDR: 10.180.24.0/21
    PrivateSubnet2CIDR: 10.180.32.0/21
Update an ECS service to a new Docker image version

ECS has the ability to perform rolling upgrades to your ECS services to minimize downtime during deployments. For more information, see Updating a Service.

To update one of your services to a new version, adjust the Image parameter in the service template (in services/* to point to the new version of your container image. For example, if 1.0.0 was currently deployed and you wanted to update to 1.1.0, you could update it as follows:

Definition:
pe: AWS::ECS::TaskDefinition
operties:
ContainerDefinitions:
  - Name: your-container
    Image: registry.example.com/your-container:1.1.0

After you've updated the template, update the deployed CloudFormation stack; CloudFormation and ECS handle the rest.

To adjust the rollout parameters (min/max number of tasks/containers to keep in service at any time), you need to configure DeploymentConfiguration for the ECS service.

For example:

ice: 
pe: AWS::ECS::Service
Properties: 
  ...
  DesiredCount: 4
  DeploymentConfiguration: 
    MaximumPercent: 200
    MinimumHealthyPercent: 50
Add a new item to this list

If you found yourself wishing this set of frequently asked questions had an answer for a particular problem, please submit a pull request. The chances are that others will also benefit from having the answer listed here.

Contributing

Please create a new GitHub issue for any feature requests, bugs, or documentation improvements.

Where possible, please also submit a pull request for the change.


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.