AWS Lambda Powertools — Serverless Best Practices

You are an expert in AWS Lambda Powertools, the developer toolkit for implementing serverless best practices. You help developers add structured logging, distributed tracing (X-Ray), custom metrics (CloudWatch EMF), idempotency, feature flags, parameter management, and event parsing to Lambda functions — with zero boilerplate using decorators and middleware.

25 stars

Best use case

AWS Lambda Powertools — Serverless Best Practices is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

You are an expert in AWS Lambda Powertools, the developer toolkit for implementing serverless best practices. You help developers add structured logging, distributed tracing (X-Ray), custom metrics (CloudWatch EMF), idempotency, feature flags, parameter management, and event parsing to Lambda functions — with zero boilerplate using decorators and middleware.

Teams using AWS Lambda Powertools — Serverless Best Practices should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/powertools-lambda/SKILL.md --create-dirs "https://raw.githubusercontent.com/ComeOnOliver/skillshub/main/skills/TerminalSkills/skills/powertools-lambda/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/powertools-lambda/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How AWS Lambda Powertools — Serverless Best Practices Compares

Feature / AgentAWS Lambda Powertools — Serverless Best PracticesStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

You are an expert in AWS Lambda Powertools, the developer toolkit for implementing serverless best practices. You help developers add structured logging, distributed tracing (X-Ray), custom metrics (CloudWatch EMF), idempotency, feature flags, parameter management, and event parsing to Lambda functions — with zero boilerplate using decorators and middleware.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# AWS Lambda Powertools — Serverless Best Practices

You are an expert in AWS Lambda Powertools, the developer toolkit for implementing serverless best practices. You help developers add structured logging, distributed tracing (X-Ray), custom metrics (CloudWatch EMF), idempotency, feature flags, parameter management, and event parsing to Lambda functions — with zero boilerplate using decorators and middleware.

## Core Capabilities

### TypeScript

```typescript
// handler.ts — Lambda with Powertools middleware
import { Logger } from "@aws-lambda-powertools/logger";
import { Tracer } from "@aws-lambda-powertools/tracer";
import { Metrics, MetricUnit } from "@aws-lambda-powertools/metrics";
import { injectLambdaContext } from "@aws-lambda-powertools/logger/middleware";
import { captureLambdaHandler } from "@aws-lambda-powertools/tracer/middleware";
import { logMetrics } from "@aws-lambda-powertools/metrics/middleware";
import middy from "@middy/core";

const logger = new Logger({ serviceName: "payment-service" });
const tracer = new Tracer({ serviceName: "payment-service" });
const metrics = new Metrics({ namespace: "PaymentService", serviceName: "payment-service" });

const lambdaHandler = async (event: APIGatewayProxyEvent) => {
  // Structured logging with correlation IDs
  logger.appendKeys({ orderId: event.pathParameters?.id });
  logger.info("Processing payment", { amount: 29.99, currency: "USD" });

  // Custom metrics (published to CloudWatch automatically)
  metrics.addMetric("PaymentProcessed", MetricUnit.Count, 1);
  metrics.addMetric("PaymentAmount", MetricUnit.None, 29.99);
  metrics.addDimension("PaymentMethod", "card");

  // Tracing (X-Ray subsegments)
  const subsegment = tracer.getSegment()?.addNewSubsegment("stripe-charge");
  try {
    const charge = await processStripePayment(event);
    subsegment?.addAnnotation("chargeId", charge.id);
    tracer.addResponseAsMetadata(charge);

    return { statusCode: 200, body: JSON.stringify(charge) };
  } catch (error) {
    subsegment?.addError(error as Error);
    logger.error("Payment failed", error as Error);
    metrics.addMetric("PaymentFailed", MetricUnit.Count, 1);
    throw error;
  } finally {
    subsegment?.close();
  }
};

// Middy middleware stack
export const handler = middy(lambdaHandler)
  .use(injectLambdaContext(logger, { logEvent: true }))
  .use(captureLambdaHandler(tracer))
  .use(logMetrics(metrics));
```

### Idempotency

```typescript
import { makeIdempotent, IdempotencyConfig } from "@aws-lambda-powertools/idempotency";
import { DynamoDBPersistenceLayer } from "@aws-lambda-powertools/idempotency/dynamodb";

const persistenceStore = new DynamoDBPersistenceLayer({
  tableName: "idempotency-table",
});

const config = new IdempotencyConfig({
  eventKeyJmesPath: "body.orderId",       // Dedup key from event
  expiresAfterSeconds: 3600,              // 1 hour TTL
});

const processPayment = async (event: any) => {
  const body = JSON.parse(event.body);
  // This function runs EXACTLY ONCE per orderId, even on retries
  const result = await chargeCard(body.orderId, body.amount);
  return { statusCode: 200, body: JSON.stringify(result) };
};

export const handler = makeIdempotent(processPayment, {
  persistenceStore,
  config,
});
```

### Python

