Skip to Content
Cloud Engineering Academy
1. Cloud Computing & AWS Fundamentals

Pricing models: On-Demand, Savings Plans, Reserved Instances and Spot

Choose the right way to pay for AWS compute and databases for each kind of banking workload, and look up real prices from the console, the CLI and C#.

beginnerโฑ 1 h 15 min๐ŸŸข FreeCLF-C02SAA-C03

Assumes: .NET 10 LTS ยท AWS SDK for .NET v4 (AWSSDK.Pricing 4.1.0.2) ยท AWS CLI v2 ยท Region us-east-1 ยท prices from the AWS Price List files published 2026-11-13 to 2026-11-17. Verified against official sources on 2026-11-17.

Learning objectives

By the end of this lesson you can:

  • Name the three things AWS mostly charges for (compute time, storage, data transfer out) and explain why data coming in is usually free.
  • Compare On-Demand, Savings Plans (Compute, EC2 Instance, Database, SageMaker AI), Reserved Instances (Standard, Convertible, regional, zonal) and Spot Instances, and pick one for a given workload.
  • Explain why Windows and SQL Server licences change the maths, and where Dedicated Hosts and bring-your-own-licence (BYOL) fit.
  • Read a tiered price (data transfer, Lambda) and a serverless price (requests plus GB-seconds).
  • Look up a live price with the AWS Price List Query API from the CLI and from C#.

Prerequisites

Why this matters in banking

Harbourline Bank's first AWS invoice after a pilot surprised the finance team. The statement portal ran on On-Demand EC2 around the clock for a whole year. A one-year Savings Plan sized to the always-on web tier would have cut that line by roughly a quarter, at no extra risk. The opposite mistake happened too: a well-meaning engineer bought a three-year commitment for a nightly batch job that was replaced by Lambda six months later, so the bank kept paying for capacity it no longer used.

Pricing models are not just a finance topic. They influence architecture: Spot only works if your code can survive being stopped with two minutes' warning, and a Savings Plan only pays off if the baseline load is genuinely steady. Banks also need to forecast spend for budgeting cycles and regulatory capital planning, so being able to explain "why this costs what it costs" is part of an engineer's job.

The idea in plain language

AWS rents you computers, storage and network by the second, the hour, the gigabyte or the request. How you agree to pay changes the price:

  • On-Demand โ€” the walk-in rate. No commitment, highest price, stop any time.
  • Savings Plans โ€” you promise to spend a fixed amount per hour (for example USD 1.50/hour) for one or three years. Any eligible usage up to that amount is billed at a discounted rate. You pay the promise whether you use it or not.
  • Reserved Instances (RIs) โ€” an older commitment model: you commit to a specific instance type (or database class) in a Region for one or three years.
  • Spot Instances โ€” spare EC2 capacity at a big discount, which AWS can take back with a two-minute warning.

Analogy: Think of Harbourline's staff canteen. On-Demand is paying full price per meal at the till. A Savings Plan is a meal card where you promise to load GBP 5 every working day for a year in exchange for a discount on whatever you eat โ€” any dish counts, but unspent money is gone. A Reserved Instance is pre-booking "the same pasta dish every day for a year". Spot is the end-of-day reduced counter: very cheap, but staff can clear your plate when the kitchen needs it back.

What problem each pricing model solves

What AWS charges for

Almost every bill is made of three ingredients:

IngredientExamplesTypical unit
ComputeEC2 instances, Fargate tasks, Lambda invocations, RDS instancesPer second (60-second minimum on EC2), per hour, per GB-second, per request
StorageS3 objects, EBS volumes, RDS storage, backupsPer GB-month (prorated)
Data transferData leaving AWS to the internet, between Regions, between Availability ZonesPer GB

Data transfer into AWS from the internet is free. In the us-east-1 price list (published 2026-11-17) the line reads USD 0.000 per GB for data in, while data out to the internet costs USD 0.09 per GB for the first 10 TB in a month, after a 100 GB per month free allowance that is shared across all services and Regions. Traffic between Availability Zones in the same Region costs USD 0.01 per GB in each direction. This asymmetry is deliberate: it is cheap to move data in and expensive to move it out, which is why architects watch egress closely.

Tiered pricing

Many prices get cheaper as volume grows. Two examples from the us-east-1 price list:

ServiceTierPrice
Data transfer out to the internetFirst 10 TB per month (after the free 100 GB)USD 0.090 per GB
Next 40 TBUSD 0.085 per GB
Next 100 TBUSD 0.070 per GB
Over 150 TBUSD 0.050 per GB
Lambda compute (x86)First 6 billion GB-seconds per monthUSD 0.0000166667 per GB-second
Next 9 billion GB-secondsUSD 0.0000150000
Over 15 billion GB-secondsUSD 0.0000133334

