Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%
26 Oct 2026 · 18 min read ·Article 74 / 208
Go

Auto Rollback Golang CI: Detect and Roll Back Problematic Deployments

Implement auto rollback for a Go service in CI/CD. Detect deployments that diverge from the spec, roll back automatically based on metrics and AI analysis, and generate post-mortems.

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

Automated Rollback: When the Implementation Diverges from the Spec

Auto rollback in Golang CI/CD is the ability to detect a problematic deployment automatically and return it to the previous version before users are significantly affected. A problematic deployment is always a stressful moment — and the longer it takes a human to notice and then act, the greater the impact.

In this article we build a system that detects problematic deployments — both from metrics thresholds and from semantic analysis using AI — and then rolls back automatically. The focus is on shrinking the time between “something broke” and “the service is healthy again.”


14.1 Why You Need Automated Rollback

Before building the mechanism, it’s important to understand how big the difference in impact is between a manual and an automatic rollback. The timeline comparison below shows the duration of degraded service for each approach.

text
 1Manual rollback timeline (typical):
 2  00:00  Deployment finished
 3  00:05  Alert reaches the on-call engineer (if an alert is configured)
 4  00:10  Engineer sees the alert
 5  00:15  Engineer investigates: is this a bug or a false alarm?
 6  00:25  Engineer decides: a rollback is needed
 7  00:30  Engineer runs the rollback command
 8  00:35  Rollback finished
 9
10  Total impact duration: 35 minutes
11  User experience: 35 minutes of degraded service
12
13Auto-rollback timeline:
14  00:00  Deployment finished
15  00:05  Metrics monitor detects threshold exceeded
16  00:06  Auto-rollback triggered
17  00:09  Rollback finished
18  00:10  Slack notification sent: "Auto-rollback executed"
19
20  Total impact duration: 9 minutes
21  User experience: 9 minutes of degraded service (vs 35 minutes)
22
23  Improvement: 74% reduction in impact duration

That 74% reduction is more than a statistic — it’s the difference between an incident users barely notice and one that triggers a flood of complaints, and that is the core value of rollback automation.


14.2 Types of Rollback Triggers

Not every rollback needs the same treatment; some can be fully automatic, some require a human. The three-tier framework below maps trigger conditions to the appropriate kind of action.

text
 1TIER 1: Immediate Rollback (no AI needed, deterministic)
 2  Trigger: error rate > 10% within 2 minutes of deploy
 3  Trigger: P99 latency > 5 seconds within 2 minutes
 4  Trigger: service health check fails consecutively
 5  Action: immediate rollback, no questions asked
 6
 7TIER 2: AI-Assisted Rollback (semantic analysis)
 8  Trigger: error rate 5-10% (borderline)
 9  Trigger: unusual log patterns detected
10  Trigger: spec compliance degradation (AI check)
11  Action: AI analyzes, recommends rollback if needed
12
13TIER 3: Human Decision Required
14  Trigger: error rate 1-5% (minor degradation)
15  Trigger: single service degraded, others healthy
16  Action: notify on-call, provide AI analysis, await decision
17
18Rollback should be:
19  - FAST: < 3 minutes from trigger to rollback complete
20  - SAFE: don't destroy current state before backup
21  - NOTIFY: the team must know immediately
22  - LOGGED: audit trail for the post-mortem

This tier split matters because an overly aggressive automatic rollback is itself dangerous — minor degradation is better left to human judgment, while extreme failures are handled by the machine without waiting.


14.3 Rollback Controller in Go

At the heart of this system is a background process that monitors metrics and triggers the rollback. The Go code below implements the full controller: threshold configuration, a monitoring loop within a given window, metrics evaluation, execution of kubectl rollout undo, and Slack notification.

