mirror of
https://github.com/hanzoai/skills.git
synced 2026-11-19 00:47:36 +00:00
hanzoskills.com/llms.txt now opens with the install line, the API reference index and the company index, so an agent that lands on any one of the three can find the rest. robots.txt claimed 537 documents while llms.txt counts 920. The number is gone from robots.txt; llms.txt derives it. public/ is regenerated from scripts/site.py, which it had fallen behind: the copy-prompt menu and agent bar were in the generator and not in the committed pages. tests/site.mjs passes against the result. Co-authored-by: Hanzo Dev <[email protected]>
877 lines
36 KiB
HTML
877 lines
36 KiB
HTML
<!doctype html>
|
|
<html lang="en"><head>
|
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>infrastructure-aws-serverless</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="alternate" type="text/markdown" href="/infrastructure-aws-serverless.md">
|
|
|
|
<link rel="icon" href="/favicon.svg">
|
|
<link rel="canonical" href="https://hanzoskills.com/infrastructure-aws-serverless">
|
|
</head>
|
|
<!-- Reading this with a machine? Every page here is also plain markdown.
|
|
This one: https://hanzoskills.com/infrastructure-aws-serverless.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>infrastructure-aws-serverless</h1><p class="lede">Building serverless APIs and backends</p><h1>AWS Serverless</h1>
|
|
<p><strong>Scope</strong>: AWS serverless architecture - Lambda, API Gateway, DynamoDB, S3, EventBridge, Step Functions <strong>Lines</strong>: 392 <strong>Last Updated</strong>: 2025-10-18 <strong>Format Version</strong>: 1.0 (Atomic)</p>
|
|
<hr>
|
|
<h2>When to Use This Skill</h2>
|
|
<p><strong>Activate when</strong>:</p>
|
|
<ul><li>Building serverless APIs and backends</li><li>Processing events asynchronously (S3 uploads, DynamoDB streams, SQS)</li><li>Creating scheduled tasks and cron jobs</li><li>Orchestrating complex workflows</li><li>Building event-driven architectures</li><li>Minimizing infrastructure management</li></ul>
|
|
<p><strong>Prerequisites</strong>:</p>
|
|
<ul><li>AWS account with IAM permissions</li><li>AWS CLI configured (<code>aws configure</code>)</li><li>Node.js, Python, or other Lambda runtime installed</li><li>Basic understanding of HTTP and REST APIs</li><li>Familiarity with JSON and IAM policies</li></ul>
|
|
<p><strong>Common scenarios</strong>:</p>
|
|
<ul><li>REST/GraphQL API backends</li><li>Image/video processing pipelines</li><li>Data transformation and ETL</li><li>Webhook handlers</li><li>Scheduled data syncs</li><li>Microservices architectures</li></ul>
|
|
<hr>
|
|
<h2>Core Concepts</h2>
|
|
<h3>1. Lambda Functions</h3>
|
|
<pre><code class="lang-python"># lambda_function.py
|
|
import json
|
|
import boto3
|
|
import os
|
|
from datetime import datetime
|
|
|
|
# Initialize clients outside handler for connection reuse
|
|
dynamodb = boto3.resource('dynamodb')
|
|
table = dynamodb.Table(os.environ['TABLE_NAME'])
|
|
|
|
def lambda_handler(event, context):
|
|
"""
|
|
Lambda handler function
|
|
|
|
Args:
|
|
event: Event data (API Gateway, S3, etc.)
|
|
context: Runtime information
|
|
|
|
Returns:
|
|
Response with statusCode and body
|
|
"""
|
|
try:
|
|
# Parse request body
|
|
body = json.loads(event.get('body', '{}'))
|
|
|
|
# Process request
|
|
item_id = body.get('id')
|
|
if not item_id:
|
|
return {
|
|
'statusCode': 400,
|
|
'body': json.dumps({'error': 'Missing id field'})
|
|
}
|
|
|
|
# DynamoDB operation
|
|
response = table.put_item(
|
|
Item={
|
|
'id': item_id,
|
|
'data': body.get('data'),
|
|
'timestamp': datetime.utcnow().isoformat()
|
|
}
|
|
)
|
|
|
|
return {
|
|
'statusCode': 200,
|
|
'headers': {
|
|
'Content-Type': 'application/json',
|
|
'Access-Control-Allow-Origin': '*'
|
|
},
|
|
'body': json.dumps({
|
|
'message': 'Success',
|
|
'id': item_id
|
|
})
|
|
}
|
|
|
|
except Exception as e:
|
|
print(f"Error: {str(e)}") # CloudWatch Logs
|
|
return {
|
|
'statusCode': 500,
|
|
'body': json.dumps({'error': 'Internal server error'})
|
|
}</code></pre>
|
|
<h3>2. API Gateway Integration</h3>
|
|
<pre><code class="lang-python"># API Gateway REST API with Lambda proxy integration
|
|
def handler(event, context):
|
|
"""Handle different HTTP methods"""
|
|
|
|
http_method = event['httpMethod']
|
|
path = event['path']
|
|
|
|
# Route handling
|
|
if http_method == 'GET' and path == '/items':
|
|
return list_items(event)
|
|
elif http_method == 'GET' and path.startswith('/items/'):
|
|
item_id = path.split('/')[-1]
|
|
return get_item(item_id)
|
|
elif http_method == 'POST' and path == '/items':
|
|
return create_item(event)
|
|
elif http_method == 'PUT' and path.startswith('/items/'):
|
|
item_id = path.split('/')[-1]
|
|
return update_item(item_id, event)
|
|
elif http_method == 'DELETE' and path.startswith('/items/'):
|
|
item_id = path.split('/')[-1]
|
|
return delete_item(item_id)
|
|
else:
|
|
return {
|
|
'statusCode': 404,
|
|
'body': json.dumps({'error': 'Not found'})
|
|
}
|
|
|
|
def list_items(event):
|
|
"""List all items with pagination"""
|
|
query_params = event.get('queryStringParameters', {}) or {}
|
|
limit = int(query_params.get('limit', 20))
|
|
|
|
response = table.scan(Limit=limit)
|
|
|
|
return {
|
|
'statusCode': 200,
|
|
'body': json.dumps({
|
|
'items': response['Items'],
|
|
'count': len(response['Items'])
|
|
})
|
|
}</code></pre>
|
|
<h3>3. DynamoDB Operations</h3>
|
|
<pre><code class="lang-python">import boto3
|
|
from boto3.dynamodb.conditions import Key, Attr
|
|
from decimal import Decimal
|
|
|
|
dynamodb = boto3.resource('dynamodb')
|
|
table = dynamodb.Table('Users')
|
|
|
|
# Put item
|
|
def create_user(user_id, email, name):
|
|
table.put_item(
|
|
Item={
|
|
'userId': user_id,
|
|
'email': email,
|
|
'name': name,
|
|
'createdAt': datetime.utcnow().isoformat()
|
|
},
|
|
ConditionExpression='attribute_not_exists(userId)' # Prevent overwrites
|
|
)
|
|
|
|
# Get item
|
|
def get_user(user_id):
|
|
response = table.get_item(
|
|
Key={'userId': user_id}
|
|
)
|
|
return response.get('Item')
|
|
|
|
# Query with index
|
|
def get_user_by_email(email):
|
|
response = table.query(
|
|
IndexName='email-index',
|
|
KeyConditionExpression=Key('email').eq(email)
|
|
)
|
|
return response['Items']
|
|
|
|
# Update item
|
|
def update_user(user_id, name):
|
|
response = table.update_item(
|
|
Key={'userId': user_id},
|
|
UpdateExpression='SET #name = :name, updatedAt = :timestamp',
|
|
ExpressionAttributeNames={'#name': 'name'},
|
|
ExpressionAttributeValues={
|
|
':name': name,
|
|
':timestamp': datetime.utcnow().isoformat()
|
|
},
|
|
ReturnValues='ALL_NEW'
|
|
)
|
|
return response['Attributes']
|
|
|
|
# Delete item
|
|
def delete_user(user_id):
|
|
table.delete_item(
|
|
Key={'userId': user_id}
|
|
)
|
|
|
|
# Batch operations
|
|
def batch_write_users(users):
|
|
with table.batch_writer() as batch:
|
|
for user in users:
|
|
batch.put_item(Item=user)
|
|
|
|
# Scan with filter
|
|
def get_active_users():
|
|
response = table.scan(
|
|
FilterExpression=Attr('status').eq('active')
|
|
)
|
|
return response['Items']</code></pre>
|
|
<h3>4. S3 Event Processing</h3>
|
|
<pre><code class="lang-python">import json
|
|
import urllib.parse
|
|
import boto3
|
|
|
|
s3 = boto3.client('s3')
|
|
|
|
def lambda_handler(event, context):
|
|
"""Process S3 upload events"""
|
|
|
|
# Parse S3 event
|
|
for record in event['Records']:
|
|
bucket = record['s3']['bucket']['name']
|
|
key = urllib.parse.unquote_plus(record['s3']['object']['key'])
|
|
|
|
print(f"Processing {bucket}/{key}")
|
|
|
|
try:
|
|
# Download file
|
|
response = s3.get_object(Bucket=bucket, Key=key)
|
|
content = response['Body'].read()
|
|
|
|
# Process content (e.g., resize image, parse CSV)
|
|
processed = process_file(content)
|
|
|
|
# Upload processed file
|
|
output_key = f"processed/{key}"
|
|
s3.put_object(
|
|
Bucket=bucket,
|
|
Key=output_key,
|
|
Body=processed,
|
|
ContentType=response['ContentType']
|
|
)
|
|
|
|
print(f"Uploaded to {output_key}")
|
|
|
|
except Exception as e:
|
|
print(f"Error processing {key}: {str(e)}")
|
|
raise e
|
|
|
|
return {
|
|
'statusCode': 200,
|
|
'body': json.dumps('Processing complete')
|
|
}</code></pre>
|
|
<hr>
|
|
<h2>Patterns</h2>
|
|
<h3>Event-Driven Architecture</h3>
|
|
<pre><code class="lang-python"># EventBridge integration
|
|
import boto3
|
|
|
|
events = boto3.client('events')
|
|
|
|
def publish_event(event_type, detail):
|
|
"""Publish custom event to EventBridge"""
|
|
response = events.put_events(
|
|
Entries=[
|
|
{
|
|
'Source': 'my.application',
|
|
'DetailType': event_type,
|
|
'Detail': json.dumps(detail),
|
|
'EventBusName': 'default'
|
|
}
|
|
]
|
|
)
|
|
return response
|
|
|
|
# Lambda handler that publishes events
|
|
def lambda_handler(event, context):
|
|
# Process request
|
|
user_id = create_user(event)
|
|
|
|
# Publish event for other services to consume
|
|
publish_event(
|
|
'UserCreated',
|
|
{
|
|
'userId': user_id,
|
|
'email': event['email'],
|
|
'timestamp': datetime.utcnow().isoformat()
|
|
}
|
|
)
|
|
|
|
return {'statusCode': 200, 'body': json.dumps({'userId': user_id})}</code></pre>
|
|
<h3>Step Functions Workflow</h3>
|
|
<pre><code class="lang-json">{
|
|
"Comment": "Image processing workflow",
|
|
"StartAt": "ValidateImage",
|
|
"States": {
|
|
"ValidateImage": {
|
|
"Type": "Task",
|
|
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:ValidateImage",
|
|
"Next": "IsValid",
|
|
"Catch": [{
|
|
"ErrorEquals": ["States.ALL"],
|
|
"Next": "HandleError"
|
|
}]
|
|
},
|
|
"IsValid": {
|
|
"Type": "Choice",
|
|
"Choices": [{
|
|
"Variable": "$.valid",
|
|
"BooleanEquals": true,
|
|
"Next": "ProcessImage"
|
|
}],
|
|
"Default": "RejectImage"
|
|
},
|
|
"ProcessImage": {
|
|
"Type": "Parallel",
|
|
"Branches": [
|
|
{
|
|
"StartAt": "GenerateThumbnail",
|
|
"States": {
|
|
"GenerateThumbnail": {
|
|
"Type": "Task",
|
|
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:GenerateThumbnail",
|
|
"End": true
|
|
}
|
|
}
|
|
},
|
|
{
|
|
"StartAt": "ExtractMetadata",
|
|
"States": {
|
|
"ExtractMetadata": {
|
|
"Type": "Task",
|
|
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:ExtractMetadata",
|
|
"End": true
|
|
}
|
|
}
|
|
}
|
|
],
|
|
"Next": "SaveResults"
|
|
},
|
|
"SaveResults": {
|
|
"Type": "Task",
|
|
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:SaveResults",
|
|
"End": true
|
|
},
|
|
"RejectImage": {
|
|
"Type": "Fail",
|
|
"Error": "InvalidImage",
|
|
"Cause": "Image failed validation"
|
|
},
|
|
"HandleError": {
|
|
"Type": "Task",
|
|
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:HandleError",
|
|
"End": true
|
|
}
|
|
}
|
|
}</code></pre>
|
|
<h3>SQS Queue Processing</h3>
|
|
<pre><code class="lang-python">import boto3
|
|
import json
|
|
|
|
sqs = boto3.client('sqs')
|
|
QUEUE_URL = os.environ['QUEUE_URL']
|
|
|
|
def lambda_handler(event, context):
|
|
"""Process SQS messages in batch"""
|
|
|
|
for record in event['Records']:
|
|
message_body = json.loads(record['body'])
|
|
receipt_handle = record['receiptHandle']
|
|
|
|
try:
|
|
# Process message
|
|
result = process_message(message_body)
|
|
|
|
# Delete message from queue after successful processing
|
|
sqs.delete_message(
|
|
QueueUrl=QUEUE_URL,
|
|
ReceiptHandle=receipt_handle
|
|
)
|
|
|
|
print(f"Processed message: {result}")
|
|
|
|
except Exception as e:
|
|
# Message will return to queue for retry
|
|
print(f"Error processing message: {str(e)}")
|
|
# Optionally send to DLQ after max retries
|
|
|
|
def process_message(message):
|
|
"""Business logic for message processing"""
|
|
# Your processing logic here
|
|
return {'status': 'processed', 'id': message['id']}
|
|
|
|
# Send message to SQS (from another Lambda)
|
|
def send_to_queue(message):
|
|
response = sqs.send_message(
|
|
QueueUrl=QUEUE_URL,
|
|
MessageBody=json.dumps(message),
|
|
MessageAttributes={
|
|
'Priority': {
|
|
'StringValue': 'high',
|
|
'DataType': 'String'
|
|
}
|
|
}
|
|
)
|
|
return response['MessageId']</code></pre>
|
|
<h3>DynamoDB Streams</h3>
|
|
<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
|
|
|
|
if event_name == 'INSERT':
|
|
new_image = record['dynamodb']['NewImage']
|
|
handle_insert(new_image)
|
|
|
|
elif event_name == 'MODIFY':
|
|
old_image = record['dynamodb']['OldImage']
|
|
new_image = record['dynamodb']['NewImage']
|
|
handle_update(old_image, new_image)
|
|
|
|
elif event_name == 'REMOVE':
|
|
old_image = record['dynamodb']['OldImage']
|
|
handle_delete(old_image)
|
|
|
|
def handle_insert(item):
|
|
"""Handle new item creation"""
|
|
# Send notification, update cache, etc.
|
|
print(f"New item created: {item}")
|
|
|
|
def handle_update(old_item, new_item):
|
|
"""Handle item updates"""
|
|
# Track changes, invalidate cache, etc.
|
|
print(f"Item updated: {old_item} -> {new_item}")
|
|
|
|
def handle_delete(item):
|
|
"""Handle item deletion"""
|
|
# Cleanup related resources
|
|
print(f"Item deleted: {item}")</code></pre>
|
|
<h3>Lambda Layers for Shared Code</h3>
|
|
<pre><code class="lang-python"># layer/python/utils.py (shared utilities)
|
|
import boto3
|
|
import json
|
|
from datetime import datetime
|
|
|
|
def get_secret(secret_name):
|
|
"""Retrieve secret from Secrets Manager"""
|
|
client = boto3.client('secretsmanager')
|
|
response = client.get_secret_value(SecretId=secret_name)
|
|
return json.loads(response['SecretString'])
|
|
|
|
def send_notification(message, topic_arn):
|
|
"""Send SNS notification"""
|
|
sns = boto3.client('sns')
|
|
sns.publish(
|
|
TopicArn=topic_arn,
|
|
Message=message,
|
|
Subject='Lambda Notification'
|
|
)
|
|
|
|
# Use layer in Lambda function
|
|
from utils import get_secret, send_notification
|
|
|
|
def lambda_handler(event, context):
|
|
# Access shared utilities from layer
|
|
db_creds = get_secret('database-credentials')
|
|
send_notification('Processing started', os.environ['SNS_TOPIC'])
|
|
|
|
# Your logic here
|
|
return {'statusCode': 200}</code></pre>
|
|
<h3>Scheduled Tasks (EventBridge Cron)</h3>
|
|
<pre><code class="lang-python"># Lambda triggered by EventBridge schedule
|
|
def lambda_handler(event, context):
|
|
"""
|
|
Scheduled task that runs daily at 2 AM UTC
|
|
EventBridge rule: cron(0 2 * * ? *)
|
|
"""
|
|
|
|
print(f"Scheduled task started at {datetime.utcnow()}")
|
|
|
|
try:
|
|
# Daily cleanup task
|
|
cleanup_old_records()
|
|
|
|
# Generate daily report
|
|
report = generate_daily_report()
|
|
|
|
# Send report via email
|
|
send_report_email(report)
|
|
|
|
return {
|
|
'statusCode': 200,
|
|
'body': json.dumps('Scheduled task completed')
|
|
}
|
|
|
|
except Exception as e:
|
|
print(f"Error in scheduled task: {str(e)}")
|
|
raise e
|
|
|
|
def cleanup_old_records():
|
|
"""Delete records older than 30 days"""
|
|
cutoff_date = (datetime.utcnow() - timedelta(days=30)).isoformat()
|
|
|
|
response = table.scan(
|
|
FilterExpression=Attr('createdAt').lt(cutoff_date)
|
|
)
|
|
|
|
with table.batch_writer() as batch:
|
|
for item in response['Items']:
|
|
batch.delete_item(Key={'id': item['id']})
|
|
|
|
print(f"Deleted {len(response['Items'])} old records")</code></pre>
|
|
<hr>
|
|
<h2>Quick Reference</h2>
|
|
<h3>Lambda Best Practices</h3>
|
|
<pre><code class="lang-python"># Environment variables
|
|
TABLE_NAME = os.environ['TABLE_NAME']
|
|
REGION = os.environ['AWS_REGION']
|
|
|
|
# Initialize clients outside handler
|
|
dynamodb = boto3.resource('dynamodb')
|
|
table = dynamodb.Table(TABLE_NAME)
|
|
|
|
# Use connection pooling
|
|
session = boto3.Session()
|
|
s3 = session.client('s3')
|
|
|
|
# Error handling
|
|
try:
|
|
result = process_data(event)
|
|
return success_response(result)
|
|
except ValueError as e:
|
|
return error_response(400, str(e))
|
|
except Exception as e:
|
|
print(f"Unexpected error: {str(e)}")
|
|
return error_response(500, "Internal server error")
|
|
|
|
# Timeouts and retries
|
|
from botocore.config import Config
|
|
|
|
config = Config(
|
|
retries={'max_attempts': 3, 'mode': 'adaptive'},
|
|
connect_timeout=5,
|
|
read_timeout=60
|
|
)
|
|
s3 = boto3.client('s3', config=config)</code></pre>
|
|
<h3>Common Lambda Configurations</h3>
|
|
<pre><code class="lang-bash"># Memory: 128 MB to 10,240 MB (affects CPU allocation)
|
|
# Recommended: 1024 MB (good balance)
|
|
|
|
# Timeout: 1 second to 15 minutes
|
|
# Recommended: 30 seconds for API, 5 minutes for processing
|
|
|
|
# Reserved concurrency: Limit concurrent executions
|
|
# Provisioned concurrency: Pre-warmed instances (reduce cold starts)
|
|
|
|
# Environment variables
|
|
TABLE_NAME=users-table
|
|
LOG_LEVEL=INFO
|
|
API_KEY=use-secrets-manager
|
|
|
|
# IAM execution role needs:
|
|
# - AWSLambdaBasicExecutionRole (CloudWatch Logs)
|
|
# - Permissions for DynamoDB, S3, etc.</code></pre>
|
|
<h3>AWS CLI Commands</h3>
|
|
<pre><code class="lang-bash"># Deploy Lambda function
|
|
aws lambda update-function-code \
|
|
--function-name my-function \
|
|
--zip-file fileb://function.zip
|
|
|
|
# Invoke function
|
|
aws lambda invoke \
|
|
--function-name my-function \
|
|
--payload '{"key": "value"}' \
|
|
response.json
|
|
|
|
# Get logs
|
|
aws logs tail /aws/lambda/my-function --follow
|
|
|
|
# Update configuration
|
|
aws lambda update-function-configuration \
|
|
--function-name my-function \
|
|
--timeout 60 \
|
|
--memory-size 1024
|
|
|
|
# Create layer
|
|
zip -r layer.zip python/
|
|
aws lambda publish-layer-version \
|
|
--layer-name my-utilities \
|
|
--zip-file fileb://layer.zip \
|
|
--compatible-runtimes python3.11</code></pre>
|
|
<hr>
|
|
<h2>Anti-Patterns</h2>
|
|
<h3>Critical Violations</h3>
|
|
<pre><code class="lang-python"># ❌ NEVER: Store credentials in code
|
|
AWS_ACCESS_KEY = "AKIAIOSFODNN7EXAMPLE" # NEVER
|
|
|
|
# ✅ CORRECT: Use IAM roles and environment variables
|
|
# Lambda execution role provides credentials automatically
|
|
|
|
# ❌ NEVER: Initialize clients inside handler
|
|
def lambda_handler(event, context):
|
|
dynamodb = boto3.resource('dynamodb') # Created every invocation
|
|
table = dynamodb.Table('users')
|
|
# ...
|
|
|
|
# ✅ CORRECT: Initialize outside handler
|
|
dynamodb = boto3.resource('dynamodb')
|
|
table = dynamodb.Table('users')
|
|
|
|
def lambda_handler(event, context):
|
|
# Reuses connection across warm starts
|
|
# ...</code></pre>
|
|
<pre><code class="lang-python"># ❌ NEVER: Ignore Lambda timeouts
|
|
def lambda_handler(event, context):
|
|
# Long-running task without timeout handling
|
|
process_large_dataset() # May timeout after 15 minutes
|
|
|
|
# ✅ CORRECT: Check remaining time
|
|
def lambda_handler(event, context):
|
|
deadline = context.get_remaining_time_in_millis()
|
|
|
|
for item in items:
|
|
if context.get_remaining_time_in_millis() < 30000: # 30 sec buffer
|
|
# Save progress and exit
|
|
save_checkpoint(item)
|
|
return {'statusCode': 202, 'message': 'Processing continues'}
|
|
|
|
process_item(item)</code></pre>
|
|
<h3>Common Mistakes</h3>
|
|
<pre><code class="lang-python"># ❌ Don't return large responses from API Gateway
|
|
def lambda_handler(event, context):
|
|
data = table.scan() # Could be MB of data
|
|
return {
|
|
'statusCode': 200,
|
|
'body': json.dumps(data) # API Gateway limit: 6 MB
|
|
}
|
|
|
|
# ✅ CORRECT: Use pagination
|
|
def lambda_handler(event, context):
|
|
limit = int(event.get('queryStringParameters', {}).get('limit', 20))
|
|
response = table.scan(Limit=limit)
|
|
|
|
return {
|
|
'statusCode': 200,
|
|
'body': json.dumps({
|
|
'items': response['Items'][:limit],
|
|
'lastKey': response.get('LastEvaluatedKey')
|
|
})
|
|
}</code></pre>
|
|
<pre><code class="lang-python"># ❌ Don't use recursion for fan-out
|
|
def lambda_handler(event, context):
|
|
for item in items:
|
|
lambda_client.invoke(
|
|
FunctionName='process-item',
|
|
InvocationType='Event',
|
|
Payload=json.dumps(item)
|
|
) # Could hit concurrency limits
|
|
|
|
# ✅ CORRECT: Use SQS for fan-out
|
|
def lambda_handler(event, context):
|
|
entries = [
|
|
{
|
|
'Id': str(i),
|
|
'MessageBody': json.dumps(item)
|
|
}
|
|
for i, item in enumerate(items)
|
|
]
|
|
|
|
# Batch send to SQS (up to 10 per batch)
|
|
for i in range(0, len(entries), 10):
|
|
sqs.send_message_batch(
|
|
QueueUrl=QUEUE_URL,
|
|
Entries=entries[i:i+10]
|
|
)</code></pre>
|
|
<hr>
|
|
<h2>Related Skills</h2>
|
|
<p><strong>Infrastructure</strong>:</p>
|
|
<ul><li><code>terraform-patterns.md</code> - Infrastructure as Code for Lambda, API Gateway, DynamoDB</li><li><code>infrastructure-security.md</code> - IAM roles, policies, secrets management</li><li><code>cost-optimization.md</code> - Lambda pricing, DynamoDB capacity modes</li></ul>
|
|
<p><strong>Development</strong>:</p>
|
|
<ul><li><code>modal-functions-basics.md</code> - Alternative serverless platform with simpler deployment</li><li><code>cloudflare-workers.md</code> - Edge computing alternative for API endpoints</li></ul>
|
|
<p><strong>Standards from CLAUDE.md</strong>:</p>
|
|
<ul><li>Use IAM roles for Lambda execution (never hardcode credentials)</li><li>CloudWatch Logs for monitoring and debugging</li><li>Environment variables for configuration</li><li>Principle of least privilege for permissions</li></ul>
|
|
<hr>
|
|
<p><strong>Last Updated</strong>: 2025-10-18 <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="/infrastructure-aws-serverless.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
|
|
</footer>
|
|
</div></body></html> |