Tiers usually apply per account, or across the whole organisation when accounts share consolidated billing โ€” one reason banks group accounts under AWS Organizations (Accounts and Organizations).

Serverless pricing

Serverless services charge for work done rather than for servers running. For Lambda in us-east-1:

  • Requests: USD 0.20 per million.
  • Compute: memory ร— duration, in GB-seconds. x86 costs USD 0.0000166667 per GB-second; Arm (Graviton) costs USD 0.0000133334 โ€” about 20% less.
  • Always free: 1 million requests and 400,000 GB-seconds per month.

Worked example: a statement-notification function with 512 MB of memory runs for 200 ms, 3 million times a month. Compute = 3,000,000 ร— 0.2 s ร— 0.5 GB = 300,000 GB-seconds, which is inside the free 400,000. Requests = 3 million โˆ’ 1 million free = 2 million ร— USD 0.20 = USD 0.40 a month.

On-Demand

  • What it is: the list price. EC2 Linux, Windows, Red Hat and Ubuntu instances bill per second with a 60-second minimum.
  • When to use it: new workloads whose shape you don't know yet, spiky or short-lived work, anything you might delete next month.
  • Limitations: it is the most expensive way to run steady workloads. On-Demand also does not guarantee capacity; if you need guaranteed capacity in one Availability Zone, you buy an On-Demand Capacity Reservation (billed whether used or not).

Savings Plans

A Savings Plan is a commitment to a dollar amount of usage per hour for 1 year (365 days) or 3 years (1,095 days). You pay All Upfront, Partial Upfront or No Upfront; more upfront and longer terms give bigger discounts. Four types exist (checked on 2026-11-17):

TypeApplies toFlexibilityMaximum discount stated by AWS
Compute Savings PlansEC2, Fargate and LambdaAny instance family, size, OS, tenancy or RegionUp to 66%
EC2 Instance Savings PlansEC2 onlyOne instance family in one Region (for example m7i in us-east-1); any size, OS, tenancy within itUp to 72%
Database Savings Plans (launched 2 December 2025)Aurora, RDS, DynamoDB, ElastiCache, DocumentDB, Neptune, Keyspaces, Timestream, DMS, OpenSearch ServiceAny engine, instance family, size, AZ or Region; also serverless usage. 1-year term, no upfrontUp to 35%
SageMaker AI Savings PlansSageMaker AI instancesAny family, size, Region or componentUp to 64%

Things to know:

  • The commitment is per hour, every hour. If you commit USD 1.00/hour and use only USD 0.40 in a given hour, you still pay USD 1.00 for that hour. Unused commitment does not roll over.
  • It is applied automatically to matching usage, starting with the usage that gets the highest discount.
  • It cannot be cancelled or changed after purchase. You can buy additional plans later.
  • Licence fees are not discounted. The Windows or SQL Server portion of an EC2 price stays at the full rate (see the worked example below).
  • Accounts on the AWS Free plan cannot buy Savings Plans or Reserved Instances (Free Tier and billing).
  • Cost Explorer shows Savings Plans recommendations based on your recent usage, and AWS Compute Optimizer suggests right-sizing. Right-size first, then commit โ€” committing to an oversized instance locks in waste.

Reserved Instances

AWS's own EC2 documentation now says it recommends Savings Plans over Reserved Instances for EC2. You still need to understand RIs because they are on the exam, many existing estates use them, and some services (RDS, ElastiCache, OpenSearch, Redshift) still offer reserved pricing.

  • Not a server. An RI is a billing discount applied to matching running instances.
  • Attributes: instance type, Region, tenancy and platform (OS).
  • Term: 1 or 3 years. RIs do not renew automatically; when they expire you silently go back to On-Demand rates.
  • Payment: All Upfront, Partial Upfront, No Upfront.
  • Offering class:
    • Standard โ€” bigger discount; can be modified but not exchanged; can be sold on the Reserved Instance Marketplace.
    • Convertible โ€” smaller discount; can be exchanged for another Convertible RI with a different family, OS or tenancy; cannot be sold on the Marketplace.
  • Scope:
    • Regional โ€” discount applies in any AZ of the Region and (for Linux, default tenancy) across sizes in the family. Does not reserve capacity.
    • Zonal โ€” applies in one AZ, one size, and does reserve capacity there.

