Platform Engineering · Lesson 165

Sustainability Engineering: Measuring and Cutting the Carbon of Software

Software uses electricity, and electricity has a carbon cost that depends on how much energy you use, where (each grid has its own carbon intensity), and when (grids are cleaner when the wind blows and the sun shines). Hardware also carries embodied carbon from being made. Sustainability engineering measures this (cloud carbon tools, the Software Carbon Intensity specification), then cuts it with the same levers as cost: use less, use it fully, put flexible work in cleaner places and hours, and keep less data. This lesson follows one nightly batch platform through a quarter, and shows two failures: a "green" Region choice that doubled data transfer, and a measure that improved because it was counted wrongly.

Difficulty: Advanced · Know this first: Lesson 164, Lesson 156

What you will learn

By the end of this lesson you can work at four levels:

This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up hours of engineering over a quarter. It is a worked example, not a measurement. The measurement and placement hops are where effort goes into numbers that do not reflect reality.

Try it: cut carbon per 1,000 reports

Pick the utilisation work, where the jobs run, and when. The readout shows grams of CO₂e per 1,000 reports and the cost change. The intensities are illustrative.

176 gCO₂e per 1,000 reports
−35%cost change

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Sustainability engineering grows in four levels: reading carbon data, measuring a service, cutting it, and running it as a practice.

Basic — Read carbon data

At the basic level you can read your provider's carbon report and say what it includes.

  • Scope of the report: which accounts, Regions, services, and scopes (1, 2, 3).
  • Location-based and market-based methods, and why they differ.
  • Operational and embodied emissions.

Where it breaks: comparing numbers produced by different methods.

Try it: Basic

This quarter uses market-based figures, last quarter location-based. Can you compare them?

Now do it: Find which method your provider's report uses.

Intermediate — Measure a service

At the intermediate level you measure one service per unit of work.

  • A functional unit and an SCI calculation: (E × I + M) per R.
  • Energy estimated from usage (or Kepler on Kubernetes); intensity per Region.
  • A monthly figure next to cost and SLOs.

Try it: Intermediate

In SCI = ((E × I) + M) per R, what is M?

Now do it: Write the SCI terms for one service.

Advanced — Cut it

At the advanced level you reduce carbon with measured changes.

  • Utilisation: rightsizing, autoscaling, scale to zero, bin-packing.
  • Hardware: ARM and newer instances benchmarked on your workload.
  • Carbon-aware timing for flexible jobs; placement only together with data.
  • Lifecycle and tiering for data.

Try it: Advanced

Which change usually saves the most carbon and money together?

Now do it: Find your least-utilised cluster.

Master — A sustainability practice

At the master level sustainability is part of architecture and reporting.

  • Intensity targets per service; a stable measurement method in writing.
  • Sustainability in design reviews and the Well-Architected review of every workload.
  • Carbon and cost reported together; trade-offs recorded.

Trade-off: some sustainability choices cost resilience or latency (fewer standby resources, distant Regions); make them deliberately, per workload.

Try it: Master

How do you keep sustainability from being forgotten in design?

Now do it: Add a sustainability question to your review template.

Go deeper

The Software Carbon Intensity (SCI) calculation for one batch run, with illustrative numbers:

