devHọc Dev

Week 4 - Day 3: Cost Management and Optimization

Week 4 – Day 3

Learning Objectives

  • Use the right tool for each job: Cost Explorer (analysis), Budgets (control), CUR (detail), Trusted Advisor/Compute Optimizer (recommendations)
  • Compare RI vs Savings Plans vs Spot in Professional-level scenarios
  • Design multi-account cost governance (tags, SCPs, budget actions)

AWS Cost Management Overview

┌─────────────────────────────────────────────────────────────┐│AWSCOSTMANAGEMENTTOOLS││││Planning&Budgeting:││├──AWSPricingCalculator││├──AWSBudgets││└──CostAllocationTags││││Monitoring&Analysis:││├──AWSCostExplorer││├──AWSCostandUsageReport(CUR)││└──CloudWatchBillingAlarms││││Optimization:││├──AWSTrustedAdvisor││├──AWSComputeOptimizer││├──SavingsPlans││└──ReservedInstances│└─────────────────────────────────────────────────────────────┘

AWS Cost Explorer

Features

┌─────────────────────────────────────────────────────────────┐│COSTEXPLORER││││Visualization:││├──Daily,Monthly,Yearlyviews││├──Filterbyservice,region,account,tag││├──Groupbymultipledimensions││└──Customdateranges││││Analysis:││├──Identifycostdrivers││├──Detectanomalies││├──Usagepatterns││└──Resource-levelanalysis││││Forecasting:││├──Upto12monthsforecast││├──Basedonhistoricalusage││└──Confidenceintervals││││Recommendations:││├──ReservedInstancerecommendations││├──SavingsPlansrecommendations││└──Right-sizingrecommendations│└─────────────────────────────────────────────────────────────┘

Cost Explorer API

Usecases:├──Customdashboards├──Automatedreporting├──IntegrationwithBItools└──ProgrammaticcostanalysisExamplemetrics:-GetCostAndUsage-GetCostForecast-GetReservationUtilization-GetSavingsPlansCoverage

AWS Budgets

Budget Types

┌─────────────────────────────────────────────────────────────┐│AWSBUDGETSTYPES││││1.COSTBUDGET││-Trackspendingagainstbudget││-Fixedorvariableamount││-Monthly,quarterly,yearly││││2.USAGEBUDGET││-Trackresourceusage││-EC2hours,S3storage,etc.││-Preventunexpectedusage││││3.RESERVATIONBUDGET││-RIutilizationtracking││-RIcoveragetracking││-IdentifyunderutilizedRIs││││4.SAVINGSPLANSBUDGET││-SavingsPlansutilization││-Coveragepercentage││-Identifyoptimizationopportunities│└─────────────────────────────────────────────────────────────┘

Budget Actions

Automatedresponseswhenthresholdreached:Actions:├──ApplyIAMpolicy(denynewresources)├──ApplySCP(organization-wide)├──Targetrunninginstances(stopEC2)└──SNSnotificationThresholds:├──Actualcost/usage├──Forecastedcost/usage└──Multiplethresholdsperbudget

Cost Allocation Tags

Tag Strategy

┌─────────────────────────────────────────────────────────────┐│COSTALLOCATIONTAGS││││AWS-GeneratedTags:││├──aws:createdBy││├──aws:cloudformation:stack-name││└──Automaticallyapplied││││User-DefinedTags:││├──Environment(dev,staging,prod)││├──Project/Application││├──CostCenter││├──Owner/Team││└──Department││││BestPractices:││├──Definetaggingpolicy││├──EnforceviaSCPsorConfigrules││├──UseTagPoliciesinOrganizations││└──Activatetagsforcostallocation│└─────────────────────────────────────────────────────────────┘

Purchase Options Comparison

EC2 Purchase Options

┌─────────────────────────────────────────────────────────────┐│EC2PURCHASEOPTIONS││││Option│Discount│Commitment│UseCase││────────────────┼──────────┼────────────┼─────────────────││On-Demand│0%│None│Short-term,spike││Reserved(1yr)│max~40%│1year│Steadyworkload││Reserved(3yr)│max72%│3years│Long-termstable││Spot│~90%│None│Flexible,fault-│││││tolerant││SavingsPlans│66%/72%│1-3years│Compute/EC2SP││DedicatedHost│Varies│Optional│License,comply││FiguresconsistentwithWeek3Day1(detailsthere)│└─────────────────────────────────────────────────────────────┘

Reserved Instances vs Savings Plans

┌─────────────────────────────────────────────────────────────┐│RESERVEDINSTANCESvsSAVINGSPLANS││││RESERVEDINSTANCES:││├──Specificinstancetype││├──Specificregion││├──Capacityreservation(optional)││├──StandardvsConvertible││└──CansellonRIMarketplace││││SAVINGSPLANS:││├──ComputeSP:Anyinstance,anyregion││├──EC2InstanceSP:Specificfamily,anysize││├──Moreflexible││├──AppliestoLambda,Fargatetoo││└──Cannotresell││││Recommendation:││-Newworkloads→SavingsPlans(flexibility)││-ExistingRIs→Keepuntilexpiration││-Capacityneeds→ReservedInstances│└─────────────────────────────────────────────────────────────┘

