We are designing a zero-downtime deployment strategy that incorporates:
- Blue-Green and Canary releases
- Traffic shifting and health checks
- Database migration patterns (expand-migrate-contract)
- Infrastructure as Code (IaC) and GitOps
- Rollback plans
- Observability
We'll provide example configurations for a Kubernetes environment, using tools like ArgoCD (for GitOps), Istio (for traffic shifting), and a database migration tool (like Flyway or Liquibase). However, note that the example configs will be illustrative.
Let's break it down:
1. Blue-Green and Canary Releases
In Kubernetes, we can use Deployments and Services to achieve blue-green and canary.
Blue-Green:
- Maintain two identical production environments (blue and green).
- Only one is live at a time.
- Use a Service that points to the active environment (by selector labels).
Example Deployment (blue) and Service:
# blue-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: app-blue
spec:
replicas: 3
selector:
matchLabels:
app: myapp
version: blue
template:
metadata:
labels:
app: myapp
version: blue
spec:
containers:
- name: myapp
image: myapp:blue
ports:
- containerPort: 8080
---
# blue-service.yaml
apiVersion: v1
kind: Service
metadata:
name: myapp-service
spec:
selector:
app: myapp
version: blue
ports:
- port: 80
targetPort: 8080
To switch to green, create a green deployment and then change the Service selector to version: green. However, note that this causes a brief downtime because the Service endpoints will change and connections to the old pods will be terminated.
Canary:
- Deploy new version (canary) alongside old version (stable).
- Gradually shift traffic from stable to canary.
We can use an ingress controller or service mesh (like Istio) for traffic splitting.
Example with Istio:
First, we have two deployments: stable and canary.
# stable-deployment.yaml (similar to blue but with label version: stable)
apiVersion: apps/v1
kind: Deployment
metadata:
name: app-stable
spec:
replicas: 3
selector:
matchLabels:
app: myapp
version: stable
template:
metadata:
labels:
app: myapp
version: stable
spec:
containers:
- name: myapp
image: myapp:stable
ports:
- containerPort: 8080
---
# canary-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: app-canary
spec:
replicas: 1 # start with one replica for canary
selector:
matchLabels:
app: myapp
version: canary
template:
metadata:
labels:
app: myapp
version: canary
spec:
containers:
- name: myapp
image: myapp:canary
ports:
- containerPort: 8080
Then, we create a VirtualService in Istio to split traffic:
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: myapp
spec:
hosts:
- myapp.example.com
http:
- route:
- destination:
host: myapp
subset: stable
weight: 90
- destination:
host: myapp
subset: canary
weight: 10
And a DestinationRule to define the subsets:
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: myapp
spec:
host: myapp
subsets:
- name: stable
labels:
version: stable
- name: canary
labels:
version: canary
The Service for the app should not have a selector for version, or we can have a headless service? Actually, in Istio, the Service should select all pods (both stable and canary). Alternatively, we can have a single Service that selects both:
apiVersion: v1
kind: Service
metadata:
name: myapp
spec:
selector:
app: myapp
ports:
- port: 80
targetPort: 8080
2. Traffic Shifting and Health Checks
In the canary example, we are shifting traffic by weight. We can gradually increase the weight for canary.
Health checks are configured at the container level (readiness and liveness probes) and also at the ingress/load balancer level.
Example liveness and readiness probes:
containers:
- name: myapp
image: myapp:canary
ports:
- containerPort: 8080
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
In Istio, we can also configure outlier detection to remove unhealthy instances from the load balancing pool.
3. Database Migration Patterns (Expand-Migrate-Contract)
For zero-downtime database migrations, we use the expand-migrate-contract pattern.
Steps:
-
Expand: Add new columns/tables that are nullable or have default values, without removing old ones. The application code should be updated to write to both old and new structures (dual writes) and read from the new structure (if possible) but still be compatible with the old structure.
-
Migrate: Copy data from old structure to new structure. This can be done in the background. The application continues to write to both.
-
Contract: Once all data is migrated and the application is reading only from the new structure, remove the old structure.
Example:
- Suppose we have a table
users with a column name and we want to change it to first_name and last_name.
Step 1 (Expand):
- Add
first_name and last_name columns (nullable).
- Application writes to both
name and the new columns (dual writes). Reads from name for now.
Step 2 (Migrate):
- Run a script to split
name into first_name and last_name and update the new columns.
- Application continues to write to both.
Step 3 (Contract):
- Change application to read from
first_name and last_name and stop writing to name.
- After all instances are updated, drop the
name column.
We need to do this in a way that is compatible with both the old and new application versions during the deployment.
4. IaC/GitOps
We use tools like Terraform for infrastructure provisioning and ArgoCD for application deployments.
Example ArgoCD Application for the canary release:
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: myapp-canary
namespace: argocd
spec:
project: default
source:
repoURL: https://github.com/myorg/myapp.git
targetRevision: HEAD
path: k8s/canary
destination:
server: https://kubernetes.default.svc
namespace: default
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions:
- CreateNamespace=true
We can have two applications: one for stable and one for canary, and then use the Istio configuration to split traffic.
Alternatively, we can use a single application with multiple environments (staging, production) and use ArgoCD's sync waves to control order.
5. Rollback Plans
For application rollback:
- In blue-green, we can simply switch the Service selector back to the previous version.
- In canary, we adjust the traffic weights to send 100% to the stable version and then delete the canary deployment.
For database rollback:
- We must be cautious because once we contract (drop old columns) we cannot easily rollback the database schema.
- Therefore, we should only contract after we are sure the new version is stable and we have a backup of the data.
- For expand and migrate steps, we can rollback by:
- If we are in the expand phase (only added new columns, not removed old ones), we can rollback the application code and continue using the old structure.
- If we have started migrating data, we might need to stop the migration and possibly revert the data if we have a way (like having a snapshot before migration).
It's common to do the database migration in a separate step and ensure it's complete before deploying the application that uses the new structure.
6. Observability
We need to monitor:
- Application metrics (response time, error rates, etc.)
- Infrastructure metrics (CPU, memory, etc.)
- Business metrics (if any)
- Logs and traces
Tools: Prometheus, Grafana, Jaeger, ELK stack, etc.
In the canary deployment, we should set up alerts on the canary version's metrics and compare with stable. If the canary shows higher error rate or latency, we rollback.
Example: We can use Prometheus queries in Grafana to compare the two versions.
Also, we can use Istio's telemetry to get metrics per route (subset).
Putting it all together:
We'll design a pipeline:
-
Develop and test in a feature branch.
-
Merge to main and trigger CI (build, test, container image push).
-
Deploy to staging (using GitOps) and run integration tests.
-
For production:
- Use blue-green for the first deployment of a new version (or for major changes) and then switch.
- Or use canary for incremental rollout.
-
Database migration:
- Step 1 (Expand): Deploy application that writes to both old and new structures (but reads from old). This is a backward-compatible change.
- Step 2 (Migrate): Run a one-time migration script (could be a Kubernetes job) to copy data. This can be done after the new application is running (since it's dual write, the migration can run in the background without downtime).
- Step 3 (Contract): After migration is complete and the application is updated to read from new structure (and stop writing to old), deploy the application that only uses the new structure. Then drop the old columns.
-
During canary, we monitor the canary pods. If health checks fail or metrics are bad, we adjust traffic to 0% and rollback.
-
Rollback plan: if something goes wrong, we have documented steps for each component (application, infrastructure, database).
Example of a migration job (step 2):
apiVersion: batch/v1
kind: Job
metadata:
name: migrate-users
spec:
template:
spec:
containers:
- name: migrate
image: myapp-migration:latest
command: ["sh", "-c", "python migrate.py"]
restartPolicy: Never
However, note that the migration script must be idempotent and safe to run multiple times.
Conclusion
This is a high-level design. In practice, each step must be carefully planned and tested.
Let's provide a summary of example configs for the key parts:
- Canary deployment with Istio (VirtualService and DestinationRule) and two Deployments (stable and canary).
- Health probes in the Deployment.
- Database migration steps (expand: ALTER TABLE to add new columns; migrate: run a job; contract: alter table to drop old column and update application to use new).
- ArgoCD Application for GitOps.
- Observability: set up Prometheus rules for canary monitoring.
Example Prometheus rule for canary error rate:
groups:
- name: canary
rules:
- alert: HighErrorRateCanary
expr: sum(rate(http_requests_total{version="canary", code=~"5.."}[5m])) / sum(rate(http_requests_total{version="canary"}[5m])) > 0.05
for: 2m
labels:
severity: critical
annotations:
summary: "High error rate on canary version"
This alert triggers if more than 5% of requests to the canary are 5xx errors for 2 minutes.
Remember, this is a simplified example. Real-world scenarios may require more complexity.
I'll design a comprehensive zero-downtime deployment strategy with modern DevOps practices and concrete examples.
Zero-Downtime Deployment Architecture
┌─────────────────────────────────────────────────────────────┐
│ Git Repository (Source of Truth) │
├──────────────┬──────────────┬──────────────┬───────────────┤
│ Feature │ Staging │ Production │ Rollback │
│ Branches │ Env │ Env │ Branch │
└──────────────┴──────────────┴──────────────┴───────────────┘
│ │ │ │
▼ ▼ ▼ ▼
┌─────────────────────────────────────────────────────────────┐
│ CI/CD Pipeline (GitOps) │
├─────────────────────────────────────────────────────────────┤
│ Build → Test → Security Scan → Artifact Push → Deploy │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Deployment Strategies │
├─────────────────────────────────────────────────────────────┤
│ 1. Blue-Green (Major Releases) │ 2. Canary (Incremental)│
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Traffic Management Layer │
├─────────────────────────────────────────────────────────────┤
│ • Service Mesh (Istio/Linkerd) │ • Ingress Controller │
│ • Progressive Delivery (Argo Rollouts) │
│ • Weight-based Routing │ • Header-based Routing│
└─────────────────────────────────────────────────────────────┘
1. Blue-Green Deployment
Concept
- Two identical production environments (Blue = current, Green = new)
- Switch traffic atomically when Green is healthy
- Quick rollback by reverting to Blue
Kubernetes Example with Istio
# green-deployment.yaml - New version
apiVersion: apps/v1
kind: Deployment
metadata:
name: app-green
spec:
replicas: 3
selector:
matchLabels:
app: myapp
version: green
template:
metadata:
labels:
app: myapp
version: green
spec:
containers:
- name: myapp
image: myapp:v2.0.0
ports:
- containerPort: 8080
readinessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
---
# blue-service.yaml - Current production
apiVersion: v1
kind: Service
metadata:
name: myapp
spec:
selector:
app: myapp
version: blue
ports:
- port: 80
targetPort: 8080
---
# istio-virtualservice.yaml - Traffic switching
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: myapp
spec:
hosts:
- myapp.example.com
http:
- route:
- destination:
host: myapp
subset: blue
weight: 100 # Initially 100% to blue
Switch command:
# After validating green deployment
kubectl patch virtualservice myapp -p '{"spec":{"http":[{"route":[{"destination":{"host":"myapp","subset":"green"},"weight":100}]}]}}'
2. Canary Release with Progressive Delivery
Argo Rollouts Example (Kubernetes)
# argo-rollouts.yaml
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
name: myapp-rollout
spec:
replicas: 5
strategy:
canary:
canaryService: myapp-canary
stableService: myapp-stable
trafficRouting:
istio:
virtualService:
name: myapp
routes:
- primary
steps:
- setWeight: 10 # 10% traffic to canary
- pause: {duration: 5m} # Automated analysis
- setWeight: 30
- pause: {duration: 10m}
- setWeight: 60
- pause: {duration: 15m}
- setWeight: 100
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: myapp
image: myapp:v2.1.0
ports:
- containerPort: 8080
env:
- name: CANARY_VERSION
value: "true"
Traffic Shifting with Istio
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: myapp
spec:
hosts:
- myapp.example.com
http:
- name: primary
route:
- destination:
host: myapp
subset: stable
weight: 90
- destination:
host: myapp
subset: canary
weight: 10
retries:
attempts: 3
perTryTimeout: 2s
retryOn: gateway-error,connect-failure,refused-stream
---
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: myapp
spec:
host: myapp
subsets:
- name: stable
labels:
version: stable
- name: canary
labels:
version: canary
trafficPolicy:
connectionPool:
tcp:
maxConnections: 100
http:
http1MaxPendingRequests: 100
maxRequestsPerConnection: 10
3. Health Checks Configuration
Kubernetes Probes
containers:
- name: myapp
image: myapp:v2.1.0
ports:
- containerPort: 8080
livenessProbe:
httpGet:
path: /health/live
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
readinessProbe:
httpGet:
path: /health/ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 2
successThreshold: 1
startupProbe:
httpGet:
path: /health/start
port: 8080
initialDelaySeconds: 10
periodSeconds: 10
failureThreshold: 30
Custom Health Check Endpoint (Spring Boot Example)
@RestController
public class HealthController {
@GetMapping("/health/live")
public ResponseEntity<String> liveness() {
// Basic process check
return ResponseEntity.ok("OK");
}
@GetMapping("/health/ready")
public ResponseEntity<Map<String, Object>> readiness() {
Map<String, Object> health = new HashMap<>();
health.put("status", "UP");
health.put("database", checkDatabase());
health.put("diskSpace", checkDiskSpace());
health.put("externalService", checkExternalService());
return ResponseEntity.ok(health);
}
}
4. Database Migration: Expand-Migrate-Contract Pattern
Phase 1: Expand (Backward Compatible Changes)
-- Expand phase - Add new nullable columns
ALTER TABLE users ADD COLUMN first_name VARCHAR(100);
ALTER TABLE users ADD COLUMN last_name VARCHAR(100);
ALTER TABLE users ADD COLUMN email_new VARCHAR(255);
-- Create new table (if needed)
CREATE TABLE orders_new LIKE orders;
ALTER TABLE orders_new ADD COLUMN user_id_new BIGINT;
Application Changes:
// Dual-write pattern
public void saveUser(User user) {
// Write to old columns (for backward compatibility)
jdbcTemplate.update("INSERT INTO users (id, name) VALUES (?, ?)",
user.getId(), user.getFullName());
// Write to new columns (for new version)
jdbcTemplate.update("UPDATE users SET first_name = ?, last_name = ? WHERE id = ?",
user.getFirstName(), user.getLastName(), user.getId());
}
Phase 2: Migrate (Data Migration)
# migration-job.yaml
apiVersion: batch/v1
kind: Job
metadata:
name: data-migration-v2.1
spec:
template:
spec:
restartPolicy: OnFailure
containers:
- name: migrator
image: data-migrator:v2.1.0
command: ["python", "migrate.py"]
env:
- name: DB_URL
valueFrom:
secretKeyRef:
name: db-secret
key: url
resources:
limits:
memory: "512Mi"
cpu: "500m"
backoffLimit: 3
Migration Script (Python Example):
import psycopg2
from contextlib import contextmanager
@contextmanager
def get_connection():
conn = psycopg2.connect(os.getenv('DB_URL'))
try:
yield conn
conn.commit()
except Exception:
conn.rollback()
raise
finally:
conn.close()
def migrate_users():
with get_connection() as conn:
cursor = conn.cursor()
# Batch processing to avoid locking
cursor.execute("""
UPDATE users
SET first_name = split_part(name, ' ', 1),
last_name = split_part(name, ' ', 2)
WHERE first_name IS NULL
AND name LIKE '% %'
""")
# Verify migration
cursor.execute("""
SELECT COUNT(*) FROM users
WHERE first_name IS NULL
AND name LIKE '% %'
""")
remaining = cursor.fetchone()[0]
if remaining == 0:
print("Migration completed successfully")
else:
print(f"Warning: {remaining} records not migrated")
Phase 3: Contract (Cleanup)
-- After verifying all app instances use new schema
ALTER TABLE users DROP COLUMN name;
ALTER TABLE users RENAME COLUMN email_new TO email;
-- Deploy application version that only uses new columns
-- Then drop old constraints/indexes
5. Infrastructure as Code (IaC) & GitOps
Terraform for Infrastructure
# main.tf
terraform {
required_version = ">= 1.0"
backend "gcs" {
bucket = "myapp-terraform-state"
prefix = "terraform/state"
}
}
provider "kubernetes" {
host = module.gke.endpoint
token = data.google_client_config.default.access_token
cluster_ca_certificate = base64decode(module.gke.ca_certificate)
}
resource "kubernetes_namespace" "production" {
metadata {
name = "production"
labels = {
environment = "production"
managed-by = "terraform"
}
}
}
resource "kubernetes_service" "myapp" {
metadata {
name = "myapp"
namespace = kubernetes_namespace.production.metadata[0].name
}
spec {
selector = {
app = "myapp"
}
port {
port = 80
target_port = 8080
}
type = "LoadBalancer"
}
}
ArgoCD Application for GitOps
# argocd-applications/production-myapp.yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: production-myapp
namespace: argocd
finalizers:
- resources-finalizer.argocd.argoproj.io
spec:
project: production
source:
repoURL: https://github.com/myorg/infrastructure.git
targetRevision: main
path: k8s/production/myapp
destination:
server: https://kubernetes.default.svc
namespace: production
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions:
- CreateNamespace=true
- PruneLast=true
retry:
limit: 5
backoff:
duration: 5s
factor: 2
maxDuration: 3m
timeout: 10m
revisionHistoryLimit: 10
6. Rollback Plans
Kubernetes Rollback Commands
# Canary rollback (Argo Rollouts)
kubectl argo rollouts undo rollout myapp-rollout
# Blue-Green rollback (switch back to blue)
kubectl patch virtualservice myapp -p '{"spec":{"http":[{"route":[{"destination":{"host":"myapp","subset":"blue"},"weight":100}]}]}}'
# Kubernetes Deployment rollback
kubectl rollout undo deployment/myapp-green
# View rollout history
kubectl rollout history deployment/myapp-green
kubectl rollout history deployment/myapp-green --revision=2
Database Rollback Script
-- Pre-migration backup table creation (expand phase)
CREATE TABLE users_backup_20240101 AS SELECT * FROM users;
-- Rollback function
CREATE OR REPLACE FUNCTION rollback_user_schema()
RETURNS void AS $$
BEGIN
-- Restore data if needed
INSERT INTO users (id, name, email)
SELECT id, name, email_backup FROM users_backup_20240101
ON CONFLICT (id) DO UPDATE SET
name = EXCLUDED.name,
email = EXCLUDED.email;
-- Drop new columns
ALTER TABLE users DROP COLUMN IF EXISTS first_name;
ALTER TABLE users DROP COLUMN IF EXISTS last_name;
ALTER TABLE users DROP COLUMN IF EXISTS email_new;
END;
$$ LANGUAGE plpgsql;
7. Observability Stack
Prometheus Monitoring Rules
# prometheus-rules.yaml
groups:
- name: deployment_health
rules:
- alert: HighErrorRate
expr: sum(rate(http_requests_total{status=~"5..",service="myapp"}[5m])) / sum(rate(http_requests_total{service="myapp"}[5m])) > 0.05
for: 2m
labels:
severity: critical
component: canary
annotations:
summary: "High error rate detected on {{$labels.service}}"
description: "Error rate is {{$value}} for last 5 minutes"
- alert: HighLatency
expr: histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket{service="myapp"}[5m])) by (le)) > 1
for: 5m
labels:
severity: warning
annotations:
summary: "High p95 latency on {{$labels.service}}"
- alert: CanaryErrorRateDeviation
expr: (sum(rate(http_requests_total{version="canary",status=~"5.."}[5m])) / sum(rate(http_requests_total{version="canary"}[5m]))) >
(sum(rate(http_requests_total{version="stable",status=~"5.."}[5m])) / sum(rate(http_requests_total{version="stable"}[5m])) * 1.5)
for: 3m
labels:
severity: critical
annotations:
summary: "Canary error rate 50% higher than stable"
Grafana Dashboard JSON
{
"dashboard": {
"title": "Canary Deployment Monitor",
"panels": [
{
"title": "Traffic Split",
"targets": [{
"expr": "sum(istio_requests_total{destination_service=\"myapp\",destination_version=\"canary\"}) by (source_workload)",
"legendFormat": "Canary"
}]
},
{
"title": "Error Rate Comparison",
"targets": [
{
"expr": "sum(rate(http_requests_total{version=\"canary\",status=~\"5..\"}[5m])) / sum(rate(http_requests_total{version=\"canary\"}[5m]))",
"legendFormat": "Canary Error Rate"
},
{
"expr": "sum(rate(http_requests_total{version=\"stable\",status=~\"5..\"}[5m])) / sum(rate(http_requests_total{version=\"stable\"}[5m]))",
"legendFormat": "Stable Error Rate"
}
]
}
]
}
}
8. Complete Deployment Pipeline (GitHub Actions Example)
# .github/workflows/deploy.yml
name: Deploy with Canary Analysis
on:
push:
branches: [main]
jobs:
deploy-canary:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build and Push
run: |
docker build -t gcr.io/$PROJECT_ID/myapp:${{ github.sha }} .
docker push gcr.io/$PROJECT_ID/myapp:${{ github.sha }}
- name: Deploy Canary
run: |
kubectl set image deployment/myapp-green \
myapp=gcr.io/$PROJECT_ID/myapp:${{ github.sha }} \
--record
kubectl argo rollouts promote myapp-rollout
- name: Wait and Analyze
run: |
sleep 300 # Wait for canary analysis
# Check metrics
ERROR_RATE=$(curl -s http://prometheus:9090/api/v1/query?query='sum(rate(http_requests_total{version="canary",status=~"5.."}[5m])) / sum(rate(http_requests_total{version="canary"}[5m]))' | jq -r '.data.result[0].value[1]')
if (( $(echo "$ERROR_RATE > 0.05" | bc -l) )); then
echo "Error rate too high: $ERROR_RATE"
kubectl argo rollouts abort myapp-rollout
exit 1
fi
- name: Promote to Stable
if: success()
run: |
kubectl argo rollouts promote myapp-rollout --step 100
rollback-on-failure:
needs: deploy-canary
if: failure()
runs-on: ubuntu-latest
steps:
- name: Rollback
run: |
kubectl argo rollouts undo myapp-rollout
kubectl argo rollouts status myapp-rollout
9. Automated Rollback Trigger (Flagger Example)
# flagger-canary-analysis.yaml
apiVersion: flagger.app/v1beta1
kind: Canary
metadata:
name: myapp
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: myapp
service:
port: 8080
targetPort: 8080
analysis:
interval: 1m
threshold: 10
maxWeight: 50
stepWeight: 5
metrics:
- name: error-rate
thresholdRange:
max: 1
interval: 1m
query: |
sum(rate(http_requests_total{namespace="production", deployment="myapp", response_code=~"5.."}[1m])) * 100
- name: latency
thresholdRange:
max: 500
interval: 1m
query: |
histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket{namespace="production", deployment="myapp"}[1m])) by (le))
webhooks:
- name: notification
url: http://notification-service/alert
timeout: 5s
failOnError: true
Best Practices Checklist
Before Deployment:
- ✅ Run integration tests in staging with production-like data
- ✅ Perform load testing on canary with production traffic patterns
- ✅ Validate health check endpoints respond correctly
- ✅ Ensure database migrations are reversible
- ✅ Document rollback procedures
During Deployment:
- ✅ Monitor key metrics: error rate, latency, throughput, saturation
- ✅ Set up automated alerts for anomalies
- ✅ Keep canary duration short (15-30 minutes minimum)
- ✅ Gradually increase traffic weight
- ✅ Have runbooks for common failure scenarios
Post-Deployment:
- ✅ Verify all instances are healthy
- ✅ Monitor for 24-48 hours for latent issues
- ✅ Clean up old deployments/versions
- ✅ Update documentation and runbooks
Key Tools Summary
| Component | Recommended Tools | Alternatives |
|---|
| Orchestration | Kubernetes | ECS, Nomad |
| Service Mesh | Istio | Linkerd, Consul |
| Progressive Delivery | Argo Rollouts | Flagger, Spinnaker |
| GitOps | ArgoCD | Flux, Jenkins X |
| IaC | Terraform | Crossplane, Pulumi |
| Monitoring | Prometheus + Grafana | Datadog, New Relic |
| Logging | Loki + Grafana | ELK, Splunk |
| Tracing | Jaeger | Zipkin, OpenTelemetry |
| Database Migration | Flyway, Liquibase | Custom scripts, Alembic |
This strategy provides multiple layers of safety: health checks prevent bad deployments from getting traffic, gradual traffic shifting limits blast radius, observability enables rapid detection, and automated rollbacks minimize MTTR. The expand-migrate-contract pattern ensures database changes are reversible and backward-compatible throughout the deployment.