E  energy           = 42 kWh per night  (CPU, memory, storage, network, estimated from usage)
I  grid intensity   = 380 g CO2e/kWh    (location-based, the Region's grid in those hours)
M  embodied         = 2,100 g per night (servers' manufacturing emissions, shared over their life)
R  functional unit  = 43,000 reports per night

SCI = (E × I + M) / R = (42 × 380 + 2,100) / 43 thousand
    = (15,960 + 2,100) / 43 ≈ 420 g CO2e per 1,000 reports

Measuring on Kubernetes: Kepler (Kubernetes-based Efficient Power Level Exporter) estimates energy per pod from hardware counters and exports it to Prometheus; combine it with a grid-intensity feed for grams per pod. Provider tools give account-level totals with a delay of weeks; use them to check the estimates.

A carbon-aware scheduling rule, in plain terms: for a job with a deadline D and a run time T, consider every start time from now to D − T, look up the forecast grid intensity for each window, and start at the lowest; if no forecast is available, start now. Never let carbon awareness miss a deadline.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. The number that halved by itself.

Timeline

  • Quarter 1Baseline reported with location-based figures for four accounts and three Regions.
  • Quarter 2A new export is set up. It uses market-based figures for one account and misses storage and two Regions. The report shows −50%, and it goes into a company update.
  • Quarter 2 + 3 weeksAn analyst comparing services finds that storage emissions are zero, which is impossible. Recalculated like for like, the reduction is 8%.
  • Quarter 2 + 5 weeksThe figure is restated publicly, and the measurement method is written down and reviewed.

What changed after

The boundary and method are fixed in a document, every report states them, exports are checked for completeness (every account, Region, and service category present), and targets are set as intensity per functional unit.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: Linux and Python 3. The first steps read your own machine's utilisation; the energy counter step needs an Intel or AMD CPU that exposes RAPL (most laptops and servers; not most VMs).

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. How busy is this machine on average? Idle capacity is where most waste starts.

    vmstat 5 6 | awk 'NR>2 {busy+=100-$15; n++} END {printf "CPU busy on average: %.0f%%\n", busy/n}'

    Expect: A single percentage over 30 seconds; on a developer laptop it is usually low. Read-only.

  2. Read the CPU package energy counter (RAPL), if the hardware exposes it.

    cat /sys/class/powercap/intel-rapl:0/name 2>/dev/null && E1=$(sudo cat /sys/class/powercap/intel-rapl:0/energy_uj); sleep 10; E2=$(sudo cat /sys/class/powercap/intel-rapl:0/energy_uj); echo "package power: $(( (E2 - E1) / 10000000 )) W"

    Options: energy_uj is a microjoule counter; the difference over 10 seconds, divided by 10 seconds, is watts.

    Expect: package-0 and a power figure in watts, or nothing on machines without RAPL. Reading needs root on recent kernels; it changes nothing.

  3. Compare the same work done two ways: CPU time is the energy proxy you can always measure.

    python3 -c "import time; t=time.process_time(); s=0
    for i in range(3_000_000): s+=i*i
    print('loop  CPU s:', round(time.process_time()-t,2))"
    python3 -c "import time; t=time.process_time(); s=sum(i*i for i in range(3_000_000)); print('sum() CPU s:', round(time.process_time()-t,2))"

    Expect: Two CPU-time figures; the built-in usually uses less. Efficient code is the cheapest carbon reduction.

2. Python: carbon.py

This program computes the Software Carbon Intensity of a nightly batch platform before and after a quarter of work, then schedules each flexible job in the cleanest window that still meets its deadline, from an hourly grid-intensity forecast. The numbers are illustrative; use your provider's data and a real forecast in practice. Save it as carbon.py, then run it.

# carbon.py
def sci(energy_kwh, intensity_g, embodied_g, reports):
    return (energy_kwh * intensity_g + embodied_g) / (reports / 1000)

before = sci(42.0, 380, 2100, 43_000)
after = sci(20.7, 380 * 0.82, 1100, 43_000)        # utilisation, ARM, cleaner hours; fewer machines' embodied share
print(f"SCI before {before:5.0f} g CO2e per 1,000 reports")
print(f"SCI after  {after:5.0f} g CO2e per 1,000 reports  ({(after - before) / before:+.0%})")
print()

FORECAST = {0: 410, 1: 395, 2: 360, 3: 310, 4: 290, 5: 305, 6: 350, 7: 400}   # g CO2e/kWh by hour
JOBS = [("daily reports", 3, 7), ("index rebuild", 2, 6), ("ml scoring", 4, 7), ("urgent fix rerun", 1, 1)]

def best_start(run_h, deadline_h):
    starts = [h for h in range(0, deadline_h - run_h + 1)]
    if not starts:
        return 0, None
    def avg(h):
        return sum(FORECAST[h + i] for i in range(run_h)) / run_h
    s = min(starts, key=avg)
    return s, avg(s)

print("job               run  deadline  start  avg g/kWh  vs midnight")
for name, run_h, deadline in JOBS:
    start, avg = best_start(run_h, deadline)
    at_midnight = sum(FORECAST[i] for i in range(run_h)) / run_h
    if avg is None:
        print(f"{name:<17} {run_h}h   {deadline:02d}:00     now    -          no slack: run immediately")
        continue
    print(f"{name:<17} {run_h}h   {deadline:02d}:00    {start:02d}:00  {avg:9.0f}  {(avg - at_midnight) / at_midnight:+.0%}")

Run it, and you should see this output:

$ python3 carbon.py
SCI before   420 g CO2e per 1,000 reports
SCI after    176 g CO2e per 1,000 reports  (-58%)

job               run  deadline  start  avg g/kWh  vs midnight
daily reports     3h   07:00    03:00        302  -22%
index rebuild     2h   06:00    04:00        298  -26%
ml scoring        4h   07:00    03:00        314  -15%
urgent fix rerun  1h   01:00    00:00        410  +0%

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/sustainability-engineering && cd ~/labs/sustainability-engineering) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "Sustainability Engineering: Measuring and Cutting the Carbon of Software", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'How busy is this machine on average? Idle capacity is where most waste starts.'
  'Read the CPU package energy counter (RAPL), if the hardware exposes it.'
  'Compare the same work done two ways: CPU time is the energy proxy you can always measure.'
)