Spot Instances Strategy

┌─────────────────────────────────────────────────────────────┐│SPOTINSTANCESBESTPRACTICES││││Diversification:││├──Multipleinstancetypes││├──MultipleAvailabilityZones││└──SpotFleet/EC2Fleet││││InterruptionHandling:││├──2-minutewarning(instancemetadata)││├──Checkpointing││├──Gracefulshutdownscripts││└──UseSpotwithOn-Demandfallback││││GoodUseCases:││├──Batchprocessing││├──CI/CDbuilds││├──Bigdataanalytics││├──Containerizedworkloads││└──Dev/Testenvironments││││BadUseCases:││├──Databases││├──Statefulapplications││└──Long-runningcriticaljobs│└─────────────────────────────────────────────────────────────┘

AWS Trusted Advisor

Cost Optimization Checks

┌─────────────────────────────────────────────────────────────┐│TRUSTEDADVISOR-COST││││FreeTier(Basic/Developer):││├──Servicelimits││└──Somesecuritychecks││││Business/EnterpriseSupport:││├──LowutilizationEC2instances││├──Idleloadbalancers││├──UnassociatedElasticIPs││├──UnderutilizedEBSvolumes││├──RDSidleinstances││├──ReservedInstanceoptimization││└──S3incompletemultipartuploads││││Automation:││├──TrustedAdvisorAPI││├──CloudWatchEventsintegration││└──Lambdaforauto-remediation│└─────────────────────────────────────────────────────────────┘

AWS Compute Optimizer

┌─────────────────────────────────────────────────────────────┐│COMPUTEOPTIMIZER││││Analyzes:││├──EC2instances││├──AutoScalinggroups││├──EBSvolumes││├──Lambdafunctions││└──ECSonFargate││││Recommendations:││├──Right-size(upordown)││├──Instancetypechanges││├──Costsavingsestimate││└──Performanceriskassessment││││Requirements:││├──CloudWatchmetrics≥30hoursinthelast14days││├──Opt-inrequired││└──Organization-wideviadelegatedadmin│└─────────────────────────────────────────────────────────────┘

AWS Cost Optimization Hub

Compute Optimizer, Savings Plans/RI recommendations, idle resources... each lives in its own console. Cost Optimization Hub (in Billing and Cost Management) consolidates all of those recommendations into a single list for the entire Organization, deduplicates them, and calculates estimated savings after existing discounts (RI/SP, EDP) — the real amount you would save, not list price.

Recommendationsources──▶CostOptimizationHub(management/delegatedaccount)├──ComputeOptimizer(right-size+idle:EC2/EBS/Lambda/ECS/RDS...)├──SavingsPlans/RIpurchaserecommendations└──Gravitonmigration,stopidleresource→Filterbyaccount/Region/tag,sortbysavings,exportCSV

Keyword: "single view of cost optimization opportunities across all accounts, prioritized by estimated savings after existing discounts" → Cost Optimization Hub (opt in at the management account, share with members via a delegated administrator). Rightsizing and idle recommendations in Cost Optimization Hub all come from Compute Optimizer; Trusted Advisor is not a source for Cost Optimization Hub (Trusted Advisor cost checks are a separate channel, and the full set requires Business/Enterprise Support).

S3 Cost Optimization

┌─────────────────────────────────────────────────────────────┐│S3COSTOPTIMIZATION││││StorageClasses:││├──Standard→IA→Glacier→DeepArchive││├──UseIntelligent-Tieringforunknownpatterns││└──Lifecyclepoliciesforautomatictransitions││││DataTransfer:││├──UseVPCEndpoints(noNATcosts)││├──CloudFrontforfrequentaccess││├──Same-regionaccesscheaper││└──S3TransferAccelerationwhenneeded││││RequestCosts:││├──Batchoperations││├──S3Select(queryinplace)││└──Avoidsmallfiles(combine)││││Analysis:││├──S3StorageLens││├──S3Analytics││└──StorageClassAnalysis│└─────────────────────────────────────────────────────────────┘

Multi-Account Cost Management

┌─────────────────────────────────────────────────────────────┐│ORGANIZATIONCOSTMANAGEMENT││││ConsolidatedBilling:││├──Singlepaymentmethod││├──Combinedusageforvolumediscounts││├──ShareRIsandSavingsPlansacrossaccounts││└──Detailedbillingbyaccount││││CostAllocation:││├──Linkedaccountseparation││├──Costallocationtags││├──AWSOrganizationstagpolicies││└──Customlineitems││││Controls:││├──SCPstolimitexpensiveservices││├──Budgetsperaccount/OU││├──BudgetActionsforenforcement││└──AWSServiceCatalogforapprovedresources│└─────────────────────────────────────────────────────────────┘

Exam Scenarios

Scenario 1: Unpredictable Workload Cost Control