```python
from aws_lambda_powertools import Logger, Tracer, Metrics
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
from aws_lambda_powertools.utilities.typing import LambdaContext
from aws_lambda_powertools.logging import correlation_paths

logger = Logger(service="user-service")
tracer = Tracer(service="user-service")
metrics = Metrics(namespace="UserService")
app = APIGatewayRestResolver()

@app.get("/users/<user_id>")
@tracer.capture_method
def get_user(user_id: str):
    logger.info("Fetching user", extra={"user_id": user_id})
    user = db.get_user(user_id)
    metrics.add_metric(name="UserFetched", unit="Count", value=1)
    return {"user": user}

@app.post("/users")
@tracer.capture_method
def create_user():
    body = app.current_event.json_body
    user = db.create_user(body)
    metrics.add_metric(name="UserCreated", unit="Count", value=1)
    return {"user": user}, 201

@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
@tracer.capture_lambda_handler
@metrics.log_metrics(capture_cold_start_metric=True)
def lambda_handler(event: dict, context: LambdaContext) -> dict:
    return app.resolve(event, context)
```

## Installation

```bash
# TypeScript
npm install @aws-lambda-powertools/logger @aws-lambda-powertools/tracer @aws-lambda-powertools/metrics

# Python
pip install aws-lambda-powertools
```

## Best Practices

1. **Structured logging** — Use Logger for JSON logs with correlation IDs; enables CloudWatch Insights queries
2. **Distributed tracing** — Use Tracer with X-Ray; trace requests across Lambda → DynamoDB → SQS → Lambda chains
3. **Custom metrics** — Use Metrics with EMF format; CloudWatch picks up without API calls, zero cost overhead
4. **Idempotency** — Use for payment/order handlers; prevents duplicate processing on Lambda retries
5. **Event parsing** — Use event handler resolvers for API Gateway, SQS, S3 events; type-safe with validation
6. **Cold start metric** — Enable `capture_cold_start_metric`; track and optimize cold starts per function
7. **Correlation IDs** — Inject automatically from API Gateway, ALB, or custom headers; trace requests end-to-end
8. **Middy middleware** — Stack Powertools as middy middleware in TypeScript; clean separation of concerns

Related Skills

visualization-best-practices

25
from ComeOnOliver/skillshub

Visualization Best Practices - Auto-activating skill for Data Analytics. Triggers on: visualization best practices, visualization best practices Part of the Data Analytics skill category.

lambda-layer-creator

25
from ComeOnOliver/skillshub

Lambda Layer Creator - Auto-activating skill for AWS Skills. Triggers on: lambda layer creator, lambda layer creator Part of the AWS Skills skill category.

lambda-function-generator

25
from ComeOnOliver/skillshub

Lambda Function Generator - Auto-activating skill for AWS Skills. Triggers on: lambda function generator, lambda function generator Part of the AWS Skills skill category.

scanning-input-validation-practices

25
from ComeOnOliver/skillshub

This skill enables Claude to automatically scan source code for potential input validation vulnerabilities. It identifies areas where user-supplied data is not properly sanitized or validated before being used in operations, which could lead to security exploits like SQL injection, cross-site scripting (XSS), or command injection. Use this skill when the user asks to "scan for input validation issues", "check input sanitization", "find potential XSS vulnerabilities", or similar requests related to securing user input. It is particularly useful during code reviews, security audits, and when hardening applications against common web vulnerabilities. The skill leverages the input-validation-scanner plugin to perform the analysis.

lambda

25
from ComeOnOliver/skillshub

AWS Lambda serverless functions for event-driven compute. Use when creating functions, configuring triggers, debugging invocations, optimizing cold starts, setting up event source mappings, or managing layers.

dotnet-best-practices

25
from ComeOnOliver/skillshub

Ensure .NET/C# code meets best practices for the solution/project.

SARIF Parsing Best Practices

25
from ComeOnOliver/skillshub

You are a SARIF parsing expert. Your role is to help users effectively read, analyze, and process SARIF files from static analysis tools.

oracle — best use

25
from ComeOnOliver/skillshub

Oracle bundles your prompt + selected files into one “one-shot” request so another model can answer with real repo context (API or browser automation). Treat output as advisory: verify against code + tests.

vue-pinia-best-practices

25
from ComeOnOliver/skillshub

Pinia stores, state management patterns, store setup, and reactivity with stores.

vue-options-api-best-practices

25
from ComeOnOliver/skillshub

Vue 3 Options API style (data(), methods, this context). Each reference shows Options API solution only.

next-best-practices

25
from ComeOnOliver/skillshub

Next.js best practices - file conventions, RSC boundaries, data patterns, async APIs, metadata, error handling, route handlers, image/font optimization, bundling

security-best-practices

25
from ComeOnOliver/skillshub

Implement security best practices for web applications and infrastructure. Use when securing APIs, preventing common vulnerabilities, or implementing security policies. Handles HTTPS, CORS, XSS, SQL Injection, CSRF, rate limiting, and OWASP Top 10.