TExcelTAD

Exercises

The first four exercises are small pure functions behind decisions you made in this course: URL validation, shutdown timing, pool sizing and burn rates. The calls are already in place; run the starter first to see the placeholder output, complete the code marked TODO until the output matches the expected output, then compare with the solution. The fifth is a real Helm session with a guard rail to add, and the last two are larger extensions to linkly to do in your own repository.

Exercise 1: Stricter URL validation

Topics: linkly: The Source, Production Hardening

linkly accepts any absolute http/https URL up to 2048 bytes. Tighten validateURL: also reject URLs with credentials (user:password@), which leak secrets into every log and redirect, and links to the shortener's own host (any letter case, with or without a port), which create redirect loops.

go · try it yourself
package main

import (
	"errors"
	"fmt"
	"net/url"
	"strings"
)

const ownHost = "lnk.example.com"

func validateURL(raw string) error {
	// TODO: length, absolute http(s) with a host, no credentials, not ownHost
	_, _ = url.Parse, errors.New
	return nil
}

func main() {
	for _, raw := range []string{
		"https://go.dev/doc/",
		"ftp://example.com/file",
		"/relative/path",
		"https://user:secret@example.com/",
		"https://lnk.example.com/docs",
		"https://LNK.Example.com:443/x",
		"https://example.com/" + strings.Repeat("a", 2100),
	} {
		label := raw
		if len(label) > 40 {
			label = label[:37] + "..."
		}
		if err := validateURL(raw); err != nil {
			fmt.Printf("%-40s rejected: %v\n", label, err)
		} else {
			fmt.Printf("%-40s ok\n", label)
		}
	}
}
https://go.dev/doc/                      ok
ftp://example.com/file                   ok
/relative/path                           ok
https://user:secret@example.com/         ok
https://lnk.example.com/docs             ok
https://LNK.Example.com:443/x            ok
https://example.com/aaaaaaaaaaaaaaaaa... ok

Expected output:

text
https://go.dev/doc/                      ok
ftp://example.com/file                   rejected: not an absolute http or https URL
/relative/path                           rejected: not an absolute http or https URL
https://user:secret@example.com/         rejected: credentials in URLs are not allowed
https://lnk.example.com/docs             rejected: links to the shortener itself are not allowed
https://LNK.Example.com:443/x            rejected: links to the shortener itself are not allowed
https://example.com/aaaaaaaaaaaaaaaaa... rejected: longer than 2048 bytes
Show solution
go
func validateURL(raw string) error {
	if len(raw) > 2048 {
		return errors.New("longer than 2048 bytes")
	}
	u, err := url.Parse(raw)
	if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
		return errors.New("not an absolute http or https URL")
	}
	if u.User != nil {
		return errors.New("credentials in URLs are not allowed")
	}
	if strings.EqualFold(u.Hostname(), ownHost) {
		return errors.New("links to the shortener itself are not allowed")
	}
	return nil
}

u.Hostname() strips the port, and strings.EqualFold ignores case; comparing u.Host directly would let LNK.Example.com:443 through. In linkly, ownHost comes from BASE_URL.

Exercise 2: Shutdown timing

Topics: The Production Chart

Write shutdown_grace(grace, prestop, margin=5): the seconds left for linkly's own SHUTDOWN_GRACE after the preStop sleep and a safety margin. Raise ValueError when less than one second is left.

python · try it yourself
def shutdown_grace(grace, prestop, margin=5):
    # TODO: grace - prestop - margin, or ValueError if < 1
    return 0

for g, p in [(30, 5), (60, 10), (30, 25), (10, 5)]:
    try:
        print(f"grace={g:>2} preStop={p:>2} -> SHUTDOWN_GRACE={shutdown_grace(g, p)}s")
    except ValueError as e:
        print(f"grace={g:>2} preStop={p:>2} -> error: {e}")
grace=30 preStop= 5 -> SHUTDOWN_GRACE=0s
grace=60 preStop=10 -> SHUTDOWN_GRACE=0s
grace=30 preStop=25 -> SHUTDOWN_GRACE=0s
grace=10 preStop= 5 -> SHUTDOWN_GRACE=0s

Expected output:

text
grace=30 preStop= 5 -> SHUTDOWN_GRACE=20s
grace=60 preStop=10 -> SHUTDOWN_GRACE=45s
grace=30 preStop=25 -> error: terminationGracePeriodSeconds=30 leaves no time after a 25s preStop and a 5s margin
grace=10 preStop= 5 -> error: terminationGracePeriodSeconds=10 leaves no time after a 5s preStop and a 5s margin
Show solution
python
def shutdown_grace(grace, prestop, margin=5):
    left = grace - prestop - margin
    if left < 1:
        raise ValueError(f"terminationGracePeriodSeconds={grace} leaves no time after a {prestop}s preStop and a {margin}s margin")
    return left