Requirement:ControlcostsforvariableworkloadSolution:├──AWSBudgetswithalerts├──BudgetActionstostopnon-essentialresources├──SpotInstancesforfault-tolerantcomponents├──AutoScalingwithtargettracking└──S3Intelligent-Tiering

Scenario 2: Multi-Account Cost Visibility

Requirement:Trackcostsacross100accountsSolution:├──AWSOrganizationsconsolidatedbilling├──Costallocationtags(enforcedviaTagPolicies)├──CostExplorerwithaccountfilter├──CURtoS3+Athenafordetailedanalysis└──QuickSightdashboards

Scenario 3: Optimize Long-Running Workload

Requirement:Reducecostfor24/7productionworkloadSolution:├──ComputeOptimizeranalysis├──Right-sizebasedonrecommendations├──SavingsPlansforbaselinecapacity├──ReservedInstancesifcapacityguaranteeneeded└──Spotforfault-tolerantcomponents

Quick Reference

┌─────────────────────────────────────────────────────────────┐│COSTOPTIMIZATIONCHECKLIST││││ImmediateActions:││□EnableCostExplorer││□SetupAWSBudgetswithalerts││□ReviewTrustedAdvisorrecommendations││□Deleteunusedresources││││Short-term:││□Implementtaggingstrategy││□Right-sizeinstances││□Useappropriatestorageclasses││□Reviewdatatransferpatterns││││Long-term:││□PurchaseSavingsPlans││□ReservedInstancesforstableworkloads││□Spotforfault-tolerantworkloads││□Automatecostoptimization│└─────────────────────────────────────────────────────────────┘

Review Questions

  1. Compute Savings Plans vs EC2 Instance Savings Plans vs Standard RI — what criteria drive the choice?

    Show answer

    Compute SP (up to ~66%): the most flexible — applies to EC2 across any family/region + Fargate + Lambda; choose it when your compute roadmap is uncertain. EC2 Instance SP (up to ~72%): locks family + region, while size/OS/AZ can change freely — same discount as Standard RI but more flexible on size. Standard RI (up to ~72%): when you need a capacity reservation (zonal RI) or want to resell on the RI Marketplace. Keyword "also uses Fargate and Lambda" → Compute SP; "guarantee capacity in specific AZ" → zonal RI/Capacity Reservation.

  2. What can Budget Actions do that a billing alarm cannot?

    Show answer

    A billing alarm only notifies. Budget Actions intervene automatically when a threshold is crossed (actual or forecasted): (1) attach an IAM policy that denies creating new resources, (2) attach an SCP to an OU (blocking entire accounts), (3) stop specified EC2/RDS instances. They support require-approval or auto-execute mode. This is the answer for "automatically prevent further spending when budget exceeded" — not a custom-written Lambda.

  3. How does CUR differ from Cost Explorer, and when do you need it?

    Show answer

    Cost Explorer: UI/API for quick analysis, group/filter by dimension, 12-month forecast — enough for "visualize/analyze" questions. CUR (Cost and Usage Report): detailed files down to each resource-hour + tag delivered to S3 — the most complete data source, used when you need custom analytics (Athena/QuickSight), accurate per-team chargeback/showback, or invoice reconciliation. Standard pattern: CUR → S3 → Athena → QuickSight dashboard.

  4. How does RI/SP sharing work in Organizations?

    Show answer

    With consolidated billing, RI/SP discounts are shared by default across all accounts: if account A buys an RI but doesn't fully use it, the discount automatically applies to matching usage in account B. You can turn off sharing per account (for example, to separate chargeback). If a zonal RI also reserves capacity, only the purchasing account can use that capacity — only the discount is shared. W3 quiz question: sharing is on by default, NO need to enable it manually.

  5. A FinOps team wants a single list of savings opportunities across 80 accounts, sorted by actual savings after accounting for existing RIs/Savings Plans. What should they use?

    Show answer

    Cost Optimization Hub: consolidates recommendations from Compute Optimizer (rightsizing, idle) and SP/RI purchase recommendations for the entire Organization, deduplicates them, and calculates savings net of existing discounts. Compute Optimizer alone only covers compute right-sizing and uses On-Demand pricing; Trusted Advisor cost checks are scattered per account; Cost Explorer only analyzes costs already incurred and does not consolidate recommendations. Enable it in the management account or a delegated administrator for Billing.

Hands-on Exercises

  1. Budget + Budget Action: create a $10/month cost budget with 2 thresholds (80% notifies SNS, 100% automatically applies an IAM policy denying new EC2 creation to a test role); verify the role is blocked when it triggers.

  2. CUR + Athena: enable CUR (Parquet, hourly, resource IDs) to S3; use the AWS-provided CloudFormation template to create the Athena table and run a query for "top 10 resources by cost this month".

  3. Tag enforcement: create a Tag Policy in Organizations requiring the CostCenter tag, combined with an SCP denying ec2:RunInstances when the tag is missing (aws:RequestTag); test that launching an instance without the tag is denied, then activate the tag in Billing so it can be used in Cost Explorer.

References


Next lesson →