Lambda + API Gateway
6.5.1kata 1 de 2

Cold Start y Optimización de Latencia

Reducir latencia en primeras invocaciones

El cold start es el retraso cuando Lambda lanza un contenedor nuevo: debe descargar el código, instanciar el runtime, ejecutar el init, luego el handler. Latencia: 100ms-2s dependiendo del lenguaje y paquete. El warmth se refiere a reutilizar un contenedor existente (subsiguientes invocaciones): ~ms en lugar de segundos.

Para aplicaciones de ML, cargar un modelo es caro: descargar desde S3 (segundos), desempaquetar (segundos), cargar en memoria (segundos). Si todo sucede en el handler, cada invocación tarda 5-10 segundos. Solución: inicializar fuera del handler (module scope), se ejecuta solo una vez por contenedor. Subsiguientes invocaciones reutilizan el modelo cargado.

Trade-offs: (1) Provisioned Concurrency (mantiene contenedores 'calientes'), costo fijo diario pero latencia baja, (2) Lambda Layers (dependencias pesadas pre-empaquetadas), reduce tamaño del zip, (3) funciones ligeras que llaman SageMaker Endpoints (Lambda hace poco, SageMaker hace el trabajo), (4) aceptar latencia (1-5s es OK para algunas apps).

structure.txt
# Bad: init inside handler (5s per invocation)
def handler(event, context):
    import torch
    model = torch.load('model.pth')  # 2 seconds
    result = model(input_data)  # 3 seconds

# Good: init outside handler (1s first, <1ms after)
import torch
model = None

def init_model():
    global model
    model = torch.load('model.pth')

def handler(event, context):
    if model is None:
        init_model()  # Called once per container
    result = model(input_data)  # <1ms warm

# Use Provisioned Concurrency to keep containers warm
# In template.yaml:
ProvisionedConcurrentExecutions: 5  # Keep 5 containers warm

Debugging lab

Detecta y corrige el error en el código.

0/5 tests passing0%
  1. 01

    def handler(event, context): import boto3 import json s3 = boto3.client('s3') # Initialize inside handler # ... rest # Function takes 500ms per invocation

  2. 02

    # Lambda invokes SageMaker endpoint 10 requests/second # Endpoint latency: 100ms # Lambda cold start: 1 second (due to model loading)

  3. 03

    # Lambda function with large numpy/scipy dependencies # Zip size: 150MB # Deploy time: 30 seconds # Cold start: slow

  4. 04

    # Measure cold start vs warm def handler(event, context): time_remaining = context.get_remaining_time_in_millis() # Doesnt measure cold start

  5. 05

    # Lambda models sentiment analysis # Startup: download Hugging Face model (500MB), takes 10 seconds # Each request: <100ms inference