Spot Instances

  • What it is: spare EC2 capacity, priced by long-term supply and demand (there is no bidding any more), at up to 90% off On-Demand according to AWS.
  • The catch: AWS can reclaim the instance. You get an interruption notice two minutes before it is stopped or terminated, available as an EventBridge event (EC2 Spot Instance Interruption Warning) and in instance metadata at spot/instance-action.
  • Good fit: stateless, restartable, checkpointed work โ€” Harbourline's nightly rendering of PDF statements, test environments, CI build agents, data-lake batch jobs.
  • Bad fit: the core ledger database, payment authorisation, anything holding state that can't be rebuilt quickly, or work with a hard regulatory deadline unless you keep an On-Demand fallback.
  • Spot prices are not in the Price List API; view them in the EC2 console (Spot Requests โ†’ Pricing history) or with aws ec2 describe-spot-price-history.

Dedicated Hosts, Dedicated Instances and licensing

  • Dedicated Instances run on hardware dedicated to your account, billed per instance plus a per-Region fee (USD 2/hour while at least one Dedicated Instance is running โ€” and this fee is not covered by Savings Plans).
  • Dedicated Hosts give you a whole physical server whose sockets and cores you can see. That visibility matters for server-bound licences such as Windows Server or SQL Server licences without Software Assurance.

Microsoft licensing in one paragraph (always confirm with your licensing team):

  • License Included (LI) is the default. The hourly price includes the Windows or SQL Server licence. There is no licence paperwork, but it is expensive at scale.
  • Windows Server BYOL is only allowed on Dedicated Hosts, and only for licences bought before 1 October 2019 (or added as a true-up under an earlier agreement). Windows Server is not eligible for License Mobility.
  • SQL Server with active Software Assurance can use License Mobility on shared (default) tenancy EC2.
  • SQL Server without Software Assurance must go on Dedicated Hosts, with version restrictions.
  • Amazon RDS for SQL Server supports License Included (Enterprise, Standard, Web, Express) and Bring Your Own Media (Enterprise, Standard and Developer). BYOM needs Software Assurance with License Mobility rights. Developer Edition is free but for non-production use only.
  • AWS License Manager tracks licence usage on Dedicated Hosts.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Pay-as-you-go VMsOn-Demand InstancesEC2 bills per second (60-second minimum) for Linux and Windows
Azure Reservations (VMs, SQL Database)Reserved Instances (EC2, RDS, ElastiCache, OpenSearch, Redshift)AWS recommends Savings Plans over EC2 RIs; Standard RIs can be resold on the RI Marketplace
Azure savings plan for computeCompute Savings PlansVery similar idea (hourly spend commitment); AWS's also covers Lambda and Fargate
โ€” (no direct equivalent)EC2 Instance Savings Plans, Database Savings PlansNarrower scope buys a bigger discount (EC2 Instance) or covers managed databases (Database)
Azure Spot VMs (30-second eviction notice)EC2 Spot Instances (two-minute notice)No bidding on AWS; price moves gradually with supply and demand
Azure Hybrid Benefit (reuse Windows/SQL licences on shared Azure hosts)BYOL on Dedicated Hosts, License Mobility for SQL Server with SA, RDS BYOMThere is no general "hybrid benefit" for Windows Server on shared AWS tenancy; budget for License Included unless your licensing team confirms otherwise
Azure Dedicated HostEC2 Dedicated HostsBoth are used mainly for licensing and isolation requirements
Azure Pricing CalculatorAWS Pricing Calculator (public site) and in-console Pricing CalculatorThe in-console version can apply your own discounts and commitments
Azure Retail Prices APIAWS Price List Query API and Bulk APIAWS's API needs a signed request (IAM permission pricing:GetProducts)
Azure Advisor reservation recommendationsCost Explorer Savings Plans/RI recommendations, Compute OptimizerSame pattern: recommendations from your last 7, 30 or 60 days of usage โš  VERIFY look-back options

Architecture

How Harbourline should map workloads to pricing models:

How a Savings Plan is applied each hour:

The second hour is the trap: a commitment sized for the busy hours is partly wasted every quiet hour. Size commitments to the minimum steady load, not to the peak.

Step-by-step implementation

This lesson changes nothing in your account. You will look up prices and model a decision.

Classify each workload

List Harbourline's statement-portal components and put each in one of four buckets: steady 24ร—7, spiky or unknown, interruptible, event-driven. Use the architecture diagram above as a guide.

Find the On-Demand price

Use the AWS CLI or the C# program below to get the On-Demand hourly price of m7i.large Linux in us-east-1. Multiply by 730 (AWS's standard hours per month) for a monthly figure.

Compare commitment options

Open the Savings Plans pricing page for the same instance and Region and note the 1-year No Upfront and 3-year All Upfront rates for both Compute and EC2 Instance Savings Plans. Compare them with the worked example table below.

Check the Spot price history

In the sandbox: Console โ†’ EC2 โ†’ Instances โ†’ Spot Requests โ†’ Pricing history, pick m7i.large, Linux/UNIX, last 30 days. Note the range across Availability Zones.

Write a one-line decision per workload

