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#.
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
- Free Tier and billing โ what the Free plan and Paid plan allow
- AWS global infrastructure โ prices differ by Region
- AWS SDK for .NET: first contact โ for the C# example (optional)
- Tools: AWS CLI v2 with the
learn-sandboxSSO profile, .NET 10 SDK
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:
| Ingredient | Examples | Typical unit |
|---|---|---|
| Compute | EC2 instances, Fargate tasks, Lambda invocations, RDS instances | Per second (60-second minimum on EC2), per hour, per GB-second, per request |
| Storage | S3 objects, EBS volumes, RDS storage, backups | Per GB-month (prorated) |
| Data transfer | Data leaving AWS to the internet, between Regions, between Availability Zones | Per 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:
| Service | Tier | Price |
|---|---|---|
| Data transfer out to the internet | First 10 TB per month (after the free 100 GB) | USD 0.090 per GB |
| Next 40 TB | USD 0.085 per GB | |
| Next 100 TB | USD 0.070 per GB | |
| Over 150 TB | USD 0.050 per GB | |
| Lambda compute (x86) | First 6 billion GB-seconds per month | USD 0.0000166667 per GB-second |
| Next 9 billion GB-seconds | USD 0.0000150000 | |
| Over 15 billion GB-seconds | USD 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):
| Type | Applies to | Flexibility | Maximum discount stated by AWS |
|---|---|---|---|
| Compute Savings Plans | EC2, Fargate and Lambda | Any instance family, size, OS, tenancy or Region | Up to 66% |
| EC2 Instance Savings Plans | EC2 only | One instance family in one Region (for example m7i in us-east-1); any size, OS, tenancy within it | Up to 72% |
| Database Savings Plans (launched 2 December 2025) | Aurora, RDS, DynamoDB, ElastiCache, DocumentDB, Neptune, Keyspaces, Timestream, DMS, OpenSearch Service | Any engine, instance family, size, AZ or Region; also serverless usage. 1-year term, no upfront | Up to 35% |
| SageMaker AI Savings Plans | SageMaker AI instances | Any family, size, Region or component | Up 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 atspot/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 equivalent | What's different |
|---|---|---|
| Pay-as-you-go VMs | On-Demand Instances | EC2 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 compute | Compute Savings Plans | Very similar idea (hourly spend commitment); AWS's also covers Lambda and Fargate |
| โ (no direct equivalent) | EC2 Instance Savings Plans, Database Savings Plans | Narrower 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 BYOM | There is no general "hybrid benefit" for Windows Server on shared AWS tenancy; budget for License Included unless your licensing team confirms otherwise |
| Azure Dedicated Host | EC2 Dedicated Hosts | Both are used mainly for licensing and isolation requirements |
| Azure Pricing Calculator | AWS Pricing Calculator (public site) and in-console Pricing Calculator | The in-console version can apply your own discounts and commitments |
| Azure Retail Prices API | AWS Price List Query API and Bulk API | AWS's API needs a signed request (IAM permission pricing:GetProducts) |
| Azure Advisor reservation recommendations | Cost Explorer Savings Plans/RI recommendations, Compute Optimizer | Same 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/hour | USD/month | Saving vs On-Demand |
|---|---|---|---|
| On-Demand | 0.1008 | 73.58 | โ |
| Compute Savings Plan, 1-year, No Upfront | 0.07406 | 54.06 | 26.5% |
| EC2 Instance Savings Plan (m7i), 1-year, No Upfront | 0.06668 | 48.68 | 33.8% |
| Compute Savings Plan, 3-year, No Upfront | 0.05112 | 37.32 | 49.3% |
| EC2 Instance Savings Plan (m7i), 3-year, All Upfront | 0.03980 | 29.05 | 60.5% |
| Spot (snapshot 2026-11-17, varies by AZ and hour) | about 0.0449 | about 32.78 | about 55% |
Now the same instance with Windows Server License Included:
| Option | USD/hour | USD/month | Saving |
|---|---|---|---|
| On-Demand Windows | 0.1928 | 140.74 | โ |
| Compute Savings Plan, 1-year, No Upfront | 0.16606 | 121.22 | 13.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-sandboxThe 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.
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.
#: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 WindowsExpected 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/monthThe 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
#:package AWSSDK.Pricing@4.1.0.2โ .NET 10 file-based apps declare NuGet packages inline.AWSSDK.Pricingis the Price List client in SDK v4.#: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.#:property TreatWarningsAsErrors=trueandNullable=enableโ the same strictness as every lab in this course.args.Length > 0 ? args[0] : "m7i.large"โ optional positional arguments: instance type, Region code, operating system.new CredentialProfileStoreChain()โ reads%USERPROFILE%\.aws\configandcredentials, the same files the CLI uses.TryGetAWSCredentials("learn-sandbox", ...)โ builds SSO credentials from the cached token created byaws sso login.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.ServiceCode = "AmazonEC2"โ the service whose price list you query. Others includeAmazonRDS,AmazonS3,AWSLambda.Filters = [...]โ C# 12 collection expression creating aList<Filter>. Every filter must match (AND logic).FilterType.TERM_MATCHโ exact match on an attribute value.capacitystatus = Usedexcludes capacity-reservation SKUs;preInstalledSw = NAexcludes "Windows with SQL Server" variants;tenancy = Sharedexcludes dedicated tenancy.await pricing.GetProductsAsync(request)โ one signed HTTPS call; needs IAM permissionpricing:GetProducts.response.PriceList ?? []โ SDK v4 returnsnullinstead of an empty list when there are no results.JsonDocument.Parse(productJson)โ each entry is a full JSON document in a string.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.decimal.Parse(usd, CultureInfo.InvariantCulture)โ money asdecimal, parsed culture-independently (a UK or German PC would otherwise misread the decimal separator).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:DescribeServicesandpricing:GetAttributeValuesonly, not*. - Purchasing commitments is a privileged financial action. In a bank,
savingsplans:CreateSavingsPlanandec2:PurchaseReservedInstancesOfferingshould 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:
- Weeks 0โ8: run On-Demand. Tag everything (
CostCentre,Application,Environment) so Cost Explorer can attribute spend. - 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.
- 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.
- 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.
- 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
| Symptom | Likely cause | Fix |
|---|---|---|
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-1 | Add --region us-east-1 (CLI) or use RegionEndpoint.USEast1 (C#) |
get-products returns an empty PriceList | A 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 type | Missing tenancy, capacitystatus or preInstalledSw filters | Add the filters shown in the CLI section |
AccessDeniedException calling the Pricing API | Permission set lacks pricing:* read actions, or an SCP blocks them | Check the permission set; the Module 0 Region guardrail already exempts pricing:* |
| C# fails with an SSO token error | Session expired | aws sso login --profile learn-sandbox |
| Savings Plans recommendations page is empty | New account with no usage history | Expected; recommendations need days of usage |
| "Savings Plans not available" when browsing purchase pages | Account is on the Free plan | Free plan accounts cannot buy Savings Plans or RIs โ and you should not buy any in this course |
| Bill higher than the On-Demand estimate | Data transfer, EBS volumes, public IPv4 addresses or NAT Gateway not included in the estimate | Use 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-sandboxDelete 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.largeandm8g.large(Graviton) in us-east-1. Calculate the monthly cost of two instances of each and the percentage difference. - ๐ก Challenge: Extend
GetEc2Price.csto accept--dband queryAmazonRDSinstead, printing the Multi-AZ On-Demand price ofdb.m6i.largefor 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
With the 2026-11-14 price list: m7i.large = USD 0.1008/hour โ 2 ร 0.1008 ร 730 = USD 147.17/month. m8g.large = USD 0.08976/hour โ 2 ร 0.08976 ร 730 = USD 131.05/month. Graviton is about 11% cheaper per instance-hour here. Why it matters: .NET 10 runs natively on Arm64, so moving a stateless ASP.NET Core service to Graviton is often just a different container image or AMI โ but load-test first, because performance per vCPU differs by workload.
Change ServiceCode to "AmazonRDS" and use filters instanceType = db.m6i.large, regionCode = us-east-1, deploymentOption = Multi-AZ, and databaseEngine = PostgreSQL or databaseEngine = SQL Server plus databaseEdition = Standard and licenseModel = License included. With the 2026-11-13 price list you should see roughly USD 0.356/hour for PostgreSQL and USD 1.954/hour for SQL Server Standard LI โ more than five times as much, because the SQL Server licence is bundled into the hourly price. Why: this is the single biggest cost lever in many Microsoft-to-AWS migrations.
A good reply: "Not yet. A 3-year All Upfront plan can't be cancelled, and the recommendation is based on past usage that is about to change: about 40% of the payments EC2 fleet moves to Lambda next quarter (Compute Savings Plans would still apply to Lambda, but the amount of compute will change shape), and the new nightly pipeline will run on Spot, which a Savings Plan doesn't need to cover. I suggest we (1) buy a smaller 1-year No Upfront Compute plan at roughly 60โ70% of the recommended commitment now, (2) review again 60 days after the migration, and (3) set Budgets alerts on Savings Plans utilisation and coverage. I'll share the Cost Explorer view showing the baseline over the last 60 days." Why: it protects against over-commitment, keeps flexibility during a known change, and gives finance a dated plan rather than a flat "no".
Knowledge check
Answer: Compute Savings Plans. EC2 Instance Savings Plans cover only EC2 in one family and Region; Database Savings Plans cover managed databases; SageMaker AI Savings Plans cover SageMaker instances.
Answer: A regional RI applies its discount in any AZ in the Region (and across sizes for Linux, default tenancy) but does not reserve capacity. A zonal RI applies only in one AZ and one size, and does reserve capacity there. Price is the same.
Answer: Two minutes, through an EventBridge EC2 Spot Instance Interruption Warning event and the spot/instance-action instance-metadata item (except with hibernation, which begins immediately).
Answer: The discount applies to the compute portion only. The Windows (and SQL Server) licence portion of the hourly price is charged at the normal rate, so the same absolute saving is a smaller share of a bigger bill.
Answer: No, inbound data transfer is free. Data transfer out to the internet is charged per GB after a 100 GB per month free allowance, and traffic between AZs is also charged.
Answer: us-east-1, eu-central-1 and ap-south-1. They can return prices for any Region.
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
A bank runs a reporting job every night for three hours. The job can restart from a checkpoint if a server disappears. Which EC2 purchasing option is the most cost-effective?
A. On-Demand Instances B. Spot Instances C. A 3-year Standard Reserved Instance D. Dedicated Hosts
Answer: B. The workload is interruptible and short, which is exactly Spot's use case. A works but costs more. C commits to 24 hours a day for three years while only three hours are used. D is for licensing and isolation and is the most expensive.
A company wants a commitment-based discount that will continue to apply if it moves workloads from EC2 to AWS Fargate and from eu-west-1 to eu-west-2. Which option should it choose?
A. EC2 Instance Savings Plans B. Zonal Reserved Instances C. Compute Savings Plans D. Spot Instances
Answer: C. Compute Savings Plans apply across instance families, Regions, operating systems, and to Fargate and Lambda. A is tied to one instance family in one Region. B is tied to one AZ and size. D is not a commitment and can be interrupted.
An application has a steady load of 6 instances all day and peaks of 20 instances for two hours each weekday. Peak work is stateless web traffic that must not be interrupted. Which combination is most cost-effective?
A. 20 instances covered by a Compute Savings Plan B. A Compute Savings Plan covering 6 instances; On-Demand for the peak C. 6 Spot Instances; On-Demand for the peak D. 20 On-Demand Instances at all times
Answer: B. Commit to the steady baseline and pay On-Demand for short peaks. A wastes commitment for 22 hours a day. C puts the always-on baseline on interruptible capacity. D pays full price for idle capacity.
A bank needs a discount for a critical m7i workload in a single Availability Zone and must be sure capacity is available there during a regional event. Which option provides both?
A. Regional Standard Reserved Instance B. Zonal Standard Reserved Instance C. Compute Savings Plan D. Spot Instances with a maximum price
Answer: B. A zonal RI gives the discount and reserves capacity in that AZ. Regional RIs (A) and Savings Plans (C) give discounts but no capacity reservation. D gives neither guarantee. (A Savings Plan plus an On-Demand Capacity Reservation is the modern alternative.)
A company wants to run Windows Server on EC2 using Windows Server licences it bought in 2018 without Software Assurance. Which option meets Microsoft licensing terms on AWS?
A. Default (shared) tenancy On-Demand Instances B. EC2 Dedicated Hosts C. Spot Instances D. Any instance with a Compute Savings Plan
Answer: B. Windows Server BYOL on AWS requires Dedicated Hosts (and licences bought before 1 October 2019). A, C and D are shared tenancy, where Windows Server must be License Included. Payment model (C, D) doesn't change licensing rules.
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
- Amazon EC2 pricing and Spot Instances
- What are Savings Plans? and Savings Plans types
- Announcing Database Savings Plans
- Reserved Instances overview, regional and zonal scope, Standard vs Convertible
- Spot Instance interruption notices
- AWS Lambda pricing
- Using the AWS Price List API and Price List Query API walkthrough
- Microsoft licensing on AWS FAQ and Licensing SQL Server on Amazon RDS
- Module 13: Microsoft-to-AWS migration and Module 15: Governance and FinOps
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.
Free Tier and billing
Understand the 2025 Free plan and Paid plan, what is always free, how AWS bills you, where to see credits and costs, how cost allocation tags work, and the traps that turn a free lab into a bill.
Lab: price a banking web app three ways in the AWS Pricing Calculator
Estimate Harbourline Bank's statement portal in the AWS Pricing Calculator with On-Demand, Savings Plans and Spot workers, compare PostgreSQL with SQL Server licensing, and check the totals in C#.