<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Utsav Ojha on Medium]]></title>
        <description><![CDATA[Stories by Utsav Ojha on Medium]]></description>
        <link>https://medium.com/@utsavojha2?source=rss-3c6e6774806------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*n7izVdmuHBXLAu9ZYfcKNg.jpeg</url>
            <title>Stories by Utsav Ojha on Medium</title>
            <link>https://medium.com/@utsavojha2?source=rss-3c6e6774806------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 16:04:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@utsavojha2/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Scaling cluster infrastructure in ECS]]></title>
            <link>https://medium.com/@utsavojha2/scaling-cluster-infrastructure-in-ecs-54509a80a670?source=rss-3c6e6774806------2</link>
            <guid isPermaLink="false">https://medium.com/p/54509a80a670</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[scaling]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Utsav Ojha]]></dc:creator>
            <pubDate>Wed, 18 Mar 2026 05:35:17 GMT</pubDate>
            <atom:updated>2026-03-18T05:35:17.786Z</atom:updated>
            <content:encoded><![CDATA[<p>If you run your containers in AWS Fargate, AWS will handle the infrastructure scaling for you. But there are various cases where you need to opt for EC2 infrastructure instead of Fargate. It could be hardware requirements, cost optimization, compliance &amp; legal issues etc. As your containers scale with usage, the burden of scaling your infrastructure falls on you as a customer. AWS will not do it for you. So the question is how would you approach your scaling strategy to ensure that infrastructure is capable enough to meet the demands of growing/shrinking containers? The answer is cluster scaling which adjusts the size of EC2 instances based on number of tasks and containers currently running on ECS.</p><p>To demonstrate cluster level scaling in action, we will build a full infrastructure from scratch. For the example, I have a boilerplate NestJS setup which will be deployed as containers in AWS ECS. The following diagram depicts the high level overview of the infra &amp; deployment architecture used in this instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k15CWRKUpIkHRd6OSnwHww.png" /></figure><p>Note that I am making use of NAT Instances in order to facilitate outbound internet access for ECS Instances and Tasks. This is generally not a great idea, and you should instead be making use of NAT gateway for resources in private subnet to get outbound internet access. NAT instance is just an EC2 instance, so the overhead of things like maintenance, patches, OS updates, fixing vulnerabilities, etc falls on the user itself. On the other hand, NAT Gateway is a managed AWS service. There is no free tier on NAT gateway, so for cost reasons I am using NAT Instances for the purpose of this article.</p><h4>Terraform Initialization</h4><p>For this example, I will be using terraform local for deploying resources. It won’t be integrated with any CI/CD pipeline. I will just deploy everything locally from terminal. The structure of our terraform configuration will look something like:</p><pre>infra/<br>├── network/<br>│   └── main.tf          ← Has terraform &amp; provider block<br>│                        ← Has its own state file<br>│<br>└── platform/ecs-cluster/<br>    └── main.tf          ← Has terraform &amp; provider block<br>                         ← Has its own state file</pre><p>We will have seperate terraform lifecycle for network, DNS, cluster, load balancer, and the actual application. They need to be deployed in order because rest of the layers are dependent on the output of previous layer to function. Seperation of concern is the primary reason for this approach. For example, any trivial changes in application layer will have zero risks on the higher level infrastructure like the network or DNS layer.</p><h4>Network Layer</h4><p>In the network infrastructure, we will make use of VPC with private and public subnets. They will span across multiple availability zones. The application load balancer and NAT instance will be in public subnet whereas the ECS instances and tasks will be deployed in private subnet. Security Groups will be in place so nothing from outside the internet will able to reach ECS tasks directly. ALB will facilitate inbound communication whereas NAT instances will facilitate outbound communication. We will go with a /16 network range for the VPC CIDR range. This corresponds to around 65,531 usable IPs, which should be plenty enough for all tasks which will be running our containers.</p><pre># main.tf file for network lifecycle<br>resource &quot;aws_vpc&quot; &quot;main&quot; {<br>  cidr_block = &quot;10.0.0.0/16&quot;<br><br>  tags = {<br>    Name = &quot;application-vpc&quot;<br>  }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;alb_primary&quot; {<br>  vpc_id     = aws_vpc.main.id<br>  cidr_block = &quot;10.0.0.0/24&quot;<br>  availability_zone = &quot;us-east-1a&quot;<br><br>  tags = {<br>    Name = &quot;alb-primary-public-subnet&quot;<br>  }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;alb_secondary&quot; {<br>  vpc_id     = aws_vpc.main.id<br>  cidr_block = &quot;10.0.1.0/24&quot;<br>  availability_zone = &quot;us-east-1b&quot;<br><br>  tags = {<br>    Name = &quot;alb-secondary-public-subnet&quot;<br>  }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;app_primary&quot; {<br>  vpc_id     = aws_vpc.main.id<br>  cidr_block = &quot;10.0.10.0/24&quot;<br>  availability_zone = &quot;us-east-1a&quot;<br><br>  tags = {<br>    Name = &quot;app-primary-private-subnet&quot;<br>  }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;app_secondary&quot; {<br>  vpc_id     = aws_vpc.main.id<br>  cidr_block = &quot;10.0.11.0/24&quot;<br>  availability_zone = &quot;us-east-1b&quot;<br><br>  tags = {<br>    Name = &quot;app-secondary-private-subnet&quot;<br>  }<br>}</pre><h4>DNS Layer</h4><p>For this example, I will be using a domain bought at Namecheap. While the domain registrar is Namecheap, we will use AWS for the hosting zone. We are going to use Route53 hosting zone which will function as authoritative nameservers for our domain. It is important to note that you will have to update your domain config in Namecheap to have the newly created AWS authoritative nameservers. Since our domain will be accessible only through HTTPS, we will be using AWS Certification Manager to request a public certificate for the domain. Before a certificate is verified, you will have to verify that you actually own the domain and that is done by adding a CNAME record provided by ACM in your hosting zone record. We will also use this certificate and attach it to our application load balancer later, so that we can access the ALB url on port 443.</p><pre>resource &quot;aws_route53_zone&quot; &quot;main&quot; {<br>  name         = var.domain_name<br>}<br><br>resource &quot;aws_acm_certificate&quot; &quot;tls_certificate&quot; {<br>  domain_name       = var.domain_name<br>  subject_alternative_names = [&quot;*.${var.domain_name}&quot;]<br>  validation_method = &quot;DNS&quot;<br><br>  lifecycle {<br>    create_before_destroy = true<br>  }<br>}<br><br><br>resource &quot;aws_route53_record&quot; &quot;cert_validation&quot; {<br>  for_each = {<br>    for dvo in aws_acm_certificate.tls_certificate.domain_validation_options : dvo.domain_name =&gt; {<br>      name   = dvo.resource_record_name<br>      record = dvo.resource_record_value<br>      type   = dvo.resource_record_type<br>    }<br>  }<br><br>  zone_id         = aws_route53_zone.main.zone_id<br>  allow_overwrite = true<br>  name            = each.value.name<br>  records         = [each.value.record]<br>  ttl             = 60<br>  type            = each.value.type<br>}<br><br>resource &quot;aws_acm_certificate_validation&quot; &quot;tls_certificate_validation&quot; {<br>  certificate_arn         = aws_acm_certificate.tls_certificate.arn<br>  validation_record_fqdns = [for record in aws_route53_record.cert_validation : record.fqdn]<br>}</pre><p>Since we are using a lifecycle based pattern for the infrastructure setup, I will be using terraform remote state in order to access outputs from previous layer. This might not be the best approach in terms of implementing a loosely coupled architecture. Any changes to a resource names or module structures inside the producer forces a breaking change on the consumer. A better way would be forming a deliberate contract between the producer and consumer. Under this model, the producer and consumer agree on a standardized pathing hierarchy to store and retrieve values. The consumer doesn’t care how the value was created, thus removing any implementation dependency. We can use a tool like AWS SSM for this approach. There are also cases where it is just better to use native terraform data source feature for real time lookup in the infrastructure state.</p><h4>Cluster Layer</h4><p>The next step in our infrastructure setup will be our cluster configuration. We will just start off by creating a cluster, which will consist of a bunch of logical resources for actually running our containers. In this layer, we will also be creating a capacity provider and associate it to the cluster. The capacity provider will actually be an Auto Scaling Group (ASG) and ECS will ensure that ASGs will scale in and out as needed. While you can associate multiple capacity provider to a single ECS cluster, we will only be using one capacity provider, i.e an ASG, for this example.</p><p>ECS managed ASG is not the same thing as a traditional ASG. A traditional ASG only emphasizes on the health of the virtual machine. It only scales based on infrastructure metrics, such as CPU utilization, memory, etc. This approach focuses on the dynamics of underlying infrastructure rather than the application workloads. On the other hand, an ECS managed ASG is proactive to the container workloads. If a newly provisioned container is unable to run due to insufficient CPU on the host machine, ECS automatically requests added compute capacity from Auto Scaling Group, which in turns spins up additional EC2 instances. So a capacity provider will act as a bridge between the cluster and infrastructure running the containers.</p><pre>resource &quot;aws_ecs_cluster&quot; &quot;application_cluster&quot; {<br>  name = &quot;application-cluster&quot;<br>}<br><br>data &quot;aws_ssm_parameter&quot; &quot;ecs_al2023_ami&quot; {<br>  name = &quot;/aws/service/ecs/optimized-ami/amazon-linux-2023/recommended/image_id&quot;<br>}<br><br>resource &quot;aws_launch_template&quot; &quot;ecs_container_instance_template&quot; {<br>  name                  = &quot;ecs-ec2instance-template&quot;<br>  description           = &quot;Launch template for ECS container instances&quot;<br>  image_id              = data.aws_ssm_parameter.ecs_al2023_ami.value<br>  instance_type         = &quot;t2.micro&quot;<br>  vpc_security_group_ids = [aws_security_group.allow_tcp.id]<br><br>  iam_instance_profile {<br>    name = aws_iam_instance_profile.ecs.name<br>  }<br><br>  user_data = base64encode(&lt;&lt;-EOF<br>#!/bin/bash<br>echo &quot;ECS_CLUSTER=${aws_ecs_cluster.application_cluster.name}&quot; &gt;&gt; /etc/ecs/ecs.config<br>EOF<br>  )<br>}<br><br>resource &quot;aws_autoscaling_group&quot; &quot;ecs_optimized_asg&quot; {<br>  name                = &quot;ecs-instance-autoscaling-group&quot;<br>  min_size            = 0<br>  desired_capacity    = 0<br>  max_size            = 5<br>  vpc_zone_identifier = data.terraform_remote_state.network.outputs.private_subnet_ids<br><br>  launch_template {<br>    id      = aws_launch_template.ecs_container_instance_template.id<br>    version = &quot;$Latest&quot;<br>  }<br><br>  tag {<br>    key                 = &quot;AmazonECSManaged&quot;<br>    value               = &quot;&quot;<br>    propagate_at_launch = true<br>  }<br><br>  lifecycle {<br>    ignore_changes = [desired_capacity]<br>  }<br>}<br><br>resource &quot;aws_ecs_capacity_provider&quot; &quot;ecs_capacity_provider_asg&quot; {<br>  name = &quot;capacity_provider_asg&quot;<br><br>  auto_scaling_group_provider {<br>    auto_scaling_group_arn         = aws_autoscaling_group.ecs_optimized_asg.arn<br><br>    managed_scaling {<br>      maximum_scaling_step_size = 1000<br>      minimum_scaling_step_size = 1<br>      status                    = &quot;ENABLED&quot;<br>      target_capacity           = 100<br>    }<br>  }<br>}<br><br>resource &quot;aws_ecs_cluster_capacity_providers&quot; &quot;cluster_capacity_providers&quot; {<br>  cluster_name = aws_ecs_cluster.application_cluster.name<br><br>  capacity_providers = [aws_ecs_capacity_provider.ecs_capacity_provider_asg.name]<br><br>  default_capacity_provider_strategy {<br>    capacity_provider = aws_ecs_capacity_provider.ecs_capacity_provider_asg.name<br>    weight            = 1<br>    base              = 0<br>  }<br>}</pre><h4>Application Load Balancer</h4><p>All of the tasks running in our cluster will have its own ENI, but they won’t possess a public IPv4 address. The tasks will also be allocated inside private subnets, which means it won’t be possible to reach our web server through the internet. As our application workload scales, more and more container spin up, each with their own network interface. In order to reach the container from the internet, we will make use of a layer 7 application load balancer. This will help make sure that the traffic is being distributed across all healthy running instances. AWS ALB offers continuous health check capabilities, so in case any tasks goes down, the ALB stops redirecting traffic to that unhealthy task.</p><pre>resource &quot;aws_lb&quot; &quot;application_load_balancer&quot; {<br>  name               = &quot;application-load-balancer&quot;<br>  load_balancer_type = &quot;application&quot;<br>  security_groups    = [aws_security_group.alb_sg.id]<br>  subnets            = data.terraform_remote_state.network.outputs.public_subnet_ids<br>}<br><br>resource &quot;aws_lb_target_group&quot; &quot;alb_target_group_to_ecs_cluster&quot; {<br>  name        = &quot;alb-target-group-to-ecs-cluster&quot;<br>  port        = 3000<br>  protocol    = &quot;HTTP&quot;<br>  target_type = &quot;ip&quot;<br>  vpc_id      = data.terraform_remote_state.network.outputs.vpc_id<br><br>  health_check {<br>    path                = &quot;/health&quot;<br>    port                = &quot;traffic-port&quot;<br>    protocol            = &quot;HTTP&quot;<br>    matcher             = &quot;200-399&quot;<br>    interval            = 30<br>    timeout             = 5<br>    healthy_threshold   = 3<br>    unhealthy_threshold = 2<br>  }<br>}<br><br>resource &quot;aws_lb_listener&quot; &quot;alb_listener&quot; {<br>  load_balancer_arn = aws_lb.application_load_balancer.arn<br>  port              = 443<br>  protocol          = &quot;HTTPS&quot;<br>  ssl_policy        = &quot;ELBSecurityPolicy-TLS13-1-2-2021-06&quot;<br>  certificate_arn   = data.terraform_remote_state.dns.outputs.acm_certificate_arn<br><br>  default_action {<br>    type             = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.alb_target_group_to_ecs_cluster.arn<br>  }<br>}<br><br>resource &quot;aws_route53_record&quot; &quot;app&quot; {<br>  zone_id = data.aws_route53_zone.root_domain.zone_id<br>  name    = &quot;api.${var.domain_name}&quot;<br>  type    = &quot;A&quot;<br><br>  alias {<br>    name                   = aws_lb.application_load_balancer.dns_name<br>    zone_id                = aws_lb.application_load_balancer.zone_id<br>    evaluate_target_health = true<br>  }<br>}</pre><p>We will make use of the same public certificate that we created in DNS layer, so that we can access the load balancer over HTTPS. Our containers are configured to listen on port 3000; consequently, the ALB’s target group is mapped to that specific port. You can see that I am creating an ‘A’ record in the domain hosting zone created earlier which will be associated as an ALIAS pointing to the load balancer DNS configuration. When a user hits that URL, the DNS resolver returns the ALB’s IP. The ALB then performs the heavy lifting: it terminates the SSL/TLS connection and forwards the plain HTTP traffic to the internal private IPs of our running tasks. Even though there is no HTTPS involved over the ALB to ECS task communication, it is still a secure one because the communication is taking place over AWS private network.</p><h4>The Application Layer</h4><p>Now we have setup all the network, DNS and cluster infrastructure, we are finally ready to spin up tasks to serve our web server. As we are using network mode of “<strong>awsvpc</strong>”, all tasks will have its own ENI. That is why we don’t need to do a host port to container mapping like we traditionally do when we use the default Docker bridge network type. We are going to use the ASG capacity provider that we created in cluster layer for the ECS service capacity strategy.</p><pre>resource &quot;aws_ecs_task_definition&quot; &quot;app&quot; {<br>  family                   = &quot;application_td&quot;<br>  network_mode             = &quot;awsvpc&quot;<br>  requires_compatibilities = [&quot;EC2&quot;]<br>  cpu                      = &quot;256&quot;<br>  memory                   = &quot;512&quot;<br><br>  execution_role_arn = aws_iam_role.ecs_task_execution.arn<br><br>  container_definitions = jsonencode([{<br>    name      = &quot;application_td&quot;<br>    image     = var.image_id<br>    essential = true<br><br>    portMappings = [{<br>      containerPort = 3000<br>      protocol      = &quot;tcp&quot;<br>      appProtocol   = &quot;http&quot;<br>    }]<br>  }])<br>}<br><br>resource &quot;aws_ecs_service&quot; &quot;app&quot; {<br>  name            = &quot;application_td&quot;<br>  cluster         = data.terraform_remote_state.ecs.outputs.cluster_arn<br>  task_definition = aws_ecs_task_definition.app.arn<br>  desired_count   = 2<br><br>  capacity_provider_strategy {<br>    capacity_provider = data.terraform_remote_state.ecs.outputs.capacity_provider_name<br>    base = 0<br>    weight = 1<br>  }<br><br>  network_configuration {<br>    subnets          = data.terraform_remote_state.network.outputs.private_subnet_ids<br>    security_groups  = [aws_security_group.app_tasks.id]<br>    assign_public_ip = false<br>  }<br><br>  load_balancer {<br>    target_group_arn = data.terraform_remote_state.alb.outputs.app_target_group_arn<br>    container_name   = &quot;application_td&quot;<br>    container_port   = 3000<br>  }<br><br>  lifecycle {<br>    ignore_changes = [desired_count]<br>  }<br>}</pre><h3>Infrastructure in Action</h3><p>Let’s start off through network lifecycle. terraform apply will be executed on that layer and we will get our first output. As you can see we now have a VPC with public and private subnets across a couple of availability zones. The public subnet has a route table attached to it, so any other addresses destined to 0.0.0.0/0 other than the internal CIDR range will be directed to the internet through the internet gateway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2PuGYhvjmVnUZKQrRjaOzg.png" /></figure><p>The next step will be the DNS layer. We are going to create the hosting zone for our domain and also be creating a public certificate for our domain, so we can access our domain only through HTTPS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVr0p1C37g83c1E6iGhfjw.png" /></figure><p>I am using a dummy domain for this example. You can see that the first two records are default records when creating a hosting zone. You will need to attach your NS records to the one that is in your domain registrar, so AWS becomes authoritative for DNS resolver. The CNAME record is the one attached by ACM to verify the domain actually belongs to you, so that the certificate can be issued for your domain to facilitate TLS connections.</p><p>Now that our network and DNS infrastructure is in place, we can proceed with creating resources for our cluster, which will include all logical resources for running our container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NIOj1k38FXXfFdv_-KN0SQ.png" /><figcaption>Cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qlq3ALH30gJ22D9uQ2CFzA.png" /><figcaption>Cluster Capacity Provider</figcaption></figure><p>I am going to use 100% as the target capacity as the focal point for ECS managed scaling to govern scale-in and scale-out actions. ECS Managed Scaling uses the CapacityProviderReservation metric which is published to AWS CloudWatch. CapacityProviderReservation continuously calculates the ratio of the number of instances needed to run all tasks to the number of currently available instances. By setting the target to 100%, ECS scheduler will initiate a scale out if the host infrastructure is fully occupied and current tasks exceed the CPU and memory resources.</p><p>For example, lets say you have one currently running t2.micro EC2 instance for your infrastructure. AWS EC2 t2.micro instance has 1 vCPU and 1 GiB of RAM. Lets assume that there are two tasks you are about to run and each task requires 0.5vCPU and 0.5GiB RAM. The number of instances needed to run all tasks (M) and the number of total available instances (N) are equal, which means the CapacityProviderReservation is now at 100% as derived by the formula: M/N * 100. Bear in mind, the limit on how many tasks can be deployed on a single EC2 machine is not limited RAM or memory or CPU usage only, it can only also be based on the number of network interfaces that can be attached to a virtual machine. For example, there is a maximum cap of 2 ENIs that can be attached EC2 instances of type t2/t3 micro or nano.</p><p>Now if you run one more identical task onto the cluster, that task enters the PROVISIONING state. There is no space on the EC2 host machine in order to run the task. Now the total number of instances need to run all tasks is now 2. ECS Scheduler publishes CapacityProviderReservation value to CloudWatch, which is now 200%. Since the CapacityProviderReservation value (200%) is greater than TargetCapacity (100%), an alarm is triggered on CloudWatch. Whenever you use a capacity provider with Managed Scaling, AWS automatically creates CloudWatch alarms linked to the ASG scaling policy. Once the alarm fires, the policy is triggered which updates the desired_capacity value of the Auto Scaling Group. Eventually, new instances are provisioned and ECS Scheduler places the new task on the infrastructure successfully.</p><p>Next, let’s create the load balancer through which we are going to access our web application. In this ALB terraform lifecycle, I have also updated our hosting zone by creating a new ‘A’ record for “api.${domain_name}” domain with an alias record pointing to load balancer DNS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MnADZNuieoSRFNYJ3OtQ6w.png" /></figure><p>Now that we have the whole network and platform infrastructure in place, let’s create ECS service resources to spin up some tasks so we can access our web application through the Internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_-oubyMEu3WuatiscuphMA.png" /><figcaption>ECS Task is now accessible through the domain</figcaption></figure><p>We have successfully deployed our containers in EC2 cluster and is now accessible through the Internet. Even though the tasks are placed in private subnet, it is still accessible via the Internet because our load balancer is bridging that gap. Similarly, the ECS agent running on EC2 hosts can successfully reach the Internet for things like pulling Docker images from AWS ECR due to the NAT instance in the public subnet.</p><h4>ECS Service Auto Scaling</h4><p>We are going to add some target tracking scaling policies on ECS service. This is the most common type of scaling policy used in ECS Service Scaling. We will only choose a metric such as CPU utilization and a target value. When your service’s average utilization drifts above the target value, the policy scales out by adding more tasks and does vice versa when that utilization drops. In this example, we are going to scale out by adding more tasks whenever the average CPU utilization metric across all tasks goes above 50%.</p><pre>resource &quot;aws_appautoscaling_target&quot; &quot;ecs_target&quot; {<br>  max_capacity       = 10<br>  min_capacity       = 2<br>  resource_id        = &quot;service/${data.terraform_remote_state.ecs.outputs.cluster_name}/${aws_ecs_service.app.name}&quot;<br>  scalable_dimension = &quot;ecs:service:DesiredCount&quot;<br>  service_namespace  = &quot;ecs&quot;<br>}<br><br>resource &quot;aws_appautoscaling_policy&quot; &quot;ecs_policy_cpu&quot; {<br>  name               = &quot;cpu-target-tracking&quot;<br>  policy_type        = &quot;TargetTrackingScaling&quot;<br>  resource_id        = aws_appautoscaling_target.ecs_target.resource_id<br>  scalable_dimension = aws_appautoscaling_target.ecs_target.scalable_dimension<br>  service_namespace  = aws_appautoscaling_target.ecs_target.service_namespace<br><br>  target_tracking_scaling_policy_configuration {<br>    predefined_metric_specification {<br>      predefined_metric_type = &quot;ECSServiceAverageCPUUtilization&quot;<br>    }<br>    target_value = 50.0<br>  }<br>}</pre><h4>Mocking CPU Load</h4><p>Since the objective is to ensure the underlying infrastructure automatically scales out proportionally to containers, I am going to manually invoke some high CPU load operations in some containers so additional replicas of containers are run for high availability. For that, I will just spin up an ephemeral Bastion host EC2 instance, and use it as an intermediary to SSH into the task instances and run some CPU intensive CLI commands to mock some spikes above 50% utilization.</p><p>You can see that there are right now two tasks currently running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qGyAKc-ftMsZ5hqU8_P6NA.png" /></figure><p>Since its a t2.micro instance which has a hard cap of 2 ENIs per instance, there are two EC2 instances in place to fit those tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7spAOdNki2iIPeeNf0qI8w.png" /></figure><p>Next up, I am going to manually spike up CPU utilization by installing a linux package known as “stress-ng” and invoke some CPU intensive commands. I am going to do this inside both the running container via docker exec command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NDZHqvpXPbAA9teRLuaJpg.png" /></figure><p>As I spawn 2 worker each on both containers to stress CPU for 5 continuous minutes, I can already see the CPU utilization going up on CloudWatch metric. CPU must stay above 50% for 2–3 minutes in order for CloudWatch to trigger an alarm. Once that criteria is fulfilled, CloudWatch moves to ALARM state and notifies ECS Service Auto Scaling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LTd2BnMCJC1S-YGP7ACzaA.png" /><figcaption>CPU Utilization Spike on CloudWatch</figcaption></figure><p>ECS uses proportional scaling, adjusting task count based on the ratio of current usage to the target value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2omp9cktVpT5R9R0_FUiYg.png" /></figure><p>As new tasks are provisioned by the service but yet don’t have enough space to be placed in current infrastructure, ECS Scheduler publishes CapacityProviderReservation metric to CloudWatch which surpasses our 100% of target capacity. An alarm is triggered linking to ASG to increase its desired_capacity, thus ultimately spinning up new instances.</p><h4>Verifying cluster scaling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1q3vldrxE6BOiM5bKKdHrA.png" /></figure><p>We can now confirm that new instances have been started to meet the demand for running all of the ECS tasks. Since we can only run 1 tasks per instance due to our basic instance type, we can see that four instances are in place to run all four of our tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54509a80a670" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Unit and Integration Tests in React]]></title>
            <link>https://medium.com/@utsavojha2/writing-unit-and-integration-tests-in-react-7931527b9139?source=rss-3c6e6774806------2</link>
            <guid isPermaLink="false">https://medium.com/p/7931527b9139</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[react-testing-library]]></category>
            <dc:creator><![CDATA[Utsav Ojha]]></dc:creator>
            <pubDate>Wed, 29 Jun 2022 07:03:44 GMT</pubDate>
            <atom:updated>2022-06-29T07:03:44.601Z</atom:updated>
            <content:encoded><![CDATA[<p>Testing is a very complicated topic in React. Especially when you’re new to testing in JavaScript, it can get quite confusing and cumbersome. Most of the examples in the internet is mostly just about testing a insanely simple counter app. There’s more to real world web applications than just a counter app. In today’s example, I will show you my process in writing tests in React for real world web applications.</p><p>Our main application will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db2d90099820e202f12aa7ee6fa0254c/href">https://medium.com/media/db2d90099820e202f12aa7ee6fa0254c/href</a></iframe><p>Let us start with testing out App.js component. We initally make a fetch request to the server on component mount. In unit / integration tests, we don’t ever make actual API requests, we just mock it out. If you’re thinking about testing request payload and response objects, this is not where it happens. End to end testing is tailor made for such use cases and there’s a great tool called Cypress for such purpose.</p><p>As I have said, since we don’t make actual API requests in unit tests, we need to mock axios for all requests we’ll be making. We’ll use manual mocks for stubbing functionality with mock data. For example, instead of accessing a remote resource like a database, we’ll want to create a manual mock that allows us to use fake data. This ensures your tests will be fast and not flaky. You can also easily mock requests with using an external library like <a href="https://www.npmjs.com/package/axios-mock-adapter"><strong>axios-mock-adapter</strong></a>, but we’ll mock axios manually in our application. Create a file inside the __mocks__ directory with the module you’ll be mocking.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4de4ace6add8fe98328fde54310e36f7/href">https://medium.com/media/4de4ace6add8fe98328fde54310e36f7/href</a></iframe><p>Now that we have created an axios mock with functionality to resolve/reject promises with fake data, we can start testing our original App.js component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/486b6fa9de4539ef29b1bd4e9601966d/href">https://medium.com/media/486b6fa9de4539ef29b1bd4e9601966d/href</a></iframe><p>Since we’re making an initial fetch request on component render, we are making sure a GET axios request returns a resolved data for each test. While this test passes, you see a big fat error on the console, something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*2KKti2UHePxaQBUL08qXEA.png" /></figure><p>This usually happens when your component invokes a set state function after the test has finished running. You should not be ignoring these warnings, since a new state might trigger new changes in the application of the UI and the test is unable to track the new updates. You can fix this by adding more expect statements to expect the change in state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cf42f282ec906ae82f109c080b0b37d/href">https://medium.com/media/0cf42f282ec906ae82f109c080b0b37d/href</a></iframe><p>We have used the waitFor method from React Testing Library, since the expect function might run before the state updates. This way, we can track changes in the application like a real DOM enviroment even thought the tests are running in JSDOM. And now, the error message in the console has gone and we’re good to go. Moreover, we have also used faker library to mock fetched resolved values rather than hardcoding them.</p><p>Moving on, we’ll be adding a test case for ability to add a post and make a POST request to the server. We’ll also show a simple validation message if a user tries to submit post without any input.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67ea30c6b65f716414ed0847b99623e4/href">https://medium.com/media/67ea30c6b65f716414ed0847b99623e4/href</a></iframe><p>Yipee 🔥, our test has passed. As you can see, we expect to see validation error if user input is empty, else we expect a POST request to be called to the server. We usually avoid testing technical implementation details and instead focus on testing our application like a real user. Please refer to this brilliant <a href="https://kentcdodds.com/blog/common-mistakes-with-react-testing-library">article</a> by Kent C. Dodds for following best testing practices in React.</p><p>Let’s start testing our individual post component that we’re mapping over userposts state in App.js. The Post.js component and it’s test file looks something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97651f5198fe0dad0444c110780f7fe0/href">https://medium.com/media/97651f5198fe0dad0444c110780f7fe0/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/762562ef3a70d5abe2ec265af9f4664f/href">https://medium.com/media/762562ef3a70d5abe2ec265af9f4664f/href</a></iframe><p>Yes the test does pass, but we can an error in terminal console about the props being marked as required but it’s value is undefined. This is a pretty common error you see in the browser console as well. Tests assist us in catching potential error &amp; bugs and provide confidence that our feature will not break in production. Now lets fix the warning message in the console.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55fb88d1d47178b5f6b637dae1edf328/href">https://medium.com/media/55fb88d1d47178b5f6b637dae1edf328/href</a></iframe><p>Let’s add a test case for functionality to delete a post item from the list and also make some refactors to this test.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8ff7e09fae11eea2991cb4e12e1f432/href">https://medium.com/media/b8ff7e09fae11eea2991cb4e12e1f432/href</a></iframe><p>We make sure we make a DELETE request on clicking the delete button on the post component and the test passes, as expected. You can add to this and cover more test cases, making sure the application is working as expected.</p><p>If you are still reading till here after I’ve bored you to death, thank you so much for reading my piece. Feel free to pin down any questions you have for me. Good day everyone😃!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7931527b9139" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>