For example: "Web tier: Compute Savings Plan 1-year No Upfront for 2 instances; month-end peak On-Demand." Keep these for the pricing calculator lab.

Worked example: one m7i.large in us-east-1

Prices below come from the AWS Price List files published on 2026-11-14 (On-Demand) and 2026-11-17 (Savings Plans). The Spot figure is a single snapshot taken on 2026-11-17 and changes constantly. Monthly = hourly ร— 730.

Pricing option (Linux, shared tenancy)Effective USD/hourUSD/monthSaving vs On-Demand
On-Demand0.100873.58โ€”
Compute Savings Plan, 1-year, No Upfront0.0740654.0626.5%
EC2 Instance Savings Plan (m7i), 1-year, No Upfront0.0666848.6833.8%
Compute Savings Plan, 3-year, No Upfront0.0511237.3249.3%
EC2 Instance Savings Plan (m7i), 3-year, All Upfront0.0398029.0560.5%
Spot (snapshot 2026-11-17, varies by AZ and hour)about 0.0449about 32.78about 55%

Now the same instance with Windows Server License Included:

OptionUSD/hourUSD/monthSaving
On-Demand Windows0.1928140.74โ€”
Compute Savings Plan, 1-year, No Upfront0.16606121.2213.9%

Look at the difference between the two tables. The Linux saving per hour is USD 0.02674, and the Windows saving is exactly the same USD 0.02674. The Windows licence portion (about USD 0.092/hour) is not discounted, so the percentage saving halves. Add SQL Server Standard License Included and the On-Demand price for the same instance rises to USD 0.6728/hour โ€” the licence becomes the dominant cost. This is why Microsoft-heavy banks spend so much effort on licensing strategy, Graviton/Linux migration and moving SQL Server workloads to PostgreSQL (Module 13 covers this).

AWS Console instructions

All read-only; nothing here costs money.

  • Savings Plans recommendations: Console โ†’ Billing and Cost Management โ†’ Savings Plans โ†’ Recommendations. Choose type, term, payment option and look-back period. In a brand-new sandbox there is no usage history, so expect no recommendation.
  • Reserved Instance recommendations: Billing and Cost Management โ†’ Reservations โ†’ Recommendations.
  • Spot price history: EC2 โ†’ Spot Requests โ†’ Pricing history.
  • Right-sizing: AWS Compute Optimizer โ†’ opt in (free for the standard recommendations โš  VERIFY current pricing of enhanced features) โ†’ view EC2 recommendations.
  • Existing commitments: Billing and Cost Management โ†’ Savings Plans โ†’ Inventory, and Reservations โ†’ Inventory (or the EC2 console โ†’ Reserved Instances).

Purchasing is under the same menus. Do not buy anything in this course. Commitments cannot be cancelled.

AWS CLI

The Price List Query API is served from only three endpoints: us-east-1, eu-central-1 and ap-south-1. The endpoint you call has nothing to do with the Region whose prices you want โ€” a Frankfurt price can be read from the us-east-1 endpoint.

# List the attribute names you can filter EC2 products on (instanceType, regionCode, operatingSystem, ...).
aws pricing describe-services --service-code AmazonEC2 --region us-east-1 --profile learn-sandbox

# Show valid values for one attribute, e.g. all operating-system labels.
aws pricing get-attribute-values --service-code AmazonEC2 --attribute-name operatingSystem --region us-east-1 --profile learn-sandbox

