Crafting deployment strategies
I’m outlining some key sections for deployment strategies: First, I’ll cover principles like immutable builds and versioned artifacts. Next, I’ll look at deployment patterns such as blue-green and canary methods. I’ll also mention traffic shifting options, like using a service mesh or ingress controller, while being careful with DNS TTL timing. Health checks are essential, so I’ll include readiness checks and smoke tests, while for database migrations, I’ll detail expanding, migrating, and contracting. I'll also touch on IaC with Terraform and rollback plans.Outlining observability and configurations
I’m detailing restore options like snapshot recovery and point-in-time restoration. For observability, I’ll outline metrics like golden signals and the importance of logging with correlation IDs. I need to mention alerting, SLO gating, and leverage analysis templates in Argo Rollouts, possibly including a Prometheus query example. Additionally, I’ll list example configurations for Kubernetes Deployments, Argo Rollouts, Istio routing, and include Terraform snippets. I'll keep it concise while ensuring it offers the necessary details for configurability.Including key components
I need to include a pre-traffic smoke test job and make sure to mention Kubernetes hooks. It's also essential to touch on potential session affinity issues and how websockets can degrade under certain conditions. This will help create a more comprehensive response. I want to ensure I’m covering all necessary aspects while keeping the information clear and relevant for the user. Let’s move forward with these considerations!
1) Core principles for zero‑downtime
- Immutable artifacts: build once (image/tag/SHA), promote the same artifact across environments.
- Backward/forward compatibility: new app version must tolerate old schema/data and vice‑versa during rollout.
- Traffic is shifted, not “stopped”: drain connections, keep old version serving until new is proven healthy.
- Automation + gates: progressive delivery controlled by health signals (metrics, logs, synthetic checks).
2) Blue‑green vs canary (when to use)
Blue‑green
- Two complete stacks: blue (current) and green (new).
- Switch traffic all at once (or near‑instant) by swapping a Service/Ingress/LB target.
- Best for: simpler rollback, big changes, shorter “mixed version” window.
Canary
- Deploy new version alongside old and shift traffic gradually (e.g., 1% → 5% → 25% → 50% → 100%).
- Best for: risk reduction, validating real traffic, continuous delivery.
Many teams combine them: canary inside a “green” environment, then promote green.
3) Traffic shifting mechanisms (common options)
- Service mesh (Istio/Linkerd): weighted routing by subset/version; best control and observability.
- Ingress controller (NGINX/ALB): canary annotations, header/cookie based routing, weighted backends.
- LB target group weights (AWS/GCP/Azure): stable, infra‑level.
- DNS weight shifting: usually last resort (TTL, caching makes it less deterministic).
Also consider:
- Sticky sessions: ensure session state is externalized (Redis/db) or routing remains consistent.
- WebSockets/long polling: need connection draining and longer termination grace.
4) Health checks, draining, and safe termination
Kubernetes probes (recommended pattern)
- startupProbe protects slow starts.
- readinessProbe gates traffic.
- livenessProbe only for “must restart” failures.
- preStop + terminationGracePeriodSeconds for connection draining.
Example Deployment snippet:
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
spec:
replicas: 6
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 0
maxSurge: 2
template:
spec:
terminationGracePeriodSeconds: 60
containers:
- name: api
image: ghcr.io/acme/api:1.2.3
ports:
- containerPort: 8080
lifecycle:
preStop:
exec:
command: ["sh","-c","sleep 10"] # allow LB/mesh to stop sending
startupProbe:
httpGet: { path: /health/startup, port: 8080 }
failureThreshold: 30
periodSeconds: 2
readinessProbe:
httpGet: { path: /health/ready, port: 8080 }
periodSeconds: 5
failureThreshold: 3
livenessProbe:
httpGet: { path: /health/live, port: 8080 }
periodSeconds: 10
failureThreshold: 3
Add a PodDisruptionBudget to avoid involuntary downtime:
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: api-pdb
spec:
minAvailable: 4
selector:
matchLabels:
app: api
Health endpoints should validate:
/health/ready: downstream deps reachable? migrations complete? config loaded?
/health/live: process isn’t wedged (don’t include DB checks here).
5) Progressive delivery configs (blue‑green + canary)
Option A: Canary with Argo Rollouts + Istio weighted routing
Rollout:
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
name: api
spec:
replicas: 6
revisionHistoryLimit: 5
selector:
matchLabels: { app: api }
template:
metadata:
labels: { app: api }
spec:
containers:
- name: api
image: ghcr.io/acme/api:1.2.3
ports: [{ containerPort: 8080 }]
readinessProbe:
httpGet: { path: /health/ready, port: 8080 }
strategy:
canary:
canaryService: api-canary
stableService: api-stable
trafficRouting:
istio:
virtualService:
name: api-vs
routes: ["http"]
destinationRule:
name: api-dr
canarySubsetName: canary
stableSubsetName: stable
analysis:
templates:
- templateName: api-success-metrics
steps:
- setWeight: 5
- pause: { duration: 2m }
- setWeight: 25
- pause: { duration: 5m }
- setWeight: 50
- pause: { duration: 10m }
- setWeight: 100
Istio VirtualService / DestinationRule (subsets by pod label rollouts-pod-template-hash managed by Argo Rollouts):
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: api-dr
spec:
host: api
subsets:
- name: stable
labels: { app: api }
- name: canary
labels: { app: api }
---
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: api-vs
spec:
hosts: ["api.example.com"]
gateways: ["public-gw"]
http:
- name: http
route:
- destination: { host: api-stable }
weight: 100
- destination: { host: api-canary }
weight: 0
Automated health gate using Prometheus (analysis template):
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
name: api-success-metrics
spec:
metrics:
- name: http-5xx-rate
interval: 30s
failureLimit: 2
successCondition: result[0] < 0.01
provider:
prometheus:
address: http://prometheus.monitoring:9090
query: |
sum(rate(http_requests_total{app="api",status=~"5.."}[2m]))
/
sum(rate(http_requests_total{app="api"}[2m]))
Option B: Blue‑green with Argo Rollouts (instant switch + preview)
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
name: api
spec:
replicas: 6
selector:
matchLabels: { app: api }
template:
metadata:
labels: { app: api }
spec:
containers:
- name: api
image: ghcr.io/acme/api:1.2.3
readinessProbe:
httpGet: { path: /health/ready, port: 8080 }
strategy:
blueGreen:
activeService: api-active
previewService: api-preview
autoPromotionEnabled: false
prePromotionAnalysis:
templates:
- templateName: api-success-metrics
You can route internal testers to api-preview while production stays on api-active. Promotion flips the Service selector (fast rollback: flip back).
6) Database migration strategy: Expand → Migrate → Contract
Goal: keep both old and new app versions working during the rollout window.
Phase 1 — Expand (backward compatible)
- Add new nullable columns/tables/indexes.
- Avoid destructive operations (drop/rename) during deployment.
- Prefer additive schema changes.
Example (Postgres):
-- V2025.12.13.001__expand_add_customer_tier.sql
ALTER TABLE customers ADD COLUMN tier TEXT; -- nullable
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_customers_tier ON customers(tier);
App vNext reads tier if present, otherwise defaults.
Phase 2 — Migrate (backfill / dual-write)
- Backfill existing data with a one‑off job.
- For risky changes, do dual write (write old+new fields) until fully cut over.
Backfill job example:
-- run as a batch job with throttling
UPDATE customers
SET tier = CASE WHEN lifetime_value > 10000 THEN 'gold' ELSE 'standard' END
WHERE tier IS NULL;
Validation queries (gate promotion):
SELECT count(*) FROM customers WHERE tier IS NULL;
Phase 3 — Contract (cleanup after old versions are gone)
- Only after you’re sure no running code depends on old columns/paths.
-- V2026.01.10.001__contract_remove_old_column.sql
ALTER TABLE customers DROP COLUMN old_tier_code;
Rules of thumb
- Avoid “down migrations” in production. Roll forward with a hotfix instead.
- If you must do a destructive change, do it in a separate, later release after verifying no old pods remain.
7) IaC + GitOps workflow (repeatable + auditable)
IaC (Terraform) for infrastructure
Provision cluster, databases, load balancers, IAM, queues, etc. Example (very minimal):
module "eks" {
source = "terraform-aws-modules/eks/aws"
cluster_name = "prod"
cluster_version = "1.30"
# node groups, IAM, networking...
}
GitOps (Argo CD) for app + rollout objects
Argo CD Application example:
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: api-prod
spec:
destination:
namespace: api
server: https://kubernetes.default.svc
source:
repoURL: https://github.com/acme/platform-gitops
targetRevision: main
path: apps/api/prod
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions:
- CreateNamespace=true
Pipeline pattern
- CI builds image
api:<git-sha>, runs tests, scans, pushes.
- CI updates GitOps repo (Helm values/Kustomize image tag).
- Argo CD syncs; Argo Rollouts performs canary/blue‑green with analysis gates.
- Promote on success; auto‑abort on failures.
8) Rollback plans (app, traffic, DB, and data)
App/traffic rollback
- Canary:
kubectl argo rollouts abort api (stops progression, routes back to stable).
- Blue‑green: switch Service back to blue (active → previous).
- Always keep N previous ReplicaSets (revisionHistoryLimit) to revert quickly.
Database rollback (practical reality)
- Prefer forward fixes:
- keep old columns until contract phase
- feature flags to disable new behavior
- If data corruption risk exists:
- point‑in‑time recovery (PITR) plan for DB
- snapshots before contract migrations
- run migrations as separate, audited steps (not hidden in app startup)
Feature flags as a “safety valve”
- Deploy code dark (flag off), then enable gradually.
- Flags reduce need for emergency rollbacks when only behavior—not availability—is wrong.
9) Observability (what to measure + how to gate)
Minimum signals (per version)
- Golden signals: latency (p95/p99), traffic, errors, saturation.
- Break down by:
- version (image tag/rollout hash)
- route/endpoint
- dependency (db/redis/external)
Practical stack
- Metrics: Prometheus + Alertmanager
- Logs: Loki/ELK with structured JSON logs
- Traces: OpenTelemetry + Tempo/Jaeger
- Dashboards: Grafana
- Release annotations: tag deploy start/end in dashboards
Example Prometheus alert for canary regression:
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: api-alerts
spec:
groups:
- name: api.rules
rules:
- alert: ApiHigh5xxRate
expr: |
(sum(rate(http_requests_total{app="api",status=~"5.."}[5m])) /
sum(rate(http_requests_total{app="api"}[5m]))) > 0.02
for: 3m
labels: { severity: page }
annotations:
summary: "API 5xx rate > 2% (5m)"
10) Operational checklist (zero‑downtime guardrails)
maxUnavailable: 0 for rolling updates (or use Rollouts).
- Adequate replica count + PDBs + HPA.
- Connection draining (
preStop, LB deregistration delay, mesh outlier detection).
- Schema changes follow expand‑migrate‑contract.
- Canary/blue‑green gated by automated analysis (5xx, latency, saturation) + smoke tests.
- Rollback is rehearsed (runbooks + game days).
If you share your environment (Kubernetes vs ECS, Istio/NGINX/ALB, DB type, and whether you already use Argo CD), I can tailor the configs to your exact stack and show a complete end‑to‑end repo layout (Terraform + GitOps + Rollouts + migration job manifests).