47544889 47a2 4362 85c3 c75765e09692

Effective Cost Optimization Strategies for Amazon EC2 Instances

Spread the love

Saving cost is a continuous operation for your infrastructure. There needs to be a process and strategy to follow in other to save cost effectively. This strategy needs to be deployed intermittently to ensure that cost is saved.

One of the strategies that can be applied is frequent audit of the infrastructure to see be able to identify unused resources and overprovisioned resources.

When performing an audit, it is essential to take note of what was observed and decide on the actions that need to be taken based on what was identified.

In most cases, the resources that cause bloated bills are either services created and are never in use or resources that have been over-provisioned because there was an overestimation of the resources a particular service requires to run. So the actions to be taken in these scenarios are simple:

1. Delete the unused EC2 instance to save cost.

2. Downgrade the overprovisioned EC2 instance.

These are simple scenarios of actions that can be taken and the effect of these actions can be immediately seen on your cost within hours.

But there are other complicated situations and broader options that exist to save costs for EC2 instances. Let us delve into some more advanced practices that can be deployed when the audit is done and cost optimisation opportunities have been identified.

Configure Start and Stop on Instances

—-

This is an operation that involves stopping certain instances and starting them again at specific schedules. This practice can be very helpful in saving cost for instances that are not needed all the time. For instance, staging and development instances are not usually used at off-peak hours and weekends. So configuring this for the instances will save an extra 8-10hrs of time daily which would significantly impact the bill at the end of the month.

Configuring a start and stop for instances can be done with Amazon EventBridge which will serve as the event trigger and scheduler while AWS Lambda executes the start and stop command. The following script can be deployed into the Lambda function to start the instance

import boto3

def lambda_handler(event, context):

  # Extract instance ID from the event

  instance_id = event.get(‘instance_id’)

   

  if not instance_id:

    return {

      ‘statusCode’: 400,

      ‘body’: ‘Instance ID is required’

    }

   

  # Create an EC2 client

  ec2 = boto3.client(‘ec2’)

  

  try:

    # Start the EC2 instance

    response = ec2.start_instances(InstanceIds=[instance_id])

    # Return success response

    return {

      ‘statusCode’: 200,

      ‘body’: f’Successfully stopped instance: {instance_id}’,

      ‘response’: response

    }

  except Exception as e:

    # Handle errors

    return {

      ‘statusCode’: 500,

      ‘body’: f’Error stopping instance: {str(e)}’

    }

While the following script can be deployed to another Lambda function to stop the instance or set of instances

import boto3

def lambda_handler(event, context):

  # Extract instance ID from the event

  instance_id = event.get(‘instance_id’)

   

  if not instance_id:

    return {

      ‘statusCode’: 400,

      ‘body’: ‘Instance ID is required’

    }

   

  # Create an EC2 client

  ec2 = boto3.client(‘ec2’)

   

  try:

    # Stop the EC2 instance

    response = ec2.stop_instances(InstanceIds=[instance_id])

     

    # Return success response

    return {

      ‘statusCode’: 200,

      ‘body’: f’Successfully stopped instance: {instance_id}’,

      ‘response’: response

    }

  except Exception as e:

    # Handle errors

    return {

      ‘statusCode’: 500,

      ‘body’: f’Error stopping instance: {str(e)}’

    }

In the end there will be two Lambda functions which will serve for start and stop respective and one EventBridge with two seperate rules to handle the start and stop and different schedules.

Use Savings Plan

One way to get discount on your EC2 resources is to use the Saving Plan pricing strategy. An AWS Savings Plan is a flexible pricing model that offers significant discounts on AWS compute usage (e.g., EC2, Fargate, Lambda) in exchange for a commitment to a consistent amount of usage (measured in $/hour) for a 1- or 3-year term. You save up to 72% compared to On-Demand pricing. There are two types: Compute Savings Plans (applies to EC2, Fargate, Lambda) and EC2 Instance Savings Plans (specific to EC2 instances). It automatically applies to eligible usage, providing flexibility across instance families, regions, and operating systems.

Implement Spot instances

Though not applicable in all workload types, Spot instances can give huge discounts when properly implemented. AWS Spot Instances allow you to use unused EC2 capacity at up to 90% off the On-Demand price. They are ideal for fault-tolerant or flexible workloads, such as batch processing, CI/CD, or testing. However, AWS can reclaim these instances with a two-minute warning when the capacity is needed elsewhere. Spot Instances are cost-effective but less reliable than On-Demand or Reserved Instances, making them suitable for interruptible tasks. You can use Spot Fleets or Spot Instance pools to manage availability and minimize interruptions.

Removed unused EIP

There are cases where Elastic IPs are left hanging and not attached to an EC2 instance this can lead to some significant cost, mostly when the Elastic IPs are much. This is usually an easy and fast fix. All you need to do is to release the IP since it is not attached to an EC2 instance. So it is important to always check this part of the EC2 infrastructure for this resource. The following screenshot shows how to release an Elastic IP in the AWS Console.

download 8

A similar resource to ElasticIP is a load balancer, which should be part of the checks and validations before they can be deleted

Delete Orphaned EBS Volumes

EBS volumes are usually hard to find like Elastic IPs. There are cases where an EC2 instance is terminated and the EBS volumes remain. This incurs cost over time because EBS volumes are billed per hour just like EC2 instances. So deleting the EBS volume that is not attached to an EC2 instance should be deleted to cut down this cost.

This issue of unattached EBS volumes is very common in Kubernetes, mostly when Statefulsets are used to provision persistent volumes and these Statefulsets get deleted. There is usually a high chance of the EBS volume attached to the persistent volume (PV), remaining and not get deleted. So it is important to perform audit to fish this out and delete accordingly.

Conclusion

Cost optimization is a major pillar of the well-architeced framework and involves regular review of account resources to identify what needs to be done to optimize cost and reduce wastage. Plan biweekly review of your infrastructure resources to keep abreast with the total cost.

Are you AWS Certified and need to test your AWS skills? You can do that these set of AWS projects to affirm your skills.


Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
×