artubss/SKILLS-CLAUDE-CODE / skills/skills/development/aws-serverless
aws-serverless
UnverifiedHabilidade especializada para construir aplicações serverless prontas para produção na AWS. Abrange funções Lambda, API Gateway, DynamoDB, padrões orientados a eventos SQS/SNS, deployment com SAM/CDK e otimização de cold start.
AWS Serverless
Padrões
Padrão Lambda Handler
Estrutura apropriada de função Lambda com tratamento de erros
Quando usar: ['Qualquer implementação de função Lambda', 'Handlers de API, processadores de eventos, tarefas agendadas']
// Node.js Lambda Handler
// handler.js
// Inicializar fora do handler (reutilizado em invocações)
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
const { DynamoDBDocumentClient, GetCommand } = require('@aws-sdk/lib-dynamodb');
const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);
// Função handler
exports.handler = async (event, context) => {
// Opcional: Não esperar pelo event loop estar vazio (Node.js)
context.callbackWaitsForEmptyEventLoop = false;
try {
// Parse da entrada baseado na origem do evento
const body = typeof event.body === 'string'
? JSON.parse(event.body)
: event.body;
// Lógica de negócio
const result = await processRequest(body);
// Retornar resposta compatível com API Gateway
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify(result)
};
} catch (error) {
console.error('Erro:', JSON.stringify({
error: error.message,
stack: error.stack,
requestId: context.awsRequestId
}));
return {
statusCode: error.statusCode || 500,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
error: error.message || 'Erro interno do servidor'
})
};
}
};
async function processRequest(data) {
// Sua lógica de negócio aqui
const result = await docClient.send(new GetCommand({
TableName: process.env.TABLE_NAME,
Key: { id: data.id }
}));
return result.Item;
}
# Python Lambda Handler
# handler.py
import json
import os
import logging
import boto3
from botocore.exceptions import ClientError
# Inicializar fora do handler (reutilizado em invocações)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(os.environ['TABLE_NAME'])
def handler(event, context):
try:
# Parse da entrada
Padrão Integração API Gateway
Integração REST API e HTTP API com Lambda
Quando usar: ['Construir REST APIs com suporte em Lambda', 'Precisa de endpoints HTTP para funções']
# template.yaml (SAM)
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Globals:
Function:
Runtime: nodejs20.x
Timeout: 30
MemorySize: 256
Environment:
Variables:
TABLE_NAME: !Ref ItemsTable
Resources:
# HTTP API (recomendado para casos simples)
HttpApi:
Type: AWS::Serverless::HttpApi
Properties:
StageName: prod
CorsConfiguration:
AllowOrigins:
- "*"
AllowMethods:
- GET
- POST
- DELETE
AllowHeaders:
- "*"
# Funções Lambda
GetItemFunction:
Type: AWS::Serverless::Function
Properties:
Handler: src/handlers/get.handler
Events:
GetItem:
Type: HttpApi
Properties:
ApiId: !Ref HttpApi
Path: /items/{id}
Method: GET
Policies:
- DynamoDBReadPolicy:
TableName: !Ref ItemsTable
CreateItemFunction:
Type: AWS::Serverless::Function
Properties:
Handler: src/handlers/create.handler
Events:
CreateItem:
Type: HttpApi
Properties:
ApiId: !Ref HttpApi
Path: /items
Method: POST
Policies:
- DynamoDBCrudPolicy:
TableName: !Ref ItemsTable
# Tabela DynamoDB
ItemsTable:
Type: AWS::DynamoDB::Table
Properties:
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
BillingMode: PAY_PER_REQUEST
Outputs:
ApiUrl:
Value: !Sub "https://${HttpApi}.execute-api.${AWS::Region}.amazonaws.com/prod"
// src/handlers/get.js
const { getItem } = require('../lib/dynamodb');
exports.handler = async (event) => {
const id = event.pathParameters?.id;
if (!id) {
return {
statusCode: 400,
body: JSON.stringify({ error: 'Parâmetro id ausente' })
};
}
const item =
Padrão Event-Driven SQS
Lambda acionada por SQS para processamento assíncrono confiável
Quando usar: ['Processamento desacoplado e assíncrono', 'Precisa de lógica de retry e DLQ', 'Processamento de mensagens em lotes']
# template.yaml
Resources:
ProcessorFunction:
Type: AWS::Serverless::Function
Properties:
Handler: src/handlers/processor.handler
Events:
SQSEvent:
Type: SQS
Properties:
Queue: !GetAtt ProcessingQueue.Arn
BatchSize: 10
FunctionResponseTypes:
- ReportBatchItemFailures # Tratamento de falha parcial de lote
ProcessingQueue:
Type: AWS::SQS::Queue
Properties:
VisibilityTimeout: 180 # 6x timeout Lambda
RedrivePolicy:
deadLetterTargetArn: !GetAtt DeadLetterQueue.Arn
maxReceiveCount: 3
DeadLetterQueue:
Type: AWS::SQS::Queue
Properties:
MessageRetentionPeriod: 1209600 # 14 dias
// src/handlers/processor.js
exports.handler = async (event) => {
const batchItemFailures = [];
for (const record of event.Records) {
try {
const body = JSON.parse(record.body);
await processMessage(body);
} catch (error) {
console.error(`Falha ao processar mensagem ${record.messageId}:`, error);
// Reportar este item como falhado (será retentado)
batchItemFailures.push({
itemIdentifier: record.messageId
});
}
}
// Retornar itens falhados para retry
return { batchItemFailures };
};
async function processMessage(message) {
// Sua lógica de processamento
console.log('Processando:', message);
// Simular trabalho
await saveToDatabase(message);
}
# Versão Python
import json
import logging
logger = logging.getLogger()
def handler(event, context):
batch_item_failures = []
for record in event['Records']:
try:
body = json.loads(record['body'])
process_message(body)
except Exception as e:
logger.error(f"Falha ao processar {record['messageId']}: {e}")
batch_item_failures.append({
'itemIdentifier': record['messageId']
})
return {'batchItemFailures': batch_item_failures}
Anti-padrões
❌ Lambda Monolítica
Por que é ruim: Pacotes de deployment grandes causam cold starts lentos. Difícil escalar operações individuais. Atualizações afetam todo o sistema.
❌ Dependências Grandes
Por que é ruim: Aumenta o tamanho do pacote de deployment. Desacelera significativamente cold starts. A maioria do SDK/biblioteca pode estar não utilizada.
❌ Chamadas Síncronas em VPC
Por que é ruim: Lambdas anexadas a VPC têm overhead de configuração ENI. Lookups de DNS ou conexões bloqueadas pioram cold starts.
⚠️ Pontos Críticos
| Problema | Severidade | Solução |
|---|---|---|
| Problema | alta | ## Medir sua fase INIT |
| Problema | alta | ## Definir timeout apropriado |
| Problema | alta | ## Aumentar alocação de memória |
| Problema | média | ## Verificar configuração de VPC |
| Problema | média | ## Avisar Lambda para não esperar pelo event loop |
| Problema | média | ## Para uploads de arquivos grandes |
| Problema | alta | ## Usar buckets/prefixos diferentes |
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deployment | Stars: 318k | Updated | Claude CodeCodex | Unverified | Install |
| xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved. | Stars: 196k | Updated | Claude CodeCodex | Verified | Install |
| shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |
| childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release. | Stars: 117k | Updated | Claude CodeCodex | Unverified | Install |