go
  1// cmd/rollback-controller/main.go
  2// Background process that monitors metrics and triggers a rollback
  3
  4package main
  5
  6import (
  7    "context"
  8    "fmt"
  9    "os"
 10    "os/exec"
 11    "time"
 12
 13    "github.com/rs/zerolog"
 14    "github.com/rs/zerolog/log"
 15)
 16
 17type RollbackConfig struct {
 18    Environment    string
 19    Namespace      string
 20    DeploymentName string
 21
 22    // Tier 1 thresholds
 23    MaxErrorRatePct float64  // e.g., 0.10 = 10%
 24    MaxP99LatencyMs float64  // e.g., 5000ms
 25
 26    // Monitoring window
 27    WindowDuration time.Duration // e.g., 2 minutes
 28    CheckInterval  time.Duration // e.g., 30 seconds
 29
 30    // Notification
 31    SlackWebhook string
 32}
 33
 34type MetricsClient interface {
 35    GetErrorRate(ctx context.Context) (float64, error)
 36    GetP99Latency(ctx context.Context) (float64, error)
 37    GetHealthStatus(ctx context.Context) (bool, error)
 38}
 39
 40type RollbackController struct {
 41    config  RollbackConfig
 42    metrics MetricsClient
 43    log     zerolog.Logger
 44}
 45
 46func (c *RollbackController) Run(ctx context.Context) error {
 47    c.log.Info().
 48        Str("environment", c.config.Environment).
 49        Dur("window", c.config.WindowDuration).
 50        Msg("Starting rollback controller")
 51
 52    ticker := time.NewTicker(c.config.CheckInterval)
 53    defer ticker.Stop()
 54
 55    deploymentTime := time.Now()
 56
 57    for {
 58        select {
 59        case <-ctx.Done():
 60            return ctx.Err()
 61        case <-ticker.C:
 62            // Only monitor within the window after the deployment
 63            if time.Since(deploymentTime) > c.config.WindowDuration {
 64                c.log.Info().Msg("Monitoring window expired, rollback controller stopping")
 65                return nil
 66            }
 67
 68            shouldRollback, reason, err := c.evaluate(ctx)
 69            if err != nil {
 70                c.log.Warn().Err(err).Msg("Error evaluating metrics, skipping")
 71                continue
 72            }
 73
 74            if shouldRollback {
 75                c.log.Error().Str("reason", reason).Msg("Rollback triggered")
 76
 77                if err := c.executeRollback(ctx, reason); err != nil {
 78                    return fmt.Errorf("rollback failed: %w", err)
 79                }
 80
 81                return fmt.Errorf("deployment rolled back: %s", reason)
 82            }
 83        }
 84    }
 85}
 86
 87func (c *RollbackController) evaluate(ctx context.Context) (bool, string, error) {
 88    errorRate, err := c.metrics.GetErrorRate(ctx)
 89    if err != nil {
 90        return false, "", fmt.Errorf("getErrorRate: %w", err)
 91    }
 92    if errorRate > c.config.MaxErrorRatePct {
 93        return true, fmt.Sprintf("error rate %.1f%% > %.1f%%", errorRate*100, c.config.MaxErrorRatePct*100), nil
 94    }
 95
 96    p99, err := c.metrics.GetP99Latency(ctx)
 97    if err != nil {
 98        return false, "", fmt.Errorf("getP99Latency: %w", err)
 99    }
100    if p99 > c.config.MaxP99LatencyMs {
101        return true, fmt.Sprintf("P99 latency %.0fms > %.0fms", p99, c.config.MaxP99LatencyMs), nil
102    }
103
104    healthy, err := c.metrics.GetHealthStatus(ctx)
105    if err != nil {
106        return false, "", fmt.Errorf("getHealthStatus: %w", err)
107    }
108    if !healthy {
109        return true, "health check failed", nil
110    }
111
112    return false, "", nil
113}
114
115func (c *RollbackController) executeRollback(ctx context.Context, reason string) error {
116    // 1. Roll back the Kubernetes deployment
117    cmd := exec.CommandContext(ctx,
118        "kubectl", "rollout", "undo",
119        fmt.Sprintf("deployment/%s", c.config.DeploymentName),
120        fmt.Sprintf("--namespace=%s", c.config.Namespace),
121    )
122    output, err := cmd.CombinedOutput()
123    if err != nil {
124        return fmt.Errorf("kubectl rollout undo: %w (output: %s)", err, output)
125    }
126
127    // 2. Wait for the rollback to complete
128    waitCmd := exec.CommandContext(ctx,
129        "kubectl", "rollout", "status",
130        fmt.Sprintf("deployment/%s", c.config.DeploymentName),
131        fmt.Sprintf("--namespace=%s", c.config.Namespace),
132        "--timeout=120s",
133    )
134    if err := waitCmd.Run(); err != nil {
135        return fmt.Errorf("kubectl rollout status: %w", err)
136    }
137
138    // 3. Notify Slack
139    c.notifySlack(reason)
140    return nil
141}
142
143func (c *RollbackController) notifySlack(reason string) {
144    if c.config.SlackWebhook == "" {
145        return
146    }
147    payload := fmt.Sprintf(`{
148        "text": ":rotating_light: *Auto-rollback executed* in *%s*\nReason: %s",
149        "username": "Rollback Bot"
150    }`, c.config.Environment, reason)
151
152    cmd := exec.Command("curl", "-s", "-X", "POST",
153        c.config.SlackWebhook,
154        "-H", "Content-Type: application/json",
155        "-d", payload,
156    )
157    if err := cmd.Run(); err != nil {
158        c.log.Warn().Err(err).Msg("Failed to send Slack notification")
159    }
160}
161
162func main() {
163    log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
164
165    config := RollbackConfig{
166        Environment:     os.Getenv("ENVIRONMENT"),
167        Namespace:       os.Getenv("K8S_NAMESPACE"),
168        DeploymentName:  os.Getenv("DEPLOYMENT_NAME"),
169        MaxErrorRatePct: 0.10, // 10%
170        MaxP99LatencyMs: 5000, // 5 seconds
171        WindowDuration:  5 * time.Minute,
172        CheckInterval:   30 * time.Second,
173        SlackWebhook:    os.Getenv("SLACK_WEBHOOK"),
174    }
175
176    metricsClient := NewPrometheusMetricsClient(os.Getenv("PROMETHEUS_URL"))
177
178    controller := &RollbackController{config: config, metrics: metricsClient, log: log.Logger}
179
180    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
181    defer cancel()
182
183    if err := controller.Run(ctx); err != nil {
184        fmt.Fprintln(os.Stderr, err)
185        os.Exit(1)
186    }
187
188    fmt.Println("Monitoring window completed, deployment stable")
189}

