Files
skills/public/infrastructure-aws-serverless.html
zeekayandHanzo Dev 9e10c1c10e Each llms index points at the other two
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]>
2026-09-11 00:27:59 -07:00

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(&#x27;dynamodb&#x27;)
table = dynamodb.Table(os.environ[&#x27;TABLE_NAME&#x27;])
def lambda_handler(event, context):
&quot;&quot;&quot;
Lambda handler function
Args:
event: Event data (API Gateway, S3, etc.)
context: Runtime information
Returns:
Response with statusCode and body
&quot;&quot;&quot;
try:
# Parse request body
body = json.loads(event.get(&#x27;body&#x27;, &#x27;{}&#x27;))
# Process request
item_id = body.get(&#x27;id&#x27;)
if not item_id:
return {
&#x27;statusCode&#x27;: 400,
&#x27;body&#x27;: json.dumps({&#x27;error&#x27;: &#x27;Missing id field&#x27;})
}
# DynamoDB operation
response = table.put_item(
Item={
&#x27;id&#x27;: item_id,
&#x27;data&#x27;: body.get(&#x27;data&#x27;),
&#x27;timestamp&#x27;: datetime.utcnow().isoformat()
}
)
return {
&#x27;statusCode&#x27;: 200,
&#x27;headers&#x27;: {
&#x27;Content-Type&#x27;: &#x27;application/json&#x27;,
&#x27;Access-Control-Allow-Origin&#x27;: &#x27;*&#x27;
},
&#x27;body&#x27;: json.dumps({
&#x27;message&#x27;: &#x27;Success&#x27;,
&#x27;id&#x27;: item_id
})
}
except Exception as e:
print(f&quot;Error: {str(e)}&quot;) # CloudWatch Logs
return {
&#x27;statusCode&#x27;: 500,
&#x27;body&#x27;: json.dumps({&#x27;error&#x27;: &#x27;Internal server error&#x27;})
}</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):
&quot;&quot;&quot;Handle different HTTP methods&quot;&quot;&quot;
http_method = event[&#x27;httpMethod&#x27;]
path = event[&#x27;path&#x27;]
# Route handling
if http_method == &#x27;GET&#x27; and path == &#x27;/items&#x27;:
return list_items(event)
elif http_method == &#x27;GET&#x27; and path.startswith(&#x27;/items/&#x27;):
item_id = path.split(&#x27;/&#x27;)[-1]
return get_item(item_id)
elif http_method == &#x27;POST&#x27; and path == &#x27;/items&#x27;:
return create_item(event)
elif http_method == &#x27;PUT&#x27; and path.startswith(&#x27;/items/&#x27;):
item_id = path.split(&#x27;/&#x27;)[-1]
return update_item(item_id, event)
elif http_method == &#x27;DELETE&#x27; and path.startswith(&#x27;/items/&#x27;):
item_id = path.split(&#x27;/&#x27;)[-1]
return delete_item(item_id)
else:
return {
&#x27;statusCode&#x27;: 404,
&#x27;body&#x27;: json.dumps({&#x27;error&#x27;: &#x27;Not found&#x27;})
}
def list_items(event):
&quot;&quot;&quot;List all items with pagination&quot;&quot;&quot;
query_params = event.get(&#x27;queryStringParameters&#x27;, {}) or {}
limit = int(query_params.get(&#x27;limit&#x27;, 20))
response = table.scan(Limit=limit)
return {
&#x27;statusCode&#x27;: 200,
&#x27;body&#x27;: json.dumps({
&#x27;items&#x27;: response[&#x27;Items&#x27;],
&#x27;count&#x27;: len(response[&#x27;Items&#x27;])
})
}</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(&#x27;dynamodb&#x27;)
table = dynamodb.Table(&#x27;Users&#x27;)
# Put item
def create_user(user_id, email, name):
table.put_item(
Item={
&#x27;userId&#x27;: user_id,
&#x27;email&#x27;: email,
&#x27;name&#x27;: name,
&#x27;createdAt&#x27;: datetime.utcnow().isoformat()
},
ConditionExpression=&#x27;attribute_not_exists(userId)&#x27; # Prevent overwrites
)
# Get item
def get_user(user_id):
response = table.get_item(
Key={&#x27;userId&#x27;: user_id}
)
return response.get(&#x27;Item&#x27;)
# Query with index
def get_user_by_email(email):
response = table.query(
IndexName=&#x27;email-index&#x27;,
KeyConditionExpression=Key(&#x27;email&#x27;).eq(email)
)
return response[&#x27;Items&#x27;]
# Update item
def update_user(user_id, name):
response = table.update_item(
Key={&#x27;userId&#x27;: user_id},
UpdateExpression=&#x27;SET #name = :name, updatedAt = :timestamp&#x27;,
ExpressionAttributeNames={&#x27;#name&#x27;: &#x27;name&#x27;},
ExpressionAttributeValues={
&#x27;:name&#x27;: name,
&#x27;:timestamp&#x27;: datetime.utcnow().isoformat()
},
ReturnValues=&#x27;ALL_NEW&#x27;
)
return response[&#x27;Attributes&#x27;]
# Delete item
def delete_user(user_id):
table.delete_item(
Key={&#x27;userId&#x27;: 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(&#x27;status&#x27;).eq(&#x27;active&#x27;)
)
return response[&#x27;Items&#x27;]</code></pre>
<h3>4. S3 Event Processing</h3>
<pre><code class="lang-python">import json
import urllib.parse
import boto3
s3 = boto3.client(&#x27;s3&#x27;)
def lambda_handler(event, context):
&quot;&quot;&quot;Process S3 upload events&quot;&quot;&quot;
# Parse S3 event
for record in event[&#x27;Records&#x27;]:
bucket = record[&#x27;s3&#x27;][&#x27;bucket&#x27;][&#x27;name&#x27;]
key = urllib.parse.unquote_plus(record[&#x27;s3&#x27;][&#x27;object&#x27;][&#x27;key&#x27;])
print(f&quot;Processing {bucket}/{key}&quot;)
try:
# Download file
response = s3.get_object(Bucket=bucket, Key=key)
content = response[&#x27;Body&#x27;].read()
# Process content (e.g., resize image, parse CSV)
processed = process_file(content)
# Upload processed file
output_key = f&quot;processed/{key}&quot;
s3.put_object(
Bucket=bucket,
Key=output_key,
Body=processed,
ContentType=response[&#x27;ContentType&#x27;]
)
print(f&quot;Uploaded to {output_key}&quot;)
except Exception as e:
print(f&quot;Error processing {key}: {str(e)}&quot;)
raise e
return {
&#x27;statusCode&#x27;: 200,
&#x27;body&#x27;: json.dumps(&#x27;Processing complete&#x27;)
}</code></pre>
<hr>
<h2>Patterns</h2>
<h3>Event-Driven Architecture</h3>
<pre><code class="lang-python"># EventBridge integration
import boto3
events = boto3.client(&#x27;events&#x27;)
def publish_event(event_type, detail):
&quot;&quot;&quot;Publish custom event to EventBridge&quot;&quot;&quot;
response = events.put_events(
Entries=[
{
&#x27;Source&#x27;: &#x27;my.application&#x27;,
&#x27;DetailType&#x27;: event_type,
&#x27;Detail&#x27;: json.dumps(detail),
&#x27;EventBusName&#x27;: &#x27;default&#x27;
}
]
)
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(
&#x27;UserCreated&#x27;,
{
&#x27;userId&#x27;: user_id,
&#x27;email&#x27;: event[&#x27;email&#x27;],
&#x27;timestamp&#x27;: datetime.utcnow().isoformat()
}
)
return {&#x27;statusCode&#x27;: 200, &#x27;body&#x27;: json.dumps({&#x27;userId&#x27;: user_id})}</code></pre>
<h3>Step Functions Workflow</h3>
<pre><code class="lang-json">{
&quot;Comment&quot;: &quot;Image processing workflow&quot;,
&quot;StartAt&quot;: &quot;ValidateImage&quot;,
&quot;States&quot;: {
&quot;ValidateImage&quot;: {
&quot;Type&quot;: &quot;Task&quot;,
&quot;Resource&quot;: &quot;arn:aws:lambda:us-east-1:123456789012:function:ValidateImage&quot;,
&quot;Next&quot;: &quot;IsValid&quot;,
&quot;Catch&quot;: [{
&quot;ErrorEquals&quot;: [&quot;States.ALL&quot;],
&quot;Next&quot;: &quot;HandleError&quot;
}]
},
&quot;IsValid&quot;: {
&quot;Type&quot;: &quot;Choice&quot;,
&quot;Choices&quot;: [{
&quot;Variable&quot;: &quot;$.valid&quot;,
&quot;BooleanEquals&quot;: true,
&quot;Next&quot;: &quot;ProcessImage&quot;
}],
&quot;Default&quot;: &quot;RejectImage&quot;
},
&quot;ProcessImage&quot;: {
&quot;Type&quot;: &quot;Parallel&quot;,
&quot;Branches&quot;: [
{
&quot;StartAt&quot;: &quot;GenerateThumbnail&quot;,
&quot;States&quot;: {
&quot;GenerateThumbnail&quot;: {
&quot;Type&quot;: &quot;Task&quot;,
&quot;Resource&quot;: &quot;arn:aws:lambda:us-east-1:123456789012:function:GenerateThumbnail&quot;,
&quot;End&quot;: true
}
}
},
{
&quot;StartAt&quot;: &quot;ExtractMetadata&quot;,
&quot;States&quot;: {
&quot;ExtractMetadata&quot;: {
&quot;Type&quot;: &quot;Task&quot;,
&quot;Resource&quot;: &quot;arn:aws:lambda:us-east-1:123456789012:function:ExtractMetadata&quot;,
&quot;End&quot;: true
}
}
}
],
&quot;Next&quot;: &quot;SaveResults&quot;
},
&quot;SaveResults&quot;: {
&quot;Type&quot;: &quot;Task&quot;,
&quot;Resource&quot;: &quot;arn:aws:lambda:us-east-1:123456789012:function:SaveResults&quot;,
&quot;End&quot;: true
},
&quot;RejectImage&quot;: {
&quot;Type&quot;: &quot;Fail&quot;,
&quot;Error&quot;: &quot;InvalidImage&quot;,
&quot;Cause&quot;: &quot;Image failed validation&quot;
},
&quot;HandleError&quot;: {
&quot;Type&quot;: &quot;Task&quot;,
&quot;Resource&quot;: &quot;arn:aws:lambda:us-east-1:123456789012:function:HandleError&quot;,
&quot;End&quot;: true
}
}
}</code></pre>
<h3>SQS Queue Processing</h3>
<pre><code class="lang-python">import boto3
import json
sqs = boto3.client(&#x27;sqs&#x27;)
QUEUE_URL = os.environ[&#x27;QUEUE_URL&#x27;]
def lambda_handler(event, context):
&quot;&quot;&quot;Process SQS messages in batch&quot;&quot;&quot;
for record in event[&#x27;Records&#x27;]:
message_body = json.loads(record[&#x27;body&#x27;])
receipt_handle = record[&#x27;receiptHandle&#x27;]
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&quot;Processed message: {result}&quot;)
except Exception as e:
# Message will return to queue for retry
print(f&quot;Error processing message: {str(e)}&quot;)
# Optionally send to DLQ after max retries
def process_message(message):
&quot;&quot;&quot;Business logic for message processing&quot;&quot;&quot;
# Your processing logic here
return {&#x27;status&#x27;: &#x27;processed&#x27;, &#x27;id&#x27;: message[&#x27;id&#x27;]}
# Send message to SQS (from another Lambda)
def send_to_queue(message):
response = sqs.send_message(
QueueUrl=QUEUE_URL,
MessageBody=json.dumps(message),
MessageAttributes={
&#x27;Priority&#x27;: {
&#x27;StringValue&#x27;: &#x27;high&#x27;,
&#x27;DataType&#x27;: &#x27;String&#x27;
}
}
)
return response[&#x27;MessageId&#x27;]</code></pre>
<h3>DynamoDB Streams</h3>
<pre><code class="lang-python">def lambda_handler(event, context):
&quot;&quot;&quot;Process DynamoDB stream events&quot;&quot;&quot;
for record in event[&#x27;Records&#x27;]:
event_name = record[&#x27;eventName&#x27;] # INSERT, MODIFY, REMOVE
if event_name == &#x27;INSERT&#x27;:
new_image = record[&#x27;dynamodb&#x27;][&#x27;NewImage&#x27;]
handle_insert(new_image)
elif event_name == &#x27;MODIFY&#x27;:
old_image = record[&#x27;dynamodb&#x27;][&#x27;OldImage&#x27;]
new_image = record[&#x27;dynamodb&#x27;][&#x27;NewImage&#x27;]
handle_update(old_image, new_image)
elif event_name == &#x27;REMOVE&#x27;:
old_image = record[&#x27;dynamodb&#x27;][&#x27;OldImage&#x27;]
handle_delete(old_image)
def handle_insert(item):
&quot;&quot;&quot;Handle new item creation&quot;&quot;&quot;
# Send notification, update cache, etc.
print(f&quot;New item created: {item}&quot;)
def handle_update(old_item, new_item):
&quot;&quot;&quot;Handle item updates&quot;&quot;&quot;
# Track changes, invalidate cache, etc.
print(f&quot;Item updated: {old_item} -&gt; {new_item}&quot;)
def handle_delete(item):
&quot;&quot;&quot;Handle item deletion&quot;&quot;&quot;
# Cleanup related resources
print(f&quot;Item deleted: {item}&quot;)</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):
&quot;&quot;&quot;Retrieve secret from Secrets Manager&quot;&quot;&quot;
client = boto3.client(&#x27;secretsmanager&#x27;)
response = client.get_secret_value(SecretId=secret_name)
return json.loads(response[&#x27;SecretString&#x27;])
def send_notification(message, topic_arn):
&quot;&quot;&quot;Send SNS notification&quot;&quot;&quot;
sns = boto3.client(&#x27;sns&#x27;)
sns.publish(
TopicArn=topic_arn,
Message=message,
Subject=&#x27;Lambda Notification&#x27;
)
# 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(&#x27;database-credentials&#x27;)
send_notification(&#x27;Processing started&#x27;, os.environ[&#x27;SNS_TOPIC&#x27;])
# Your logic here
return {&#x27;statusCode&#x27;: 200}</code></pre>
<h3>Scheduled Tasks (EventBridge Cron)</h3>
<pre><code class="lang-python"># Lambda triggered by EventBridge schedule
def lambda_handler(event, context):
&quot;&quot;&quot;
Scheduled task that runs daily at 2 AM UTC
EventBridge rule: cron(0 2 * * ? *)
&quot;&quot;&quot;
print(f&quot;Scheduled task started at {datetime.utcnow()}&quot;)
try:
# Daily cleanup task
cleanup_old_records()
# Generate daily report
report = generate_daily_report()
# Send report via email
send_report_email(report)
return {
&#x27;statusCode&#x27;: 200,
&#x27;body&#x27;: json.dumps(&#x27;Scheduled task completed&#x27;)
}
except Exception as e:
print(f&quot;Error in scheduled task: {str(e)}&quot;)
raise e
def cleanup_old_records():
&quot;&quot;&quot;Delete records older than 30 days&quot;&quot;&quot;
cutoff_date = (datetime.utcnow() - timedelta(days=30)).isoformat()
response = table.scan(
FilterExpression=Attr(&#x27;createdAt&#x27;).lt(cutoff_date)
)
with table.batch_writer() as batch:
for item in response[&#x27;Items&#x27;]:
batch.delete_item(Key={&#x27;id&#x27;: item[&#x27;id&#x27;]})
print(f&quot;Deleted {len(response[&#x27;Items&#x27;])} old records&quot;)</code></pre>
<hr>
<h2>Quick Reference</h2>
<h3>Lambda Best Practices</h3>
<pre><code class="lang-python"># Environment variables
TABLE_NAME = os.environ[&#x27;TABLE_NAME&#x27;]
REGION = os.environ[&#x27;AWS_REGION&#x27;]
# Initialize clients outside handler
dynamodb = boto3.resource(&#x27;dynamodb&#x27;)
table = dynamodb.Table(TABLE_NAME)
# Use connection pooling
session = boto3.Session()
s3 = session.client(&#x27;s3&#x27;)
# 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&quot;Unexpected error: {str(e)}&quot;)
return error_response(500, &quot;Internal server error&quot;)
# Timeouts and retries
from botocore.config import Config
config = Config(
retries={&#x27;max_attempts&#x27;: 3, &#x27;mode&#x27;: &#x27;adaptive&#x27;},
connect_timeout=5,
read_timeout=60
)
s3 = boto3.client(&#x27;s3&#x27;, 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 &#x27;{&quot;key&quot;: &quot;value&quot;}&#x27; \
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 = &quot;AKIAIOSFODNN7EXAMPLE&quot; # 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(&#x27;dynamodb&#x27;) # Created every invocation
table = dynamodb.Table(&#x27;users&#x27;)
# ...
# ✅ CORRECT: Initialize outside handler
dynamodb = boto3.resource(&#x27;dynamodb&#x27;)
table = dynamodb.Table(&#x27;users&#x27;)
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() &lt; 30000: # 30 sec buffer
# Save progress and exit
save_checkpoint(item)
return {&#x27;statusCode&#x27;: 202, &#x27;message&#x27;: &#x27;Processing continues&#x27;}
process_item(item)</code></pre>
<h3>Common Mistakes</h3>
<pre><code class="lang-python"># ❌ Don&#x27;t return large responses from API Gateway
def lambda_handler(event, context):
data = table.scan() # Could be MB of data
return {
&#x27;statusCode&#x27;: 200,
&#x27;body&#x27;: json.dumps(data) # API Gateway limit: 6 MB
}
# ✅ CORRECT: Use pagination
def lambda_handler(event, context):
limit = int(event.get(&#x27;queryStringParameters&#x27;, {}).get(&#x27;limit&#x27;, 20))
response = table.scan(Limit=limit)
return {
&#x27;statusCode&#x27;: 200,
&#x27;body&#x27;: json.dumps({
&#x27;items&#x27;: response[&#x27;Items&#x27;][:limit],
&#x27;lastKey&#x27;: response.get(&#x27;LastEvaluatedKey&#x27;)
})
}</code></pre>
<pre><code class="lang-python"># ❌ Don&#x27;t use recursion for fan-out
def lambda_handler(event, context):
for item in items:
lambda_client.invoke(
FunctionName=&#x27;process-item&#x27;,
InvocationType=&#x27;Event&#x27;,
Payload=json.dumps(item)
) # Could hit concurrency limits
# ✅ CORRECT: Use SQS for fan-out
def lambda_handler(event, context):
entries = [
{
&#x27;Id&#x27;: str(i),
&#x27;MessageBody&#x27;: 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>