Exercise 3: Pool size per pod

Topics: Production Hardening, Field Notes

Write pool_per_pod(max_connections, reserved, hpa_max): the largest pool_max_conns that keeps all pods under the database's limit at the HPA's maximum. Fewer than two connections per pod isn't workable: say so instead.

python · try it yourself
def pool_per_pod(max_connections, reserved, hpa_max):
    # TODO
    return "?"

for mc, r, h in [(100, 10, 12), (100, 10, 3), (200, 20, 40), (100, 10, 60)]:
    print(f"max_connections={mc:>3} reserved={r:>2} hpa_max={h:>2} -> {pool_per_pod(mc, r, h)}")
max_connections=100 reserved=10 hpa_max=12 -> ?
max_connections=100 reserved=10 hpa_max= 3 -> ?
max_connections=200 reserved=20 hpa_max=40 -> ?
max_connections=100 reserved=10 hpa_max=60 -> ?

Expected output:

text
max_connections=100 reserved=10 hpa_max=12 -> pool_max_conns=7
max_connections=100 reserved=10 hpa_max= 3 -> pool_max_conns=30
max_connections=200 reserved=20 hpa_max=40 -> pool_max_conns=4
max_connections=100 reserved=10 hpa_max=60 -> 1 per pod: too few, add a pooler (PgBouncer) or raise max_connections
Show solution
python
def pool_per_pod(max_connections, reserved, hpa_max):
    per_pod = (max_connections - reserved) // hpa_max
    if per_pod < 2:
        return f"{per_pod} per pod: too few, add a pooler (PgBouncer) or raise max_connections"
    return f"pool_max_conns={per_pod}"

Integer division rounds down, which is the safe direction. During a rolling update the Deployment briefly runs up to maxSurge extra pods, so leave headroom in reserved for them too.

Exercise 4: Burn rates

Topics: SLO Alerts & Dashboards, SRE: Burn Rate

For a 99.9% SLO over 30 days, write burn(error_ratio) returning the burn rate (error ratio divided by the error budget) and the hours until the whole budget is gone at that rate.

python · try it yourself
def burn(error_ratio, slo=0.999, window_days=30):
    # TODO: return (rate, hours)
    return 0.0, 0.0

for er in [0.0005, 0.001, 0.0144, 0.05]:
    r, h = burn(er)
    print(f"errors {er:.2%}: burn rate {r:5.1f}, budget gone in {h:6.1f} h")
errors 0.05%: burn rate   0.0, budget gone in    0.0 h
errors 0.10%: burn rate   0.0, budget gone in    0.0 h
errors 1.44%: burn rate   0.0, budget gone in    0.0 h
errors 5.00%: burn rate   0.0, budget gone in    0.0 h

Expected output:

text
errors 0.05%: burn rate   0.5, budget gone in 1440.0 h
errors 0.10%: burn rate   1.0, budget gone in  720.0 h
errors 1.44%: burn rate  14.4, budget gone in   50.0 h
errors 5.00%: burn rate  50.0, budget gone in   14.4 h
Show solution
python
def burn(error_ratio, slo=0.999, window_days=30):
    rate = error_ratio / (1 - slo)
    hours = window_days * 24 / rate
    return rate, hours

1.44% errors is the page threshold of LinklyErrorBudgetBurn: at burn rate 14.4 the month's budget lasts about two days, and one hour of it uses 2%.

Exercise 5: A guard rail in the chart

Topics: The Production Chart, Helm: Flow Control

Someone sets preStopSleepSeconds: 30 "to be safe". The chart happily renders SHUTDOWN_GRACE: "-5s", kubeconform can't object (ConfigMap values are just strings), and linkly would fail to start in production. Make the chart refuse such values with a clear message. The starter session shows the problem:

bash · try it yourself
mkdir -p chart/linkly/templates && cd chart/linkly
cat > Chart.yaml <<'YAML'
apiVersion: v2
name: linkly
description: linkly, a link shortener (Go, PostgreSQL, Redis)
type: application
version: 0.0.0-dev
appVersion: "0.0.0-dev"
kubeVersion: ">= 1.30.0-0"
YAML
cat > values.yaml <<'YAML'
replicaCount: 2
image:
  repository: ghcr.io/acme/linkly
  tag: ""          # defaults to appVersion
  digest: ""       # sha256:...; wins over the tag when set
config:
  logLevel: info
  baseUrl: https://lnk.example.com
  redisAddr: linkly-redis:6379
  cacheTTL: 1h
database:
  existingSecret: linkly-db   # created outside the chart (CloudNativePG, External Secrets)
  secretKey: url
service:
  port: 80
httpRoute:
  enabled: true
  parentRefs: [{name: public, namespace: gateway-system}]
  hostnames: [lnk.example.com]