Notice the design: the controller is only active within a window after the deployment, it returns an error when a rollback happens (as a signal to CI), and it separates evaluate from executeRollback so the decision logic is easy to test in isolation.


14.4 GitHub Actions: Rollback Workflow

The controller above needs to run automatically after every production deployment completes. The workflow below builds the controller, runs it as a monitor for a few minutes, and translates the exit code into the correct pipeline status.

yaml
 1# .github/workflows/deployment-monitor.yml
 2name: Post-Deployment Monitor
 3
 4on:
 5  workflow_run:
 6    workflows: ["Deploy to Production"]
 7    types: [completed]
 8
 9jobs:
10  monitor-deployment:
11    name: Monitor Deployment Health
12    runs-on: ubuntu-latest
13    if: ${{ github.event.workflow_run.conclusion == 'success' }}
14    steps:
15      - uses: actions/checkout@v4
16      - uses: actions/setup-go@v5
17        with: { go-version: '1.22' }
18
19      - name: Build rollback controller
20        run: go build -o /tmp/rollback-controller ./cmd/rollback-controller/
21
22      - name: Run deployment monitor (5 minutes)
23        env:
24          ENVIRONMENT: production
25          K8S_NAMESPACE: production
26          DEPLOYMENT_NAME: santekno-shop
27          PROMETHEUS_URL: ${{ secrets.PROMETHEUS_URL }}
28          SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}
29          KUBECONFIG: ${{ secrets.PRODUCTION_KUBECONFIG }}
30        run: |
31          timeout 360 /tmp/rollback-controller || {
32            EXIT_CODE=$?
33            if [ "$EXIT_CODE" -eq 124 ]; then
34              echo "Monitor timeout (normal — deployment stable for 5 min)"
35            else
36              echo "::error::Deployment monitor triggered rollback"
37              exit 1
38            fi
39          }

The important trick is in handling exit code 124 from timeout: a monitoring window that expires without trouble is treated as success (a stable deployment), while any other exit code means a rollback was triggered and the pipeline is marked as failed.


14.5 Spec-Based Rollback Trigger

Metrics alone are not enough — a deployment can be “healthy” technically yet violate the acceptance criteria from the spec. The script below runs spec-based tests against the live service and triggers a rollback if too many ACs fail.

