Golang CI/CD Pipeline: GitHub Actions, AI Quality Gates, Auto Deploy
The complete CI/CD pipeline for Santekno Shop. GitHub Actions with AI-assisted code review, a specify audit gate, golangci-lint, integration tests, and automated deployment to staging.
The Golang CI/CD pipeline for Santekno Shop is not just “run tests, deploy.” Here we integrate spec audit, AI-assisted code review, architecture validation, and automated deployment — all in a single GitHub Actions workflow that is fully auditable and keeps the implementation aligned with the spec.
17.01 Pipeline Overview: 5 Stages
Before diving into YAML, it’s important to understand the big picture: the pipeline is split into five stages, each with its own time target. The summary below shows the order and contents of each stage.
1Stage 1: VALIDATE (fast, < 3 minutes)
2 ├── go build ./...
3 ├── golangci-lint run
4 ├── go vet ./...
5 └── Architecture guard (depguard)
6
7Stage 2: TEST (medium, 5-8 minutes)
8 ├── Unit tests + coverage gate (≥ 80%)
9 ├── Integration tests (PostgreSQL + Redis)
10 └── Race condition detection
11
12Stage 3: AI QUALITY GATES (2-3 minutes)
13 ├── Specify audit → score ≥ 80
14 ├── Security scan (gosec)
15 └── Dependency vulnerability check
16
17Stage 4: BUILD (3-5 minutes)
18 ├── Docker multi-stage build
19 ├── Image tagging (sha + semver)
20 └── Push to container registry
21
22Stage 5: DEPLOY (5-10 minutes, main branch only)
23 ├── Database migration
24 ├── Rolling update to staging
25 ├── Smoke test (health check)
26 └── Slack notificationThis ordering is deliberately expensive-at-the-back: the fast stage (validate) gives feedback within minutes, while the slow stage (deploy) only runs after every gate has passed.
17.02 Main Workflow File
Now we translate those five stages into a single GitHub Actions workflow file. The file below defines the entire pipeline from validate through staging deploy.
1# .github/workflows/main.yml
2
3name: Santekno Shop CI/CD
4
5on:
6 push:
7 branches: [main, develop]
8 pull_request:
9 branches: [main, develop]
10
11env:
12 GO_VERSION: '1.22'
13 REGISTRY: ghcr.io
14 IMAGE_NAME: ${{ github.repository }}/santekno-shop
15
16concurrency:
17 group: ${{ github.workflow }}-${{ github.ref }}
18 cancel-in-progress: true # Cancel stale runs on new push
19
20jobs:
21 # ─── STAGE 1: VALIDATE ───────────────────────────────────────
22 validate:
23 name: "Validate"
24 runs-on: ubuntu-latest
25 steps:
26 - uses: actions/checkout@v4
27
28 - uses: actions/setup-go@v5
29 with:
30 go-version: ${{ env.GO_VERSION }}
31 cache: true
32
33 - name: Build
34 run: go build ./...
35
36 - name: Vet
37 run: go vet ./...
38
39 - name: Lint
40 uses: golangci/golangci-lint-action@v6
41 with:
42 version: v1.59
43 args: --timeout=5m
44
45 - name: Generate mocks (verify go:generate is in sync)
46 run: |
47 go generate ./...
48 git diff --exit-code testutil/mock/ || \
49 (echo "Mocks out of sync. Run 'go generate ./...' and commit." && exit 1)
50
51 # ─── STAGE 2: TEST ───────────────────────────────────────────
52 unit-test:
53 name: "Unit Test"
54 needs: validate
55 runs-on: ubuntu-latest
56 steps:
57 - uses: actions/checkout@v4
58 - uses: actions/setup-go@v5
59 with: { go-version: '${{ env.GO_VERSION }}', cache: true }
60
61 - name: Run unit tests
62 run: |
63 go test -race -count=1 -timeout=60s \
64 -coverprofile=coverage.out -covermode=atomic \
65 ./internal/domain/... ./internal/usecase/... ./pkg/...
66
67 - name: Coverage gate
68 run: |
69 COVERAGE=$(go tool cover -func=coverage.out | grep total | awk '{print $3}' | sed 's/%//')
70 echo "Coverage: $COVERAGE%"
71 if (( $(echo "$COVERAGE < 80" | bc -l) )); then
72 echo "Coverage $COVERAGE% < 80% threshold"
73 exit 1
74 fi
75 echo "Coverage $COVERAGE% passes"
76
77 - name: Upload coverage
78 uses: actions/upload-artifact@v4
79 with:
80 name: coverage-report
81 path: coverage.out
82
83 integration-test:
84 name: "Integration Test"
85 needs: validate
86 runs-on: ubuntu-latest
87 services:
88 postgres:
89 image: postgres:15-alpine
90 env:
91 POSTGRES_DB: santekno_test
92 POSTGRES_USER: santekno
93 POSTGRES_PASSWORD: secret
94 ports: ["5432:5432"]
95 options: >-
96 --health-cmd pg_isready
97 --health-interval 10s
98 --health-timeout 5s
99 --health-retries 5
100
101 redis:
102 image: redis:7-alpine
103 ports: ["6379:6379"]
104 options: >-
105 --health-cmd "redis-cli ping"
106 --health-interval 10s
107
108 steps:
109 - uses: actions/checkout@v4
110 - uses: actions/setup-go@v5
111 with: { go-version: '${{ env.GO_VERSION }}', cache: true }
112
113 - name: Install migrate CLI
114 run: |
115 curl -L https://github.com/golang-migrate/migrate/releases/download/v4.18.1/migrate.linux-amd64.tar.gz | tar xvz
116 sudo mv migrate /usr/local/bin/
117
118 - name: Run migrations on test DB
119 run: migrate -path migrations -database "$TEST_DATABASE_URL" up
120 env:
121 TEST_DATABASE_URL: postgres://santekno:secret@localhost:5432/santekno_test?sslmode=disable
122
123 - name: Run integration tests
124 run: |
125 go test -race -tags=integration -count=1 -timeout=120s \
126 ./internal/repository/... ./internal/infrastructure/...
127 env:
128 TEST_DATABASE_URL: postgres://santekno:secret@localhost:5432/santekno_test?sslmode=disable
129 TEST_REDIS_ADDR: localhost:6379
130
131 # ─── STAGE 3: AI QUALITY GATES ────────────────────────────────
132 ai-quality-gates:
133 name: "AI Quality Gates"
134 needs: [unit-test, integration-test]
135 runs-on: ubuntu-latest
136 steps:
137 - uses: actions/checkout@v4
138 - uses: actions/setup-go@v5
139 with: { go-version: '${{ env.GO_VERSION }}', cache: true }
140
141 - name: Install specify CLI
142 run: go install github.com/specifyapp/specify-cli@latest
143
144 - name: Spec audit gate
145 run: |
146 SCORE=$(specify audit --output json | jq '.score')
147 echo "Spec audit score: $SCORE"
148 if [ "$SCORE" -lt 80 ]; then
149 echo "Spec audit score $SCORE < 80 threshold"
150 specify audit --output text
151 exit 1
152 fi
153 echo "Spec audit score $SCORE passes"
154
155 - name: Security scan (gosec)
156 run: |
157 go install github.com/securego/gosec/v2/cmd/gosec@latest
158 gosec -exclude=G204,G304 ./... 2>&1 | tee gosec-report.txt
159 # G204: subprocess (intentional), G304: file path (intentional)
160
161 - name: Dependency vulnerability check
162 run: |
163 go install golang.org/x/vuln/cmd/govulncheck@latest
164 govulncheck ./...
165
166 - name: Architecture check (depguard)
167 run: golangci-lint run --enable=depguard --disable-all
168
169 - name: Upload security report
170 uses: actions/upload-artifact@v4
171 if: always()
172 with:
173 name: security-report
174 path: gosec-report.txt
175
176 # ─── STAGE 4: BUILD ───────────────────────────────────────────
177 build:
178 name: "Build & Push"
179 needs: ai-quality-gates
180 runs-on: ubuntu-latest
181 if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop'
182 outputs:
183 image-tag: ${{ steps.meta.outputs.tags }}
184 image-digest: ${{ steps.build.outputs.digest }}
185
186 steps:
187 - uses: actions/checkout@v4
188
189 - name: Set up Docker Buildx
190 uses: docker/setup-buildx-action@v3
191
192 - name: Login to Container Registry
193 uses: docker/login-action@v3
194 with:
195 registry: ${{ env.REGISTRY }}
196 username: ${{ github.actor }}
197 password: ${{ secrets.GITHUB_TOKEN }}
198
199 - name: Extract metadata
200 id: meta
201 uses: docker/metadata-action@v5
202 with:
203 images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
204 tags: |
205 type=sha,prefix=sha-
206 type=semver,pattern={{version}}
207 type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
208
209 - name: Build and push image
210 id: build
211 uses: docker/build-push-action@v5
212 with:
213 context: .
214 push: true
215 tags: ${{ steps.meta.outputs.tags }}
216 labels: ${{ steps.meta.outputs.labels }}
217 cache-from: type=gha
218 cache-to: type=gha,mode=max
219 build-args: |
220 BUILD_VERSION=${{ github.sha }}
221 BUILD_TIME=${{ github.event.head_commit.timestamp }}
222
223 # ─── STAGE 5: DEPLOY ──────────────────────────────────────────
224 deploy-staging:
225 name: "Deploy → Staging"
226 needs: build
227 runs-on: ubuntu-latest
228 if: github.ref == 'refs/heads/develop'
229 environment:
230 name: staging
231 url: https://shop-staging.santekno.com
232
233 steps:
234 - uses: actions/checkout@v4
235
236 - name: Run DB migrations on staging
237 run: |
238 migrate -path migrations \
239 -database "$STAGING_DATABASE_URL" up
240 env:
241 STAGING_DATABASE_URL: ${{ secrets.STAGING_DATABASE_URL }}
242
243 - name: Deploy to staging (kubectl rolling update)
244 run: |
245 kubectl set image deployment/santekno-shop \
246 app=${{ needs.build.outputs.image-tag }} \
247 --record
248 kubectl rollout status deployment/santekno-shop --timeout=300s
249 env:
250 KUBECONFIG_DATA: ${{ secrets.STAGING_KUBECONFIG }}
251
252 - name: Smoke test
253 run: |
254 sleep 10
255 STATUS=$(curl -s -o /dev/null -w "%{http_code}" \
256 https://shop-staging.santekno.com/health)
257 if [ "$STATUS" != "200" ]; then
258 echo "Smoke test failed: HTTP $STATUS"
259 exit 1
260 fi
261 echo "Smoke test passed"
262
263 - name: Notify Slack
264 if: always()
265 uses: slackapi/slack-github-action@v1
266 with:
267 payload: |
268 {
269 "text": "${{ job.status == 'success' && 'OK' || 'FAIL' }} Staging deploy: ${{ github.event.head_commit.message }}"
270 }
271 env:
272 SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}Notice the concurrency block above: a new push automatically cancels the older run on the same ref, preventing a queue from piling up when commits arrive in quick succession.
17.03 golangci-lint Configuration
Code quality is guarded not by manual reviewers alone, but by a linter that enforces the architecture rules. The .golangci.yml configuration below enables essential linters plus depguard to enforce boundaries between layers.
1# .golangci.yml
2
3run:
4 timeout: 5m
5 go: '1.22'
6
7linters:
8 enable:
9 - errcheck # check for ignored errors
10 - govet # go vet standard
11 - staticcheck # static analysis
12 - gosimple # simplify code
13 - unused # detect unused code
14 - gocyclo # cyclomatic complexity
15 - depguard # architecture layer enforcement
16 - gosec # security linter
17 - misspell # typo detection
18 - noctx # context propagation check
19 - bodyclose # HTTP response body close check
20
21linters-settings:
22 gocyclo:
23 min-complexity: 15
24
25 depguard:
26 rules:
27 # Handlers may not import database packages
28 handler-no-db:
29 files:
30 - "**/delivery/http/handler/**"
31 deny:
32 - pkg: "github.com/jackc/pgx"
33 desc: "handlers must not import pgx directly"
34 - pkg: "github.com/redis/go-redis"
35 desc: "handlers must not import redis directly"
36
37 # Domain may not import a framework
38 domain-pure:
39 files:
40 - "**/domain/**"
41 deny:
42 - pkg: "github.com/labstack/echo"
43 desc: "domain must not import echo"
44 - pkg: "github.com/jackc/pgx"
45 desc: "domain must not import pgx"
46 - pkg: "github.com/redis/go-redis"
47 desc: "domain must not import redis"
48
49 # UseCase may not import an HTTP framework
50 usecase-no-http:
51 files:
52 - "**/usecase/**"
53 deny:
54 - pkg: "github.com/labstack/echo"
55 desc: "usecases must not import echo"
56 - pkg: "github.com/jackc/pgx"
57 desc: "usecases must not import pgx"
58
59issues:
60 exclude-rules:
61 - path: "_test.go"
62 linters: [gosec, errcheck] # relax in test filesWith these depguard rules, a Clean Architecture violation — for example a handler importing pgx directly — is caught as a lint error in CI, rather than surfacing only once the code is already running in production.
17.04 Pre-commit Hooks
The fastest feedback happens before code is even committed. The pre-commit configuration below runs build, unit tests, lint, and a quick spec check on the developer’s machine.
1# .pre-commit-config.yaml
2
3repos:
4 - repo: local
5 hooks:
6 - id: go-build
7 name: Go Build
8 entry: bash -c 'go build ./...'
9 language: system
10 pass_filenames: false
11
12 - id: go-test-unit
13 name: Go Unit Tests
14 entry: bash -c 'go test -race -count=1 ./internal/domain/... ./internal/usecase/... ./pkg/...'
15 language: system
16 pass_filenames: false
17
18 - id: golangci-lint
19 name: golangci-lint
20 entry: golangci-lint run --fix
21 language: system
22 pass_filenames: false
23
24 - id: specify-audit-quick
25 name: Specify Quick Check
26 entry: bash -c 'specify audit --output json | jq -e ".score >= 70" || (echo "Spec score below 70 — fix before commit" && exit 1)'
27 language: system
28 pass_filenames: false
29
30 - id: no-debug-code
31 name: No debug/TODO critical
32 entry: bash -c '! grep -r "fmt.Println\|log.Println\|TODO: CRITICAL\|FIXME:" --include="*.go" internal/'
33 language: system
34 pass_filenames: false
35
36# Install: pre-commit installNotice the specify audit threshold here is 70 — looser than the CI gate (80) — deliberately set so local commits stay smooth while still catching a severe spec regression early.
17.05 AI-Assisted PR Review
One of the most interesting quality gates is automated code review by Claude against the rules in CLAUDE.md. The workflow below fetches the changed files, sends them to the Claude API, and posts the result as a PR comment.
1# .github/workflows/ai-review.yml
2
3name: AI Code Review
4
5on:
6 pull_request:
7 types: [opened, synchronize]
8 branches: [main, develop]
9
10jobs:
11 ai-review:
12 name: "AI Review"
13 runs-on: ubuntu-latest
14 permissions:
15 pull-requests: write
16 contents: read
17
18 steps:
19 - uses: actions/checkout@v4
20 with:
21 fetch-depth: 0
22
23 - name: Get changed files
24 id: changed-files
25 run: |
26 CHANGED=$(git diff --name-only ${{ github.event.pull_request.base.sha }} HEAD \
27 | grep '\.go$' | head -20 | tr '\n' ' ')
28 echo "files=$CHANGED" >> $GITHUB_OUTPUT
29
30 - name: AI Review with Claude API
31 env:
32 ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
33 run: |
34 # Build prompt from CLAUDE.md + changed files
35 CHANGED_CODE=$(cat ${{ steps.changed-files.outputs.files }})
36 CLAUDE_MD=$(cat CLAUDE.md)
37
38 curl -s https://api.anthropic.com/v1/messages \
39 -H "x-api-key: $ANTHROPIC_API_KEY" \
40 -H "anthropic-version: 2023-06-01" \
41 -H "Content-Type: application/json" \
42 -d "{
43 \"model\": \"claude-sonnet-4-20250514\",
44 \"max_tokens\": 2000,
45 \"messages\": [{
46 \"role\": \"user\",
47 \"content\": \"Review PR based on CLAUDE.md rules:\\n$CLAUDE_MD\\n\\nChanged files:\\n$CHANGED_CODE\\n\\nFocus: architecture violations, error handling, spec coverage, performance issues. Be concise.\"
48 }]
49 }" | jq -r '.content[0].text' > ai-review.txt
50
51 - name: Post review comment
52 uses: actions/github-script@v7
53 with:
54 script: |
55 const fs = require('fs');
56 const review = fs.readFileSync('ai-review.txt', 'utf8');
57 github.rest.issues.createComment({
58 issue_number: context.issue.number,
59 owner: context.repo.owner,
60 repo: context.repo.repo,
61 body: `## AI Code Review\n\n${review}\n\n*Powered by Claude + CLAUDE.md*`
62 });Because the prompt includes the contents of CLAUDE.md, this AI review evaluates the code against the exact same project rules a human reviewer uses — not generic rules, but the Santekno Shop architecture conventions.
17.06 Rollback Strategy
A safe deploy needs a fast way back. The rollback workflow below lets the team return a deployment to a specific SHA via workflow_dispatch.
1# .github/workflows/rollback.yml
2
3name: Rollback
4
5on:
6 workflow_dispatch:
7 inputs:
8 target_sha:
9 description: 'Git SHA to rollback to'
10 required: true
11 environment:
12 description: 'Environment (staging/production)'
13 required: true
14 default: 'staging'
15
16jobs:
17 rollback:
18 name: "Rollback Deployment"
19 runs-on: ubuntu-latest
20 environment: ${{ inputs.environment }}
21
22 steps:
23 - uses: actions/checkout@v4
24 with:
25 ref: ${{ inputs.target_sha }}
26
27 - name: Rollback image
28 run: |
29 IMAGE="${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:sha-${{ inputs.target_sha }}"
30 kubectl set image deployment/santekno-shop app=$IMAGE
31 kubectl rollout status deployment/santekno-shop --timeout=300s
32
33 - name: Verify rollback
34 run: |
35 CURRENT=$(kubectl get deployment santekno-shop \
36 -o jsonpath='{.spec.template.spec.containers[0].image}')
37 echo "Current image: $CURRENT"
38 curl -sf https://shop-${{ inputs.environment }}.santekno.com/health
39
40 - name: Notify rollback
41 uses: slackapi/slack-github-action@v1
42 with:
43 payload: |
44 {"text": "Rollback executed: ${{ inputs.environment }} → SHA ${{ inputs.target_sha }}"}
45 env:
46 SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}Rollback relies on SHA-based image tags (sha-abc1234), so any old deployment can always be reinstalled — the key to making incident recovery a matter of minutes, not hours.
17.07 Branch Protection Rules
A pipeline is only useful if it cannot be bypassed. The branch protection rules below force every status check to pass before a merge to main.
1GitHub Settings → Branches → Add Rule → main
2
3[x] Require pull request reviews before merging
4 - Required approving reviews: 1
5 - Dismiss stale reviews when new commits are pushed
6
7[x] Require status checks before merging
8 - validate
9 - unit-test
10 - integration-test
11 - ai-quality-gates
12
13[x] Require branches to be up to date before merging
14
15[x] Do not allow bypassing the above settings
16 (even for admins)
17
18[x] Restrict pushes that create matching branches
19 (prevent direct push to main)The “Do not allow bypassing … even for admins” option matters: without it, the gate only applies to part of the team, and spec-first discipline leaks out through the admin path.
17.08 Environment Secrets
Deployment needs credentials that must never enter the repo. The list below summarizes the GitHub secrets the pipeline needs and how to add them via CLI.
1# GitHub Repository Secrets that are needed:
2
3# Deployment
4STAGING_DATABASE_URL # postgres://... to staging DB
5STAGING_KUBECONFIG # base64-encoded kubeconfig
6PRODUCTION_DATABASE_URL # postgres://... to production DB
7PRODUCTION_KUBECONFIG # base64-encoded kubeconfig
8
9# AI Review
10ANTHROPIC_API_KEY # Claude API key for code review
11
12# Notifications
13SLACK_WEBHOOK # Slack webhook URL
14
15# Registry (automatic from GitHub Actions)
16GITHUB_TOKEN # auto-provided, for ghcr.io push
17
18# Add via GitHub CLI:
19gh secret set ANTHROPIC_API_KEY --body "sk-ant-xxx"
20gh secret set STAGING_DATABASE_URL --body "postgres://..."
21gh secret set SLACK_WEBHOOK --body "https://hooks.slack.com/..."GITHUB_TOKEN is provided automatically by Actions for pushing to ghcr.io — the rest must be set manually, and should be rotated whenever team membership changes.
17.09 Deployment Environments
GitHub Environments allow different protection rules between staging and production. The configuration below makes staging auto-deploy while production requires approval and a wait timer.
1# GitHub Environments for protection rules
2
3# Staging environment:
4# - Auto-deploy from the develop branch
5# - No approval required
6# - URL: shop-staging.santekno.com
7
8# Production environment:
9# - Auto-deploy from the main branch
10# - Required reviewers: 2 approvers
11# - Wait timer: 10 minutes (rollback window)
12# - URL: shop.santekno.com
13
14# Create via GitHub CLI:
15gh api repos/$OWNER/$REPO/environments/staging \
16 --method PUT \
17 --field deployment_branch_policy='{"protected_branches": false}'
18
19gh api repos/$OWNER/$REPO/environments/production \
20 --method PUT \
21 --field wait_timer=600 \
22 --field reviewers='[{"type":"User","id":123456}]'The 10-minute wait timer on production is an emergency brake: it gives the team time to cancel the deploy if there’s any sign of trouble before real traffic hits the new version.
17.10 Specify Audit in CI
The most distinctively SDD gate is specify audit, which verifies that every spec AC is implemented. The example below shows how the CLI detects coverage and the spec.yaml format it reads.
1# specify audit → check that all spec ACs are implemented
2
3# How the specify CLI detects coverage:
4# 1. Read spec.yaml (created in Article 01)
5# 2. Search for patterns in the code: test functions, handler paths, error types
6# 3. Match the test name convention: Test[Feature]_[AC]_[Expected]
7# 4. Score = (ACs covered / ACs total) * 100
8
9# Configuration: spec.yaml
10features:
11 - name: place-order
12 acceptance_criteria:
13 - id: AC1
14 description: "valid order → 201"
15 patterns:
16 - test_name: "TestPlaceOrder_ValidItems"
17 - handler_path: "POST /api/v1/orders"
18 - response_code: 201
19 - id: AC2
20 description: "insufficient stock → 422"
21 patterns:
22 - test_name: "TestPlaceOrder_InsufficientStock"
23 - error_type: "ErrInsufficientStock"
24 - response_code: 422
25
26# CI threshold: score >= 80
27# End of Article 08: ~80/100 ← threshold reached for the first time
28# End of Article 09: ~90/100
29# End of Article 10: ~95/100The score climbing from article to article is no accident — it’s measurable proof that the implementation is increasingly aligned with the spec, and the 80 gate ensures that trend never quietly regresses.
17.11 Docker Build Optimization
A fast image build depends on correct layering. The multi-stage Dockerfile below separates dependency download, build, and the final image so CI caching is maximized.
1# Dockerfile — optimized for CI build cache
2
3# Stage 1: download dependencies (layer cached if go.sum unchanged)
4FROM golang:1.22-alpine AS deps
5WORKDIR /app
6COPY go.mod go.sum ./
7RUN go mod download
8
9# Stage 2: build (layer cached if source unchanged)
10FROM deps AS builder
11COPY . .
12ARG BUILD_VERSION=dev
13ARG BUILD_TIME=unknown
14RUN CGO_ENABLED=0 GOOS=linux go build \
15 -ldflags="-X main.version=${BUILD_VERSION} -X main.buildTime=${BUILD_TIME} -s -w" \
16 -o /app/server ./cmd/server/
17
18# Stage 3: final image (minimal, ~21MB)
19FROM scratch
20COPY --from=builder /app/server /server
21COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
22EXPOSE 8080
23ENTRYPOINT ["/server"]For these layers to truly be cached across runs, enable the GitHub Actions cache in the build step below.
1# Build cache in CI with the GitHub Actions Cache
2- name: Build and push
3 uses: docker/build-push-action@v5
4 with:
5 cache-from: type=gha # read from GHA cache
6 cache-to: type=gha,mode=max # write to GHA cache
7 # mode=max: cache all layers, slower but more effectiveThe combination of a separate deps stage and the type=gha cache makes a build with no code changes finish in ~1 minute — it only changes drastically when go.sum changes too.
17.12 Smoke Test after Deploy
A technically successful deploy does not necessarily mean the application is healthy. The smoke test script below verifies critical endpoints immediately after the rollout completes.
1# scripts/smoke-test.sh
2#!/bin/bash
3BASE_URL=$1
4TIMEOUT=30
5
6echo "Running smoke tests against $BASE_URL..."
7
8# Test 1: Health check
9STATUS=$(curl -sf -o /dev/null -w "%{http_code}" --max-time $TIMEOUT "$BASE_URL/health")
10[[ "$STATUS" == "200" ]] || { echo "Health check failed: $STATUS"; exit 1; }
11echo "Health check: $STATUS"
12
13# Test 2: Products endpoint
14STATUS=$(curl -sf -o /dev/null -w "%{http_code}" --max-time $TIMEOUT "$BASE_URL/api/v1/products")
15[[ "$STATUS" == "200" ]] || { echo "Products endpoint failed: $STATUS"; exit 1; }
16echo "Products endpoint: $STATUS"
17
18# Test 3: Auth endpoint exists (no registration — just check 400 for invalid req)
19STATUS=$(curl -sf -o /dev/null -w "%{http_code}" -X POST --max-time $TIMEOUT \
20 -H "Content-Type: application/json" -d '{}' "$BASE_URL/api/v1/auth/register")
21[[ "$STATUS" == "400" ]] || { echo "Auth endpoint failed: $STATUS"; exit 1; }
22echo "Auth endpoint: $STATUS"
23
24echo "All smoke tests passed"A failing smoke test triggers an auto-rollback, so a clearly broken version never survives long receiving real traffic.
17.13 Pipeline Execution Time Target
A slow pipeline will be avoided by developers. The time targets below serve as a guide so each stage stays within reasonable bounds.
1Pipeline execution time targets:
2
3Stage 1 (validate): 2-3 min ← fast feedback
4Stage 2 (unit-test): 3-5 min ← parallel with integration
5Stage 2 (integration): 5-8 min ← slowest, parallel
6Stage 3 (ai-gates): 2-3 min ← after tests
7Stage 4 (build): 3-5 min ← only on main/develop
8Stage 5 (deploy): 5-10 min ← only on main/develop
9
10Total PR check: ~10-15 minutes (parallel execution)
11Total main deploy: ~25-30 minutes (end-to-end)
12
13Optimization tips:
14 - go mod download cached with setup-go cache: true
15 - Docker build cached with type=gha
16 - Stages run in parallel as much as possible
17 - Unit test and integration test run in parallelThe key to keeping the PR check under 15 minutes is parallelism: unit tests and integration tests run at the same time, not in sequence.
17.14 Monitoring Pipeline Health
The pipeline itself needs monitoring so failures don’t slip by unnoticed. The Slack notifications below alert the team both when a stage fails and when a deploy succeeds.
1# Slack notification for all pipeline events
2
3# Notify on failure (any stage):
4- name: Notify on failure
5 if: failure()
6 uses: slackapi/slack-github-action@v1
7 with:
8 payload: |
9 {
10 "text": "CI Failed: ${{ github.workflow }} on ${{ github.ref_name }}\n${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
11 }
12 env:
13 SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}
14
15# Notify on successful deploy:
16- name: Notify success
17 if: success() && github.ref == 'refs/heads/main'
18 uses: slackapi/slack-github-action@v1
19 with:
20 payload: |
21 {
22 "text": "Deploy successful: ${{ github.event.head_commit.message }}\n${{ env.DEPLOY_URL }}"
23 }The failure notification includes a direct link to the problematic run, cutting the time from “something is red” to “here’s the cause” down to a single click.
17.15 Pipeline Badge in the README
Pipeline status should be visible right on the repo’s front page. The Markdown badges below display CI/CD status, spec compliance, and the Go version in the README.
1<!-- README.md -->
2
3# Santekno Shop
4
5[](https://github.com/santekno/santekno-shop/actions/workflows/main.yml)
6[](https://goreportcard.com/report/github.com/santekno/santekno-shop)
7[](https://github.com/santekno/santekno-shop/actions)
8[](https://golang.org)
9
10Build production-grade e-commerce with Spec-Driven Development + Clean Architecture.A green spec compliance badge in the README makes SDD discipline something visible and worth being proud of — and a quick signal to new contributors about the project’s standards.
17.16 Pipeline Metrics
Long-term pipeline health needs to be measured, not felt. The list of metrics below, along with their targets and alert thresholds, becomes the CI/CD health dashboard.
1Key metrics for tracking pipeline health:
2
31. Pipeline success rate
4 target: > 95%
5 alert: < 90% over 7 days
6
72. Average pipeline duration
8 target: < 15 minutes (PR check)
9 alert: > 20 minutes
10
113. Test failure rate
12 target: < 5% non-flaky failures
13 alert: > 10%
14
154. Coverage trend
16 target: stable or rising
17 alert: drop > 5% in a single PR
18
195. Spec audit score trend
20 target: stable or rising
21 alert: drop > 10 points
22
23Track via the GitHub Actions API or a Datadog/Grafana integration.The “test failure rate” metric is especially important for detecting flaky tests — failures that aren’t caused by a real bug will erode team trust in the CI gate if left unchecked.
17.17 Production Deploy Approval Flow
Deploying to production is the highest-risk moment and needs an explicit flow. The sequence of steps below describes the process from merge to production deploy, including the emergency hotfix path.
1Production deploy flow (main branch):
2
31. Developer merges PR to main
42. CI runs: validate → test → ai-gates
53. Build + push Docker image
64. Notify team: "Ready for production deploy"
75. Required reviewers (2 people) approve in GitHub Environments
86. 10-minute wait timer (rollback window if there's an issue)
97. Deploy: migrate + rolling update + smoke test
108. If smoke test fails → auto rollback to previous image
119. Notify team: success / failure
12
13Emergency deploy (hotfix):
14 → Branch: hotfix/* → bypass wait timer
15 → Still needs 1 approver
16 → Smoke test remains mandatoryNotice that the hotfix path trims the wait timer but still keeps approval and the smoke test — emergency speed must not sacrifice the minimum verification.
17.18 Dependency Update Automation
Keeping dependencies current and secure is best automated. The Dependabot configuration below schedules weekly updates for Go modules, Docker images, and GitHub Actions.
1# .github/dependabot.yml
2
3version: 2
4updates:
5 # Go module updates
6 - package-ecosystem: gomod
7 directory: "/"
8 schedule:
9 interval: weekly
10 day: monday
11 time: "09:00"
12 open-pull-requests-limit: 5
13 labels: ["dependencies", "go"]
14 commit-message:
15 prefix: "chore(deps)"
16 # Group minor + patch updates together (reduce PR noise)
17 groups:
18 minor-and-patch:
19 update-types:
20 - minor
21 - patch
22
23 # Docker base image updates
24 - package-ecosystem: docker
25 directory: "/"
26 schedule:
27 interval: weekly
28 labels: ["dependencies", "docker"]
29
30 # GitHub Actions updates
31 - package-ecosystem: github-actions
32 directory: "/"
33 schedule:
34 interval: weekly
35 labels: ["dependencies", "github-actions"]Grouping minor and patch updates into a single PR trims the noise — the team can still review major updates separately without being flooded by dozens of small PRs each week.
17.19 Full Pipeline Sequence Diagram
So the whole flow is easy to picture, the sequence diagram below illustrates the interaction between the developer, GitHub, the CI runner, the registry, and Kubernetes from push to notification.
sequenceDiagram
participant Dev as Developer
participant GH as GitHub
participant CI as CI Runner
participant Reg as Registry
participant K8s as Kubernetes
Dev->>GH: Push / Open PR
GH->>CI: Trigger workflow
par Stage 1: Validate
CI->>CI: go build + lint + vet
and Stage 2: Test
CI->>CI: unit tests (parallel)
CI->>CI: integration tests (parallel)
end
CI->>CI: Stage 3: AI Quality Gates
note over CI: specify audit ≥ 80<br/>gosec scan<br/>govulncheck
CI->>Reg: Stage 4: Build & Push Docker image
alt Branch: develop → staging
CI->>K8s: Run migrations
CI->>K8s: Rolling update
CI->>CI: Smoke test
else Branch: main → production
CI->>Dev: Wait for approval
Dev->>GH: Approve deployment
CI->>K8s: Run migrations
CI->>K8s: Rolling update
CI->>CI: Smoke test
end
CI-->>Dev: Slack notificationThis diagram highlights one key difference: the develop branch flows smoothly to staging, whereas the main branch stops to wait for human approval before touching production.
17.20 Summary: The Santekno Shop CI/CD Pipeline
The Santekno Shop pipeline is essentially a “spec compliance machine” — every push ensures the implementation stays aligned with the spec, the architecture stays clean, and deployment stays safe.
5 stages: validate → test → ai-gates → build → deploy, with parallelism maximized for speed.
AI Quality Gates: specify audit, gosec, govulncheck, and depguard — all automated.
Branch protection: no one can merge to main without every gate passing, not even an admin.
Deployment safety: smoke tests, automatic rollback, and the production approval flow keep a bad deploy from ever surviving.
Observability: Slack notifications for every event, badges in the README, and metrics tracking keep pipeline health always visible. Every merge to main is an artifact that is provably spec-compliant, architecturally sound, and already security-scanned.