• DevOps
    Case Study

    How we built a resilient multi-account, multi-cloud solution for a Health Tech service provider!

    READ CASESTUDY
    icon

    24/7 DevOps as a Service

    Round-the-clock DevOps for uninterrupted efficiency.

    icon

    Infrastructure as a Code

    Crafting infrastructure with ingenious code.

    icon

    CI/CD Pipeline

    Automated CI/CD pipeline for seamless deployments.

    icon

    DevSecOps

    Integrated security in continuous DevOps practices.

    icon

    Hire DevOps Engineers

    Level up your team with DevOps visionaries.

    icon

    Consulting Services

    Navigate success with expert DevOps consulting.

  • TechOps
    Case Study

    How we built a scalable Odoo solution for a Travel Tech service provider!

    READ CASESTUDY

    WEB HOSTING SUPPORT

    icon

    HelpDesk Support

    Highly skilled 24/7 HelpDesk Support

    icon

    Product Support

    Boost your product support with our expertise.

    MANAGED SERVICES

    icon

    Server Management

    Don’t let server issues slow you down. Let us manage them for you.

    icon

    Server Monitoring

    Safeguard your server health with our comprehensive monitoring solutions.

    STAFF AUGMENTATION

    icon

    Hire an Admin

    Transform your business operations with our expert administrative support.

    icon

    Hire a Team

    Augment your workforce with highly skilled professionals from our diverse talent pool.

  • CloudOps
    Case Study

    How we helped a Private Deemed University in India, save US $3500/m on hosting charges!

    READ CASESTUDY
    icon

    AWS Well Architected Review

    Round-the-clock for uninterrupted efficiency

    icon

    Optimize

    Efficient CloudOps mastery for seamless cloud management

    icon

    Manage

    Automated CI/CD pipeline for seamless deployments

    icon

    Migrate

    Upgrade the journey, Migrate & Modernize seamlessly

    icon

    Modernize

    Simplify compliance complexities with our dedicated services

    icon

    FinOps as a Service

    FinOps as a Service

  • SecOps
    Case Study

    How we built a scalable Odoo solution for TravelTech service provider!

    READ CASESTUDY
    icon

    VAPT

    Vulnerability Assessment and Penetration Testing

    icon

    Source Code Review

    Ensuring source code security ans safe practices to reduce risks

    icon

    Security Consultation

    On demand services for improving server security

    icon

    System Hardening

    Reduced vulnerability and proactive protection

    icon

    Managed SoC

    Monitors and maintains system security. Quick response on incidents.

    icon

    Compliance as a Service

    Regulatory compliance, reduced risk

  • Insights
    Case Study

    How we helped a Private Deemed University in India, save US $3,500/m on hosting charges!

    READ CASESTUDY
    icon

    Blog

    Explore our latest articles and insights

    icon

    Case Studies

    Read about our client success stories

    icon

    Flipbook

    Explore our latest Flipbook

    icon

    Events

    Join us at upcoming events and conferences

    icon

    Webinars

    Watch our educational webinar series

  • Our Story
  • Contact Us

Interested to collaborate?

Get in touch with us!

Ready to elevate your business with certified cloud expertise? Contact us today to learn how our team can help you leverage cloud technology to drive growth, streamline operations, and enhance security.

  • AWSAWS
  • Azure CloudAzure Cloud
  • Google CloudGoogle Cloud
  • Akamai CloudAkamai Cloud
  • OVHOVH
  • Digital OceanDigital Ocean
  • HetznerHetzner
  • Kubernetes Consultancy Services
  • K8s & Cloud native Solutions
  • 24/7 Infrastructure Monitoring
  • DevOps as a Service
  • Cloud CI/CD Solutions
  • White Labeled MSP Support
  • Our story
  • Life@SupportSages
  • Insights
  • Careers
  • Events
  • Contact Us

Connect with us!


LinkedInFacebookXInstagramYouTube

aws partneraws advanced partner
SupportSages

Copyright © 2008 – 2026 SupportSages Pvt Ltd. All Rights Reserved.
Privacy PolicyLegal TermsData ProtectionCookie Policy
Automating RDS Instance Resizing with AWS Lambda

Automating RDS Instance Resizing with AWS Lambda

Arya P B

  • 4 min read
Automating RDS Instance Resizing with AWS Lambda

Generating audio, please wait...

In the ever-evolving landscape of cloud computing, the ability to efficiently manage and adapt database resources is crucial. This blog post details a step-by-step guide on automating the resizing of Amazon RDS instances using AWS Lambda. By leveraging predefined scaling tags and schedules, you can ensure that your RDS instances dynamically adjust to varying workloads.

Prerequisites:

Before delving into the implementation, make sure you have the following prerequisites in place:

  • AWS Account with necessary Lambda and RDS permissions.
  • RDS Instances tagged with specific keys: scale-up, scale-down, scale-up-time, and scale-down-time.

Implementation Steps:

Lambda Function Setup

  • Configure Lambda function with Python 3.10 runtime.
  • Ensure the Lambda role has RDS and DynamoDB permissions.
  • Set up CloudWatch Events for scheduled execution triggers.

Lambda Function Code:

import boto3
import datetime

rds_client = boto3.client('rds')
current_time = datetime.datetime.utcnow()
current_time_minus_30min = (current_time - datetime.timedelta(minutes=30)).strftime('%H:%M')
current_time = current_time.strftime('%H:%M')
print("time:",current_time)
dynamodb = boto3.resource('dynamodb')
table_name ='RDSlogs'
table = dynamodb.Table(table_name)

def modify_rds(new_instance_class,db_instance_identifier):
try:
rds_client.modify_db_instance(
DBInstanceIdentifier=db_instance_identifier,
DBInstanceClass=new_instance_class,
ApplyImmediately=True
)
return {
'statusCode': 200,
'body': 'Operation completed successfully'
}