autoscaling:
  enabled: false
  minReplicas: 2
  maxReplicas: 10
  targetCPUUtilizationPercentage: 70
podDisruptionBudget:
  enabled: true
  maxUnavailable: 1
serviceMonitor:
  enabled: false
  interval: 30s
networkPolicy:
  enabled: true
  ingressNamespaces: [gateway-system, monitoring]
terminationGracePeriodSeconds: 30
preStopSleepSeconds: 5
resources:
  requests: {cpu: 100m, memory: 64Mi}
  limits: {memory: 128Mi}
YAML
cat > templates/_helpers.tpl <<'YAML'
{{- define "linkly.fullname" -}}
{{- if contains .Chart.Name .Release.Name }}{{ .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}{{ printf "%s-%s" .Release.Name .Chart.Name | trunc 63 | trimSuffix "-" }}{{ end }}
{{- end }}
{{- define "linkly.selectorLabels" -}}
app.kubernetes.io/name: {{ .Chart.Name }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
{{- define "linkly.labels" -}}
{{ include "linkly.selectorLabels" . }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
helm.sh/chart: {{ printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" }}
{{- end }}
{{- define "linkly.image" -}}
{{- if .Values.image.digest }}{{ .Values.image.repository }}@{{ .Values.image.digest }}
{{- else }}{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}{{ end }}
{{- end }}
YAML
cat > templates/configmap.yaml <<'YAML'
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
data:
  LISTEN_ADDR: ":8080"
  LOG_LEVEL: {{ .Values.config.logLevel | quote }}
  BASE_URL: {{ .Values.config.baseUrl | quote }}
  REDIS_ADDR: {{ .Values.config.redisAddr | quote }}
  CACHE_TTL: {{ .Values.config.cacheTTL | quote }}
  SHUTDOWN_GRACE: "{{ sub (sub .Values.terminationGracePeriodSeconds .Values.preStopSleepSeconds) 5 }}s"
YAML
cat > templates/deployment.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  {{- if not .Values.autoscaling.enabled }}
  replicas: {{ .Values.replicaCount }}
  {{- end }}
  revisionHistoryLimit: 5
  strategy: {rollingUpdate: {maxSurge: 25%, maxUnavailable: 0}}
  selector:
    matchLabels: {{- include "linkly.selectorLabels" . | nindent 6 }}
  template:
    metadata:
      labels: {{- include "linkly.selectorLabels" . | nindent 8 }}
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum | trunc 16 }}
    spec:
      automountServiceAccountToken: false
      terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }}
      securityContext: {runAsNonRoot: true, runAsUser: 65532, runAsGroup: 65532, seccompProfile: {type: RuntimeDefault}}
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: kubernetes.io/hostname
          whenUnsatisfiable: ScheduleAnyway
          labelSelector:
            matchLabels: {{- include "linkly.selectorLabels" . | nindent 14 }}
      containers:
        - name: linkly
          image: {{ include "linkly.image" . | quote }}
          ports: [{name: http, containerPort: 8080}]
          envFrom: [{configMapRef: {name: {{ include "linkly.fullname" . }}}}]
          env:
            - name: DATABASE_URL
              valueFrom: {secretKeyRef: {name: {{ .Values.database.existingSecret }}, key: {{ .Values.database.secretKey }}}}
          readinessProbe: {httpGet: {path: /readyz, port: http}, periodSeconds: 5, failureThreshold: 2}
          livenessProbe: {httpGet: {path: /healthz, port: http}, periodSeconds: 10, failureThreshold: 3}
          lifecycle:
            preStop: {sleep: {seconds: {{ .Values.preStopSleepSeconds }}}}
          resources: {{- toYaml .Values.resources | nindent 12 }}
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities: {drop: [ALL]}
YAML
cat > templates/service.yaml <<'YAML'
apiVersion: v1
kind: Service
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  selector: {{- include "linkly.selectorLabels" . | nindent 4 }}
  ports: [{name: http, port: {{ .Values.service.port }}, targetPort: http}]
YAML
cat > templates/httproute.yaml <<'YAML'
{{- if .Values.httpRoute.enabled }}
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  parentRefs: {{- toYaml .Values.httpRoute.parentRefs | nindent 4 }}
  hostnames: {{- toYaml .Values.httpRoute.hostnames | nindent 4 }}
  rules:
    - matches: [{path: {type: PathPrefix, value: /}}]
      backendRefs: [{name: {{ include "linkly.fullname" . }}, port: {{ .Values.service.port }}}]
{{- end }}
YAML
cat > templates/hpa.yaml <<'YAML'
{{- if .Values.autoscaling.enabled }}
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  scaleTargetRef: {apiVersion: apps/v1, kind: Deployment, name: {{ include "linkly.fullname" . }}}
  minReplicas: {{ .Values.autoscaling.minReplicas }}
  maxReplicas: {{ .Values.autoscaling.maxReplicas }}
  metrics:
    - type: Resource
      resource: {name: cpu, target: {type: Utilization, averageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }}}}
{{- end }}
YAML
cat > templates/pdb.yaml <<'YAML'
{{- if .Values.podDisruptionBudget.enabled }}
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  maxUnavailable: {{ .Values.podDisruptionBudget.maxUnavailable }}
  selector:
    matchLabels: {{- include "linkly.selectorLabels" . | nindent 6 }}
{{- end }}
YAML
cat > templates/networkpolicy.yaml <<'YAML'
{{- if .Values.networkPolicy.enabled }}
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  podSelector:
    matchLabels: {{- include "linkly.selectorLabels" . | nindent 6 }}
  policyTypes: [Ingress]
  ingress:
    - from:
        {{- range .Values.networkPolicy.ingressNamespaces }}
        - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: {{ . }}}}
        {{- end }}
      ports: [{port: http}]
{{- end }}
YAML
cat > templates/servicemonitor.yaml <<'YAML'
{{- if .Values.serviceMonitor.enabled }}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  selector:
    matchLabels: {{- include "linkly.selectorLabels" . | nindent 6 }}
  endpoints:
    - port: http
      path: /metrics
      interval: {{ .Values.serviceMonitor.interval }}
{{- end }}
YAML
cd ../..
printf 'preStopSleepSeconds: 30\n' > risky-values.yaml
helm template linkly chart/linkly -f risky-values.yaml > out.yaml && echo "rendered"
yq 'select(.kind == "ConfigMap") | .data.SHUTDOWN_GRACE' out.yaml
kubeconform -summary out.yaml
rendered
-5s
Summary: 6 resources found in 1 file - Valid: 6, Invalid: 0, Errors: 0, Skipped: 0