bash
 1#!/bin/bash
 2# scripts/spec-compliance-check.sh
 3# Check that the deployed service still complies with the spec
 4
 5set -euo pipefail
 6
 7HOST="${1:-production.santekno.com}"
 8SPEC_DIR=".specify/features"
 9
10TOTAL_ACS=0
11PASSING_ACS=0
12FAILING_ACS=()
13
14for spec_file in "$SPEC_DIR"/*/spec.md; do
15  feature=$(dirname "$spec_file" | xargs basename)
16
17  # Example: test cancel order endpoint
18  if [ "$feature" == "cancel-order" ]; then
19    # AC4: an invalid order ID must return 404
20    RESPONSE=$(curl -sf -w "\n%{http_code}" \
21      "https://${HOST}/api/v1/orders/00000000-0000-0000-0000-000000000000" \
22      -X DELETE \
23      -H "Authorization: Bearer ${SMOKE_TEST_TOKEN}" 2>/dev/null)
24
25    HTTP_CODE=$(echo "$RESPONSE" | tail -1)
26
27    TOTAL_ACS=$((TOTAL_ACS + 1))
28    if [ "$HTTP_CODE" == "404" ]; then
29      PASSING_ACS=$((PASSING_ACS + 1))
30    else
31      FAILING_ACS+=("cancel-order AC4: expected 404, got $HTTP_CODE")
32    fi
33  fi
34done
35
36echo "Spec compliance: $PASSING_ACS/$TOTAL_ACS ACs passing"
37
38if [ "${#FAILING_ACS[@]}" -gt 0 ]; then
39  echo "Failing ACs:"
40  for ac in "${FAILING_ACS[@]}"; do
41    echo "  - $ac"
42  done
43
44  FAILURE_RATE=$(awk "BEGIN {print ${#FAILING_ACS[@]} / $TOTAL_ACS}")
45  if awk "BEGIN {exit ($FAILURE_RATE > 0.20) ? 0 : 1}"; then
46    echo "::error::Spec compliance < 80% — triggering rollback"
47    kubectl rollout undo deployment/santekno-shop --namespace=production
48    exit 1
49  fi
50fi

This spec-based trigger closes a gap that metrics can’t see: a deployment that runs smoothly yet behaves differently from the contract the spec promised — exactly the kind of regression that most often slips into production.


14.6 Rollback Post-Mortem with AI

After a rollback, the next crucial step is to understand the root cause. The script below collects the commit that was deployed and the error logs from the failed pod, then asks the AI to compose a structured post-mortem report in Indonesian.

bash
 1#!/bin/bash
 2# scripts/generate-post-mortem.sh
 3# AI generates a post-mortem after a rollback
 4
 5set -euo pipefail
 6
 7ROLLBACK_REASON="${1}"
 8DEPLOYMENT_SHA="${2}"
 9ROLLBACK_TIMESTAMP="${3:-$(date -u +%Y-%m-%dT%H:%M:%SZ)}"
10
11COMMIT_LOG=$(git log --oneline "${DEPLOYMENT_SHA}^..${DEPLOYMENT_SHA}" 2>/dev/null || echo "unknown")
12ERROR_LOGS=$(kubectl logs deployment/santekno-shop \
13  --namespace=production --since=10m --previous \
14  2>/dev/null | grep -E "ERROR|PANIC|FATAL" | head -20 || echo "no logs available")
15
16PROMPT="Generate a concise post-mortem report for a production rollback.
17
18Deployment SHA: $DEPLOYMENT_SHA
19Rollback timestamp: $ROLLBACK_TIMESTAMP
20Rollback reason: $ROLLBACK_REASON
21
22Commit that was deployed:
23$COMMIT_LOG
24
25Error logs from the failed deployment:
26$ERROR_LOGS
27
28Write a post-mortem in Bahasa Indonesia with:
29## Incident Summary
30## Timeline
31## Root Cause
32## Impact
33## Immediate Action Taken
34## Follow-up Actions
35## Prevention (untuk mencegah kejadian serupa)
36
37Keep it factual and actionable. Max 400 words."
38
39RESULT=$(./scripts/claude-call.sh "$PROMPT" 600)
40
41FILENAME="postmortem-${ROLLBACK_TIMESTAMP//[: ]/-}.md"
42mkdir -p docs/postmortems
43{
44  echo "# Post-Mortem: Rollback ${DEPLOYMENT_SHA:0:8}"
45  echo ""
46  echo "$RESULT"
47} > "docs/postmortems/$FILENAME"
48
49echo "Post-mortem saved: docs/postmortems/$FILENAME"

A post-mortem drafted automatically right after a rollback captures the context while it’s still fresh — the engineer just corrects and deepens it, rather than writing from scratch once the details have started to fade.


14.7 Rollback Testing

A rollback mechanism that is never tested is a time bomb. The scheduled workflow below routinely deploys an intentionally broken image to staging, then verifies that the system actually returns the service to the previous version.

yaml
 1# Test that the rollback mechanism works correctly (staging, weekly)
 2name: Rollback Test
 3
 4on:
 5  schedule:
 6    - cron: '0 3 * * 0'  # Sunday at 03:00 UTC
 7
 8jobs:
 9  test-rollback:
10    name: Test Rollback Mechanism
11    runs-on: ubuntu-latest
12    environment: staging-rollback-test
13    steps:
14      - uses: actions/checkout@v4
15
16      - name: Record current version
17        id: current
18        env:
19          KUBECONFIG: ${{ secrets.STAGING_KUBECONFIG }}
20        run: |
21          VERSION=$(kubectl get deployment santekno-shop -n staging \
22            -o jsonpath='{.spec.template.spec.containers[0].image}')
23          echo "version=$VERSION" >> $GITHUB_OUTPUT
24
25      - name: Simulate bad deployment
26        env:
27          KUBECONFIG: ${{ secrets.STAGING_KUBECONFIG }}
28        run: |
29          kubectl set image deployment/santekno-shop \
30            api=ghcr.io/santekno/shop:intentionally-broken \
31            --namespace=staging
32
33      - name: Verify rollback triggers
34        run: |
35          sleep 60  # Wait for the deployment and monitoring
36          CURRENT=$(kubectl get deployment santekno-shop -n staging \
37            -o jsonpath='{.spec.template.spec.containers[0].image}')
38          if [ "$CURRENT" == "${{ steps.current.outputs.version }}" ]; then
39            echo "Rollback test passed — service restored to previous version"
40          else
41            echo "Rollback test FAILED — service still running bad image"
42            exit 1
43          fi

The principle is simple but often ignored: a rollback you have never tested is a rollback that will fail exactly when you need it most — so make its testing routine, not an improvisation during an incident.


14.8 Rollback vs Forward Fix

Not every problem should be solved with a rollback; sometimes a forward fix is more appropriate. The script below gives the AI context about the change and its impact, then asks for a structured recommendation between rollback, forward fix, or escalation to a human.

bash
 1#!/bin/bash
 2# scripts/rollback-or-forward.sh
 3# AI assist for the decision: rollback or forward fix?
 4
 5set -euo pipefail
 6
 7ISSUE="${1}"
 8DEPLOYMENT_SHA="${2}"
 9ENVIRONMENT="${3:-production}"
10
11COMMIT_INFO=$(git log --format="%h %s %an" -1 "$DEPLOYMENT_SHA" 2>/dev/null || echo "unknown")
12CHANGES=$(git diff "${DEPLOYMENT_SHA}^..${DEPLOYMENT_SHA}" --stat 2>/dev/null | tail -5 || echo "unknown")
13
14PROMPT="Help decide: rollback or forward fix for this production issue.
15
16Issue: $ISSUE
17Deployment: $DEPLOYMENT_SHA
18Environment: $ENVIRONMENT
19Commit: $COMMIT_INFO
20
21Changes summary:
22$CHANGES
23
24Evaluate:
251. ROLLBACK if: issue is critical, fix unclear, or rollback is safe
262. FORWARD FIX if: fix is known, quick to implement, rollback is risky
27
28Factors to consider:
29- How critical is the impact on users?
30- Is there a clear, quick fix available?
31- Is rollback safe (no data migration that can't be reversed)?
32- How many users are affected?
33
34Output:
35RECOMMENDATION: ROLLBACK | FORWARD_FIX | ESCALATE_TO_HUMAN
36RATIONALE: [2-3 sentences]
37NEXT_STEP: [specific action to take]"
38
39./scripts/claude-call.sh "$PROMPT" 300

Here the AI is not the final decision-maker but a fast analysis provider — especially helpful when there’s a factor that’s easy to forget under pressure, like “the migration already ran, so a rollback is actually risky.”


14.9 Monitoring Dashboard for Deployments

The team needs one place to see which version is active in each environment and how healthy it is. The Go code below serves a simple HTTP dashboard that returns the deployment status of each environment as JSON.

go
 1// cmd/deployment-dashboard/main.go
 2// Simple HTTP dashboard to track deployment status
 3
 4package main
 5
 6import (
 7    "encoding/json"
 8    "fmt"
 9    "net/http"
10    "time"
11)
12
13type DeploymentStatus struct {
14    Environment string    `json:"environment"`
15    Version     string    `json:"version"`
16    DeployedAt  time.Time `json:"deployed_at"`
17    Status      string    `json:"status"` // HEALTHY|DEGRADED|ROLLED_BACK
18    ErrorRate   float64   `json:"error_rate"`
19    P99Latency  float64   `json:"p99_latency_ms"`
20}
21
22func main() {
23    http.HandleFunc("/status", func(w http.ResponseWriter, r *http.Request) {
24        statuses := []DeploymentStatus{
25            {
26                Environment: "production",
27                Version:     getCurrentVersion("production"),
28                DeployedAt:  time.Now().Add(-2 * time.Hour),
29                Status:      "HEALTHY",
30                ErrorRate:   0.001,
31                P99Latency:  250,
32            },
33            {
34                Environment: "staging",
35                Version:     getCurrentVersion("staging"),
36                DeployedAt:  time.Now().Add(-30 * time.Minute),
37                Status:      "HEALTHY",
38                ErrorRate:   0.002,
39                P99Latency:  180,
40            },
41        }
42
43        w.Header().Set("Content-Type", "application/json")
44        json.NewEncoder(w).Encode(statuses)
45    })
46
47    fmt.Println("Dashboard running on :8090")
48    http.ListenAndServe(":8090", nil)
49}
50
51func getCurrentVersion(env string) string {
52    // Get from Kubernetes or a deployment record
53    return "v1.5.0"
54}

A dashboard this simple already answers the question that comes up most often during an incident — “which version is running in production right now, and since when?” — without having to open kubectl.


14.10 Tips & Gotchas

Building a reliable auto-rollback requires awareness of a number of subtle traps. Here are the practical lessons that bite most often in the field.

Tip 1: Test rollback in staging regularly. A rollback mechanism that is never tested will fail when it’s needed most. A scheduled rollback test is best practice.

Tip 2: Rollback vs migration. If a deployment already included a migration that isn’t backward compatible, a rollback can make the application crash. Design database changes to be backward compatible.

Tip 3: False positive rate. An auto-rollback that is too sensitive will trigger on spikes that aren’t actually a problem. Calibrate the threshold against baseline production metrics.

Tip 4: Rollback time window. A window that’s too short (1 minute) misses slow-burn issues. Too long (30 minutes) means a long time before rollback. 5–10 minutes is the sweet spot for most services.

Gotcha 1: Kubernetes revision limit. kubectl rollout undo can only go to the previous revision. If the deployment has already been updated 3 times, you can’t roll back to 3 deploys ago. Configure revisionHistoryLimit.

Gotcha 2: Rollback loop. If the previous version is also broken (due to a misconfiguration), the rollback will loop between two broken versions. A human checkpoint is required in this scenario.

Gotcha 3: Metrics lag. Prometheus metrics usually have a 30–60 second lag. There’s no need to panic if the error rate spikes 30 seconds after a deploy — it may just be metrics that have refreshed.

The common thread: good auto-rollback is about calibration, not aggressiveness — a system that’s too trigger-happy is just as troublesome as one that’s too slow.


14.11 Zero-Downtime Rollback Strategy

A rollback, too, must be smooth for users. The graceful-shutdown configuration and Kubernetes strategy below ensure the old pod is killed only after in-flight requests finish and the replacement pod is ready.

go
 1// Handler with graceful shutdown for zero-downtime rollback
 2func main() {
 3    srv := &http.Server{Addr: ":8080", Handler: router}
 4    go srv.ListenAndServe()
 5
 6    quit := make(chan os.Signal, 1)
 7    signal.Notify(quit, syscall.SIGTERM)
 8    <-quit
 9
10    // Graceful: wait 30s for in-flight requests
11    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
12    defer cancel()
13    srv.Shutdown(ctx)
14}
15
16// Kubernetes: maxUnavailable: 0 ensures a zero-downtime rollback
17// The old pod stays alive until the new pod is healthy → safe rollback

With maxUnavailable: 0 plus graceful shutdown, a rollback becomes an operation invisible to users — exactly the property we want from an emergency recovery mechanism.


14.12 Rollback SLA

For a rollback to be measurable, we need to set clear time targets per severity level. The SLA table below separates the expectations for P1 and P2 incidents.

text
 1Rollback SLA by severity:
 2
 3P1 (production completely down):
 4  Detection:         < 2 minutes (automated metrics)
 5  Rollback trigger:  < 1 minute after detect
 6  Rollback complete: < 5 minutes
 7  Total:             < 8 minutes
 8
 9P2 (partial degradation):
10  Detection:     < 5 minutes
11  Human review:  5 minutes
12  Decision:      < 10 minutes
13  Rollback:      < 5 minutes
14  Total:         < 20 minutes
15
16Tracking: log timestamps for every event
17Monthly review: is the SLA being met?

A written SLA turns rollback from an ad-hoc effort into a measurable process — and the monthly review of this SLA becomes the feedback on whether the thresholds and automation need to be re-tuned.


14.13 Rollback in a Monorepo Scenario

When many services are deployed together, blindly rolling back all of them is wasteful. The script below only rolls back the services that actually fail the smoke test, leaving the healthy ones running.

bash
 1# If multiple services are deployed together
 2# and one fails → roll back only the failing service
 3
 4SERVICES_TO_ROLLBACK=()
 5
 6for service in order payment notification; do
 7  HEALTH=$(./scripts/smoke-test.sh "${service}.santekno.internal")
 8  if echo "$HEALTH" | grep -q "FAIL"; then
 9    SERVICES_TO_ROLLBACK+=("$service")
10    echo "$service: FAILED"
11  else
12    echo "$service: HEALTHY"
13  fi
14done
15
16for service in "${SERVICES_TO_ROLLBACK[@]}"; do
17  echo "Rolling back $service..."
18  kubectl rollout undo deployment/"santekno-${service}" --namespace=production
19done

A selective, per-service rollback minimizes the blast radius of the recovery itself — you don’t sacrifice a perfectly healthy service just because one of its neighbors has a problem.


14.14 Deployment History API

Deployment history is useful not only during an incident, but also for audit and support. The Go struct sketch below outlines a simple API to track deployment records along with their status and actor.

go
 1// cmd/deployment-api/main.go
 2// Simple API to track deployment history
 3
 4type Deployment struct {
 5    Timestamp   time.Time `json:"timestamp"`
 6    Environment string    `json:"environment"`
 7    Version     string    `json:"version"`
 8    Status      string    `json:"status"` // SUCCESS | ROLLED_BACK
 9    Actor       string    `json:"actor"`
10}
11
12// GET /deployments?env=production&limit=10
13// Returns last 10 deployment records
14//
15// Useful for:
16// - Developer: "which version is currently in production?"
17// - Support:   "when was the last deployment?"
18// - Auditor:   "what was deployed on 2026-07-15?"

Storing deployment history as structured data turns investigative questions that normally require digging through chat logs into a simple API query anyone can answer.


14.15 Summary: Automation Complete

With auto-rollback, the Santekno Shop pipeline no longer just enforces quality and automates documentation — it also heals itself when a deployment goes wrong.

Key elements:

  • Layered triggers (deterministic, AI-assisted, human decision)
  • A rollback controller in Go that monitors metrics within a window
  • A spec-based trigger to catch regressions that slip past metrics
  • Automatic post-mortems to speed up learning
  • Periodic rollback testing so the mechanism is always reliable

End state: across this Part 3 series, the pipeline now prevents bad code, limits the blast radius via canary, and recovers automatically within minutes — a system where each layer reinforces the others.

Related Articles

💬 Comments