mirror of
https://github.com/hanzoai/skills.git
synced 2026-11-19 00:47:36 +00:00
Every page now loads /webmcp.js, scripts/webmcp.ts with its types stripped (npm run webmcp). Where the browser has document.modelContext it registers two read-only tools: search_skills over the published skills index, and get_skill, which returns a skill's markdown checked against the index digest. The markdown alternate link moves from build.py to site.py, so CI holds every page to it. The API catalog gains the site itself (llms.txt and the skills index) and hanzo.ai/agents; the live discovery check now fetches every catalog link. tests/site.mjs drives the tools through a recording modelContext, and checks a browser without one loads clean.
754 lines
38 KiB
HTML
754 lines
38 KiB
HTML
<!doctype html>
|
|
<html lang="en"><head>
|
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>cloud-aws-lambda-functions</title>
|
|
<meta name="color-scheme" content="dark">
|
|
<style>
|
|
/* Committed to one visual world: a dark instrument panel. No light variant —
|
|
the dot field and the hairline rules only read on black, and a naive
|
|
inversion would wash both out. Every colour is painted explicitly so the page
|
|
never borrows a host background. */
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
|
|
|
|
:root{
|
|
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
|
|
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
|
|
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
|
|
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
|
|
--font-zen-pixel-square:'Zen Pixel Square',monospace;
|
|
--mono:var(--font-zen-mono);
|
|
--sans:var(--font-zen-sans);
|
|
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
|
|
--r:999px; --r-soft:14px;
|
|
}
|
|
*{box-sizing:border-box}
|
|
html{-webkit-text-size-adjust:100%}
|
|
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
|
|
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
|
|
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
|
|
|
|
/* The dot field. A halftone made of one repeating radial-gradient, faded out
|
|
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
|
|
/* No overflow clip here: the dot field is inset to the box already, and a clip
|
|
would cut off the copy-prompt menu. */
|
|
.hero{position:relative;border-bottom:1px solid var(--line)}
|
|
.hero::before{content:"";position:absolute;inset:0;
|
|
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
|
|
background-size:7px 7px;
|
|
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
pointer-events:none}
|
|
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
|
|
|
|
nav{border-bottom:1px solid var(--line)}
|
|
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
|
|
justify-content:space-between;align-items:center;gap:1rem}
|
|
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--ink);text-decoration:none;
|
|
display:inline-flex;align-items:center;gap:.6rem}
|
|
.brand i{font-style:normal;color:var(--faint)}
|
|
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
|
|
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--soft);text-decoration:none}
|
|
nav a.up:hover{color:var(--ink)}
|
|
|
|
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
|
|
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
|
|
h1 em{font-style:normal;color:var(--faint)}
|
|
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
|
|
|
|
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
|
|
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
|
|
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
|
|
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
|
|
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
|
|
line-height:1.2;font-weight:400}
|
|
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
|
|
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
|
|
.btn.solid:hover{background:#d8d8d4}
|
|
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
|
|
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
|
|
|
|
/* Copy-prompt selector. Each row copies the prompt for its own target. */
|
|
.copy{position:relative;display:inline-flex}
|
|
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
|
|
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
|
|
padding:.4rem;display:flex;flex-direction:column;
|
|
box-shadow:0 12px 32px rgba(0,0,0,.75)}
|
|
.menu[hidden]{display:none}
|
|
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
|
|
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
|
|
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
|
|
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
|
|
white-space:nowrap}
|
|
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
|
|
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
|
|
.mi:hover .mark{color:var(--ink)}
|
|
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
|
|
letter-spacing:.1em;text-transform:uppercase}
|
|
|
|
/* Works-with bar: one scrolling row, name and mark per agent. */
|
|
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
|
|
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
|
|
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
|
|
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
|
|
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
|
|
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
|
|
display:flex;align-items:center}
|
|
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
|
|
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
|
|
-webkit-overflow-scrolling:touch;
|
|
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
|
|
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
|
|
.bar::-webkit-scrollbar{display:none}
|
|
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
|
|
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
|
|
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
|
|
text-decoration:none;background:var(--ground)}
|
|
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
|
|
.agent .mark{width:.95rem;height:.95rem}
|
|
|
|
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
|
|
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
|
|
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
|
|
p{margin:0 0 1rem;max-width:70ch}
|
|
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
|
|
li{margin:.22rem 0}
|
|
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
|
|
text-decoration-color:var(--line-hi)}
|
|
a:hover{text-decoration-color:var(--ink)}
|
|
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
|
|
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
|
|
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
|
|
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
|
|
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
|
|
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
|
|
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
|
|
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
|
|
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
|
|
display:block;overflow-x:auto}
|
|
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
|
|
|
|
.curl{display:block;background:var(--panel);border:1px solid var(--line);
|
|
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
|
|
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
|
|
white-space:pre;line-height:1.9}
|
|
.curl b{color:var(--ink);font-weight:400}
|
|
.curl i{font-style:normal;color:var(--faint)}
|
|
|
|
/* index */
|
|
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
|
|
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
|
|
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
|
|
#q:focus{outline:none;border-color:var(--soft)}
|
|
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
|
|
text-transform:uppercase;margin:0 0 2rem}
|
|
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
|
|
padding-bottom:.45rem}
|
|
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
|
|
border-radius:var(--r-soft);text-decoration:none}
|
|
.row:hover{background:#0a0a0a}
|
|
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
|
|
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
|
|
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
|
|
color:var(--faint);font-size:.85rem}
|
|
footer a{color:var(--soft)}
|
|
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
|
|
margin:0 0 2rem;font-size:.85rem}
|
|
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
|
|
border-bottom:1px solid var(--line);padding-bottom:.4rem}
|
|
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
|
|
.fmap a:hover{text-decoration:underline}
|
|
.fmap div{color:var(--faint);line-height:1.5}
|
|
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
|
|
|
|
@media (max-width:640px){
|
|
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
|
|
.btns{gap:.5rem}
|
|
.btn{padding:.75rem 1.15rem;font-size:.68rem}
|
|
.copy,.copy .btn{width:100%;justify-content:center}
|
|
.menu{left:0;right:0;min-width:0}
|
|
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
|
|
.strip b{border-right:0;padding-right:0}
|
|
.bar{width:100%}
|
|
}
|
|
</style>
|
|
<link rel="icon" href="/favicon.svg">
|
|
<link rel="canonical" href="https://hanzoskills.com/cloud-aws-lambda-functions">
|
|
<link rel="alternate" type="text/markdown" href="/cloud-aws-lambda-functions.md">
|
|
<script type="module" src="/webmcp.js"></script>
|
|
</head>
|
|
<!-- Reading this with a machine? Every page here is also plain markdown.
|
|
This one: https://hanzoskills.com/cloud-aws-lambda-functions.md
|
|
Index: https://hanzoskills.com/llms.txt
|
|
Corpus: https://hanzoskills.com/all.md
|
|
Append .md to any path for the markdown twin. -->
|
|
<body>
|
|
<nav><div class="in">
|
|
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
|
|
<a class="up" href="/">All skills</a>
|
|
</div></nav>
|
|
|
|
<div class="wrap">
|
|
<h1>cloud-aws-lambda-functions</h1><p class="lede">AWS Lambda function development, runtime configuration, triggers, and optimization</p><h1>AWS Lambda Functions</h1>
|
|
<p><strong>Scope</strong>: Lambda function development - handlers, runtimes, layers, triggers, cold starts, concurrency <strong>Lines</strong>: ~350 <strong>Last Updated</strong>: 2025-10-25 <strong>Format Version</strong>: 1.0 (Atomic)</p>
|
|
<hr>
|
|
<h2>When to Use This Skill</h2>
|
|
<p>Activate this skill when:</p>
|
|
<ul><li>Building serverless functions triggered by events</li><li>Processing API requests without managing servers</li><li>Implementing event-driven architectures with Lambda</li><li>Optimizing Lambda cold start times and memory usage</li><li>Configuring Lambda layers for shared dependencies</li><li>Setting up triggers from API Gateway, S3, DynamoDB, SQS</li><li>Managing Lambda concurrency and performance</li><li>Troubleshooting Lambda timeout or memory issues</li></ul>
|
|
<h2>Core Concepts</h2>
|
|
<h3>Concept 1: Lambda Handler and Context</h3>
|
|
<p><strong>Handler function</strong>:</p>
|
|
<ul><li>Entry point for Lambda execution</li><li>Receives event data and context object</li><li>Returns response or raises exception</li><li>Initialize resources outside handler for reuse</li></ul>
|
|
<pre><code class="lang-python">import os
|
|
import boto3
|
|
|
|
# Initialize outside handler - reused across warm invocations
|
|
dynamodb = boto3.resource('dynamodb')
|
|
table = dynamodb.Table(os.environ['TABLE_NAME'])
|
|
|
|
def lambda_handler(event, context):
|
|
"""
|
|
Lambda handler - invoked for each request
|
|
|
|
Args:
|
|
event: Input data (varies by trigger source)
|
|
context: Runtime information and methods
|
|
|
|
Returns:
|
|
Response dict (format depends on integration type)
|
|
"""
|
|
# Access context information
|
|
request_id = context.request_id
|
|
remaining_ms = context.get_remaining_time_in_millis()
|
|
memory_limit = context.memory_limit_in_mb
|
|
|
|
print(f"Request {request_id}, {remaining_ms}ms remaining, {memory_limit}MB limit")
|
|
|
|
# Process event
|
|
try:
|
|
result = process_event(event)
|
|
return {
|
|
'statusCode': 200,
|
|
'body': json.dumps(result)
|
|
}
|
|
except Exception as e:
|
|
print(f"Error: {str(e)}")
|
|
return {
|
|
'statusCode': 500,
|
|
'body': json.dumps({'error': 'Internal server error'})
|
|
}
|
|
|
|
def process_event(event):
|
|
"""Business logic - separate from handler"""
|
|
# Your logic here
|
|
return {'message': 'Success'}</code></pre>
|
|
<h3>Concept 2: Lambda Runtimes and Execution Environment</h3>
|
|
<p><strong>Runtime selection</strong>:</p>
|
|
<ul><li>Python 3.11/3.12: Fast cold start, good for data processing</li><li>Node.js 18/20: Fastest cold start, excellent for APIs</li><li>Java 17/21: High throughput, slower cold start</li><li>Go: Compiled binary, fast execution</li><li>Custom runtimes: Container images up to 10GB</li></ul>
|
|
<pre><code class="lang-python"># Python runtime best practices
|
|
import json
|
|
import os
|
|
from datetime import datetime
|
|
|
|
# Environment variables for configuration
|
|
STAGE = os.environ.get('STAGE', 'dev')
|
|
DEBUG = os.environ.get('DEBUG', 'false').lower() == 'true'
|
|
|
|
# Lambda layers for shared code
|
|
# Add layer ARN in Lambda configuration
|
|
# Layer content available in /opt directory
|
|
from shared_utils import logger, metrics # From layer
|
|
|
|
def lambda_handler(event, context):
|
|
"""Using Lambda layers for shared utilities"""
|
|
|
|
# Structured logging from layer
|
|
logger.info('Processing request', extra={
|
|
'request_id': context.request_id,
|
|
'function_name': context.function_name
|
|
})
|
|
|
|
# Emit metrics from layer
|
|
metrics.increment('requests.count')
|
|
|
|
# Your logic
|
|
return {'statusCode': 200}</code></pre>
|
|
<h3>Concept 3: Cold Starts vs Warm Starts</h3>
|
|
<p><strong>Cold start optimization</strong>:</p>
|
|
<ul><li>Minimize function package size</li><li>Initialize connections outside handler</li><li>Use provisioned concurrency for critical paths</li><li>Consider Lambda SnapStart (Java 11+)</li></ul>
|
|
<pre><code class="lang-python">import boto3
|
|
from functools import lru_cache
|
|
|
|
# ❌ Bad: Initialize inside handler
|
|
def lambda_handler_slow(event, context):
|
|
dynamodb = boto3.resource('dynamodb') # New connection every time
|
|
table = dynamodb.Table('Users')
|
|
# Cold AND warm invocations pay initialization cost
|
|
return table.get_item(Key={'id': event['userId']})
|
|
|
|
# ✅ Good: Initialize outside handler
|
|
dynamodb = boto3.resource('dynamodb')
|
|
table = dynamodb.Table('Users')
|
|
|
|
def lambda_handler_fast(event, context):
|
|
# Warm invocations reuse connection
|
|
return table.get_item(Key={'id': event['userId']})
|
|
|
|
# ✅ Better: Lazy initialization with caching
|
|
@lru_cache(maxsize=1)
|
|
def get_table():
|
|
"""Initialize on first use, cache for subsequent calls"""
|
|
dynamodb = boto3.resource('dynamodb')
|
|
return dynamodb.Table('Users')
|
|
|
|
def lambda_handler_lazy(event, context):
|
|
table = get_table() # Cached after first call
|
|
return table.get_item(Key={'id': event['userId']})</code></pre>
|
|
<h3>Concept 4: Lambda Layers</h3>
|
|
<p><strong>Layer benefits</strong>:</p>
|
|
<ul><li>Share code across multiple functions</li><li>Separate dependencies from function code</li><li>Reduce deployment package size</li><li>Version dependencies independently</li></ul>
|
|
<pre><code class="lang-bash"># Create Lambda layer structure
|
|
mkdir -p layer/python
|
|
cd layer/python
|
|
|
|
# Install dependencies
|
|
pip install requests boto3-stubs -t .
|
|
|
|
# Create layer zip
|
|
cd ..
|
|
zip -r layer.zip python/
|
|
|
|
# Publish layer
|
|
aws lambda publish-layer-version \
|
|
--layer-name shared-dependencies \
|
|
--description "Common Python dependencies" \
|
|
--zip-file fileb://layer.zip \
|
|
--compatible-runtimes python3.11 python3.12</code></pre>
|
|
<pre><code class="lang-python"># Use layer in Lambda function
|
|
# Layer ARN added in function configuration
|
|
# Code available in /opt/python
|
|
|
|
import requests # From layer
|
|
from shared_utils import validate_input # From layer
|
|
|
|
def lambda_handler(event, context):
|
|
"""Function using dependencies from layer"""
|
|
|
|
# Validate using shared utility
|
|
if not validate_input(event):
|
|
return {'statusCode': 400, 'body': 'Invalid input'}
|
|
|
|
# Use third-party library from layer
|
|
response = requests.get('https://api.example.com/data')
|
|
|
|
return {
|
|
'statusCode': 200,
|
|
'body': response.text
|
|
}</code></pre>
|
|
<hr>
|
|
<h2>Patterns</h2>
|
|
<h3>Pattern 1: API Gateway Lambda Proxy Integration</h3>
|
|
<p><strong>When to use</strong>:</p>
|
|
<ul><li>Building REST APIs with Lambda backend</li><li>Need access to HTTP headers and query parameters</li><li>Return custom HTTP status codes</li></ul>
|
|
<pre><code class="lang-python">import json
|
|
|
|
def lambda_handler(event, context):
|
|
"""Handle API Gateway proxy integration"""
|
|
|
|
# Parse request
|
|
http_method = event['httpMethod']
|
|
path = event['path']
|
|
query_params = event.get('queryStringParameters') or {}
|
|
headers = event['headers']
|
|
body = json.loads(event.get('body', '{}'))
|
|
|
|
# Route request
|
|
if http_method == 'GET':
|
|
return get_items(query_params)
|
|
elif http_method == 'POST':
|
|
return create_item(body)
|
|
elif http_method == 'PUT':
|
|
item_id = path.split('/')[-1]
|
|
return update_item(item_id, body)
|
|
elif http_method == 'DELETE':
|
|
item_id = path.split('/')[-1]
|
|
return delete_item(item_id)
|
|
else:
|
|
return {
|
|
'statusCode': 405,
|
|
'headers': {'Allow': 'GET, POST, PUT, DELETE'},
|
|
'body': json.dumps({'error': 'Method not allowed'})
|
|
}
|
|
|
|
def get_items(query_params):
|
|
"""Get items with pagination"""
|
|
limit = int(query_params.get('limit', 20))
|
|
|
|
# Your logic
|
|
items = fetch_items(limit)
|
|
|
|
return {
|
|
'statusCode': 200,
|
|
'headers': {
|
|
'Content-Type': 'application/json',
|
|
'Access-Control-Allow-Origin': '*'
|
|
},
|
|
'body': json.dumps({'items': items, 'count': len(items)})
|
|
}</code></pre>
|
|
<p><strong>Benefits</strong>:</p>
|
|
<ul><li>Full control over HTTP response</li><li>Access to request metadata</li><li>Simple routing logic</li></ul>
|
|
<h3>Pattern 2: S3 Event Processing</h3>
|
|
<p><strong>Use case</strong>: Process files uploaded to S3 bucket</p>
|
|
<pre><code class="lang-python">import urllib.parse
|
|
import boto3
|
|
|
|
s3 = boto3.client('s3')
|
|
|
|
def lambda_handler(event, context):
|
|
"""Process S3 upload events"""
|
|
|
|
for record in event['Records']:
|
|
bucket = record['s3']['bucket']['name']
|
|
key = urllib.parse.unquote_plus(record['s3']['object']['key'])
|
|
size = record['s3']['object']['size']
|
|
|
|
print(f"Processing s3://{bucket}/{key} ({size} bytes)")
|
|
|
|
try:
|
|
# Download file
|
|
response = s3.get_object(Bucket=bucket, Key=key)
|
|
content = response['Body'].read()
|
|
|
|
# Process based on file type
|
|
if key.endswith('.json'):
|
|
data = json.loads(content)
|
|
process_json(data)
|
|
elif key.endswith('.csv'):
|
|
process_csv(content.decode('utf-8'))
|
|
else:
|
|
print(f"Unsupported file type: {key}")
|
|
continue
|
|
|
|
# Upload result
|
|
output_key = f"processed/{key}"
|
|
s3.put_object(
|
|
Bucket=bucket,
|
|
Key=output_key,
|
|
Body=json.dumps({'status': 'processed'})
|
|
)
|
|
|
|
except Exception as e:
|
|
print(f"Error processing {key}: {str(e)}")
|
|
raise
|
|
|
|
return {'statusCode': 200, 'message': f'Processed {len(event["Records"])} files'}</code></pre>
|
|
<h3>Pattern 3: DynamoDB Stream Processing</h3>
|
|
<p><strong>Use case</strong>: React to DynamoDB table changes</p>
|
|
<pre><code class="lang-python">def lambda_handler(event, context):
|
|
"""Process DynamoDB stream events"""
|
|
|
|
for record in event['Records']:
|
|
event_name = record['eventName'] # INSERT, MODIFY, REMOVE
|
|
event_id = record['eventID']
|
|
|
|
if event_name == 'INSERT':
|
|
new_image = record['dynamodb']['NewImage']
|
|
handle_insert(deserialize_item(new_image))
|
|
|
|
elif event_name == 'MODIFY':
|
|
old_image = record['dynamodb']['OldImage']
|
|
new_image = record['dynamodb']['NewImage']
|
|
handle_update(
|
|
deserialize_item(old_image),
|
|
deserialize_item(new_image)
|
|
)
|
|
|
|
elif event_name == 'REMOVE':
|
|
old_image = record['dynamodb']['OldImage']
|
|
handle_delete(deserialize_item(old_image))
|
|
|
|
print(f"Processed event {event_id}: {event_name}")
|
|
|
|
def deserialize_item(dynamo_item):
|
|
"""Convert DynamoDB JSON format to Python dict"""
|
|
from boto3.dynamodb.types import TypeDeserializer
|
|
deserializer = TypeDeserializer()
|
|
return {k: deserializer.deserialize(v) for k, v in dynamo_item.items()}
|
|
|
|
def handle_insert(item):
|
|
"""Handle new item - send notification, update cache, etc."""
|
|
print(f"New item: {item}")
|
|
# Send SNS notification, update ElastiCache, etc.
|
|
|
|
def handle_update(old_item, new_item):
|
|
"""Handle update - audit log, trigger workflow, etc."""
|
|
changes = {k: new_item[k] for k in new_item if old_item.get(k) != new_item[k]}
|
|
print(f"Updated fields: {changes}")
|
|
|
|
def handle_delete(item):
|
|
"""Handle delete - cleanup, archive, etc."""
|
|
print(f"Deleted item: {item}")</code></pre>
|
|
<h3>Pattern 4: SQS Queue Processing with Batching</h3>
|
|
<p><strong>Use case</strong>: Process messages from SQS queue in batch</p>
|
|
<pre><code class="lang-python">import boto3
|
|
|
|
sqs = boto3.client('sqs')
|
|
|
|
def lambda_handler(event, context):
|
|
"""Process SQS messages with batch failure handling"""
|
|
|
|
successful = []
|
|
failed = []
|
|
|
|
for record in event['Records']:
|
|
message_id = record['messageId']
|
|
body = json.loads(record['body'])
|
|
|
|
try:
|
|
result = process_message(body)
|
|
successful.append(message_id)
|
|
print(f"Processed {message_id}: {result}")
|
|
|
|
except Exception as e:
|
|
failed.append({
|
|
'itemIdentifier': message_id,
|
|
'failureReason': str(e)
|
|
})
|
|
print(f"Failed {message_id}: {str(e)}")
|
|
|
|
# Report batch item failures (SQS will retry only failed messages)
|
|
return {
|
|
'batchItemFailures': [
|
|
{'itemIdentifier': msg_id} for msg_id in failed
|
|
]
|
|
}
|
|
|
|
def process_message(message):
|
|
"""Business logic for message processing"""
|
|
# Validate
|
|
if not message.get('userId'):
|
|
raise ValueError('Missing userId')
|
|
|
|
# Process
|
|
result = perform_work(message)
|
|
|
|
return result</code></pre>
|
|
<h3>Pattern 5: Timeout Handling and Progress Checkpointing</h3>
|
|
<p><strong>Use case</strong>: Long-running tasks that may exceed Lambda timeout</p>
|
|
<pre><code class="lang-python">import time
|
|
|
|
def lambda_handler(event, context):
|
|
"""Process items with timeout awareness"""
|
|
|
|
items = event['items']
|
|
processed = []
|
|
|
|
# Reserve 30 seconds for cleanup/checkpoint
|
|
deadline_buffer_ms = 30000
|
|
|
|
for i, item in enumerate(items):
|
|
# Check remaining time
|
|
remaining_ms = context.get_remaining_time_in_millis()
|
|
|
|
if remaining_ms < deadline_buffer_ms:
|
|
print(f"Approaching timeout, processed {len(processed)}/{len(items)}")
|
|
|
|
# Save checkpoint
|
|
save_checkpoint({
|
|
'processed': processed,
|
|
'remaining': items[i:],
|
|
'next_index': i
|
|
})
|
|
|
|
# Trigger continuation Lambda
|
|
invoke_continuation(event, i)
|
|
|
|
return {
|
|
'statusCode': 202,
|
|
'message': f'Partial completion: {len(processed)} items',
|
|
'checkpoint': i
|
|
}
|
|
|
|
# Process item
|
|
result = process_item(item)
|
|
processed.append(result)
|
|
|
|
return {
|
|
'statusCode': 200,
|
|
'message': f'Completed all {len(processed)} items',
|
|
'results': processed
|
|
}
|
|
|
|
def save_checkpoint(state):
|
|
"""Save processing state to DynamoDB"""
|
|
table.put_item(Item={
|
|
'id': state['job_id'],
|
|
'state': json.dumps(state),
|
|
'timestamp': datetime.utcnow().isoformat()
|
|
})</code></pre>
|
|
<h3>Pattern 6: Provisioned Concurrency for Low Latency</h3>
|
|
<p><strong>Use case</strong>: Eliminate cold starts for critical endpoints</p>
|
|
<pre><code class="lang-bash"># Enable provisioned concurrency via AWS CLI
|
|
aws lambda put-provisioned-concurrency-config \
|
|
--function-name critical-api-function \
|
|
--provisioned-concurrent-executions 10 \
|
|
--qualifier v1
|
|
|
|
# Use with alias
|
|
aws lambda create-alias \
|
|
--function-name critical-api-function \
|
|
--name prod \
|
|
--function-version 1
|
|
|
|
aws lambda put-provisioned-concurrency-config \
|
|
--function-name critical-api-function \
|
|
--provisioned-concurrent-executions 5 \
|
|
--qualifier prod</code></pre>
|
|
<pre><code class="lang-python">def lambda_handler(event, context):
|
|
"""
|
|
Function with provisioned concurrency
|
|
- Always warm (no cold starts)
|
|
- Consistent latency
|
|
- Higher cost (charged for provisioned capacity)
|
|
"""
|
|
|
|
# Immediate response, no initialization delay
|
|
return {
|
|
'statusCode': 200,
|
|
'body': json.dumps({'message': 'Fast response'})
|
|
}</code></pre>
|
|
<hr>
|
|
<h2>Quick Reference</h2>
|
|
<h3>Lambda Runtime Configuration</h3>
|
|
<p>| Setting | Range | Recommended | Notes | |---------|-------|-------------|-------| | Memory | 128 MB - 10,240 MB | 1024 MB | CPU scales with memory | | Timeout | 1 sec - 15 min | 30 sec (API), 5 min (processing) | Set based on workload | | Ephemeral storage | 512 MB - 10,240 MB | 512 MB | Temporary /tmp storage | | Reserved concurrency | 0 - account limit | Only if needed | Limits max concurrent executions | | Provisioned concurrency | 0 - reserved limit | Critical paths only | Pre-warmed instances |</p>
|
|
<h3>Common Triggers and Event Sources</h3>
|
|
<pre><code>Trigger Type | Use Case | Invocation Type
|
|
-------------------|---------------------------|------------------
|
|
API Gateway | REST/HTTP APIs | Synchronous
|
|
S3 | File upload processing | Asynchronous
|
|
DynamoDB Streams | Table change reactions | Synchronous (stream)
|
|
SQS | Queue processing | Synchronous (batch)
|
|
SNS | Notifications | Asynchronous
|
|
EventBridge | Scheduled tasks, events | Asynchronous
|
|
CloudWatch Logs | Log processing | Asynchronous
|
|
ALB | Load balanced APIs | Synchronous</code></pre>
|
|
<h3>Key Guidelines</h3>
|
|
<pre><code>✅ DO: Initialize SDK clients outside handler function
|
|
✅ DO: Use environment variables for configuration
|
|
✅ DO: Set appropriate memory based on workload (monitor CloudWatch)
|
|
✅ DO: Use Lambda layers for shared dependencies
|
|
✅ DO: Check remaining time for long operations
|
|
✅ DO: Return early with informative errors
|
|
✅ DO: Use structured logging (JSON format)
|
|
|
|
❌ DON'T: Store credentials in code (use IAM roles)
|
|
❌ DON'T: Create new connections on every invocation
|
|
❌ DON'T: Assume unlimited execution time
|
|
❌ DON'T: Use /tmp for permanent storage (ephemeral)
|
|
❌ DON'T: Return large payloads (6 MB limit for API Gateway)</code></pre>
|
|
<hr>
|
|
<h2>Anti-Patterns</h2>
|
|
<h3>Critical Violations</h3>
|
|
<pre><code class="lang-python"># ❌ NEVER: Hardcode credentials
|
|
AWS_ACCESS_KEY = "AKIAIOSFODNN7EXAMPLE"
|
|
AWS_SECRET_KEY = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
|
|
|
|
# ✅ CORRECT: Use IAM execution role (automatic credentials)
|
|
# No credentials needed - boto3 uses role automatically
|
|
|
|
# ❌ NEVER: Initialize clients inside handler
|
|
def lambda_handler(event, context):
|
|
s3 = boto3.client('s3') # Created every invocation
|
|
return s3.list_buckets()
|
|
|
|
# ✅ CORRECT: Initialize outside handler
|
|
s3 = boto3.client('s3') # Reused across warm invocations
|
|
|
|
def lambda_handler(event, context):
|
|
return s3.list_buckets()</code></pre>
|
|
<p>❌ <strong>Cold start on every invocation</strong>: Initializing heavy resources inside handler adds latency to every request, not just cold starts</p>
|
|
<p>✅ <strong>Correct approach</strong>: Initialize outside handler, use provisioned concurrency for critical paths</p>
|
|
<h3>Common Mistakes</h3>
|
|
<pre><code class="lang-python"># ❌ Don't ignore timeout limits
|
|
def lambda_handler(event, context):
|
|
# May timeout after 15 minutes max
|
|
process_all_items(event['items']) # No progress tracking
|
|
|
|
# ✅ Correct: Monitor remaining time and checkpoint
|
|
def lambda_handler(event, context):
|
|
for item in event['items']:
|
|
if context.get_remaining_time_in_millis() < 30000:
|
|
save_checkpoint_and_continue(item)
|
|
return {'statusCode': 202, 'message': 'Continuing'}
|
|
process_item(item)</code></pre>
|
|
<p>❌ <strong>Exceeding timeout without checkpointing</strong>: Lose all progress when timeout occurs</p>
|
|
<p>✅ <strong>Better</strong>: Track remaining time, save progress, invoke continuation if needed</p>
|
|
<pre><code class="lang-python"># ❌ Don't use /tmp for permanent storage
|
|
def lambda_handler(event, context):
|
|
with open('/tmp/cache.json', 'w') as f:
|
|
json.dump(data, f)
|
|
# File may disappear on next invocation
|
|
|
|
# ✅ Correct: Use S3 or DynamoDB for persistence
|
|
def lambda_handler(event, context):
|
|
s3.put_object(
|
|
Bucket='my-bucket',
|
|
Key='cache.json',
|
|
Body=json.dumps(data)
|
|
)</code></pre>
|
|
<p>❌ <strong>/tmp is ephemeral</strong>: Content may not persist across invocations</p>
|
|
<p>✅ <strong>Better</strong>: Use S3 for files, DynamoDB for structured data</p>
|
|
<hr>
|
|
<h2>Level 3: Resources</h2>
|
|
<h3>Reference Material</h3>
|
|
<p><strong>Comprehensive Reference</strong>: <code>~/.hanzo/skills/cloud/aws-lambda-deployment/resources/REFERENCE.md</code> (~1,800 lines)</p>
|
|
<ul><li>Lambda fundamentals and execution model</li><li>All supported runtimes (Python, Node.js, Go, Rust, Java, .NET, custom)</li><li>Function configuration (memory, timeout, environment variables, layers)</li><li>IAM roles and permissions (least privilege patterns)</li><li>Event sources and triggers (API Gateway, S3, DynamoDB, SQS, SNS, EventBridge, Kinesis)</li><li>VPC configuration (when and why, NAT Gateway, VPC endpoints)</li><li>Deployment methods (AWS CLI, SAM, Serverless Framework, CDK, Terraform, containers)</li><li>Monitoring and logging (CloudWatch Logs, X-Ray, Lambda Insights, alarms)</li><li>Performance optimization (cold start reduction, memory tuning, connection pooling, caching)</li><li>Error handling (retries, DLQ, destinations, idempotency)</li><li>Testing strategies (unit, integration, local, load testing)</li><li>Cost optimization</li><li>Production best practices (blue/green deployment, versioning, aliases)</li><li>Advanced patterns (layers, extensions, Step Functions, Lambda@Edge)</li></ul>
|
|
<h3>Executable Scripts</h3>
|
|
<p><strong><code>deploy_lambda.py</code></strong> - Deploy Lambda functions with best practices</p>
|
|
<ul><li>Automatic deployment package creation</li><li>Layer support</li><li>VPC configuration</li><li>Environment variables with KMS encryption</li><li>Versioning and aliases</li><li>Monitoring setup (CloudWatch alarms, X-Ray)</li><li>Blue/green deployments with traffic shifting</li><li>Example: <code>./deploy_lambda.py --function-name my-function --source-dir ./src --handler app.handler --runtime python3.12 --role-arn arn:aws:iam::123456789012:role/lambda-role --blue-green --setup-monitoring</code></li></ul>
|
|
<p><strong><code>analyze_performance.py</code></strong> - Analyze Lambda function performance</p>
|
|
<ul><li>Cold start detection and analysis</li><li>Duration percentiles</li><li>Memory utilization analysis</li><li>Error rate tracking</li><li>Throttle detection</li><li>Cost analysis</li><li>Optimization recommendations</li><li>Example: <code>./analyze_performance.py --function-name my-function --hours 24 --detailed</code></li></ul>
|
|
<p><strong><code>test_function.sh</code></strong> - Test Lambda functions comprehensively</p>
|
|
<ul><li>Synchronous and asynchronous invocation</li><li>Load testing with configurable concurrency</li><li>Event file support</li><li>Response validation</li><li>Performance timing</li><li>Example: <code>./test_function.sh --function-name my-function --event event.json --load-test --concurrency 10 --duration 60</code></li></ul>
|
|
<h3>Example Implementations</h3>
|
|
<p><strong>Python Examples</strong>:</p>
|
|
<ul><li><code>hello_lambda.py</code> - Basic Lambda function with JSON response</li><li><code>api_lambda.py</code> - API Gateway integration with routing, validation, error handling</li></ul>
|
|
<p><strong>Node.js Examples</strong>:</p>
|
|
<ul><li><code>dynamodb_trigger.js</code> - DynamoDB Streams processor with INSERT/MODIFY/REMOVE handling</li></ul>
|
|
<p><strong>Infrastructure as Code</strong>:</p>
|
|
<ul><li><code>sam/template.yaml</code> - SAM deployment with API Gateway, DynamoDB, SNS, alarms</li><li><code>terraform/lambda.tf</code> - Terraform deployment with API Gateway v2, DynamoDB, monitoring</li></ul>
|
|
<p><strong>Container Images</strong>:</p>
|
|
<ul><li><code>Dockerfile</code> - Container Lambda examples for Python, Node.js, Go with multi-stage builds</li></ul>
|
|
<p>All resources located in: <code>~/.hanzo/skills/cloud/aws-lambda-deployment/resources/</code></p>
|
|
<hr>
|
|
<h2>Related Skills</h2>
|
|
<ul><li><code>aws-api-gateway.md</code> - Configure API Gateway triggers and Lambda proxy integration</li><li><code>aws-ec2-compute.md</code> - Alternative to Lambda for long-running or stateful workloads</li><li><code>aws-storage.md</code> - S3 integration for Lambda file processing</li><li><code>aws-databases.md</code> - DynamoDB and RDS integration with Lambda</li><li><code>aws-iam-security.md</code> - IAM roles and policies for Lambda execution</li><li><code>infrastructure/aws-serverless.md</code> - Full serverless architecture patterns with Lambda</li></ul>
|
|
<hr>
|
|
<p><strong>Last Updated</strong>: 2025-10-27 <strong>Format Version</strong>: 1.0 (Atomic)</p>
|
|
<footer>
|
|
<div class="fmap">
|
|
<div><b>Build</b>
|
|
<a href="https://hanzo.app">hanzo.app</a> app builder
|
|
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
|
|
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
|
|
<div><b>Run</b>
|
|
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
|
|
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
|
|
<div><b>Account</b>
|
|
<a href="https://hanzo.id">hanzo.id</a> sign in
|
|
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
|
|
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
|
|
<div><b>Company</b>
|
|
<a href="https://hanzo.ai">hanzo.ai</a> canonical
|
|
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
|
|
</div>
|
|
<div class="fend"><a href="/cloud-aws-lambda-functions.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
|
|
</footer>
|
|
</div></body></html> |