Cost-Optimizing Strategies Using AWS Serverless Solutions: Maximizing Resources While Minimizing Expense.


AWS Lambda is a compute service that allows us to run code without managing servers, executing it only when needed and scaling automatically. Its event-driven, scalable nature enhances deployment efficiency, charging us only for the compute time consumed. By handling infrastructure management including maintenance and capacity provisioning, Lambda revolutionizes application development, enabling developers to focus solely on their code. All we need to do is supply our code in one of the supported languages.
What is Serverless Model !!
AWS Lambda operates on a serverless model, freeing developers from server management tasks. With AWS handling all infrastructure, developers can focus on code and application logic, optimizing resource allocation and eliminating over-provisioning needs.
Cost evffective on Serverless !!
Serverless computing enables developers to pay for services on a pay-as-you-go basis, charging only for usage, similar to paying for gym time instead of a monthly membership. Importantly, developers incur no costs for idle capacity, as resources are provisioned only when needed and de-provisioned afterward, reducing costs through scaling to zero.
Where to use Lambda : Event-driven apps, microservices, automated backends, IoT and real-time file processing.
Where not to use Lambda : Long-running processes, high-performance computing, steady load apps and complex state management.
Security implications : Least privilege, secure environment variables, VPC integration, IAM roles and logging.
Performance considerations : Mitigate cold starts, optimize resource allocation and manage concurrency limits.
Cost impacts : Utilize pay-per-use, leverage free tier, regular cost review and optimization.
Enough of Serverless Introduction.
Step 1 : On the search bar type Lambda and hit that to create a function.
Step 2 : Hit Create function and choose a function name then choose your suitable language then hit save and create.
Step 3 : Here is our function created.
Step 4 : Side by side we’ll create a virtual server for demonstration purpose.
Step 5 : Here we’ll see the attached EBS volume with instance.
Step 6 : Here with the volume first we’ll create a snapshot. Hitting by Action drop menu.
Step 7 : Here is our snapshot created. Now get back on the serverless function.
Step 8 : It just a example overview. You need put a few lines of python code here which i picked from Abhishek Veeramalla’s bucket. You can use it from here or you can also pick this from his bucket doesn’t matter. Overall the code says here that imported boto3 client and set a client api and using this api it will catch all the snapshots. After having a snapshot they have their volume ID or not if there is no volume ID then it will delete the snapshot if volume exist then no worry.
import boto3
def lambda_handler(event, context):
ec2 = boto3.client('ec2')
# Get all EBS snapshots
response = ec2.describe_snapshots(OwnerIds=['self'])
# Get all active EC2 instance IDs
instances_response = ec2.describe_instances(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
active_instance_ids = set()
for reservation in instances_response['Reservations']:
for instance in reservation['Instances']:
active_instance_ids.add(instance['InstanceId'])
# Iterate through each snapshot and delete if it's not attached to any volume or the volume is not attached to a running instance
for snapshot in response['Snapshots']:
snapshot_id = snapshot['SnapshotId']
volume_id = snapshot.get('VolumeId')
if not volume_id:
# Delete the snapshot if it's not attached to any volume
ec2.delete_snapshot(SnapshotId=snapshot_id)
print(f"Deleted EBS snapshot {snapshot_id} as it was not attached to any volume.")
else:
# Check if the volume still exists
try:
volume_response = ec2.describe_volumes(VolumeIds=[volume_id])
if not volume_response['Volumes'][0]['Attachments']:
ec2.delete_snapshot(SnapshotId=snapshot_id)
print(f"Deleted EBS snapshot {snapshot_id} as it was taken from a volume not attached to any running instance.")
except ec2.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidVolume.NotFound':
# The volume associated with the snapshot is not found (it might have been deleted)
ec2.delete_snapshot(SnapshotId=snapshot_id)
print(f"Deleted EBS snapshot {snapshot_id} as its associated volume was not found.")
Step 9 : Here we’ll put the above code here and try to save and test. And it is over the 3 second that means it is a timeout problem.
Step 10 : Here we tried to configure the code time-out and we increase the time at 10 second.
Step 11 : After the configuration and next is Cost-Optimization-role
Step 12 : Here the policies are defines or displayed
Step 13 : Here after the role and policies. Now we‘ll terminate virtual server named Demo-Server.
Step 14 : Here is server is free then volume wouldn’t be there then the snapshot are there.
Step 15 : Here are the functions logs it defines that there is no volume. Claim that there is a empty resources what ever we want to waiveoff.
Overall, Serverless computing is ideal for applications where users focus on business operations rather than IT management. Despite some limitations, it remains a preferred method for quick, efficient development of event-based applications, conserving resources and boosting organizational productivity and efficiency.
Subscribe to my newsletter
Read articles from RAKESH DUTTA directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
