Build a Scalable API on AWS Spot Instances

Hello! My name is Kirill, I am a CTO at Adapty. Most of our architecture is on AWS, and today I'm going to talk about how we cut server costs by 3x by using Spot instances in a production environment, as well as how to configure them to autoscale. First there will be an overview of how it works, and then detailed instructions for starting.



What are Spot Instances?



Spot instances are other AWS users' servers that are currently idle and they are selling at a deep discount (Amazon writes up to 90%, ~ 3x in our experience, varies by region, AZ and instance type). Their main difference from conventional ones is that they can turn off at any time. Therefore, for a long time we believed that it is normal to use them for virgin environments, or for tasks of calculating something, with saving intermediate results on S3 or in the base, but not for selling. There are third-party solutions that allow you to use spots on sale, but there are a lot of crutches for our case, so we did not implement them. The approach described in the article works completely within the standard AWS functionality, without additional scripts, crowns, etc.



Below are some screenshots that show the history of Spot Instance prices.



m5.large in the eu-west-1 region (Ireland). Price mostly stable for 3 months, currently 2.9x savings .



image



m5.large in the us-east-1 region (N. Virginia). The price has been constantly changing for 3 months, currently the savings are from 2.3x to 2.8x depending on the availability zone.



image



t3.small in the us-east-1 region (N. Virginia). The price is stable for 3 months, currently the savings are 3.4x .



image



Service architecture



The basic architecture of the service, which we will talk about in this article, is shown in the diagram below.



image



Application Load Balancer β†’ EC2 Target Group β†’ Elastic Container Service



Application Load Balancer (ALB), EC2 Target Group (TG). TG , ALB Elastic Container Service (ECS). ECS β€” Kubernetes AWS, Docker .



, . ECS TG, ( Kubernetes ), . TG , health check, - , .



EC2 Auto Scaling Groups + ECS Capacity Providers



EC2 Auto Scaling Groups (ASG). , . AWS ECS. ECS , , CPU, RAM . , .



ECS Capacity Providers (ECS CP). ECS ASG, , ( ASG). , ECS CP , ASG, . ECS CP , , , .



EC2 Launch Templates



, , , β€” EC2 Launch Templates. , , . , , . , . , , ECS .



β€” ECS_ENABLE_SPOT_INSTANCE_DRAINING=true. , ECS , , , Draining. , , , . . 2 . 2 , .



β€” AWS Elastic File System (EFS) ECS, , , . SIGINT ( Draining) 30 , , ECS_CONTAINER_STOP_TIMEOUT. 2 .





. , . , - . AWS, CloudFormation Terraform. Adapty Terraform.



EC2 Launch Template



, . EC2 -> Instances -> Launch templates.



Amazon machine image (AMI) β€” , . ECS Amazon. ECS. ID , Amazon ECS-optimized AMIs, AMI ID . , us-east-1 ID β€” ami-00c7c1cf5bdc913ed. ID Specify a custom value.



Instance type β€” . , .



Key pair (login) β€” , SSH, .



Network settings β€” . Networking platform Virtual Private Cloud (VPC). Security groups β€” . , , . 2 , , (inbound) 80 (http) 443 (https), , . (outbound) TCP . , , - .



Storage (volumes) β€” . , AMI, ECS Optimized β€” 30 GiB.



Advanced details β€” .



Purchasing option β€” . , , Auto Scaling Group, .



IAM instance profile β€” , . , ECS, , ecsInstanceRole. , , , . .

, , . EBS-optimized instance T2/T3 Unlimited, burstable .



User data β€” . /etc/ecs/ecs.config, ECS.

, user data:



#!/bin/bash
echo ECS_CLUSTER=DemoApiClusterProd >> /etc/ecs/ecs.config
echo ECS_ENABLE_SPOT_INSTANCE_DRAINING=true >> /etc/ecs/ecs.config
echo ECS_CONTAINER_STOP_TIMEOUT=1m >> /etc/ecs/ecs.config
echo ECS_ENGINE_AUTH_TYPE=docker >> /etc/ecs/ecs.config
echo "ECS_ENGINE_AUTH_DATA={\"registry.gitlab.com\":{\"username\":\"username\",\"password\":\"password\"}}" >> /etc/ecs/ecs.config


ECS_CLUSTER=DemoApiClusterProd β€” , , . , .



ECS_ENABLE_SPOT_INSTANCE_DRAINING=true β€” , , Draining.



ECS_CONTAINER_STOP_TIMEOUT=1m β€” , SIGINT, 1 , .



ECS_ENGINE_AUTH_TYPE=docker β€” , docker-



ECS_ENGINE_AUTH_DATA=... β€” container registry, Docker . , .



Docker Hub, ECS_ENGINE_AUTH_TYPE ECS_ENGINE_AUTH_DATA .



: AMI, Docker, Linux, ECS . , . email , Lambda-, Launch Template AMI.



