Instantly share code, notes, and snippets.

Embed
What would you like to do?
Effectively using AWS Reserved Instances

Effectively using AWS Reserved Instances

Learn how Stripe uses AWS Reserved Instances and capacity planning to effectively manage a dynamic, scalable cloud infrastructure: https://stripe.com/blog/aws-reserved-instances

Usage

Included are three files:

  • Makefile: This generates our Python environment for running the ETL.
  • reserved_instance_etl.py: This Python notebook performs an ETL job analyze the snapshot of our fleet and outputs a report of how many reserved instances to buy.
  • reserved_instance_etl.sql: This SQL query takes a snapshot of our fleet, including usage for reserved and on demand instances.

You can automate a report showing which and how many reserved instances to buy using these components.

First run reserved_instance_etl.sql on the Redshift cluster containing your cost and usage report. Save the results as a CSV. Then run the ETL, for example:

make
. venv/bin/activate
./reserved_instance_etl.py us-west-2 reserved-instance-2018-06.csv
The MIT License
Copyright (c) 2018- Stripe, Inc. (https://stripe.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
.PHONY: all
all: init lint
.PHONY: init
init: virtualenv
.PHONY: virtualenv
virtualenv: venv/bin/activate
venv/bin/pip install -U pip
venv/bin/pip install pandas flake8 isort
venv/bin/activate:
which virtualenv || pip install virtualenv
virtualenv venv
echo '*' > venv/.gitignore
.PHONY: lint
lint:
venv/bin/flake8 *.py
venv/bin/isort -y *.py
#!/usr/bin/env python
from __future__ import print_function
import argparse
import sys
from collections import defaultdict
import pandas as pd
def adjusted_reservation(ri_size):
def adjust(family):
if ri_size[family] == 1:
return '{family}.xlarge'.format(family=family)
return '{family}.{size}xlarge'.format(
family=family,
size=ri_size[family])
return adjust
def notebook(csv, region):
ri_size = defaultdict(lambda: 1)
ri_size['x1'] = 16
ri_size['p3'] = 2
df = pd.read_csv(csv, header=0, index_col=0)
df = df[df.index == region].set_index('instance_family')
df['reservation_size'] = df.index.map(lambda family: ri_size[family])
df['adj_reservation'] = df.index.map(adjusted_reservation(ri_size))
df['adj_to_purchase'] = df['to_purchase'] // df['reservation_size']
return df[['adj_reservation', 'adj_to_purchase']]
def parse_args(args):
parser = argparse.ArgumentParser(
description='Calculate reserved instances to purchase')
parser.add_argument('region', help='RI purchase region')
parser.add_argument('input', help='CSV from SQL ETL')
return parser.parse_args(args)
def main(args):
parsed_args = parse_args(args)
df = notebook(parsed_args.input, parsed_args.region)
print('## Reserved Instances to Purchase in {region}'.format(
region=parsed_args.region))
print('')
print(df)
return 0
if __name__ == '__main__':
try:
sys.exit(main(sys.argv[1:]))
except Exception as e:
print(e, file=sys.stderr)
sys.exit(1)
WITH constants AS (
-- Set these values according to your cloud strategy
SELECT
0.75 AS ri_allocation_target,
0.70 AS ri_allocation_range_lower_thresh,
0.80 AS ri_allocation_range_upper_thresh,
date_trunc('day', CURRENT_DATE - interval '4 days') AS analysis_day,
-- https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/apply_ri.html
8.0 AS base_size_normalization_factor
),
line_items AS (
-- get the base data set, filtered by time range, product, etc
SELECT
date_trunc('hour', lineitem_usagestartdate::timestamp) AS hour,
lineitem_normalizedusageamount::float /
(SELECT base_size_normalization_factor FROM constants) AS normalized_usage,
product_region AS region,
split_part(product_instancetype, '.', 1) AS instance_family,
lineitem_lineitemtype AS lineitemtype
FROM aws.cost_and_usage_201806 -- point this at your most recent cost and usage report
WHERE lineitem_productcode = 'AmazonEC2'
AND lineitem_lineitemtype IN ('Usage', 'DiscountedUsage')
AND product_instancetype <> ''
AND product_tenancy = 'Shared' -- we do not purchase RIs for Dedicated Instances
AND date_trunc('day', lineitem_usagestartdate::timestamp) = (SELECT analysis_day FROM constants)
),
total_usage AS (
-- get the usage sum by region/instance/hour family for all instances
SELECT hour, region, instance_family, SUM(normalized_usage) AS total_usage
FROM line_items
GROUP BY hour, region, instance_family
),
ri_usage AS (
-- get the usage sum by region/instance/hour for only reserved instances
SELECT region, instance_family, SUM(normalized_usage) AS reservation_usage
FROM line_items
WHERE lineitemtype = 'DiscountedUsage'
-- grab the most recent snapshot of normalized reservations, no need to aggregate here
AND hour = (SELECT analysis_day FROM constants) + interval '23 hours'
GROUP BY region, instance_family
),
minimums AS (
-- roll up into minimums by region/instance, and add zeroes
SELECT
region,
instance_family,
NVL(reservation_usage, 0.0) AS reservation_usage,
MIN(total_usage) AS total_usage -- account for workloads that scale daily
-- only purchase for usage troughs to avoid
-- unused RIs
FROM total_usage
LEFT OUTER JOIN ri_usage USING(region, instance_family)
GROUP BY region, instance_family, reservation_usage
)
-- do a little math
SELECT
region,
instance_family,
FLOOR(reservation_usage) AS normalized_reservations,
FLOOR(total_usage) AS normalized_usage,
FLOOR(
CASE
WHEN reservation_usage < (SELECT ri_allocation_range_lower_thresh FROM constants) * total_usage THEN
(SELECT ri_allocation_target FROM constants) * total_usage - reservation_usage
WHEN reservation_usage > (SELECT ri_allocation_range_upper_thresh FROM constants) * total_usage THEN
(SELECT ri_allocation_target FROM constants) * total_usage - reservation_usage
ELSE 0
END
) AS to_purchase,
TO_CHAR(100.0 * reservation_usage / total_usage, 'FM990D0%') AS ri_allocation
FROM minimums
ORDER BY region, instance_family
@smbourke

This comment has been minimized.

Show comment
Hide comment
@smbourke

smbourke Jul 3, 2018

Great Stuff! We had a similar tool up and running using the old DBR reporting so great to see how we can move this to the CUR.
I may be missing something but one thing you may want to consider in including in this solution is accounting for any RIs that are expiring as well.

smbourke commented Jul 3, 2018

Great Stuff! We had a similar tool up and running using the old DBR reporting so great to see how we can move this to the CUR.
I may be missing something but one thing you may want to consider in including in this solution is accounting for any RIs that are expiring as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment