DEV Community

Yoandy Rodriguez Martinez
Yoandy Rodriguez Martinez

Posted on • Originally published at yorodm.github.io on

3 1

Trucos con AWS Lambda. (Parte 1)

Truco 1: Recursividad asíncrona.

A veces queremos garantizar que una lambda se ejecute siempre de formaasíncrona.

def lambda_handler(event, context):
    if not event.get('async'):
        invoke_self_async(event, context)
        return

def invoke_self_async(event, context):
    new_event = {
        'async': True,
        'data': event
    }
    boto3.client('lambda').invoke_async(
        FunctionName=context.invoked_function_arn,
        InvokeArgs=json.dumps(new_event)
    )

Este truco es muy útil cuando no nos interesa el resultado de la ejecución o elmismo es enviado por vías alternativas (ej. usando SNS )

Truco 2: Planificación dinámica.

A veces la planificación de un servicio debe ser alterada en dependencia de ciertas condiciones.

def lambda_handler(event, context):
    reschedule_event()
    keep_working()

REGULAR_SCHEDULE = 'rate(20 minutes)'
WEEKEND_SHEDULE = 'rate(1 hour)'
RULE_NAME = 'My Rule'

def reschedule_event():
    """
    Cambia la planificación de la lambda, para que descanse los findes :D
    """
    sched = boto3.client('events')
    current = sched.describe_rule(Name=RULE_NAME)
    if is_weekend() and 'minutes' in current['ScheduleExpression']:
        sched.put_rule(
            Name=RULE_NAME,
            ScheduleExpression=WEEKEND_SCHEDULE,
        )
    if not is_weekend and 'hour' in current['ScheduleExpression']:
        sched.put_rule(
            Name=RULE_NAME,
            ScheduleExpression=REGULAR_SCHEDULE,
        )

Truco 3: Flujos de negocio

Cuando vayas a usar StepFunctions recuerda:

Nunca uses un cañón para matar un mosquito

def lambda_handler(event, context):
    return dispatch_workflow(event)

def dispatch_workflow(activity):
    workflow_id = event.get('workflow_id'):
    if workflow_id:
        # Retrieve the state from Dynamo
        state = get_saved_state(event['workflow_id'])
    else:
        workflow_id = create_workflow_id() # uuid maybe
        state = None
    workflow = Workflow(workflow_id)
    return workflow(state,events) # Workflow is a callable

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay