Courses / Cloud and DevOps Interview Prep / Chapter 10
Module 6 · Security and cost · Chapter 10 of 13
Cost and FinOps: Seeing, Shaping and Guarding the Bill
Builds on Infrastructure as Code: State, Drift and Policy Checks. Next up: Running AI Workloads: Serving, Delivery and Guardrails.
Part 1 · FinOps as a practice and unit cost
What FinOps is
A cloud bill arrives after the money has been spent, so controlling it is a habit of the whole team and not a month-end task. FinOps is the name for that habit.
FinOps is the practice of managing cloud spend by bringing engineering, finance and product together, so that the people who can change usage can see what it costs. The FinOps Foundation publishes a framework for it. Its six principles, in plain words, are these.
- Teams collaborate: engineering, finance and the business work from the same numbers.
- Business value drives technology decisions: a bigger bill is fine when it buys more than it costs.
- Every team owns its own usage, so cost is a property of the thing you built and not a finance problem.
- Cost data is accessible, timely and accurate. A report that arrives six weeks late cannot change behaviour.
- FinOps is enabled centrally. A small central team provides the tools, reports and rate negotiation, and the teams act on them.
- The variable cost model is an advantage: capacity can follow demand instead of being bought for the peak.
The framework describes a repeating journey in three phases. Inform means getting visibility: who spends what, on which product, compared with a budget. Optimize means acting on it: removing waste, choosing better pricing, resizing. Operate means making it routine, with owners, reviews, budgets and alerts, so the first two phases do not decay.
Allocation and tags come first because you cannot optimise a cost nobody owns. Rightsizing and pricing come next, then the network charges that surprise people, then the guardrails that keep it from drifting back.
Unit cost
A total bill is a poor measure of efficiency, because a successful product spends more. If the bill doubles and orders triple, the service got cheaper per order. A unit cost divides spend by something the business counts: cost per order, per active user, per thousand requests. It is the number that connects business value to accurate data.
Here is a worked example for a small order API. All prices were read on 2026-11-22 from the public AWS pages, for US East. Mumbai rates were not on the pages that could be read, so the example is in dollars and in a Region whose numbers are known. Lambda costs $0.20 per million requests and $0.0000166667 per GB-second on x86, and the account gets 1 million requests and 400,000 GB-seconds free each month. The API handles 1.2 crore requests a month at 200 ms and 512 MB, and 15 lakh orders, so about eight requests per order.
const requests = 12_000_000 // a month: 1.2 crore requests const avgSeconds = 0.2 const memoryGb = 0.5 const orders = 1_500_000 // 15 lakh orders, so 8 requests per order const gbSeconds = requests * avgSeconds * memoryGb const requestCost = ((requests - 1_000_000) / 1_000_000) * 0.2 const computeCost = (gbSeconds - 400_000) * 0.0000166667 const lambda = requestCost + computeCost const nat = 125.01 // from nat-cost.mts: one gateway, 2 TB console.log(`GB-seconds: ${gbSeconds.toLocaleString('en-US')}`) console.log(`requests: $${requestCost.toFixed(2)}`) console.log(`compute: $${computeCost.toFixed(2)}`) console.log(`lambda total: $${lambda.toFixed(2)}`) const total = lambda + nat console.log(`with NAT: $${total.toFixed(2)} for ${orders} orders`) const per1000 = (total / orders) * 1000 console.log(`per 1,000 orders: $${per1000.toFixed(4)}`) const noNat = (lambda / orders) * 1000 console.log(`without NAT: $${noNat.toFixed(4)} per 1,000 orders`) const share = (nat / total) * 100 console.log(`NAT share of the bill: ${share.toFixed(1)}%`)
unit-cost.mts, the calculation
GB-seconds: 1,200,000 requests: $2.20 compute: $13.33 lambda total: $15.53 with NAT: $140.54 for 1500000 orders per 1,000 orders: $0.0937 without NAT: $0.0104 per 1,000 orders NAT share of the bill: 88.9%
Output
The compute is 1.2 million GB-seconds, which after the free tier costs $15.53. Added to a NAT gateway bill of $125.01 for 2 TB of traffic (worked out in a later lesson), the month costs $140.54. That is about nine cents per 1,000 orders.
The last two lines are the useful ones. Without the NAT gateway the same traffic would cost about one cent per 1,000 orders, and NAT is 88.9 percent of the bill. Looking only at the Lambda charges would have pointed at the wrong thing.
Using a unit cost
Pick the denominator carefully. It should rise when the product succeeds and be something a product owner already tracks. Orders, completed payments or active users work. CPU hours or requests do not, because they describe the system and not the value.
Two words from the FinOps vocabulary help in conversations with finance. Showback means showing each team what its usage cost, without moving money. Chargeback means actually billing the cost to each team's budget. Showback is where most teams start, because it needs only good allocation data and creates the habit.
A unit cost earns its keep over time. Plot it per week. A rise with no matching change in features points at a regression, a forgotten environment or a pricing change. A slow fall after a rightsizing exercise is evidence the exercise worked. Put the number in the same dashboard as latency and error rate, so cost is treated as a quality attribute of the service.
Spend doubled this quarter but orders tripled. Did the service get more or less efficient?
- More efficient. Cost per order fell to two thirds of what it was, since total spend doubled while the denominator tripled.
- The total alone would have suggested a problem.
In the worked example, which line of the bill matters most and why?
- The NAT gateway: $125.01 of $140.54, 88.9 percent, against $15.53 for Lambda.
- Optimising Lambda memory would move the bill by cents, while removing most NAT traffic would change it by dollars.
What is the difference between showback and chargeback?
- Showback reports each team's cost to it without changing budgets. Chargeback moves the cost into the team's own budget.
- Both need reliable allocation, so tagging comes first.
Part 2 · Seeing who spends what
Cost allocation tags
Billing data says what was spent, by service and account. To say who spent it, you label the resources. A tag is a key and a value attached to a resource, such as cost-center = orders. A cost allocation tag is a tag that you have told billing to use for reporting.
The AWS documentation lists two kinds. User-defined tags are the ones you create. AWS-generated tags are created by AWS, such as createdBy, which records who created a resource, and they use the aws: prefix, while user-defined ones use the user: prefix in reports. Both kinds must be activated separately before they appear in Cost Explorer or the cost allocation report. All tags can take up to 24 hours to appear in the Billing console, so a tag you added this morning does not explain this afternoon's spike.
Only the management account of an organisation, or a single account that is not a member of one, has access to the cost allocation tags manager. Every other account can apply tags but cannot activate them. That makes the first task a conversation with whoever owns the management account: which keys to activate.
Keep the key set small and agreed: cost-center or team, service, environment. Keys are case sensitive and a spelling variant becomes a different category in reports. The documentation also advises not putting sensitive information in tags, because tags show up in many places.
Untagged spend is the number to track. The cost allocation report includes tagged and untagged resources, so you can see the share with no owner. A target of "untagged below five percent" is something you can measure and a team can be asked to fix.
Tagging in the CDK, and checking it
Tagging by hand does not scale. With the CDK you tag a scope once and every taggable resource under it inherits the tag. This app tags the whole app, then removes the tag from one bucket, to play the part of the resource somebody forgot.
Tags.of(app).add('cost-center', 'orders') new s3.Bucket(stack, 'Archive', { removalPolicy: RemovalPolicy.RETAIN }) new sqs.Queue(stack, 'Jobs') const scratch = new s3.Bucket(stack, 'Scratch') Tags.of(scratch).remove('cost-center')
cost-app.ts, the relevant lines
After synthesis, the tags are in the template as a Tags property on each resource. A short script reads the template and lists any resource whose type is taggable but which lacks cost-center. The script treats a type as taggable when at least one resource of that type in the template carries tags, which is a heuristic, not a rule from the CloudFormation schema.
taggable resources: 17 with cost-center: 16 missing cost-center: AWS::S3::Bucket ScratchF72D2ED6
tag-report.mts on the synthesised template
Seventeen resources carry tags and sixteen have cost-center. The scratch bucket is the one that does not, and its logical ID tells you where to look. Run this as a pipeline step and fail the build, or at least comment on the pull request. The check happens before the resource exists, so there is no untagged spend to clean up later.
Some costs have no single owner: a shared NAT gateway, support charges, a logging account. Decide an allocation rule and write it down, for example "split the NAT bill by each team's share of bytes". A rough rule that everyone knows is better than a precise rule nobody can reproduce.
Kubernetes cost by namespace
Tags do not reach inside a cluster. A node is one billable instance and many teams' Pods share it. To show cost by team you divide the node cost among the workloads on it, usually in proportion to their resource requests, since requests are what the scheduler reserved for them. OpenCost's specification charges the greater of what a container requested and what it used; the model below uses requests only.
OpenCost is an open-source project that does this kind of allocation for Kubernetes and supports showback and chargeback; it can also use cloud billing data to improve accuracy. The idea can be shown with a model. One node costs an assumed $0.10 an hour, so $73.00 for 730 hours, and has 4000m of allocatable CPU. Three namespaces have requests on it.
const NODE_MONTH = 730 * 0.1 const CAPACITY = 4000 // allocatable millicores on the node const requests: Record<string, number> = { shop: 2000, search: 1000, batch: 500, } let used = 0 for (const [ns, m] of Object.entries(requests)) { const cost = (m / CAPACITY) * NODE_MONTH used += m const cpu = String(m).padStart(5) console.log(`${ns.padEnd(7)} ${cpu}m $${cost.toFixed(2)}`) } const idle = CAPACITY - used const idleCost = (idle / CAPACITY) * NODE_MONTH const idleCpu = String(idle).padStart(5) console.log(`idle ${idleCpu}m $${idleCost.toFixed(2)}`) console.log(`node total: $${NODE_MONTH.toFixed(2)}`)
k8s-split.mts: a model, with an assumed rate
shop 2000m $36.50 search 1000m $18.25 batch 500m $9.13 idle 500m $9.13 node total: $73.00
Output, rounded to cents
The shop namespace pays half the node because it requests half the CPU. The unrequested 500m is idle: capacity you pay for that no Pod has reserved. How idle cost is shown is a policy choice. Some teams spread it over the namespaces, others report it separately so that the platform team owns it. Reporting it separately is more honest, since no namespace caused it.
The model also shows why requests matter for cost and not only for scheduling. A namespace that requests 2000m and uses 200m is charged for 2000m. Lowering requests to what the workload needs is the cheapest saving in most clusters.
Why is a cost allocation tag you added this morning not in today's report?
- Tags must be activated, and the documentation says tags can take up to 24 hours to appear in the Billing console.
Part 3 · Rightsizing and pricing models
Rightsizing
Rightsizing means matching the size of a resource to what the workload needs. It is the cheapest saving because it needs no commitment: a service using 15 percent of a large instance can move to a smaller one the same day, and the bill falls.
Measure before cutting. Look at utilisation over a period that includes the busiest hour of the month, not an average, because the peak decides whether a smaller size is safe. CPU, memory, network and disk each have their own limit, and a workload can be bound by any of them. A job that is idle on CPU may be using almost all of the memory.
AWS Compute Optimizer is the AWS service that analyses configuration and utilisation metrics, gives rightsizing recommendations and finds idle resources. The same idea applies to your own tooling. Treat a recommendation as a hypothesis and test it in a lower environment first. Resize one step at a time, and watch latency and error rate after each change, because a resize that saves money and breaks a service is not a saving.
Inside Kubernetes the same lesson applies to requests. Requests set far above real use waste the node capacity that the previous lesson priced. Many teams keep a dashboard showing requested against used for each workload, and review the largest gaps first.
Rightsizing is also an ongoing task, not a project. Traffic changes, code changes and instance generations change. Schedule the review, and keep its output in the same place as the unit cost.
Pricing models
Once a resource is the right size, the next question is how you pay for it. There are three common answers.
| Model | How it works | Good for | Watch out for |
|---|---|---|---|
| On-demand | pay the list rate for each hour used, with no commitment | new, variable or short-lived workloads | the highest rate per hour |
| Savings Plan | commit to a dollar amount of compute per hour for one or three years, and get a lower rate for usage up to it | a steady baseline you are sure will run | you pay the commitment even when usage drops below it |
| Spot | use spare capacity at a discount; EC2 can take it back | fault-tolerant, restartable work | an interruption gives two minutes of warning |
How it workspay the list rate for each hour used, with no commitment
Good fornew, variable or short-lived workloads
Watch out forthe highest rate per hour
How it workscommit to a dollar amount of compute per hour for one or three years, and get a lower rate for usage up to it
Good fora steady baseline you are sure will run
Watch out for
Commit to the baseline, not the peak
The most common error with a commitment is sizing it to the busiest hour. A plan costs its full hourly amount every hour, used or not, so a commitment above the steady baseline pays for capacity that sits idle most of the month.
The script below models a month. It uses assumptions and not real prices: $0.10 an hour on-demand per instance, and a 30 percent discount for the plan. The workload runs eight instances all month, plus four more for 200 peak hours.
const RATE = 0.1 const DISCOUNT = 0.3 const HOURS = 730 const BASE = 8 // instances running all month const PEAK = 4 // extra instances const PEAK_HOURS = 200 // The commitment is in discounted dollars per hour; it covers that // many instances of usage at the discounted rate. function month(commitInstances: number) { const commitPerHour = commitInstances * RATE * (1 - DISCOUNT) const commit = commitPerHour * HOURS const baseExtra = Math.max(0, BASE - commitInstances) * HOURS * RATE const peakCovered = Math.max(0, commitInstances - BASE) const peakLeft = Math.max(0, PEAK - peakCovered) const peakOnDemand = peakLeft * PEAK_HOURS * RATE return commit + baseExtra + peakOnDemand } const allOnDemand = month(0) console.log(`all on-demand: $${allOnDemand.toFixed(2)}`) for (const c of [6, 8, 10, 12]) { const m = month(c) const saved = (allOnDemand - m).toFixed(2) console.log(`commit ${c}: $${m.toFixed(2)}, saves $${saved}`) }
pricing-models.mts, assumed rates
all on-demand: $664.00 commit 6: $532.60, saves $131.40 commit 8: $488.80, saves $175.20 commit 10: $551.00, saves $113.00 commit 12: $613.20, saves $50.80
Output
Committing to eight instances, the baseline, saves $175.20 of $664.00. Committing to six leaves part of the baseline on-demand. Committing to ten or twelve pays for peak capacity that is used 200 hours out of 730, and the saving shrinks to $50.80 at twelve. The best commitment is the level you use every hour.
Saved against all on-demand $664.00: $175.20 (the discount and rates here are assumptions)
Read it as steps
Part 4 · Costs that hide in the network
NAT gateways, public addresses and endpoints
The costs people expect are compute and storage. The ones that surprise them are network charges that depend on traffic pattern, not on instance size.
A NAT gateway lets resources in a private subnet start connections to the internet. It is billed in two parts, and every figure below is from the AWS VPC pricing page for US East (Ohio), read on 2026-11-22. Mumbai rates were not on the page text, so use these as shapes, not as your bill.
| Charge | Rate (US East, Ohio) | Notes |
|---|---|---|
| NAT gateway | $0.045 per hour | charged for every hour the gateway exists, even with no traffic |
| NAT gateway data processing | $0.045 per GB | every GB that passes through the gateway |
| Public IPv4 address | $0.005 per hour | for each address, in use or idle |
| Gateway VPC endpoint | no hourly or data charge | the page says there is none for gateway endpoints |
A gateway endpoint is a route from your VPC to a service, with S3 and DynamoDB being the two services that offer this type. Traffic to S3 through a gateway endpoint does not pass the NAT gateway, so it avoids the NAT processing charge. A private subnet that downloads container images and writes to S3 through a NAT gateway pays by the gigabyte for traffic that an endpoint would carry for free.
Public IPv4 addresses are charged hourly whether or not they are attached to anything, so an Elastic IP left behind after an experiment keeps billing. A NAT gateway needs one, which is why a second gateway adds both lines.
What the template says
You can see these resources before deploying. The VPC construct in the CDK creates a NAT gateway and an Elastic IP for each one, and a gateway endpoint is one extra line. The app below runs with one NAT gateway, then with two, as a team might do for resilience across two Availability Zones.
const vpc = new ec2.Vpc(stack, 'Net', { maxAzs: 2, natGateways: variant === 'v1' ? 1 : 2, gatewayEndpoints: { S3: { service: ec2.GatewayVpcEndpointAwsService.S3 }, }, })
cost-app.ts: natGateways depends on the variant
A short script compares the two synthesised templates and prices the difference for the resources it knows. The prices are the Ohio rates above, over 730 hours.
AWS::EC2::NatGateway: +1, +$32.85/month AWS::EC2::EIP: +1, +$3.65/month fixed monthly change: $36.50 (before data)
cost-review.mts: version 2 against version 1
The second NAT gateway adds $32.85 a month before any data, and its address adds $3.65. The resilience is real, since each Availability Zone then has its own gateway and does not depend on another, so this is a trade to decide on purpose and not by default. The same template also holds one gateway endpoint of type Gateway, so S3 traffic stays off the NAT path.
NetS36F3DB7FB endpoint ok Gateway
AppLogsC5DF83A6 RetentionInDays 30From the version 1 template
Cross-AZ traffic is the quieter cost. The VPC pricing page notes that data transfer between a NAT gateway and an instance in a different Availability Zone is charged, without giving a general rate on that page, so read the current rate for your Region before you design around it. A single gateway reached from several zones saves hours and adds transfer.
Pricing a month of traffic
To turn the rates into a bill, take 2 TB a month through one NAT gateway, counting 1 TB as 1,024 GB. The month has 730 hours.
// NAT gateway cost for a month, US East (Ohio) prices read 2026-11-22. const HOURLY = 0.045 // per NAT gateway-hour const PER_GB = 0.045 // per GB processed const HOURS = 730 function nat(gateways: number, gb: number) { const hours = gateways * HOURS * HOURLY const data = gb * PER_GB return { hours, data, total: hours + data } } const gb = 2 * 1024 // 2 TB, taking 1 TB as 1,024 GB for (const g of [1, 2]) { const r = nat(g, gb) const hours = `hours $${r.hours.toFixed(2)}` const data = `data $${r.data.toFixed(2)}` const total = `$${r.total.toFixed(2)}` console.log(`${g} gateway(s): ${hours} + ${data} = ${total}`) } console.log('gateway endpoint to S3, same bytes: $0.00') const ipv4 = (0.005 * HOURS).toFixed(2) console.log(`public IPv4, one address: $${ipv4}/month`)
nat-cost.mts: hours plus gigabytes
1 gateway(s): hours $32.85 + data $92.16 = $125.01 2 gateway(s): hours $65.70 + data $92.16 = $157.86 gateway endpoint to S3, same bytes: $0.00 public IPv4, one address: $3.65/month
Output
Monthly NAT bill for the traffic: $125.01 (Mumbai rates were not read; this is Ohio)
Read it as steps
Hours plus gigabytes at US East (Ohio) rates read on 2026-11-22.
The processing charge is about 74 percent of the bill, and it grows with traffic while the hourly part does not. If most of that 2 TB is S3 or DynamoDB, the endpoint removes it and leaves only the $32.85 for the gateway itself. If it is traffic to the public internet, the options are different: cache it, compress it, or move the work to where the data is. Add a second gateway and the hours double to $65.70.
Part 5 · Guardrails for spend
Budgets and anomaly alerts
Visibility shows you where money went. Guardrails stop a surprise from growing before the next monthly review. AWS offers two tools for this, and they answer different questions.
AWS Budgets compares spend or usage with a number you set. The documentation lists cost budgets, usage budgets and utilisation or coverage budgets for Reserved Instances and Savings Plans. You can be alerted on actual spend after it accrues and on forecast spend before it does, by email or an Amazon SNS topic. A budget can also take an action, such as applying an IAM policy that denies new provisioning once a threshold is crossed. Budgets data updates up to three times a day, and the documentation warns that there can be a delay between a charge and its notification, so costs may pass the threshold before the alert arrives.
AWS Cost Anomaly Detection uses machine learning to flag spend that departs from its normal pattern, including weekly and monthly seasonality, and ranks root causes by dollar impact across service, account, Region and usage type. It runs about three times a day on Cost Explorer data, which can be up to 24 hours late, so an anomaly can take up to 24 hours to appear. A new service subscription needs 10 days of history.
Neither tool stops a runaway resource by itself in real time. They shorten the time to notice from a month to a day. That is worth having and not worth over-promising: for hard limits, use quotas, small accounts per team and the budget action that denies provisioning.
A budget with no filter watches the whole account. Budgets accept filters, such as a linked account or a cost allocation tag, so each team can have its own budget and its own alert, which ties back to the tags of the second lesson. Cost Anomaly Detection monitors can likewise be scoped to member accounts, cost allocation tags or cost categories. A sensible start is one account-wide budget with a forecast alert, then per-team budgets once the tags can be trusted, and an owner for each alert, since an alert nobody owns is read by nobody.
A budget in code
Budgets can be created in the console, but a budget no one can see in review is easy to lose. Here a monthly budget of $20,000 alerts at 80 percent of the forecast. It is part of the same stack, so it is created with the environment and reviewed like any resource.
new budgets.CfnBudget(stack, 'MonthlyBudget', { budget: { budgetType: 'COST', timeUnit: 'MONTHLY', budgetLimit: { amount: 20000, unit: 'USD' }, }, notificationsWithSubscribers: [ { notification: { notificationType: 'FORECASTED', comparisonOperator: 'GREATER_THAN', threshold: 80, thresholdType: 'PERCENTAGE', }, subscribers: [ { subscriptionType: 'EMAIL', address: 'finops@example.com' }, ], }, ], })
cost-app.ts: a cost budget with a forecast alert
The synthesised template passed cfn-lint with exit code 0. The address is on example.com, so nothing would actually be mailed.
cfn-lint exit 0cfn-lint 1.60.0 on the synthesised template
The same stack holds the other cheap guardrail: log retention. A log group with no retention keeps data forever and is billed for storage forever. The app sets one month.
AppLogsC5DF83A6 RetentionInDays 30From the template: the log group retains 30 days
Schedules and review steps
Environments that nobody uses overnight still cost money overnight. A development environment that runs all week and is used from 9 to 7 on weekdays is on for 168 hours and used for 50. The model below uses four instances at an assumed $0.10 an hour.
const RATE = 0.1 const INSTANCES = 4 const WEEKS_PER_MONTH = 730 / 168 // 730 hours in a month, 168 in a week const alwaysOn = 24 * 7 const office = 10 * 5 // 10 hours a day, Monday to Friday const monthly = (hoursPerWeek: number) => INSTANCES * hoursPerWeek * WEEKS_PER_MONTH * RATE const costOn = monthly(alwaysOn).toFixed(2) const costOffice = monthly(office).toFixed(2) console.log(`always on: ${alwaysOn} h/week, $${costOn}`) console.log(`office hours: ${office} h/week, $${costOffice}`) const saved = (1 - office / alwaysOn) * 100 console.log(`hours saved: ${saved.toFixed(1)}%`)
idle.mts: always on against office hours
always on: 168 h/week, $292.00 office hours: 50 h/week, $86.90 hours saved: 70.2%
Output
Running only in office hours cuts 70.2 percent of the hours. A schedule that stops and starts the environment is one of the easiest savings, with two cautions: anything that is stateful needs a clean start, and a Savings Plan commitment that covered those hours keeps billing, so schedule only what is not committed.
The last guardrail is a cost review in the pipeline. The script from the network lesson compares the synthesised templates before and after a change and prices the resources on a watch list. In a pull request it turns a line of code into a number a reviewer can read.
node cost-review.mts v1.template.json v2.template.json 30The last argument is the limit, in dollars a month
AWS::EC2::NatGateway: +1, +$32.85/month AWS::EC2::EIP: +1, +$3.65/month fixed monthly change: $36.50 (before data) over the $30.00 limit: needs approval exit 1
Output; the exit status is 1, so the pipeline step fails
A sensible rule: any change that adds more than a set amount of fixed monthly cost needs an extra approval. The threshold and the watch list belong in version control. Prices change, so put the date next to each rate, as the script does.
Why does a budget alert not prevent an overspend by itself?
- Budgets data updates up to three times a day and there can be a delay between a charge and its notification, so costs can pass the threshold before the alert arrives.
All chapters · Previous: Security, Secrets and the Software Supply Chain