EC2 Auto Scaling Group



Auto Scaling Group . EC2 -> Auto Scaling -> Auto Scaling Groups.



Launch template β€” . .



Purchase options and instance types β€” . Adhere to launch template Launch Template. Combine purchase options and instance types . .



Optional On-Demand base β€” , , .



On-Demand percentage above base β€” , 50-50 , 20-80 4 . 50-50, 20-80, 0-100.



Instance types β€” , . , . , . , )



image



Network β€” , VPC , .



Load balancing β€” , , . Health checks .



Group size β€” . , .



Scaling policies β€” , , ECS , .



Instance scale-in protection β€” . , ASG , . , , ECS Capacity Provider.



Add tags β€” ( Tag new instances). Name, , , , .



image



Advanced configurations, .



Termination policies β€” , . . , . Launch Template (, AMI, , ). , . .



image



: , Instance Refresh. Lambda- , . instance scale-in protection . , , Instance management.



Application Load Balancer EC2 Target Group



EC2 β†’ Load Balancing β†’ Load Balancers. Application Load Balancer, .



Listeners β€” 80 443 80 443 .



Availability Zones β€” .



Configure Security Settings β€” SSL- , β€” ACM. Security Policy , ELBSecurityPolicy-2016-08. , DNS name, CNAME . , Cloudflare.



image



Security Group β€” , EC2 Launch Template β†’ Network settings.



Target group β€” , , . Target type Instance, Protocol Port , HTTPS , . , 80 .



Health checks β€” . , -, -. , , . Success codes 200-399, Docker , , 304 .



image



Register Targets β€” , ECS, .



: , S3 . , SQL- S3 Athena. - . S3 .



ECS Task Definition



, , , . ECS β†’ Task Definitions.



Launch type compatibility β€” EC2.



Task execution IAM role β€” ecsTaskExecutionRole. , .



Container Definitions Add Container.



Image β€” , Docker Hub bitnami/node-example:0.0.1.



Memory Limits β€” . Hard Limit β€” , , docker kill, . Soft Limit β€” , , . , 4 GiB , soft limit β€” 2048 MiB, 2 . 4 GiB β€” , 4096 MiB, ECS Instances . Soft limit hard limit. , , .



Port mappings β€” Host port 0, , , Target Group. Container Port β€” , , , , Dockerfile . 3000, Dockerfile .



Health check β€” , , Target Group.



Environment β€” . CPU units β€” Memory limits, . β€” 1024 , , 512, 4 . CPU units , .



Command β€” , . gunicorn, npm . , CMD Dockerfile. npm,start.



Environment variables β€” . , Secrets Manager Parameter Store.



Storage and Logging β€” CloudWatch Logs ( AWS). Auto-configure CloudWatch Logs. Task Definition CloudWatch. , Retention period Never Expire . CloudWatch Log groups, .



image



ECS Cluster ECS Capacity Provider



ECS β†’ Clusters, . EC2 Linux + Networking.



Cluster name β€” , , Launch Template ECS_CLUSTER, β€” DemoApiClusterProd. Create an empty cluster. Container Insights, CloudWatch. , ECS Instances , Auto Scaling group.



image



Capacity Providers . , , ECS . , .



Auto Scaling group β€” .



Managed scaling β€” , .



Target capacity % β€” . 100%, . 50%, . , , , .



Managed termination protection β€” , . , Target capacity %.



ECS Service



:) , Services.



Launch type β€” Switch to capacity provider strategy .



image



Task Definition β€” Task Definition .



Service name β€” , , Task Definition.



Service type β€” Replica.



Number of tasks β€” . , .



Minimum healthy percent Maximum percent β€” . 100 200, , 2 , . 1 , min=0, max=100, , , . 1 , min=50, max=150, , 1 .



Deployment type β€” Rolling update.



Placement Templates β€” . AZ Balanced Spread β€” , , . BinPack β€” CPU Spread β€” AZ, CPU. , .



image



Load balancer type β€” Application Load Balancer.



Service IAM role β€” ecsServiceRole.



Load balancer name β€” .



Health check grace period β€” , 60 .



Container to load balance β€” Target group name , .



image



Service Auto Scaling β€” . Configure Service Auto Scaling to adjust your service’s desired count. .



IAM role for Service Auto Scaling β€” AWSServiceRoleForApplicationAutoScaling_ECSService.



Automatic task scaling policies β€” . 2 :



  1. Target tracking β€” ( CPU/RAM ). , 85%, , , . , , (Disable scale-in).
  2. Step scaling β€” . (CloudWatch Alarm), , , .


, , , .





Docker , .



image



  1. , . .
  2. , , .
  3. , .
  4. , , 3 .
  5. , , .
  6. Capacity Provider, (), .
  7. .


, , email-, .



. , - . 1+ . API, . , - , , .



, ECS - .



, serverless ( ) GitLab CI Terraform Cloud.



, !




All Articles