# Get the On-Demand Linux product for m7i.large in us-east-1.
# All filters are ANDed. capacitystatus=Used and preInstalledSw=NA remove capacity-reservation and SQL variants.
aws pricing get-products --service-code AmazonEC2 --region us-east-1 --profile learn-sandbox `
  --filters Type=TERM_MATCH,Field=instanceType,Value=m7i.large `
            Type=TERM_MATCH,Field=regionCode,Value=us-east-1 `
            Type=TERM_MATCH,Field=operatingSystem,Value=Linux `
            Type=TERM_MATCH,Field=tenancy,Value=Shared `
            Type=TERM_MATCH,Field=preInstalledSw,Value=NA `
            Type=TERM_MATCH,Field=capacitystatus,Value=Used `
  --max-results 1 --query "PriceList[0]" --output text > m7i.json

# Each PriceList entry is a JSON document stored as a string, so parse it in PowerShell.
$p = Get-Content m7i.json -Raw | ConvertFrom-Json
$p.terms.OnDemand.PSObject.Properties.Value.priceDimensions.PSObject.Properties.Value |
  Select-Object description, @{n='USD';e={$_.pricePerUnit.USD}}

# Spot price history is NOT in the Price List API; use EC2 instead (last 10 data points).
aws ec2 describe-spot-price-history --instance-types m7i.large --product-descriptions "Linux/UNIX" `
  --max-items 10 --region us-east-1 --profile learn-sandbox `
  --query "SpotPriceHistory[].[AvailabilityZone,SpotPrice,Timestamp]" --output table

# Your own Savings Plans and RIs (empty in a new sandbox).
aws savingsplans describe-savings-plans --region us-east-1 --profile learn-sandbox
aws ec2 describe-reserved-instances --region us-east-1 --profile learn-sandbox

The PowerShell backtick at the end of a line continues the command; in Git Bash use \ instead.

Infrastructure as Code

Pricing models show up in code in one place: how instances are launched. Savings Plans and RIs are pure billing constructs โ€” you never declare them in IaC; they apply automatically to matching usage. Spot, on the other hand, is a launch option. The templates below create two launch templates for the statement worker, one On-Demand and one Spot. Launch templates themselves are free, and no instance is started.

StatementWorkerTemplateStack.cs
using Amazon.CDK;
using Amazon.CDK.AWS.EC2;
using Constructs;

namespace Harbourline.Learn.Pricing;

public sealed class StatementWorkerTemplateStack : Stack
{
    public StatementWorkerTemplateStack(Construct scope, string id, IStackProps? props = null)
        : base(scope, id, props)
    {
        // Same instance type, two purchase options: the pricing model is a launch-time setting.
        _ = new LaunchTemplate(this, "OnDemandWorker", new LaunchTemplateProps
        {
            LaunchTemplateName = "hl-m01-statement-worker-ondemand",
            InstanceType = new InstanceType("m7i.large"),
            MachineImage = MachineImage.LatestAmazonLinux2023(),
            RequireImdsv2 = true,
        });

        _ = new LaunchTemplate(this, "SpotWorker", new LaunchTemplateProps
        {
            LaunchTemplateName = "hl-m01-statement-worker-spot",
            InstanceType = new InstanceType("m7i.large"),
            MachineImage = MachineImage.LatestAmazonLinux2023(),
            RequireImdsv2 = true,
            SpotOptions = new LaunchTemplateSpotOptions
            {
                RequestType = SpotRequestType.ONE_TIME,
                InterruptionBehavior = SpotInstanceInterruption.TERMINATE,
            },
        });

        // Inside a Stack, "Tags" is the stack's own TagManager property, so qualify the static class.
        Amazon.CDK.Tags.Of(this).Add("Project", "cea-lab");
        Amazon.CDK.Tags.Of(this).Add("Lab", "m01-pricing");
        Amazon.CDK.Tags.Of(this).Add("Environment", "learn");
        Amazon.CDK.Tags.Of(this).Add("Owner", "your-name");
    }
}

This compiles against Amazon.CDK.Lib 2.277.0 (checked in a .NET 10 container on 2026-11-17).

In production you would not hard-code one market type. An EC2 Auto Scaling group with a mixed instances policy (Module 12) can keep, say, 20% On-Demand as a floor and fill the rest with Spot across several instance types, which greatly reduces the chance of all workers being interrupted at once.

Complete code

A .NET 10 file-based app (no project file needed) that reads the On-Demand price of an instance type through the Price List Query API. It uses your SSO profile, so run aws sso login --profile learn-sandbox first. It only reads public price data and costs nothing.

GetEc2Price.cs
#:package AWSSDK.Pricing@4.1.0.2
#:package AWSSDK.SSO@4.1.0.2
#:package AWSSDK.SSOOIDC@4.1.0.2
#:property TreatWarningsAsErrors=true
#:property Nullable=enable

// Looks up the public On-Demand hourly price of one EC2 instance type
// using the AWS Price List Query API. Read-only; costs nothing.
using System.Globalization;
using System.Text.Json;
using Amazon;
using Amazon.Pricing;
using Amazon.Pricing.Model;
using Amazon.Runtime.CredentialManagement;

var instanceType = args.Length > 0 ? args[0] : "m7i.large";
var regionCode = args.Length > 1 ? args[1] : "us-east-1";
var operatingSystem = args.Length > 2 ? args[2] : "Linux";

// The Price List API is served from a few endpoints only (us-east-1, eu-central-1, ap-south-1).
// The endpoint Region has nothing to do with the Region whose prices you want.
var chain = new CredentialProfileStoreChain();
if (!chain.TryGetAWSCredentials("learn-sandbox", out var credentials))
{
    Console.Error.WriteLine("Profile 'learn-sandbox' not found. Run: aws configure sso");
    return 2;
}

using var pricing = new AmazonPricingClient(credentials, RegionEndpoint.USEast1);

var request = new GetProductsRequest
{
    ServiceCode = "AmazonEC2",
    MaxResults = 10,
    Filters =
    [
        new Filter { Type = FilterType.TERM_MATCH, Field = "instanceType", Value = instanceType },
        new Filter { Type = FilterType.TERM_MATCH, Field = "regionCode", Value = regionCode },
        new Filter { Type = FilterType.TERM_MATCH, Field = "operatingSystem", Value = operatingSystem },
        new Filter { Type = FilterType.TERM_MATCH, Field = "tenancy", Value = "Shared" },
        new Filter { Type = FilterType.TERM_MATCH, Field = "preInstalledSw", Value = "NA" },
        new Filter { Type = FilterType.TERM_MATCH, Field = "capacitystatus", Value = "Used" },
        new Filter { Type = FilterType.TERM_MATCH, Field = "licenseModel", Value = "No License required" },
    ],
};

var response = await pricing.GetProductsAsync(request);

// SDK v4: collections are null (not empty) when nothing matched.
foreach (var productJson in response.PriceList ?? [])
{
    using var doc = JsonDocument.Parse(productJson);
    var root = doc.RootElement;
    var sku = root.GetProperty("product").GetProperty("sku").GetString();

    // terms -> OnDemand -> {offerTermCode} -> priceDimensions -> {rateCode} -> pricePerUnit -> USD
    foreach (var term in root.GetProperty("terms").GetProperty("OnDemand").EnumerateObject())
    {
        foreach (var dimension in term.Value.GetProperty("priceDimensions").EnumerateObject())
        {
            var usd = dimension.Value.GetProperty("pricePerUnit").GetProperty("USD").GetString() ?? "0";
            var hourly = decimal.Parse(usd, CultureInfo.InvariantCulture); // money is decimal, never double
            var monthly = hourly * 730m; // AWS estimates use 730 hours per month
            Console.WriteLine($"{instanceType} {operatingSystem} {regionCode} SKU {sku}: {hourly:0.0000} USD/hour = ~{monthly:0.00} USD/month");
        }
    }
}

return 0;

Run it:

aws sso login --profile learn-sandbox
dotnet run GetEc2Price.cs
dotnet run GetEc2Price.cs -- m8g.large us-east-1 Linux
dotnet run GetEc2Price.cs -- m7i.large eu-west-2 Windows

Expected output for the first run (price as of 2026-11-14):

m7i.large Linux us-east-1 SKU <sku>: 0.1008 USD/hour = ~73.58 USD/month

The program was compiled in the mcr.microsoft.com/dotnet/sdk:10.0 container on 2026-11-17. For Windows, the licenseModel filter still says No License required because the licence is bundled into the Windows product; if you get no results for other combinations, remove that filter and inspect what comes back.

Code explained line by line

  1. #:package AWSSDK.Pricing@4.1.0.2 โ€” .NET 10 file-based apps declare NuGet packages inline. AWSSDK.Pricing is the Price List client in SDK v4.
  2. #:package AWSSDK.SSO / AWSSDK.SSOOIDC โ€” needed at runtime so the SDK can turn an Identity Center profile into credentials. Without them the code compiles but fails when the profile loads.
  3. #:property TreatWarningsAsErrors=true and Nullable=enable โ€” the same strictness as every lab in this course.
  4. args.Length > 0 ? args[0] : "m7i.large" โ€” optional positional arguments: instance type, Region code, operating system.
  5. new CredentialProfileStoreChain() โ€” reads %USERPROFILE%\.aws\config and credentials, the same files the CLI uses.
  6. TryGetAWSCredentials("learn-sandbox", ...) โ€” builds SSO credentials from the cached token created by aws sso login.
  7. new AmazonPricingClient(credentials, RegionEndpoint.USEast1) โ€” the pricing endpoint. It must be us-east-1, eu-central-1 or ap-south-1; any other Region fails to resolve.
  8. ServiceCode = "AmazonEC2" โ€” the service whose price list you query. Others include AmazonRDS, AmazonS3, AWSLambda.
  9. Filters = [...] โ€” C# 12 collection expression creating a List<Filter>. Every filter must match (AND logic).
  10. FilterType.TERM_MATCH โ€” exact match on an attribute value. capacitystatus = Used excludes capacity-reservation SKUs; preInstalledSw = NA excludes "Windows with SQL Server" variants; tenancy = Shared excludes dedicated tenancy.
  11. await pricing.GetProductsAsync(request) โ€” one signed HTTPS call; needs IAM permission pricing:GetProducts.
  12. response.PriceList ?? [] โ€” SDK v4 returns null instead of an empty list when there are no results.
  13. JsonDocument.Parse(productJson) โ€” each entry is a full JSON document in a string.
  14. GetProperty("terms").GetProperty("OnDemand") โ€” price terms are keyed by generated codes, so we enumerate rather than hard-code them. Reserved terms appear under "Reserved". Savings Plans rates are not returned by this API.
  15. decimal.Parse(usd, CultureInfo.InvariantCulture) โ€” money as decimal, parsed culture-independently (a UK or German PC would otherwise misread the decimal separator).
  16. hourly * 730m โ€” AWS's calculator convention for a month (8,760 hours รท 12).

Security considerations

  • The Price List API returns public data, but the call is still signed and logged in CloudTrail. Grant pricing:GetProducts, pricing:DescribeServices and pricing:GetAttributeValues only, not *.
  • Purchasing commitments is a privileged financial action. In a bank, savingsplans:CreateSavingsPlan and ec2:PurchaseReservedInstancesOffering should be limited to a FinOps role in the management account, ideally with an approval step. Deny them in developer permission sets with an SCP (Module 15).
  • Spot and data security: an interrupted Spot worker may leave partly written files. Write output to S3 with server-side encryption and use idempotent processing, so a re-run never produces a duplicate or half-finished customer statement.
  • Spot instances run on the same hardware and isolation as On-Demand. Spot is a pricing model, not a weaker security tier.

โš  Learning shortcut โ€” not for production

The C# sample hard-codes the learn-sandbox profile and uses your SandboxAdmin session, which has far more permission than it needs. In production, a cost-reporting service would run under an IAM role whose policy allows only the three pricing: read actions, and it would cache results (prices change rarely) instead of calling the API on every request.

โš  Learning shortcut โ€” not for production

The worked example compares single instances. Real commitment decisions use at least 30โ€“60 days of Cost Explorer data across the whole organisation, factor in planned migrations (for example Windows to Linux, x86 to Graviton) and are approved by finance. Never buy a commitment from a lesson table.

Banking use case

Harbourline Bank's platform team publishes a "pricing policy" that every new service follows:

  1. Weeks 0โ€“8: run On-Demand. Tag everything (CostCentre, Application, Environment) so Cost Explorer can attribute spend.
  2. After 60 days of stable usage: FinOps reviews Cost Explorer recommendations and buys Compute Savings Plans (1-year, No Upfront) covering about 70โ€“80% of the organisation-wide steady baseline. Compute rather than EC2 Instance plans are chosen because the bank is moving .NET services from EC2 to Fargate and from x86 to Graviton, and Compute plans follow that move.
  3. Databases: the core customer database on RDS PostgreSQL gets a Database Savings Plan. SQL Server instances still on License Included are flagged for review, because the licence is the biggest line on their bill.
  4. Batch: nightly statement rendering, reconciliation report generation and data-lake compaction run on Spot with an On-Demand floor and checkpointing. Each job writes results to S3 using idempotency keys, so an interruption costs only a re-run.
  5. Never Spot: payment authorisation, the ledger, sanctions screening and anything on the critical path for Faster Payments (FPS) settlement deadlines.

Whether a commitment is acceptable from a third-party-risk or exit-planning perspective (for example under PRA outsourcing expectations) is decided by the bank's risk and procurement teams, not by engineering alone.

Common mistakes

  • Sizing a Savings Plan to peak usage โ†’ you look at the busiest hour โ†’ every quiet hour wastes the unused commitment. Size to the minimum steady baseline.
  • Buying EC2 Instance Savings Plans or Standard RIs just before a migration โ†’ the bigger discount is tempting โ†’ you lock in an instance family or Region you are about to leave. Prefer Compute Savings Plans when change is planned.
  • Forgetting RIs expire silently โ†’ there is no auto-renew โ†’ costs jump back to On-Demand. Set expiry alerts (AWS Budgets has RI and Savings Plans coverage and utilisation budgets).
  • Expecting a Savings Plan to discount Windows or SQL Server licences โ†’ the percentages on marketing pages are for the compute portion โ†’ licence-heavy workloads save much less.
  • Assuming Azure Hybrid Benefit works the same on AWS โ†’ it doesn't โ†’ Windows Server BYOL needs Dedicated Hosts and pre-2019 licences.
  • Running stateful or deadline-critical work on Spot โ†’ the discount is attractive โ†’ a two-minute interruption at the wrong moment causes missed settlement or data loss.
  • Ignoring data transfer โ†’ estimates only include instances โ†’ cross-AZ chatter and internet egress quietly add up.
  • Committing before right-sizing โ†’ you lock in waste for one or three years. Use Compute Optimizer first.

Troubleshooting

SymptomLikely causeFix
Could not connect to the endpoint URL: https://api.pricing.eu-west-2.amazonaws.com/Pricing API is only in us-east-1, eu-central-1 and ap-south-1Add --region us-east-1 (CLI) or use RegionEndpoint.USEast1 (C#)
get-products returns an empty PriceListA filter value doesn't match exactly (case, spelling)Run get-attribute-values for that attribute and copy the exact value
Many products returned for one instance typeMissing tenancy, capacitystatus or preInstalledSw filtersAdd the filters shown in the CLI section
AccessDeniedException calling the Pricing APIPermission set lacks pricing:* read actions, or an SCP blocks themCheck the permission set; the Module 0 Region guardrail already exempts pricing:*
C# fails with an SSO token errorSession expiredaws sso login --profile learn-sandbox
Savings Plans recommendations page is emptyNew account with no usage historyExpected; recommendations need days of usage
"Savings Plans not available" when browsing purchase pagesAccount is on the Free planFree plan accounts cannot buy Savings Plans or RIs โ€” and you should not buy any in this course
Bill higher than the On-Demand estimateData transfer, EBS volumes, public IPv4 addresses or NAT Gateway not included in the estimateUse Cost Explorer grouped by Usage type to find the extra line items

Cost and cleanup

Cost: USD 0. Price List API calls, Spot price history, Cost Explorer recommendations in the console and the public Pricing Calculator are free. Launch templates are free to create.

If you deployed the IaC example, remove the launch templates:

# CDK
cdk destroy hl-m01-pricing-demo --profile learn-sandbox

# Terraform
terraform destroy

# Confirm nothing tagged for this lesson remains
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab Key=Lab,Values=m01-pricing --region us-east-1 --profile learn-sandbox

Delete the local m7i.json file if you created it.

Exercises

  • ๐ŸŸข Guided: Use the CLI commands above to find the On-Demand Linux price of m7i.large and m8g.large (Graviton) in us-east-1. Calculate the monthly cost of two instances of each and the percentage difference.
  • ๐ŸŸก Challenge: Extend GetEc2Price.cs to accept --db and query AmazonRDS instead, printing the Multi-AZ On-Demand price of db.m6i.large for PostgreSQL and for SQL Server Standard (License Included). Explain the difference in one sentence.
  • ๐Ÿ”ด Live problem: The finance business partner forwards you this: "Cost Explorer recommends a USD 2.10/hour Compute Savings Plan, 3-year All Upfront. Can we just buy it?" You know that the payments team plans to move 40% of their EC2 fleet to Lambda next quarter, and the data team wants to start a Spot-based nightly pipeline. Write the reply you would send.

Assignment

In your learning-journal repository, add docs/pricing-policy.md: a one-page pricing policy for a fictional Harbourline service of your choice. Include a table of components, chosen pricing model, reason, and the risk if usage changes. Add the output of GetEc2Price.cs for two instance types as evidence.

Solutions

Knowledge check

Interview questions

  • "How would you reduce the compute bill for a steady .NET API on EC2?" โ€” Right-size with Compute Optimizer, consider Graviton and Linux containers, then cover the steady baseline with a Compute Savings Plan (1-year No Upfront if change is expected), leave peaks On-Demand, and monitor Savings Plans utilisation and coverage.
  • "When would you use Spot in a bank?" โ€” For interruptible, idempotent, checkpointed work: batch statement rendering, CI agents, test environments, data-lake processing. Never for the ledger, payment authorisation or deadline-critical settlement without an On-Demand fallback.
  • "Savings Plans or Reserved Instances?" โ€” For EC2, Savings Plans: same-level discounts with more flexibility, and AWS recommends them. RIs still matter for services without Savings Plans coverage and for zonal capacity reservations; Database Savings Plans now cover many database services.
  • "What's different about licensing SQL Server on AWS compared with Azure?" โ€” No general Azure-Hybrid-Benefit equivalent. Options are License Included, License Mobility with Software Assurance, or Dedicated Hosts for licences without SA. On RDS: License Included or Bring Your Own Media (with SA). Licensing teams must confirm.

Certification practice

Completion checklist

  • I can explain On-Demand, Savings Plans, Reserved Instances and Spot in two sentences each
  • I looked up a real price with the CLI or the C# program
  • I can explain why a Savings Plan must be sized to the baseline, not the peak
  • I can explain License Included vs BYOL for Windows Server and SQL Server
  • I did not buy any commitment, and I destroyed any launch templates I created

Key takeaways

  • AWS charges mainly for compute time, storage and data transfer out; inbound transfer is free and egress is where surprises hide.
  • On-Demand for unknown or spiky work; Savings Plans for the steady baseline; Spot for interruptible batch; RIs mostly for databases and capacity reservations.
  • Commitments cannot be cancelled: right-size first, size to the baseline, prefer flexibility (Compute Savings Plans, 1-year) when change is coming.
  • Licences are not discounted by Savings Plans; for Microsoft workloads, licensing strategy often matters more than the pricing model.
  • Prices are data: the Price List API, the Pricing Calculator and Cost Explorer let you justify every decision with numbers.

Further reading

Independent learning resource โ€” not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page