Saltar al contenido principal

Solución de problemas Lambda

Errores comunes​

Visión general​

┌─────────────────────────────────────────────────────────────┐
│ ERRORES COMUNES DE LAMBDA │
├─────────────────────────────────────────────────────────────┤
│ │
│ CATEGORÍA ERROR CAUSA TÍPICA │
│ ───────── ────── ───────────── │
│ │
│ PERMISOS AccessDenied Falta rol IAM │
│ ResourceNotFound ARN incorrecto │
│ │
│ EJECUCIÓN Timeout Código muy lento │
│ OutOfMemory RAM insuficiente │
│ HandlerNotFound Handler mal config│
│ │
│ CÓDIGO ImportError Falta módulo │
│ SyntaxError Error de sintaxis│
│ RuntimeError Bug en el código │
│ │
│ CONFIGURACIÓN InvalidParameter Configuración errónea│
│ TooManyRequests Throttling │
│ │
└─────────────────────────────────────────────────────────────┘

Timeout​

Síntomas y soluciones​

┌─────────────────────────────────────────────────────────────┐
│ TIMEOUT │
├─────────────────────────────────────────────────────────────┤
│ │
│ SÍNTOMA : │
│ "Task timed out after X seconds" │
│ │
│ POSIBLES CAUSAS : │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ 1. Operación demasiado larga │ │
│ │ • Llamada a API externa lenta │ │
│ │ • Procesamiento de archivos grandes │ │
│ │ • Cálculo intensivo │ │
│ │ │ │
│ │ 2. Timeout configurado demasiado corto │ │
│ │ • Por defecto: 3 segundos │ │
│ │ • Máx: 15 minutos │ │
│ │ │ │
│ │ 3. Bloqueo de red │ │
│ │ • VPC mal configurado │ │
│ │ • Falta NAT Gateway │ │
│ │ • Security Group bloqueando │ │
│ │ │ │
│ │ 4. Código en espera infinita │ │
│ │ • Conexión a BD que no responde │ │
│ │ • Bucle infinito │ │
│ │ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ SOLUCIONES : │
│ ✅ Aumentar el timeout (si está justificado) │
│ ✅ Optimizar el código │
│ ✅ Usar timeouts en el código (requests, BD) │
│ ✅ Verificar la configuración de red (VPC, NAT) │
│ ✅ Dividir en funciones más pequeñas │
│ │
└─────────────────────────────────────────────────────────────┘

Código con Timeout​

import requests
import boto3

# ❌ MALO: Sin timeout
response = requests.get('https://api.example.com/data')

# ✅ BUENO: Con timeout
response = requests.get('https://api.example.com/data', timeout=5)

# ✅ BUENO: Verificar el tiempo restante
def lambda_handler(event, context):
remaining = context.get_remaining_time_in_millis()

if remaining < 5000: # Menos de 5 segundos
return {'error': 'Not enough time remaining'}

# Continuar el procesamiento...

Out of Memory​

┌─────────────────────────────────────────────────────────────┐
│ OUT OF MEMORY │
├─────────────────────────────────────────────────────────────┤
│ │
│ SÍNTOMA : │
│ "Runtime exited with error: signal: killed" │
│ "Process exited before completing request" │
│ │
│ CAUSAS : │
│ • Carga de archivos grandes en memoria │
│ • Fugas de memoria │
│ • RAM configurada demasiado baja │
│ │
│ DIAGNÓSTICO : │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ En los logs de CloudWatch: │ │
│ │ │ │
│ │ REPORT RequestId: xxx │ │
│ │ Duration: 1500.00 ms │ │
│ │ Billed Duration: 1500 ms │ │
│ │ Memory Size: 128 MB │ │
│ │ Max Memory Used: 127 MB ← ¡Cerca del máximo! │ │
│ │ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ SOLUCIONES : │
│ ✅ Aumentar la memoria asignada │
│ ✅ Procesar archivos en streaming │
│ ✅ Liberar recursos después de usarlos │
│ ✅ Usar archivos temporales (/tmp) │
│ │
└─────────────────────────────────────────────────────────────┘

Código optimizado para memoria​

import json

# ❌ MALO: Carga todo en memoria
def process_large_file_bad(bucket, key):
s3 = boto3.client('s3')
response = s3.get_object(Bucket=bucket, Key=key)
data = response['Body'].read() # ¡Todo en RAM!
return json.loads(data)

# ✅ BUENO: Streaming
def process_large_file_good(bucket, key):
s3 = boto3.client('s3')
response = s3.get_object(Bucket=bucket, Key=key)

# Procesar línea por línea
for line in response['Body'].iter_lines():
process_line(line)

Errores de permisos​