Expected output once the guard is in place (the starter's last three lines replaced by helm template linkly chart/linkly -f risky-values.yaml 2>&1 | head -1):

text
Error: execution error at (linkly/templates/deployment.yaml:18:28): terminationGracePeriodSeconds (30) must be more than preStopSleepSeconds (30) + 5
Show solution

Compute the value once at the top of templates/configmap.yaml, fail if it is too small, and use the variable:

yaml
{{- $shutdown := sub (sub .Values.terminationGracePeriodSeconds .Values.preStopSleepSeconds) 5 }}
{{- if lt $shutdown 1 }}
{{- fail (printf "terminationGracePeriodSeconds (%v) must be more than preStopSleepSeconds (%v) + 5" .Values.terminationGracePeriodSeconds .Values.preStopSleepSeconds) }}
{{- end }}
apiVersion: v1
kind: ConfigMap
# ... unchanged ...
  SHUTDOWN_GRACE: "{{ $shutdown }}s"

The error points at deployment.yaml:18:28, not at the ConfigMap: the Deployment's checksum/config annotation renders the ConfigMap template through include, and that happens first. A values.schema.json can't express this rule (it compares two values), which is exactly what fail is for.

Exercise 6: linkly migrate (in your repository)

Topics: Production Hardening, GitOps Delivery

Move the schema migration out of startup, so the PreSync Job from the hardening lesson can run it:

  1. In main, if os.Args[1] == "migrate", load the configuration, open the pool, run migrate, log "migrated" and exit 0 (non-zero on failure).
  2. Add RUN_MIGRATIONS (default true for local development); the chart sets it to false and enables the Job behind migrations.enabled.
  3. Extend the integration test: run the migrate path twice and check it is idempotent.
  4. Verify: go run . migrate against the session database from Running linkly, then psql -c '\d links'.

Exercise 7: Rate limit link creation (in your repository)

Topics: Production Hardening, SRE: Load Shedding

Protect POST /links without touching redirects. Either add a per-client token bucket in linkly (key on the client IP from the Gateway's X-Forwarded-For, answer 429 Too Many Requests with a Retry-After header, count http_requests_total{code="429"}), or configure the limit at the Gateway (Envoy Gateway's BackendTrafficPolicy) and write down in an ADR why you chose that layer. Test the in-app version with httptest, the same way TestBadRequests does.

Test yourself

Why compare u.Hostname() rather than u.Host with the shortener's own host?

  1. Host is always empty
  2. Hostname() strips the port, so lnk.example.com:443 can't slip through
  3. Hostname() lowercases nothing
  4. Host includes the path

Why can't kubeconform catch SHUTDOWN_GRACE: "-5s"?

  1. It doesn't read ConfigMaps
  2. ConfigMap data values are arbitrary strings to the Kubernetes schema; only the chart (or the app) knows what they mean
  3. The value is valid
  4. kubeconform needs -strict