except Exception as e:
print("reason:", e)
return {
'statusCode': 500,
'body': 'Error occurred'
}
def find_nearest_times(target_time_str, time_list, current_time_str):
"""Find the nearest times in the list to the target time within a 30-minute window."""
current_time = datetime.datetime.strptime(current_time_str, '%H:%M')
target_time = datetime.datetime.strptime(target_time_str, '%H:%M')
window_start_time = current_time - datetime.timedelta(minutes=30)
window_end_time = current_time + datetime.timedelta(minutes=30)

nearest_up_time = None
nearest_down_time = None
min_difference_up = float('inf')
min_difference_down = float('inf')

for time_str in time_list:
time_obj = datetime.datetime.strptime(time_str, '%H.%M')

# Check if the time is within the 30-minute window
if window_start_time <= time_obj <= window_end_time:
difference = abs((time_obj - target_time).total_seconds())

if time_obj < target_time and difference < min_difference_up:
min_difference_up = difference
nearest_up_time = time_obj

if time_obj > target_time and difference < min_difference_down:
min_difference_down = difference
nearest_down_time = time_obj

return nearest_up_time.strftime('%H.%M') if nearest_up_time else None, \
nearest_down_time.strftime('%H.%M') if nearest_down_time else None


def update_table(db_instance_identifier, current_time, new_instance_class):
dynamodb_client = boto3.client('dynamodb')
try:
dynamodb_client.put_item(
TableName=table_name,
Item={
'DBidentifier': {'S': db_instance_identifier},
'InstanceClass': {'S': new_instance_class},
'Timestamp': {'S': current_time}
}
)
print(f"Successfully wrote to DynamoDB for DB Identifier: {db_instance_identifier}")
except Exception as e:
print("Failed to write to DynamoDB:", str(e))

def lambda_handler(event, context):
print("event:",event)
response = rds_client.describe_db_instances()
print(response)
for i in response['DBInstances']:
db_instance_name = i['DBInstanceIdentifier']
print(db_instance_name)
each_response = rds_client.describe_db_instances(DBInstanceIdentifier=db_instance_name)
print(response)
db_instance_class = each_response['DBInstances'][0]['DBInstanceClass']
up_value = None
down_value = None
scale_down_time_value = None

for tag in response['DBInstances'][0]['TagList']:
if tag['Key'] == 'scale-up':
up_value = tag['Value']
elif tag['Key'] == 'scale-down':
down_value = tag['Value']
elif tag['Key'] == 'scale-up-time':
scale_up_time_value = tag['Value']
elif tag['Key'] == 'scale-down-time':
scale_down_time_value = tag['Value']

# Print the obtained scale values
print("Scale Up Value:", up_value)
print("Scale Down Value:", down_value)
up_time_part = scale_up_time_value.split('/')
down_time_part= scale_down_time_value.split('/')

nearest_up_time, nearest_down_time = find_nearest_times(current_time, up_time_part + down_time_part, current_time)

print("Nearest Scale Up Time within 30 minutes:", nearest_up_time)
print("Nearest Scale Down Time within 30 minutes:", nearest_down_time)

for up_time, down_time in zip(up_time_part, down_time_part):
print(up_time)
if nearest_up_time and nearest_up_time == up_time and db_instance_class == down_value:
new_instance_class = up_value
modify_rds(new_instance_class,db_instance_name)
update_table(db_instance_name, current_time, new_instance_class)


elif nearest_up_time and nearest_up_time == down_time and db_instance_class == up_value:
new_instance_class = down_value
modify_rds(new_instance_class,db_instance_name)
update_table(db_instance_name, current_time, new_instance_class)
  • Utilize the provided Python code with Boto3 for RDS and DynamoDB interactions.
  • The code includes functions for modifying RDS instance class, finding nearest times within a 30-minute window, and updating DynamoDB logs.

Testing:

  • Manually trigger the Lambda function and observe logs.
  • Verify the correct identification of RDS instance class and successful execution of resizing operations.

Scheduling:

  • Set up a recurring CloudWatch Events rule for periodic Lambda execution.
  • Use a cron expression for desired intervals (e.g., cron(0 0 * * ? *) for daily execution).
  1. RDS Tags:
  • Tag RDS instances with specific keys and values:
  • scale-up: Target instance class for scale-up.
  • scale-down: Target instance class for scale-down.
  • scale-up-time: Time window for scale-up operations (e.g., 17:51/01:10).
  • scale-down-time: Time window for scale-down operations (e.g., 17:00/02:30).

Conclusion:

Automating the resizing of your RDS instances based on workload demands streamlines database management in your AWS environment. The combination of AWS Lambda, RDS, and DynamoDB creates a powerful solution that adapts to changing requirements without manual intervention.

Take control of your RDS costs and ensure optimal performance by automating database scaling! This blog provided a step-by-step guide using AWS Lambda, RDS, and DynamoDB. Implement the Python code we shared to automatically resize your RDS instances based on predefined tags and schedules. Start saving money and improve efficiency today!

  • AWS
  • DevOps

Continue Your Journey With…

DevOps as a Service

DevOps as a Service

Let us do the heavy lifting for you

Promotional banner
Promotional banner

Analyzing AWS IAM Users: Access Key and Password Age

Analyzing AWS IAM Users: Access Key and Password Age
  • DevOps
logo

Analyzing AWS IAM Users: Access Key and Password Age

Analyzing AWS IAM Users: Access Key and Password Age
  • AWS
  • DevOps
logo

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide
  • DevOps
logo

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide
  • AWS
  • DevOps
logo

Posts by Arya P B

Athena