Cost optimisation and security on AWS
Practical study notes on cost optimisation and security on AWS: key concepts, formulas for cost calculation, worked examples (cost and IAM), common exam mistakes, and quick-check questions.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Two core concerns when running systems on AWS are controlling what you pay and keeping systems secure. Engineers use cost optimisation to reduce ongoing cloud bills while meeting performance needs, and use security best practices to protect data, meet compliance, and prevent breaches.
Key ideas
Principle of Least Privilege: grant users and services the minimum permissions required to perform tasks. Exact definition: for any identity or service, allowed actions should be the smallest set that accomplishes required tasks. In exams, explain how to tighten IAM policies, use roles, and avoid long-lived credentials.
Cost drivers: typical drivers are compute (EC2, Lambda invocations), storage (S3, EBS, S3 Glacier), networking (data transfer out, inter-AZ data, NAT Gateway hours/GB), managed databases, and support or licensing. State assumptions when calculating costs (region, instance type, storage class).
Savings mechanisms:
- Right-sizing: choose instance types or storage classes matched to workload; use AWS Compute Optimizer and Trusted Advisor recommendations.
- Buying options: On-Demand (no commitment), Reserved Instances / Savings Plans (commit to 1 or 3 years for discounts), Spot Instances (very low cost for interruptible workloads).
- Storage tiering: move infrequently accessed data to colder tiers (S3 Standard-IA, S3 One Zone-IA, S3 Intelligent-Tiering, S3 Glacier Flexible Retrieval/Deep Archive).
- Auto Scaling: scale out and in with demand to reduce idle capacity.
- Lifecycle policies: automatic transition of objects to cheaper classes.
Guardrails and governance:
- AWS Organizations allows central billing and policy enforcement; use AWS Control Tower to automate multi-account landing zone setup. Use Service Control Policies (SCPs) to limit services across accounts; SCPs set maximum permissions (guardrails) and never grant access by themselves.
- AWS Budgets and Cost Explorer provide alerts and cost analysis; enable Cost Anomaly Detection and use cost allocation tags for chargeback/showback.
Security controls to use together with cost practices:
- Identity and Access Management (IAM): use roles for services, MFA (Multi-Factor Authentication) for users with privileges, rotate keys, and avoid root account use.
- Network security: Security Groups (stateful, attached to ENIs/instances) and Network ACLs (stateless, subnet-level) should be used with least open ports principle; use VPC endpoints (Gateway/Interface) to keep traffic private and reduce NAT egress costs. Draw diagram in exams: VPC box, subnets, route table, IGW, security group attached to ENI/instance, NACL on subnet.
- Encryption: at rest (EBS, S3 server-side encryption with KMS) and in transit (TLS). Manage keys with AWS KMS and use key rotation.
- Logging and monitoring: CloudTrail (API audit logs), CloudWatch (metrics and alarms), AWS Config (resource configuration history). Create an organization-wide, multi-Region CloudTrail and deliver to S3; combine logs with S3 + lifecycle + S3 Glacier to store audit trails cheaply.
- Principle of defense in depth: multiple layers (network, host, app, identity, data). Also know managed security services: GuardDuty (threat detection), Security Hub (security posture), IAM Access Analyzer, S3 Block Public Access, AWS WAF and AWS Shield for edge protection.
Trade-offs: cheaper options often reduce availability or add management complexity (Spot instances can be terminated; Glacier retrieval has latency). In exams, state explicit assumptions and consequences.
Formulas
Total monthly cost = Σ (unit_price_i × usage_i) + fixed_monthly_fees
- unit_price_i: price per unit (₹/hour, ₹/GB-month, ₹/GB transferred)
- usage_i: quantity used in the month (hours, GB-month, GB)
- Currency unit: ₹ (Indian Rupee). Applies when you have per-unit pricing.
Savings % = (Cost_before - Cost_after) / Cost_before × 100
- Percentage saving when applying an optimisation.
Break-even time (months) = Additional_commit_cost / Monthly_savings
- Use for Reserved vs On-Demand decisions where a one-time upfront or higher committed cost yields lower monthly rate.
Cost per request = (Total_monthly_cost_for_service) / (Number_of_requests_per_month)
- Useful for APIs or serverless cost analysis.
When working with AWS CLI/SDKs, remember these key syntaxes to check in exams (reference only):
- IAM role creation (AWS CLI):
aws iam create-role --role-name NAME --assume-role-policy-document file://trust.json - Create budget (AWS CLI):
aws budgets create-budget --account-id 123456789012 --budget file://budget.json(Exact flags may vary; verify in docs.)
Worked examples
- Monthly cost for an EC2 web server (numerical) Assumptions (state them): Region prices vary; assume On-Demand price = ₹0.40 per hour for chosen instance type, EBS gp3 storage = ₹1.20 per GB-month, 100 GB storage, 200 GB data transfer out per month at ₹0.50 per GB. Steps:
- Compute cost = hours_in_month × price_per_hour Hours_in_month = 24 × 30 = 720 h Compute = 720 h × ₹0.40/h = ₹288.00
- Storage cost = 100 GB × ₹1.20/GB-month = ₹120.00
- Data transfer = 200 GB × ₹0.50/GB = ₹100.00
- Total = ₹288 + ₹120 + ₹100 = ₹508.00 per month (Write these assumptions when you answer in exams.)
- Break-even Reserved vs On-Demand (numerical) Assume On-Demand = ₹0.40/h, 1-year Reserved effective = ₹0.25/h (no upfront; if upfront exists, include it as Additional_commit_cost). Monthly hours = 720.
- Monthly On-Demand = 720 × ₹0.40 = ₹288
- Monthly Reserved = 720 × ₹0.25 = ₹180
- Monthly saving = ₹108
- If Reserved required a one-time extra payment of ₹500, break-even months = 500 / 108 ≈ 4.63 → 5 months to recover.
- IAM policy example (theory + step trace) Question: Allow a Lambda function role to write logs to a single S3 bucket prefix only. Model answer steps:
- Define role trust policy for Lambda service.
- Define inline permission policy with least privilege:
- Action:
s3:PutObject - Resource:
arn:aws:s3:::my-bucket/logs/${aws:PrincipalTag/log-prefix}/*(tag the Lambda execution role with log-prefix=the function’s log folder; IAM policy variables like aws:PrincipalTag are supported for S3 resource ARNs)
- Action:
- Explain testing: try PutObject outside prefix -> denied; PutObject into prefix -> allowed. In an exam draw a small table showing attempt and result (Allowed/Denied).
Common mistakes
- Mixing up Security Groups (stateful) and NACLs (stateless) behaviour.
- Applying broad IAM policies like
Resource: "*"orAction: "s3:*"instead of least privilege. - Assuming Reserved Instances always save money without calculating utilization and break-even.
- Not enabling CloudTrail or not storing logs with lifecycle rules for long-term audit needs (leading to missed forensic evidence or hidden costs).
For your exam
Question types: definitions (Shared Responsibility Model, least privilege), short notes (cost drivers, Savings Plans), derivations (break-even calculation), numericals (monthly cost, savings %), programs/CLI snippets (IAM role creation), diagrams (VPC with security layers). What a full-marks answer includes:
- Clear statement of definitions with bolded terms.
- All assumptions listed (region, prices, usage patterns).
- Step-by-step calculation with formulas shown before substitution; units included and final answer highlighted.
- For security questions: include diagrams of architecture, list controls at each layer, and explain trade-offs.
Quick check
- What is the Shared Responsibility Model? (one line)
- Write the formula for monthly cost when you have hourly compute and GB-month storage.
- Name two AWS services useful for cost governance.
Answers: 1) AWS secures the cloud infrastructure; the customer secures what they run in the cloud (OS, data, configurations). 2)
Total monthly cost = Σ (unit_price × usage)(e.g., compute_hours×price_per_hour + GB-month×price_per_GB-month). 3) AWS Cost Explorer and AWS Budgets (also AWS Organizations for consolidated billing).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?