Infrastructure Optimization
Improve cost, performance, and efficiency without sacrificing reliability: measure first, right-size, scale sensibly, reduce waste in infrastructure and pipelines, and use AI to find opportunities safely.
Introduction
A working pipeline and a stable deployment are the goal. Once you have them, two questions follow: what does this cost, and can it be faster or leaner without becoming fragile?
Optimization is easy to do badly. Cutting resources without measurement causes outages; chasing small savings wastes engineering time; tuning for imagined load adds complexity. This lesson gives a disciplined approach: measure, find the biggest opportunities, change one thing at a time, and verify that reliability did not suffer.
All figures below are illustrative. Replace them with your own measurements.
Learning Objectives
- Define efficiency goals and measure cost, performance, and utilization.
- Allocate and attribute cost using tags and budgets.
- Right-size compute, storage, and databases using evidence.
- Choose scaling approaches that match the load pattern.
- Reduce waste in pipelines, images, environments, and logs.
- Balance cost against reliability and other quality attributes.
- Use AI to analyze usage and propose optimizations, and verify them safely.
1. Start With Goals and Measurement
Do not optimize in the dark. Decide what you are optimizing for, then measure.
| Dimension | Example measures |
|---|---|
| Cost | Monthly spend by environment and service; cost per customer or per import (unit cost) |
| Performance | Latency percentiles, throughput, import duration for a 50,000-row file |
| Utilization | CPU, memory, storage, and connection use versus provisioned capacity |
| Reliability | Availability, error rate, saturation (do not trade this away) |
| Pipeline efficiency | Duration, queue time, compute minutes per run, cost per run |
| Developer productivity | Time to feedback, time to deploy |
Record a baseline for each before changing anything, and define the success criterion (“reduce staging cost by 40% with no change in test results”).
Two principles:
- Optimize the largest cost or bottleneck first. A twenty percent saving on the largest line item beats elimination of three small ones.
- Reliability is a constraint, not a variable. An optimization that harms reliability is a trade-off that someone accountable must accept explicitly.
2. Make Cost Visible
You cannot reduce what you cannot attribute.
- Tag everything by environment, service, owner, and cost center, defined in infrastructure code (lesson 4) and enforced by policy. Untagged resources are a finding.
- Report costs by environment and service on a regular schedule, to the team that owns them.
- Set budgets and alerts for each environment, with thresholds that trigger a human look before the bill arrives.
- Compute unit costs: cost per active workspace, per import, per generated summary. Unit costs show whether growth is sustainable and where design choices matter. Costs of model provider calls often dominate for AI-backed features.
- Look for anomalies: a sudden rise usually has a cause (a runaway job, a log flood, an unbounded loop calling the model provider).
3. Right-Sizing
Most systems are provisioned for imagined peaks.
| Resource | Evidence to gather | Possible action |
|---|---|---|
| Compute | CPU and memory utilization over a representative period, including peaks | Reduce instance size or count; use autoscaling for variable load |
| Database | CPU, memory, connections, I/O, slow queries, storage growth | Resize; fix queries and add indexes before buying a larger instance; use read replicas only where reads dominate |
| Storage | Growth rate, access patterns, retention requirements | Lifecycle rules, cheaper tiers for rarely accessed data, deletion of expired data |
| Queue and cache | Depth, hit rate, memory | Resize; tune retention |
| Network | Data transfer between zones and out to the internet | Place chatty components together; compress; cache |
Rules:
- Use at least a few weeks of data, including peak periods (month-end imports, for instance).
- Leave headroom for spikes and growth (for example, sustained peaks below 60 to 70 percent of capacity, an illustrative range).
- Fix inefficiency before buying capacity: a missing index or an unbounded query costs more than hardware.
- Change one thing at a time and compare metrics before and after.
- Make changes reversible through infrastructure code, with the plan reviewed.
4. Scaling
Match capacity to load.
- Vertical scaling (a bigger instance) is simple but has limits and often downtime.
- Horizontal scaling (more instances) needs stateless services (lesson 3) and a load-balanced entry point.
- Autoscaling adds and removes capacity from metrics. Choose a metric that reflects real demand: for the API, request rate or latency; for the worker, queue depth or oldest message age, not CPU.
- Set minimums and maximums: a minimum for resilience and a maximum as a cost and safety limit, so a bug cannot create unbounded spend.
- Test scaling with a load test: does it scale up in time, and does it scale down without dropping work?
- Scale to zero for non-production environments outside working hours, or create them on demand.
- Protect shared dependencies: scaling the worker can overwhelm the database or the model provider. Apply concurrency limits, backoff, and rate limits.
5. Reducing Waste
Environments
- Shut down or destroy idle development and preview environments automatically (scheduled shutdowns, time-to-live tags).
- Right-size staging; use production scale only for planned rehearsals.
- Find and remove orphaned resources: unattached volumes, old snapshots, unused addresses, stale images.
Pipelines
- Cache dependencies and layers; parallelize sensibly; skip unnecessary work for changes that do not affect a stage.
- Cancel superseded runs when a newer commit arrives on the same branch.
- Run expensive suites (full end-to-end, mutation tests) on a schedule or before release, not on every push, as set out in the quality strategy.
- Right-size runners: an oversized runner wastes money; an undersized one wastes time. Measure.
- Limit artifact and log retention to what you need for audit and debugging.
Images and registry
- Smaller images pull faster and store cheaper (lesson 3); enforce retention to delete old untagged images.
Observability data
- Logs and metrics are a major hidden cost. Reduce log volume (levels, sampling of noisy debug logs), set retention by value, and avoid high-cardinality metric labels. Never reduce what you need for incident response.
AI usage
- Cache repeated model calls where acceptable, limit input size, choose the smallest model that meets the quality bar (with evaluation from the quality course), set budgets and rate limits, and monitor spend per feature.
6. Performance
Improve performance where users or costs feel it.
- Measure before tuning. Use profiling and tracing to find the real bottleneck.
- Fix the biggest bottleneck first: database queries, serial processing of large imports, unnecessary data transfer.
- Batch and parallelize safely: process rows in batches, keep idempotency, and respect limits on shared systems.
- Cache with care: define invalidation, and avoid caching data scoped by workspace in a way that can cross workspaces (the isolation requirement from the quality course).
- Set performance budgets (for example, p95 API latency, import time for a reference file) and test against them in the pipeline or in scheduled checks.
7. Trade-offs: Cost, Reliability, and Simplicity
Every optimization trades something.
| Optimization | Saves | Risk |
|---|---|---|
| Single-zone database | Cost | Outage if the zone fails |
| Smaller instances | Cost | Less headroom for spikes |
| Aggressive autoscale-down | Cost | Slow response to bursts |
| Spot or preemptible capacity | Cost | Interruptions; needs tolerant workloads (workers can often use it; the database cannot) |
| Longer log retention reduction | Cost | Less data for investigations |
| Reserved or committed capacity | Cost | Lock-in if needs change |
| Caching | Latency and cost | Stale or incorrect data |
| Heavy custom tuning | Performance | Complexity for maintainers |
State the trade-off, name the person who accepts it, and record important ones as ADRs. Simplicity is a form of reliability: the cheapest system you cannot operate is not cheap.
8. Continuous Improvement
- Review costs and utilization monthly, and after each major release.
- Keep an optimization backlog with estimated savings, risk, and effort, and work from the top.
- Verify results: after each change, compare with the baseline and record the actual savings and any side effects.
- Automate guardrails: budgets, tag policies, scheduled shutdowns, and alerts, so that savings persist.
- Share the numbers with the team. Engineers make better design choices when they can see what choices cost.
9. Using AI for Optimization
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Act as a cloud cost and performance analyst.
Inputs:
- Monthly cost report by service and environment (identifiers
redacted): [paste]
- Utilization metrics for compute, database, and queue over the
last 30 days, including peaks: [paste]
- Infrastructure definitions: [paste]
- Pipeline run statistics: duration, queue time, compute minutes: [paste]
- Reliability objectives and constraints: [paste]
Tasks:
1. Identify the five largest cost items and the five lowest-utilization
resources.
2. For each, propose an optimization with estimated saving,
reliability risk, effort, and how to verify it.
3. Identify resources that look unused or orphaned, as questions
for their owners.
4. Identify pipeline changes that would reduce duration or cost
without removing a gate.
5. List optimizations you considered and rejected because of the
reliability objectives, and why.
Base every claim on the inputs. Give estimates as ranges and state
assumptions. Do not recommend removing capacity that the peak
metrics need.
Treat output as a candidate list. Verify each saving estimate against pricing, check the utilization over the right period, and test changes in non-production first. Models often recommend cutting capacity based on averages that hide peaks, or suggest resources that do not exist in your provider. Never let an automated process delete resources on the model’s advice without human review of what will be removed.
10. Practical Exercise
For SignalDesk (or your project):
- Define optimization goals and success criteria, and record baselines for cost, utilization, performance, and pipeline duration.
- Enforce tags with a policy, and produce a cost report by environment and service, including unit costs.
- Set budgets and alerts for each environment.
- Right-size one resource using at least two weeks of data, change it through infrastructure code, and compare before and after.
- Configure autoscaling for the worker based on queue depth, with minimum and maximum limits, and test it with a load of imports.
- Schedule automatic shutdown of non-production environments outside working hours, and delete orphaned resources.
- Reduce pipeline cost or duration by at least 20 percent through caching, cancellation of superseded runs, or scheduling heavy suites.
- Review log volume and retention; reduce noise without losing incident evidence.
- Run the AI analysis prompt, verify each recommendation against data, and record the trade-offs accepted as ADRs.
Verification
You are ready to continue when:
- Baselines exist, and every optimization has a measured result.
- Costs are attributable by environment and service, with budgets and alerts.
- Right-sizing decisions rest on utilization data that includes peaks.
- Autoscaling uses a meaningful metric and has limits, and was tested under load.
- Non-production environments do not run idle at full size.
- No optimization reduced reliability below the agreed objectives.
- Accepted trade-offs are recorded with an owner.
Key Takeaways
- Measure first, attribute costs, and optimize the largest opportunity.
- Treat reliability as a constraint; record trade-offs and who accepted them.
- Right-size with evidence, fix inefficiency before adding capacity, and change one thing at a time.
- Scale on demand-related metrics, with limits, and protect shared dependencies.
- AI finds candidate savings from data; people verify the evidence and own the consequences.
What’s Next?
You have all the parts of a delivery system. In the capstone, you assemble them into a Production Deployment Pipeline, rehearse it end to end, and assess whether the release candidate is ready to go to production.