┌─────────────────────────────────────────────────────────────┐
│ ERRORES IAM │
├─────────────────────────────────────────────────────────────┤
│ │
│ "AccessDeniedException" │
│ "User is not authorized to perform..." │
│ │
│ CHECKLIST : │
│ │
│ ☐ ¿El rol de ejecución tiene los permisos correctos? │
│ aws lambda get-function --function-name xxx │
│ → Verificar "Role" ARN │
│ │
│ ☐ ¿La política IAM es correcta? │
│ aws iam get-role-policy --role-name xxx │
│ → Verificar las acciones permitidas │
│ │
│ ☐ ¿Los recursos están correctamente especificados? │
│ → ARN exacto vs wildcard (*) │
│ │
│ ☐ ¿No hay Deny explícito que bloquee? │
│ → Verificar SCP, policies │
│ │
│ EJEMPLO DE POLÍTICA CORRECTA : │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ { │ │
│ │ "Effect": "Allow", │ │
│ │ "Action": [ │ │
│ │ "s3:GetObject", │ │
│ │ "s3:PutObject" │ │
│ │ ], │ │
│ │ "Resource": "arn:aws:s3:::my-bucket/*" │ │
│ │ } │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘

Cold Start​

┌─────────────────────────────────────────────────────────────┐
│ COLD START │
├─────────────────────────────────────────────────────────────┤
│ │
│ El "Cold Start" es el tiempo de inicialización cuando │
│ Lambda crea un nuevo entorno de ejecución. │
│ │
│ TIMELINE : │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ COLD START (1ª invocación) │ │
│ │ ├── Descarga del código (50-200ms) │ │
│ │ ├── Inicio del runtime (100-500ms) │ │
│ │ ├── Inicialización (su código init) │ │
│ │ └── Ejecución del handler │ │
│ │ │ │
│ │ WARM (invocaciones siguientes) │ │
│ │ └── Solo ejecución del handler (~10ms) │ │
│ │ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ FACTORES QUE AUMENTAN EL COLD START : │
│ • Paquete grande (muchas dependencias) │
│ • Runtime pesado (Java > Python > Node) │
│ • VPC (¡añade 1-10 segundos!) │
│ • Inicialización compleja │
│ │
│ OPTIMIZACIONES : │
│ ✅ Provisioned Concurrency (mantiene instancias warm) │
│ ✅ Reducir el tamaño del paquete │
│ ✅ Inicializar fuera del handler │
│ ✅ Evitar VPC si no es necesario │
│ ✅ Usar runtimes ligeros │
│ │
└─────────────────────────────────────────────────────────────┘

Logs CloudWatch​

Lectura de logs​

┌─────────────────────────────────────────────────────────────┐
│ LOGS CLOUDWATCH │
├─────────────────────────────────────────────────────────────┤
│ │
│ Ubicación : │
│ /aws/lambda/<function-name> │
│ │
│ Formato de un log : │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ START RequestId: abc-123 │ │
│ │ [INFO] Processing event... │ │
│ │ [ERROR] Failed to connect to database │ │
│ │ END RequestId: abc-123 │ │
│ │ REPORT RequestId: abc-123 │ │
│ │ Duration: 1234.56 ms │ │
│ │ Billed Duration: 1300 ms │ │
│ │ Memory Size: 256 MB │ │
│ │ Max Memory Used: 128 MB │ │
│ │ Init Duration: 234.56 ms ← ¡Cold start! │ │
│ │ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Comandos CLI : │
│ # Ver los últimos logs │
│ aws logs tail /aws/lambda/my-function --follow │
│ │
│ # Filtrar errores │
│ aws logs filter-log-events \ │
│ --log-group-name /aws/lambda/my-function \ │
│ --filter-pattern "ERROR" │
│ │
└─────────────────────────────────────────────────────────────┘

Método de diagnóstico​

┌─────────────────────────────────────────────────────────────┐
│ MÉTODO DE DIAGNÓSTICO │
├─────────────────────────────────────────────────────────────┤
│ │
│ 1. IDENTIFICAR EL SÍNTOMA │
│ • Mensaje de error exacto │
│ • Código HTTP devuelto │
│ • Comportamiento observado │
│ │
│ 2. CONSULTAR LOS LOGS │
│ • CloudWatch Logs │
│ • X-Ray traces (si está activado) │
│ • Logs de la aplicación │
│ │
│ 3. VERIFICAR LA CONFIGURACIÓN │
│ • Timeout │
│ • Memoria │
│ • Variables de entorno │
│ • VPC / Security Groups │
│ │
│ 4. VERIFICAR LOS PERMISOS │
│ • Rol de ejecución │
│ • Políticas adjuntas │
│ • Resource policies │
│ │
│ 5. PROBAR AISLADAMENTE │
│ • Invocar manualmente │
│ • Simplificar el payload │
│ • Desactivar features una por una │
│ │
│ 6. CORREGIR Y VALIDAR │
│ • Aplicar la solución │
│ • Probar con el mismo escenario │
│ • Documentar la solución │
│ │
└─────────────────────────────────────────────────────────────┘

Resumen de soluciones​

ErrorCausaSolución
TimeoutCódigo lentoOptimizar, aumentar timeout
OutOfMemoryRAM insuficienteAumentar memoria, streaming
AccessDeniedFalta IAMAñadir permisos
Cold StartInicializaciónProvisioned Concurrency
Handler not foundNombre incorrectoVerificar configuración del handler

Próxima sección : Lab Solución de problemas