Carbon-Aware Scheduling: Building Sustainable Kubernetes Workloads
The environmental impact of digital infrastructure is no longer a peripheral concern for software engineers. Data centers currently account for approximately 1% to 2% of global electricity consumption, a figure poised to rise with the proliferation of AI and high-performance computing. While cloud providers have made significant strides in purchasing renewable energy credits, the physical reality of the grid is more complex. At any given moment, the carbon intensity of the electricity powering your nodes fluctuates based on the mix of wind, solar, gas, and coal feeding the local grid.
As engineers, we have a new optimization metric to consider alongside latency, throughput, and cost: Carbon Intensity. By implementing carbon-aware workload scheduling, we can move beyond passive consumption and start operationalizing sustainability. This article explores how to use the Green Software Foundation’s Carbon-Aware SDK in conjunction with Kubernetes to dynamically shift non-urgent tasks to periods of cleaner energy.
Understanding Carbon Intensity: Marginal vs. Average
Before diving into implementation, we must understand what we are measuring. Carbon intensity is measured in grams of CO2 equivalent per kilowatt-hour (gCO2e/kWh).
There are two primary ways to look at this:
- Average Carbon Intensity: The mean emissions of all energy generators on the grid.
- Marginal Carbon Intensity: The emissions produced by the next power plant that would be turned on to meet an increase in demand.
For workload shifting, marginal carbon intensity is the critical metric. When we decide to run a heavy batch job, we are adding load to the grid. If that load forces a coal-fired "peaker" plant to spin up, our marginal impact is high, even if the average intensity of the grid is relatively low. The Carbon-Aware SDK allows us to query these signals to make informed scheduling decisions.
The Carbon-Aware SDK: An Overview
The Green Software Foundation (GSF) developed the Carbon-Aware SDK to provide a standardized interface for accessing carbon intensity data. Instead of writing custom integrations for various data providers like WattTime or Electricity Maps, the SDK abstracts these sources into a common set of APIs.
The SDK can be used as a CLI, a Web API, or a library. For Kubernetes-based environments, we typically interact with the SDK's Web API or integrate the library directly into our custom controllers or sidecars. The core functionality we care about is the ability to ask: "When, in the next 24 hours, will the carbon intensity be at its lowest in this specific region?"
Strategy: Temporal vs. Spatial Shifting
There are two primary levers we can pull to reduce carbon impact:
Temporal Shifting
This involves delaying a workload until a time when the grid is cleaner. This is ideal for non-urgent, asynchronous tasks like batch processing, ML model retraining, or generating monthly reports. If a job needs to be done by tomorrow morning, it doesn't matter if it runs at 2:00 PM or 2:00 AM—but the carbon difference can be as high as 40-60%.
Spatial Shifting
This involves moving the workload to a different geographic region where the grid is currently greener. While powerful, spatial shifting is often more complex due to data residency requirements, egress costs, and the latency involved in moving large datasets.
For the remainder of this guide, we will focus on Temporal Shifting within a Kubernetes environment.
Implementing Carbon-Awareness in Kubernetes
To make Kubernetes carbon-aware, we need to bridge the gap between the Carbon-Aware SDK and the K8s scheduler. There are three common architectural patterns for this:
- The CronJob Wrapper (Simple): A script that checks intensity before triggering a job.
- The Admission Controller (Intermediate): Mutating webhooks that delay pod creation based on carbon signals.
- The Custom Scheduler or Operator (Advanced): Using a project like
Kueueor a custom operator to manage a queue of pending work based on carbon thresholds.
Example: The Carbon-Aware Check Pattern
Let's look at a practical implementation using a simple Go-based check that can be used as an initContainer or a wrapper for a Kubernetes Job. This script queries the Carbon-Aware SDK to see if the current intensity is below a certain threshold.
// Simplified logic for a carbon-aware trigger func main() { region := os.Getenv("CLOUD_REGION") threshold := 250 // gCO2e/kWh carbonClient := carbonaware.NewClient("http://carbon-aware-sdk-api") currentIntensity, err := carbonClient.GetCurrentIntensity(region) if err != nil { log.Fatalf("Failed to fetch carbon data: %v", err) } if currentIntensity.Value > threshold { fmt.Printf("Current intensity %v is above threshold %v. Postponing...", currentIntensity.Value, threshold) os.Exit(1) // Exit with error to trigger K8s backoff or custom retry logic } fmt.Println("Grid is clean. Proceeding with workload.") }
Leveraging Kueue for Advanced Batch Scheduling
For enterprise-grade workloads, simple retry loops are insufficient. Kueue is a Kubernetes-native quota management and job queuing system. We can integrate carbon-awareness into Kueue by creating a controller that manages ResourceFlavors or ClusterQueues based on carbon data.
When carbon intensity is high, the controller can "suspend" a queue, preventing new jobs from starting. When the intensity drops below the target threshold, the controller resumes the queue, and Kubernetes begins scheduling the pods.
Practical Scenario: ML Model Training
Imagine a scenario where a data science team needs to retrain a recommendation model daily. The training takes 4 hours.
The Naive Approach: A CronJob starts the training at 12:00 AM UTC. Depending on the region (e.g., US-East), this might coincide with a period of low wind production, leading to a high carbon footprint.
The Carbon-Aware Approach:
- The CronJob triggers a "Scheduler" pod.
- The Scheduler queries the Carbon-Aware SDK: "Find the 4-hour window with the lowest carbon intensity between now and 8:00 AM."
- The SDK returns a start time of 3:15 AM.
- The Scheduler creates the Kubernetes Job with a
startAfterannotation or simply sleeps until the designated time.
By shifting this single 4-hour window, the team could reduce the carbon footprint of that specific training run by 30% without affecting the business requirement of having the model ready by the morning.
Architectural Considerations and Trade-offs
Implementing carbon-aware scheduling is not without its challenges. As a senior engineer, you must weigh these factors:
1. Idempotency and State
If you are killing or suspending workloads when carbon intensity spikes, your applications must be idempotent. They need to handle interruptions gracefully using checkpoints. This is particularly important for long-running ML or simulation jobs.
2. Data Gravity
Spatial shifting is difficult because data has "mass." Moving 10TB of data to a greener region might consume more energy in network transit than you save by running the compute there. Always calculate the "Carbon ROI" of moving data.
3. The "Thundering Herd" Problem
If every company uses the same Carbon-Aware SDK and the same data providers, everyone might try to start their batch jobs at the exact same minute when the grid turns green. This could create a new peak in demand. Implementing a "jitter" or randomized delay within the green window is a best practice to avoid stressing the grid.
4. SLAs and Deadlines
Carbon-awareness should never break a business SLA. Your scheduling logic must include a "must-run-by" timestamp. If the deadline is approaching and the grid hasn't reached the desired low-carbon threshold, the job must run regardless of intensity.
Measuring and Reporting Success
You cannot improve what you do not measure. To validate the impact of your carbon-aware scheduler, you should export carbon metrics to your observability stack (e.g., Prometheus and Grafana).
Key metrics to track include:
- Estimated Carbon Saved: The difference between the carbon produced at the scheduled time vs. the carbon that would have been produced at the original request time.
- Deferred Time: How long, on average, workloads are being shifted.
- Success Rate: How often jobs meet their low-carbon threshold vs. hitting their hard deadline.
Using the kube-state-metrics along with a custom exporter for carbon intensity allows you to create dashboards that show the "Greenness" of your clusters in real-time.
Conclusion: Your Action Plan
Carbon-aware computing is the next frontier of cloud-native architecture. It transforms sustainability from a corporate social responsibility (CSR) report into a technical specification.
To get started:
- Identify Candidates: Look for non-urgent, batch-oriented workloads in your Kubernetes clusters.
- Deploy the SDK: Set up the Carbon-Aware SDK Web API in your cluster.
- Start Small: Implement a simple "Carbon Gate" in a non-production CronJob using an initContainer or a wrapper script.
- Scale with Tooling: Explore more robust queuing solutions like Kueue for managing large-scale batch processing.
By treating carbon as a finite resource—much like CPU or memory—we can build systems that are not only efficient and cost-effective but also fundamentally aligned with the health of the planet.