Your dev RDS instance and ECS services run 24/7, including weekends when nobody is using them. That is money leaving your account for no reason. A Lambda function on an EventBridge schedule can stop them on Friday night and restart them Monday morning with zero intervention.
TL;DR: Use AWS Lambda + EventBridge cron schedules to automatically start and stop RDS and ECS services during off-hours, reducing costs.
Stack: AWS Lambda, EventBridge, RDS, ECS, Python, boto3, IAM
Level: Intermediate
Reading time: ~6 min
Create EventBridge cron + Lambda IAM role
Create an IAM role for the Lambda with permissions to stop/start RDS instances and update ECS services:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["rds:StopDBInstance", "rds:StartDBInstance"],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "ecs:UpdateService",
"Resource": "arn:aws:ecs:sa-east-1:YOUR_ACCOUNT:service/your-cluster/your-service"
}
]
}
Implement the Lambda
import boto3
from datetime import datetime
def lambda_handler(event, context):
now = datetime.utcnow()
current_hour = now.hour
ecs_client = boto3.client('ecs')
rds_client = boto3.client('rds')
ecs_services = [
{'cluster': 'my-cluster', 'service': 'my-service'},
]
rds_instances = ['my-db-instance']
# Business hours: 8am to 5pm UTC
if 8 <= current_hour < 17:
desired_count = 1
rds_action = 'start'
else:
desired_count = 0
rds_action = 'stop'
results = []
try:
for svc in ecs_services:
ecs_client.update_service(
cluster=svc['cluster'],
service=svc['service'],
desiredCount=desired_count
)
results.append({'service': svc['service'], 'desired_count': desired_count, 'status': 'success'})
for db in rds_instances:
if rds_action == 'stop':
rds_client.stop_db_instance(DBInstanceIdentifier=db)
else:
rds_client.start_db_instance(DBInstanceIdentifier=db)
results.append({'db': db, 'action': rds_action, 'status': 'success'})
return results
except Exception as e:
return [{'status': 'error', 'message': str(e)}]
What you've built
An automated cost-saving setup: a Lambda with the right IAM permissions, triggered by EventBridge on a cron schedule, that stops your RDS and ECS resources outside business hours and starts them again when needed. Think of it as an office manager who turns off the lights when everyone leaves.
Next steps
- Add SNS notifications so you get a Slack or email alert when the start/stop runs successfully or fails.
- Expand the Lambda to handle other costly resources: EC2 instances, Elasticache clusters, OpenSearch domains.
- Tag your resources (Environment=dev) and update the Lambda to target by tag rather than hardcoded IDs, so it works as your infrastructure grows.
Questions or feedback? Find me on LinkedIn or GitHub.