step_1() {
vmstat 5 6 | awk 'NR>2 {busy+=100-$15; n++} END {printf "CPU busy on average: %.0f%%\n", busy/n}'
}

step_2() {
cat /sys/class/powercap/intel-rapl:0/name 2>/dev/null && E1=$(sudo cat /sys/class/powercap/intel-rapl:0/energy_uj); sleep 10; E2=$(sudo cat /sys/class/powercap/intel-rapl:0/energy_uj); echo "package power: $(( (E2 - E1) / 10000000 )) W"
}

step_3() {
python3 -c "import time; t=time.process_time(); s=0
for i in range(3_000_000): s+=i*i
print('loop  CPU s:', round(time.process_time()-t,2))"
python3 -c "import time; t=time.process_time(); s=sum(i*i for i in range(3_000_000)); print('sum() CPU s:', round(time.process_time()-t,2))"
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Your company commits to cutting the carbon intensity of its cloud workloads by 40% in two years. Design the engineering programme.

Clarifying questions to ask

How do you measure, with which boundary and method? Which functional units per service? Which levers first, and how do you verify them? Which workloads can shift in time or place? How is it reported, and how does it enter design reviews?

Rough sizing

Say 60 services, 3 Regions, average utilisation of 25%, 2 PB of storage growing 4% a month, and nightly batch work that is 40% of compute.

Shape of the answer

Provider carbon reports plus usage-based estimates (Kepler on Kubernetes) with a written location-based method and fixed boundary; SCI per service with a functional unit each; utilisation work first (rightsizing, autoscaling, scale to zero, bin-packing), then ARM and newer instances after benchmarks; carbon-aware windows for batch jobs within deadlines; Region moves only where data can move too; lifecycle and archive tiers for storage; a monthly dashboard of carbon intensity, cost, and SLOs per service; a sustainability question in every architecture review.

Trade-offs to name

Utilisation and storage work save money as well; carbon-aware timing needs slack in deadlines; Region moves are limited by residency and latency; tighter utilisation leaves less headroom for spikes, so keep it within reliability targets.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
Green Region, far from the dataHop 5: PlacementBreaksThe batch jobs are moved to the lowest-carbon Region, 6,000 km from the data lake, which stays where it is because of residency rules on some tables.
Green Region, far from the dataHop 7: Data and storageDegradesCross-Region copies add 30 TB a month of transfer.
Counted wronglyHop 1: MeasurementBreaksThis quarter's report uses market-based figures for one account, and its export left out storage and two Regions, while last quarter used location-based figures for everything. The headline says emissions halved.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Measurement → Functional unit → Utilisation → Hardware → Placement → Timing → Data and storage → Trade-offs → Reporting. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

Architecture review checklist

Review the design in this lesson, or your own, against these ten areas. Tick an area when you can answer its question with evidence: a number, a test, a document, or an owner. Your ticks stay in this browser.

  1. Business outcomeWhich result for users or the business does this design serve, and which number shows it is working?
  2. SecurityWho and what can reach each part, how is identity proven, and how is data protected in transit and at rest?
  3. ReliabilityWhat is the target (SLO), which single failures does the design survive, and how was that tested?
  4. PerformanceWhat latency and throughput are required at peak, and where is the first bottleneck?
  5. OperationsHow is it deployed, observed, and changed safely, and who is paged when it breaks?
  6. CostWhat does it cost per month and per unit of work (request, tenant, model call), and what grows the bill?
  7. SustainabilityWhich resources sit idle, which region and hardware does it run on, and what can scale to zero?
  8. GovernanceWhich policies, guardrails, and compliance rules apply, and how are they enforced in code?
  9. OwnershipWhich team owns each component, its budget, and its on-call, and where is that written down?
  10. Failure and recovery planWhat is the RTO and RPO, what is the runbook for a region or dependency loss, and when was it last rehearsed?

References and review

The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.

Last updated . Next review due by November 2027. Found something out of date? Tell me.

Saved on this device, in this browser.
Next in this series · Lesson 166
Cloud Governance, Policy as Code, and Automated Architecture Reviews

Cloud governance is how an organisation makes sure hundreds of teams build in the cloud safely, within budget, and within the rules, without a review board in the way of every change.

Go to Lesson 166 →

Or browse the full course from the Lessons index.