<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Deepak Geddam on Medium]]></title>
        <description><![CDATA[Stories by Deepak Geddam on Medium]]></description>
        <link>https://medium.com/@dpacgdm?source=rss-5281b93b7a0d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6a6bQJxmc4PnlRU_5NFWEg.jpeg</url>
            <title>Stories by Deepak Geddam on Medium</title>
            <link>https://medium.com/@dpacgdm?source=rss-5281b93b7a0d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 11:58:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dpacgdm/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Stop Guessing Your Kubernetes Costs. Build Namespace-Level Budgets That Actually Bite.]]></title>
            <link>https://dpacgdm.medium.com/stop-guessing-your-kubernetes-costs-build-namespace-level-budgets-that-actually-bite-0e27d5df713a?source=rss-5281b93b7a0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e27d5df713a</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[finops]]></category>
            <category><![CDATA[cloud-cost-optimization]]></category>
            <dc:creator><![CDATA[Deepak Geddam]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 10:16:31 GMT</pubDate>
            <atom:updated>2026-03-01T10:16:31.948Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5eaT26mW6mP_cwJAC0kPcw.png" /><figcaption>The Chaos of Guesswork</figcaption></figure><p>A Go CLI tool that turned our monthly “why is the AWS bill so high” meeting into a solved problem.</p><p>Every month, the same ritual plays out in engineering organizations running Kubernetes. The AWS bill arrives. Someone in finance flags that compute costs went up 18%. An email chain starts. The platform team is asked to “look into it.”</p><p>Someone opens AWS Cost Explorer, squints at a graph grouped by instance type, and tries to reverse-engineer which team or service is responsible.</p><p>This is a terrible way to manage cloud costs.</p><p>The fundamental problem is that Kubernetes abstracts away the infrastructure layer. That’s the whole point — developers think in Pods and Deployments, not EC2 instances. But it also means cost attribution becomes a massive mapping exercise. Which Pods ran on which nodes? How much of that m5.2xlarge was consumed by the search service versus the recommendation engine?</p><p>AWS Cost Explorer doesn’t know about namespaces. Kubernetes doesn’t natively know about dollars. The gap between them is where your money disappears.</p><p>I wrote a Go CLI tool to close that gap.</p><h3>The Math Behind Kubernetes Cost Attribution</h3><p>Before writing any code, I needed to understand how to convert Kubernetes resource consumption into dollar amounts. The logic is straightforward:</p><ol><li>Each node in the cluster has a known hourly cost (based on instance type and region).</li><li>Each Pod on that node consumes a fraction of the node’s CPU and memory capacity.</li><li>A Pod’s cost is proportional to the resources it consumes relative to the node’s total capacity.</li><li>A namespace’s cost is the sum of all Pod costs within it.</li></ol><p>Simple in theory. Tricky in practice because of one major complication: <strong>Requests vs. Actual Usage.</strong></p><p>A Pod might request 2 CPU cores but only use 0.1 cores. Do you charge the team based on what they reserved (requests) or what they actually consumed (usage)?</p><p>I went with <strong>requests</strong>. Requests dictate how the Kubernetes scheduler allocates capacity and prevents other Pods from being scheduled. You are paying AWS for reserved resources whether your application uses them or not. Charging by requests forces teams to right-size their manifests.</p><h3>The CLI Design</h3><p>I wanted a single command that tells you exactly where the money is going, who is over budget, and which specific workloads are responsible. No clicking through AWS consoles. No spreadsheets.</p><p>The output looks like this:</p><pre>$ kube-budget report --context production<br><br>NAMESPACE COST REPORT — production cluster<br>Period: Last 30 Days<br>═══════════════════════════════════════════════════════<br>Namespace          CPU ($)    Memory ($)   Total ($)    Budget ($)   Status<br>─────────────────────────────────────────────────────────────────────────────<br>checkout           $1,247     $891         $2,138       $3,000       ✅ 71%<br>search             $2,103     $1,456       $3,559       $3,500       ⚠️ 101%<br>recommendations    $3,891     $2,234       $6,125       $4,000       🔴 153%<br>catalog            $567       $312         $879         $2,000       ✅ 44%<br>─────────────────────────────────────────────────────────────────────────────<br>CLUSTER TOTAL      $7,808     $4,893       $12,701<br><br>ALERTS:<br>  🔴 recommendations is 53% over budget. Top consumers:<br>     - deployment/reco-engine: $4,102 (67% of namespace cost)</pre><h3>The Code: Calculating Costs in Go</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ro89qwtHmceDaGFDNgQc0Q.png" /><figcaption>The BudgetOperator Takes Action</figcaption></figure><p>The tool uses k8s.io/client-go to pull Node and Pod data. For each Pod, it calculates what fraction of the underlying Node it is consuming.</p><pre>func CalculatePodCost(pod corev1.Pod, node NodeCost, periodHours float64) (float64, error) {<br> var cpuRequest, memRequest float64<br>    <br>    // Sum requests across all containers in the pod<br> for _, container := range pod.Spec.Containers {<br>  if req, ok := container.Resources.Requests[corev1.ResourceCPU]; ok {<br>   cpuRequest += req.AsApproximateFloat64()<br>  }<br>  if req, ok := container.Resources.Requests[corev1.ResourceMemory]; ok {<br>   memRequest += req.AsApproximateFloat64() / (1024 * 1024 * 1024) // GiB<br>  }<br> }<br><br> // Split node cost 50/50 between CPU and memory <br> cpuHourlyCost := node.HourlyCost * 0.5<br> memHourlyCost := node.HourlyCost * 0.5<br><br> // Pod&#39;s share of the node&#39;s CPU and memory cost<br> podCPUCost := (cpuRequest / node.CPUCapacity) * cpuHourlyCost * periodHours<br> podMemCost := (memRequest / node.MemCapacity) * memHourlyCost * periodHours<br><br> return podCPUCost + podMemCost, nil<br>}</pre><p><em>Note: The 50/50 split between CPU and memory is a simplification. For absolute billing-grade precision, you would weight this by the specific local market rates for CPU vs RAM. But for driving developer behavior, directional accuracy is perfectly fine.</em></p><h3>Budget Enforcement (Proration)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lk26WsHcGoceXL1N9CbDyw.png" /><figcaption>Structured Budgets that Actually Bite</figcaption></figure><p>The cost calculation is passive. Budget definitions make it actionable. But raw comparisons are dangerous if you don’t prorate.</p><p>If it’s June 12th and the Search team has spent $2,138 against a $3,500 monthly budget, a naive comparison says they are at 61%. Looks fine, right?</p><p>Wrong. We are only 40% through the month. Prorated, they should have only spent $1,400 by now. They have actually spent 152% of their prorated budget and are on track to blow past their limit.</p><pre>func EvaluateBudget(actual float64, monthlyBudget float64) string {<br> now := time.Now()<br> daysInMonth := float64(time.Date(now.Year(), now.Month()+1, 0, 0, 0, 0, 0, time.UTC).Day())<br> daysSoFar := float64(now.Day())<br> <br> monthProgress := daysSoFar / daysInMonth<br> proratedBudget := monthlyBudget * monthProgress<br> <br> usagePercent := (actual / proratedBudget) * 100<br><br> if usagePercent &gt;= 100 {<br>  return &quot;CRITICAL&quot;<br> } else if usagePercent &gt;= 80 {<br>  return &quot;WARNING&quot;<br> }<br> return &quot;HEALTHY&quot;<br>}</pre><h3>Running It in CI/CD</h3><p>A CLI is great for SREs, but the real behavioral shift happens when you put this in CI/CD.</p><p>We run this as a scheduled GitLab CI/GitHub Actions pipeline every morning at 9 AM. The tool outputs JSON, evaluates it against a budgets.yaml config, and posts directly to each team’s Slack channel.</p><p>No dashboards to check. No reports to request. The financial impact of their infrastructure choices comes directly to them.</p><h3>What I Learned</h3><p><strong>Cost attribution is a political problem, not a technical one.</strong> Getting teams to agree that requests-based attribution is fair — that they should pay for resources they requested but didn’t actually use — is a hard conversation. There is no objectively correct answer. Pick a model, document it clearly, and be consistent.</p><p><strong>Approximate is better than absent.</strong> This tool doesn’t produce AWS billing-grade numbers. It ignores EBS volumes, NAT Gateway data transfer, and ELB hourly charges. But 85% accuracy delivered daily into a team’s Slack channel is infinitely more valuable than 100% accuracy delivered monthly in a spreadsheet nobody reads.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e27d5df713a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Runbooks Are Rotting in Confluence. Turn Them Into Kubernetes Operators]]></title>
            <link>https://dpacgdm.medium.com/your-runbooks-are-rotting-in-confluence-turn-them-into-kubernetes-operators-5ba8ff2f24b0?source=rss-5281b93b7a0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ba8ff2f24b0</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[incident-response]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Deepak Geddam]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 08:23:37 GMT</pubDate>
            <atom:updated>2026-03-01T08:23:37.427Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UYdgN-sLFjdCv4O_z3uQKA.png" /><figcaption>The Transformation</figcaption></figure><p>I got tired of reading documentation at 3am. So, I taught the cluster to read it instead.</p><p>There’s a specific kind of despair that hits when you’re paged at 3:17 AM, you open the runbook for the service that’s on fire, and the first line says, “Last updated: March 2023.”</p><p>You scroll down. Step 3 references a script that no longer exists. Step 5 says “ask @david” and David left the company eight months ago. Step 7 says “if the above doesn’t work, escalate to the database team” with no indication of what that escalation looks like.</p><p>I’ve been on the receiving end of this enough times. Every SRE team I know maintains runbooks. Every SRE team I know also knows their runbooks are partially outdated, partially wrong, and consistently ignored during actual incidents because the cognitive load of following a document while troubleshooting a production fire at 3 AM is just too high.</p><p>The standard response is “we should update our runbooks more often.” This is like saying “we should floss more.” Correct, well-intentioned, and never going to happen consistently.</p><p>Instead of writing better documentation for humans to follow under stress, I started writing runbooks that the cluster executes on its own.</p><h3>The Insight That Started This</h3><p>During an on-call shift, I noticed the majority of our pages fell into a small number of recurring patterns:</p><ol><li><strong>OOMKill loops</strong> — A pod gets OOMKilled, restarts, gets OOMKilled again. The fix: capture a heap dump, bump the memory limit temporarily, page the owning team in the morning.</li><li><strong>Connection pool exhaustion</strong> — Database connections fill up, latency spikes. The fix: rolling restart of the affected pods to reset connections.</li><li><strong>Crashloop after a bad deploy</strong> — A deployment goes out, pods crashloop. The fix: auto-rollback to the previous ReplicaSet.</li></ol><p>These aren’t complex problems. They don’t require creative debugging. They require executing a known sequence of steps quickly. That’s not a human problem. That’s a controller problem.</p><h3>Modeling Runbooks as Kubernetes Resources</h3><p>A runbook has two parts: a trigger condition and a sequence of actions. That maps cleanly to a Custom Resource Definition (CRD):</p><pre>apiVersion: respond.kuberespond.dev/v1<br>kind: Playbook<br>metadata:<br>  name: oomkill-response<br>  namespace: production<br>spec:<br>  description: &quot;Auto-respond to OOMKill loops in production&quot;<br>  trigger:<br>    type: prometheus<br>    query: |<br>      increase(kube_pod_container_status_oomkilled_total{namespace=&quot;production&quot;}[5m]) &gt; 3<br>    evaluationInterval: 30s<br>  conditions:<br>    cooldown: 15m<br>  actions:<br>    - name: capture-diagnostics<br>      type: execInPod<br>      config:<br>        command:[&quot;/bin/sh&quot;, &quot;-c&quot;, &quot;jmap -dump:format=b,file=/tmp/heapdump.hprof 1&quot;]<br>    - name: bump-memory<br>      type: patchResource<br>      config:<br>        resource: deployment<br>        patch: |<br>          spec:<br>            template:<br>              spec:<br>                containers:<br>                  - name: app<br>                    resources:<br>                      limits:<br>                        memory: &quot;2Gi&quot;<br>    - name: notify-team<br>      type: slack<br>      config:<br>        channel: &quot;#incidents&quot;<br>        message: &quot;OOMKill Auto-Response Triggered. Memory bumped to 2Gi.&quot;</pre><p>Notice what this replaces: a Confluence page with screenshots, a manual checklist, and tribal knowledge.</p><p>Now the runbook is version-controlled in Git, reviewed via pull request, deployed via ArgoCD, and executed consistently regardless of how tired the on-call engineer is.</p><h3>The Controller Architecture</h3><p>The operator I built uses controller-runtime and splits into two main loops:</p><p><strong>Trigger Evaluation Loop:</strong> Periodically queries Prometheus for each Playbook’s trigger condition. When a condition evaluates to true (and the cooldown period has elapsed), it creates a PlaybookExecution resource.</p><p><strong>Action Execution Loop:</strong> Watches PlaybookExecution resources and runs each action in sequence, updating the status after each step.</p><p>This separation means trigger evaluation and action execution have independent lifecycles. If the action executor crashes mid-sequence, it can resume from the last completed step when it restarts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0JpzJ_iAJcNtvGI0nqLEYw.png" /></figure><h3>Executing Actions Safely</h3><p>Giving a controller permission to modify deployments and execute commands in pods is dangerous. Safety mechanisms are non-negotiable.</p><p><strong>1. Cooldown Enforcement:</strong><br>Without cooldowns, a memory leak would trigger the OOMKill playbook over and over until you’ve allocated 128Gi to a single pod. The operator checks the creation timestamp of the last PlaybookExecution and enforces a hard 15-minute cooldown before allowing another run.</p><p><strong>2. Fail-Fast on Action Errors:</strong><br>If step 2 of a 4-step playbook fails, the operator halts. Partial execution with gaps is worse than stopping and alerting a human.</p><p><strong>3. State Persistence:</strong><br>The operator persists the result of each action to the PlaybookExecution.status subresource. If the controller is evicted between step 2 and step 3, the next reconciliation sees two completed actions and resumes strictly from step 3.</p><h3>The Audit Trail</h3><p>Every action must be auditable. When the morning shift asks “why is the checkout API running with 2Gi memory?”, the answer needs to be findable in seconds.</p><p>Each PlaybookExecution acts as a permanent, immutable record:</p><pre>status:<br>  phase: Completed<br>  triggerTime: &quot;2025-06-12T03:17:23Z&quot;<br>  completedActions:<br>    - name: capture-diagnostics<br>      status: success<br>      startTime: &quot;2025-06-12T03:17:24Z&quot;<br>      endTime: &quot;2025-06-12T03:17:31Z&quot;<br>    - name: bump-memory<br>      status: success<br>      startTime: &quot;2025-06-12T03:17:31Z&quot;</pre><p>Running kubectl get playbookexecutions -n production gives you the complete history of every automated response. No digging through Slack threads.</p><h3>What This Doesn’t Replace</h3><p>This system handles <strong>known failure modes with known responses.</strong> It is not an AI that magically fixes novel outages, and it doesn’t replace the need for incident commanders during complex degradation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y8x2uwZI_ez-rFZLhXlXZA.png" /><figcaption>The 3 AM Page</figcaption></figure><p>The 3 AM page for “a thing that’s happened before and has a documented fix” should be automated away. The 3 AM page for “something we’ve never seen before” still needs a human. In practice, I found that roughly 60% of recurring pages fell into patterns that could be expressed as Playbooks. That is 60% fewer 3 AM wake-ups.</p><p>Runbooks shouldn’t be documentation. They should be code. And if they’re going to be code, they should be Kubernetes resources.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ba8ff2f24b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your SLOs Should Be Kubernetes Resources, Not Grafana Dashboards]]></title>
            <link>https://dpacgdm.medium.com/your-slos-should-be-kubernetes-resources-not-grafana-dashboards-8d94820e2b32?source=rss-5281b93b7a0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d94820e2b32</guid>
            <category><![CDATA[crd]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[slo]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Deepak Geddam]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 17:30:56 GMT</pubDate>
            <atom:updated>2026-02-23T17:30:56.270Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How treating Service Level Objectives as declarative infrastructure changed the way I think about reliability</em></p><p>Every SRE team I’ve talked to has the same problem. Somewhere in their stack, there’s a Google Doc or a Confluence page titled something like “SLO Definitions — Q3 2024.” It lists targets. 99.95% availability for checkout. P99 latency under 300ms for search. 99.9% success rate for payments.</p><p>And somewhere else entirely — in a completely different system — there are Prometheus recording rules that may or may not implement those targets correctly. And in yet another system, Grafana dashboards that may or may not visualize them accurately. And in someone’s head, there’s tribal knowledge about what the actual burn rate thresholds should be.</p><p>None of these things are connected. None of them are version-controlled together. None of them go through pull request review as a single unit.</p><p>I started asking myself a question that seemed obvious once I said it out loud: if we treat deployments, services, ingress rules, and network policies as declarative Kubernetes resources — versioned in Git, reconciled by controllers, reviewed in PRs — why don’t we do the same thing with SLOs?</p><p>This post walks through why I think SLOs belong in the Kubernetes API, how to build an operator that makes this work, and the architectural decisions that come up when you try.</p><h3>The Problem With How We Define SLOs Today</h3><p>The standard SRE approach to SLOs goes something like this:</p><p>Step 1: A team sits in a meeting and agrees on targets. Someone writes them down.</p><p>Step 2: An SRE translates those targets into Prometheus recording rules. Something like:</p><pre>groups:<br>  - name: slo_checkout_availability<br>    rules:<br>      - record: slo:checkout:error_rate:5m<br>        expr: |<br>          sum(rate(http_requests_total{service=&quot;checkout&quot;, code=~&quot;5..&quot;}[5m]))<br>          /<br>          sum(rate(http_requests_total{service=&quot;checkout&quot;}[5m]))</pre><p>Step 3: Someone creates a Grafana dashboard that visualizes error budgets based on these rules.</p><p>Step 4: Someone configures alerting rules for burn rate thresholds, hopefully following the multi-window multi-burn-rate approach from Google’s SRE workbook.</p><p>Step 5: Six months later, the team revises the SLO target from 99.95% to 99.9%. Someone updates the Confluence page. The Prometheus rules don’t get updated for three weeks. The Grafana dashboard still shows the old target. The alerts fire at wrong thresholds for a month until someone notices.</p><p>I’ve seen this exact sequence play out at scale. The fundamental issue is that an SLO is a single concept being expressed across four disconnected systems maintained by different people at different times.</p><p>This is a configuration drift problem. And we already know how to solve configuration drift.</p><h3>What If SLOs Were CRDs?</h3><p>Imagine this is your entire SLO definition:</p><pre>apiVersion: slo.kubeslo.dev/v1<br>kind: ServiceSLO<br>metadata:<br>  name: checkout-availability<br>  namespace: production<br>  labels:<br>    team: payments<br>    tier: critical<br>spec:<br>  service: checkout-api<br>  description: &quot;Checkout API availability for end users&quot;<br>  objective: 99.95<br>  window: 30d<br>  indicator:<br>    type: availability<br>    metric: http_requests_total<br>    totalFilter: &#39;service=&quot;checkout-api&quot;&#39;<br>    errorFilter: &#39;code=~&quot;5..&quot;&#39;<br>  alerting:<br>    burnRates:<br>      - severity: critical<br>        shortWindow: 5m<br>        longWindow: 1h<br>        factor: 14.4<br>      - severity: warning<br>        shortWindow: 30m<br>        longWindow: 6h<br>        factor: 6</pre><p>One file. Version-controlled in Git. Reviewed in a pull request by both the SRE and the product owner. Applied with kubectl apply. And a controller running in the cluster takes this single source of truth and generates everything else automatically.</p><p>No manual Prometheus rules. No hand-crafted Grafana JSON. No copy-paste alerting configs. One resource, reconciled continuously.</p><h3>Building the Operator</h3><p>I built this using kubebuilder and controller-runtime. The high-level architecture is straightforward:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CWQ-F_ki4TSUn5DnlZA3rA.png" /></figure><p>The controller watches for ServiceSLO resources and reconciles three downstream objects:</p><ol><li>A PrometheusRule resource (if you’re using prometheus-operator) containing the recording rules</li><li>A second PrometheusRule resource containing multi-burn-rate alerting rules</li><li>A ConfigMap containing generated Grafana dashboard JSON</li></ol><p>Let me walk through the interesting parts.</p><pre>// api/v1/serviceslo_types.go<br><br>package v1<br><br>import (<br>    metav1 &quot;k8s.io/apimachinery/pkg/apis/meta/v1&quot;<br>)<br><br>type SLOIndicatorType string<br><br>const (<br>    SLOAvailability SLOIndicatorType = &quot;availability&quot;<br>    SLOLatency      SLOIndicatorType = &quot;latency&quot;<br>)<br><br>type SLOIndicator struct {<br>    Type          SLOIndicatorType `json:&quot;type&quot;`<br>    Metric        string           `json:&quot;metric&quot;`<br>    TotalFilter   string           `json:&quot;totalFilter&quot;`<br>    ErrorFilter   string           `json:&quot;errorFilter,omitempty&quot;`<br>    // For latency SLOs<br>    ThresholdMs   float64          `json:&quot;thresholdMs,omitempty&quot;`<br>    LatencyMetric string           `json:&quot;latencyMetric,omitempty&quot;`<br>}<br><br>type BurnRateAlert struct {<br>    Severity    string  `json:&quot;severity&quot;`<br>    ShortWindow string  `json:&quot;shortWindow&quot;`<br>    LongWindow  string  `json:&quot;longWindow&quot;`<br>    Factor      float64 `json:&quot;factor&quot;`<br>}<br><br>type SLOAlerting struct {<br>    BurnRates []BurnRateAlert `json:&quot;burnRates&quot;`<br>}<br><br>type ServiceSLOSpec struct {<br>    Service     string       `json:&quot;service&quot;`<br>    Description string       `json:&quot;description,omitempty&quot;`<br>    Objective   float64      `json:&quot;objective&quot;`<br>    Window      string       `json:&quot;window&quot;`<br>    Indicator   SLOIndicator `json:&quot;indicator&quot;`<br>    Alerting    SLOAlerting  `json:&quot;alerting&quot;`<br>}<br><br>type ServiceSLOStatus struct {<br>    // Track what we&#39;ve generated<br>    RecordingRuleGenerated bool   `json:&quot;recordingRuleGenerated&quot;`<br>    AlertRuleGenerated     bool   `json:&quot;alertRuleGenerated&quot;`<br>    DashboardGenerated     bool   `json:&quot;dashboardGenerated&quot;`<br>    LastReconciled         string `json:&quot;lastReconciled&quot;`<br>}<br><br>// +kubebuilder:object:root=true<br>// +kubebuilder:subresource:status<br>type ServiceSLO struct {<br>    metav1.TypeMeta   `json:&quot;,inline&quot;`<br>    metav1.ObjectMeta `json:&quot;metadata,omitempty&quot;`<br><br>    Spec   ServiceSLOSpec   `json:&quot;spec,omitempty&quot;`<br>    Status ServiceSLOStatus `json:&quot;status,omitempty&quot;`<br>}</pre><p>Nothing clever here. Standard kubebuilder boilerplate. The interesting decisions start in the reconciler.</p><h4>The Reconciliation Loop</h4><pre>// internal/controller/serviceslo_controller.go<br><br>func (r *ServiceSLOReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {<br>    log := log.FromContext(ctx)<br><br>    // Fetch the ServiceSLO resource<br>    var slo slov1.ServiceSLO<br>    if err := r.Get(ctx, req.NamespacedName, &amp;slo); err != nil {<br>        if apierrors.IsNotFound(err) {<br>            // SLO was deleted — downstream resources get garbage<br>            // collected via OwnerReferences<br>            log.Info(&quot;ServiceSLO deleted, owned resources will be cleaned up&quot;)<br>            return ctrl.Result{}, nil<br>        }<br>        return ctrl.Result{}, err<br>    }<br><br>    // Generate and apply Prometheus recording rules<br>    if err := r.reconcileRecordingRules(ctx, &amp;slo); err != nil {<br>        log.Error(err, &quot;failed to reconcile recording rules&quot;)<br>        return ctrl.Result{}, err<br>    }<br><br>    // Generate and apply alerting rules<br>    if err := r.reconcileAlertingRules(ctx, &amp;slo); err != nil {<br>        log.Error(err, &quot;failed to reconcile alerting rules&quot;)<br>        return ctrl.Result{}, err<br>    }<br><br>    // Generate and apply Grafana dashboard ConfigMap<br>    if err := r.reconcileDashboard(ctx, &amp;slo); err != nil {<br>        log.Error(err, &quot;failed to reconcile dashboard&quot;)<br>        return ctrl.Result{}, err<br>    }<br><br>    // Update status<br>    slo.Status.LastReconciled = time.Now().UTC().Format(time.RFC3339)<br>    slo.Status.RecordingRuleGenerated = true<br>    slo.Status.AlertRuleGenerated = true<br>    slo.Status.DashboardGenerated = true<br>    if err := r.Status().Update(ctx, &amp;slo); err != nil {<br>        return ctrl.Result{}, err<br>    }<br><br>    return ctrl.Result{RequeueAfter: 5 * time.Minute}, nil<br>}</pre><p>A few decisions worth explaining:</p><p>Why RequeueAfter: 5 * time.Minute? The controller primarily reacts to changes in ServiceSLO resources via watches. But periodic reconciliation catches cases where downstream resources (PrometheusRules, ConfigMaps) were manually deleted or modified. Five minutes is a reasonable balance between responsiveness and API server load.</p><p>Why OwnerReferences for cleanup? When someone deletes a ServiceSLO, the recording rules, alerting rules, and dashboard ConfigMap should disappear too. Setting OwnerReferences on all generated resources lets Kubernetes garbage collection handle this automatically. No finalizer complexity needed.</p><h4>Generating Multi-Burn-Rate Alerts</h4><p>This is where the actual SRE thinking lives. A naive implementation would generate a single alert when error rate exceeds the budget. But that’s useless in practice — it fires too late for fast burns and too noisy for slow ones.</p><p>The multi-window multi-burn-rate approach from Google’s SRE workbook uses different time windows to catch different failure modes:</p><pre>func (r *ServiceSLOReconciler) generateAlertRules(slo *slov1.ServiceSLO) []monitoringv1.Rule {<br>    var rules []monitoringv1.Rule<br><br>    errorBudget := 1 - (slo.Spec.Objective / 100)<br>    sloName := slo.Name<br><br>    for _, br := range slo.Spec.Alerting.BurnRates {<br>        burnThreshold := br.Factor * errorBudget<br><br>        // Both windows must be breaching to fire<br>        // This dramatically reduces false positives<br>        expr := fmt.Sprintf(<br>            `(<br>              slo:%s:error_rate:%s &gt; %.6f<br>              and<br>              slo:%s:error_rate:%s &gt; %.6f<br>            )`,<br>            sloName, br.ShortWindow, burnThreshold,<br>            sloName, br.LongWindow, burnThreshold,<br>        )<br><br>        rules = append(rules, monitoringv1.Rule{<br>            Alert: fmt.Sprintf(&quot;SLOBurnRate_%s_%s&quot;, sloName, br.Severity),<br>            Expr:  intstr.FromString(expr),<br>            For:   monitoringv1.Duration(&quot;60s&quot;),<br>            Labels: map[string]string{<br>                &quot;severity&quot;: br.Severity,<br>                &quot;slo&quot;:      sloName,<br>                &quot;service&quot;:  slo.Spec.Service,<br>            },<br>            Annotations: map[string]string{<br>                &quot;summary&quot;: fmt.Sprintf(<br>                    &quot;SLO %s is burning error budget at %.1fx the allowed rate&quot;,<br>                    sloName, br.Factor,<br>                ),<br>                &quot;description&quot;: fmt.Sprintf(<br>                    &quot;Service %s has been exceeding its %.2f%% SLO target. &quot;+<br>                    &quot;At current burn rate, the entire error budget will be &quot;+<br>                    &quot;exhausted in %.1f hours.&quot;,<br>                    slo.Spec.Service,<br>                    slo.Spec.Objective,<br>                    parseWindowHours(slo.Spec.Window)/br.Factor,<br>                ),<br>            },<br>        })<br>    }<br><br>    return rules<br>}</pre><p>The and between short and long windows is the critical detail. The short window catches real incidents (something broke in the last 5 minutes). The long window confirms it’s not a transient blip (it’s been degraded for the last hour too). Both conditions must be true simultaneously. This alone eliminates most false positive SLO alerts.</p><h3>Decisions I Argued With Myself About</h3><p>Should the operator generate PrometheusRule resources or write to Prometheus directly?</p><p>I went with PrometheusRule CRDs. This means the operator depends on prometheus-operator being installed, which is an opinionated choice. The alternative — writing rules to a ConfigMap that Prometheus picks up via rule_files — is more universal but loses the nice reconciliation that prometheus-operator provides.</p><p>If I were building this for a broader audience, I’d support both via a configuration flag. For now, prometheus-operator is common enough that coupling to it is acceptable.</p><p>Should the Grafana dashboard be a ConfigMap or use the Grafana API?</p><p>ConfigMap. Using the Grafana API means the operator needs Grafana credentials and network access, which is a security and operational headache. Most teams using Grafana on Kubernetes already use sidecar-based dashboard provisioning where Grafana watches for ConfigMaps with a specific label and auto-imports them. The operator creates a ConfigMap with the right label and Grafana picks it up. Clean separation of concerns.</p><p>Should SLOs be namespace-scoped or cluster-scoped?</p><p>Namespace-scoped. Teams own namespaces. SLOs are team-level concerns. A platform team shouldn’t need cluster-admin privileges to define an SLO for their service. Namespace scoping also means OwnerReferences work correctly for garbage collection.</p><h3>What Happens When Someone Bypasses the Operator</h3><p>This is the question every operator builder needs to answer. What if someone manually edits the generated PrometheusRule? What if they modify the Grafana ConfigMap directly?</p><p>The reconciliation loop handles this automatically. Every 5 minutes (or on any change event), the controller regenerates the expected state from the ServiceSLO spec and patches the downstream resources. Manual edits get overwritten.</p><p>This is intentional. The ServiceSLO CRD is the source of truth. If you want to change the alerting threshold, you change the CRD in Git and let ArgoCD sync it. You don’t edit PrometheusRules by hand.</p><p>Some operators add an annotation like kubeslo.dev/managed: true to generated resources so it’s obvious to anyone who stumbles across them that they shouldn’t be edited directly.</p><pre>func managedLabels(slo *slov1.ServiceSLO) map[string]string {<br>    return map[string]string{<br>        &quot;app.kubernetes.io/managed-by&quot;: &quot;kube-slo&quot;,<br>        &quot;kubeslo.dev/slo-name&quot;:        slo.Name,<br>    }<br>}</pre><h3>Extending to Latency SLOs</h3><p>Availability SLOs are straightforward — count errors, divide by total, compare to target. Latency SLOs are trickier because they depend on histogram buckets.</p><pre>apiVersion: slo.kubeslo.dev/v1<br>kind: ServiceSLO<br>metadata:<br>  name: search-latency<br>spec:<br>  service: search-api<br>  objective: 99.0<br>  window: 30d<br>  indicator:<br>    type: latency<br>    metric: http_request_duration_seconds_bucket<br>    totalFilter: &#39;service=&quot;search-api&quot;&#39;<br>    thresholdMs: 300<br>  alerting:<br>    burnRates:<br>      - severity: critical<br>        shortWindow: 5m<br>        longWindow: 1h<br>        factor: 14.4</pre><p>The recording rule generation for latency looks different:</p><pre>func (r *ServiceSLOReconciler) latencyRecordingExpr(slo *slov1.ServiceSLO) string {<br>    thresholdSec := slo.Spec.Indicator.ThresholdMs / 1000<br><br>    // Fraction of requests slower than threshold<br>    return fmt.Sprintf(<br>        `1 - (<br>          sum(rate(%s{%s,le=&quot;%.3f&quot;}[%%s]))<br>          /<br>          sum(rate(%s{%s,le=&quot;+Inf&quot;}[%%s]))<br>        )`,<br>        slo.Spec.Indicator.Metric,<br>        slo.Spec.Indicator.TotalFilter,<br>        thresholdSec,<br>        slo.Spec.Indicator.Metric,<br>        slo.Spec.Indicator.TotalFilter,<br>    )<br>}</pre><p>The %%s is a format placeholder that gets filled in later with the actual window duration for each recording rule. The math is simple: count the requests that fit within the latency bucket, divide by total requests, subtract from 1 to get the “bad” ratio. This becomes the SLI that feeds into the same burn-rate alerting logic.</p><h3>Why This Matters Beyond Tooling</h3><p>The real value isn’t the automation. It’s the workflow change.</p><p>When SLOs live in Git as Kubernetes resources:</p><ul><li>Product managers can read the YAML and understand what reliability target their service has</li><li>SLO changes go through pull requests where both SREs and developers review them</li><li>Audit history is Git history — you know exactly when a target changed and who approved it</li><li>Rollbacks are git revert</li><li>New services get SLOs on day one because it’s just another YAML file in the deployment repo</li></ul><p>The cultural shift matters more than the technical one. SLOs stop being an SRE team concern and become a shared vocabulary that lives next to the deployment manifests, network policies, and everything else that defines how a service runs in production.</p><p>I’ve been running this against a test cluster for a few weeks now. The code is on GitHub at [link]. It’s rough around the edges — error handling needs work, the Grafana dashboard templates are basic, and I haven’t written admission webhooks for CRD validation yet. But the core reconciliation loop works and it’s already changed how I think about SLO management.</p><p>If your team’s SLO definitions live in a wiki that nobody updates, consider whether they should live in your cluster instead.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d94820e2b32" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>