Pular para conteúdo

Rollback Procedure

Como reverter um deploy problemático.

Quick Rollback

Para reverter rapidamente um deploy com problemas:

# 1. Revert merge commit
git revert <merge-commit-sha> -m 1
git push origin main

# 2. Deploy automático ocorre (3-5 min)

# 3. Verificar que problema foi resolvido
curl https://api.seuapp.com/health

Duração total: ~10 minutos

Rollback Detalhado

1. Identificar Problema

# Ver último deploy
git log -1 --oneline main

# Ver mudanças
git diff HEAD~1

# Ver CloudWatch logs
aws logs tail /aws/lambda/app-user-function --since 30m --follow

# Identificar se é o deploy atual que causou

2. Decidir Estratégia

Opção A: Revert (Recomendado) - ✅ Mais rápido (10 min) - ✅ Menor risco - ❌ Perde todas as mudanças do PR

Opção B: Forward Fix (Hotfix) - ✅ Mantém mudanças boas - ✅ Corrige apenas o problema - ❌ Mais demorado (30-60 min) - ❌ Mais arriscado

Opção C: Rollback para Versão Anterior (Tag) - ✅ Confiável - ✅ Versão conhecida como boa - ❌ Perde múltiplos deploys

Decisão: - P0/P1: Opção A (revert) - P2: Pode considerar B (hotfix) - P3: B (hotfix)

3. Comunicar

🔄 **Iniciando rollback em production**

**Incident**: #123
**Reason**: API returning 502 errors
**Action**: Reverting PR #456
**ETA**: 10 minutes
**Impact**: Brief service disruption expected

Monitoring and will update.

4. Executar Rollback

Opção A: Revert Commit

# 1. Identificar merge commit
git log --oneline --merges -5 main

# 2. Revert
git checkout main
git pull origin main
git revert abc123 -m 1  # -m 1 para reverter merge

# 3. Push
git push origin main

# 4. Aguardar deploy automático
# Ou forçar:
sam deploy --config-env production --force-upload

Opção B: Rollback para Tag Anterior

# 1. Ver tags recentes
git tag -l | tail -5

# 2. Checkout versão anterior
git checkout v2026.01.19

# 3. Force deploy desta versão
sam build --use-container
sam deploy --config-env production --force-upload

# 4. Criar branch de emergência
git checkout -b emergency/rollback-to-v20260119
git push origin emergency/rollback-to-v20260119

# 5. Atualizar main depois
git checkout main
git reset --hard v2026.01.19
git push origin main --force-with-lease  # CUIDADO!

Opção C: Rollback de Database

Se migration causou problema:

# 1. Rollback application code primeiro (acima)

# 2. Rollback migration
alembic -c alembic.prod.ini downgrade -1

# 3. Verificar
alembic -c alembic.prod.ini current
python scripts/verify_schema.py

Ver Database Rollback →

5. Verificar Rollback

# Health check
curl https://api.seuapp.com/health

# Test critical endpoints
curl https://api.seuapp.com/api/v1/users

# Check logs
aws logs tail /aws/lambda/app-user-function --since 5m

# Verify metrics
# - Check CloudWatch dashboard
# - Error rate back to normal?
# - Latency acceptable?

6. Monitorar (30 min)

  • Logs sem erros críticos
  • Métricas estáveis
  • Alarmes silenciosos
  • User reports diminuíram
  • Smoke tests passando

7. Comunicar Conclusão

✅ **Rollback completed successfully**

**Incident**: #123
**Duration**: 12 minutes
**Status**: Resolved
**Current Version**: v2026.01.19 (previous stable)

Production is stable. Investigating root cause.

Postmortem: [will be posted]

8. Post-Rollback

  • Atualizar incident report
  • Identificar root cause
  • Criar issue para fix
  • Schedule postmortem (P0/P1)
  • Update dev branch se necessário

Rollback de Frontend

Se apenas frontend tem problema:

# CloudFront invalidation para versão anterior
aws cloudfront create-invalidation \
  --distribution-id XXXXX \
  --paths "/*"

# Ou reverter no S3
aws s3 sync s3://backup-bucket/previous-version/ s3://app-static-assets/ --delete

Rollback de Database Apenas

Se apenas database migration tem problema:

# 1. Rollback migration
alembic -c alembic.prod.ini downgrade -1

# 2. Verificar
alembic current
python scripts/verify_schema.py

# 3. Testar aplicação
curl https://api.seuapp.com/health/db

# 4. Deploy código antigo se necessário (código pode depender de schema)

Rollback Fail Scenarios

Se Rollback Falhar

  1. Não entre em pânico
  2. Escale para Tech Lead / CTO
  3. Considere:
  4. Restore database snapshot
  5. Deploy versão estável conhecida
  6. Temporary maintenance mode

Rollback Impossível

Algumas situações rollback não é possível:

  • Migration que deletou dados (sem backup)
  • Mudanças externas não reversíveis
  • State distribuído inconsistente

Solução: Forward fix obrigatório

Testing Rollback

Staging

Testar rollback em staging regularmente:

# 1. Deploy versão N
sam deploy --config-env staging

# 2. Deploy versão N+1
# Make changes...
sam deploy --config-env staging

# 3. Rollback para N
git revert HEAD
git push origin dev

# 4. Verificar que funciona

Frequência: Uma vez por mês

Automation Scripts

scripts/quick_rollback.sh:

#!/bin/bash
set -e

COMMIT_TO_REVERT=$1

if [ -z "$COMMIT_TO_REVERT" ]; then
    echo "Usage: ./quick_rollback.sh <commit-hash>"
    exit 1
fi

echo "🔄 Starting rollback of commit $COMMIT_TO_REVERT"

# Revert
git revert $COMMIT_TO_REVERT -m 1 --no-edit
git push origin main

echo "✅ Rollback committed. GitHub Actions will deploy automatically."
echo "⏱️  ETA: ~10 minutes"
echo "📊 Monitor: https://github.com/seu-org/backend-api/actions"

Emergency Contacts

  • Tech Lead: [Nome] - [Telefone]
  • DevOps: [Nome] - [Telefone]
  • CTO: [Nome] - [Telefone]
  • On-Call: Ver schedule em [link]

Referências