powertools

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 11, 2026 License: MIT Imports: 3 Imported by: 0

README

Powertools for AWS Lambda (Go)

A Go port of Powertools for AWS Lambda (Python) v3.35.0, the toolkit AWS maintains to implement serverless best practices. Every Powertools utility is here, written the way Go is written today, and compatible with the Python one on the wire: the same environment variables, log keys, EMF documents and DynamoDB items.

go get github.com/alessandrolattao/powertools-lambda-go

It needs Go 1.27 (generic methods, encoding/json/v2 on by default).

Quick start

package main

import (
	"context"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"

	"github.com/alessandrolattao/powertools-lambda-go/logging"
	"github.com/alessandrolattao/powertools-lambda-go/metrics"
	"github.com/alessandrolattao/powertools-lambda-go/tracing"
)

var (
	logger  = logging.New()
	tracer  = tracing.New()
	meter   = metrics.New(metrics.WithNamespace("Shop"))
)

func handle(ctx context.Context, e events.SQSEvent) (string, error) {
	logger.InfoContext(ctx, "batch received", "records", len(e.Records))
	tracing.PutAnnotation(ctx, "records", len(e.Records))
	if err := meter.AddMetric(ctx, "BatchReceived", metrics.Count, 1); err != nil {
		return "", err
	}
	return "ok", nil
}

func main() {
	lambda.Start(logger.InjectContext(tracer.CaptureLambdaHandler(meter.LogMetrics(handle))))
}

Every handler-level utility is a decorator: a function that takes a handler and returns one, with the event and result types inferred. They stack with each other and with your own middlewares.

Utilities

Package What it does Guide
logging Structured JSON logs on log/slog, with Lambda context, cold start, correlation ids, sampling and buffering docs/logging.md
tracing OpenTelemetry traces exported to AWS X-Ray, annotations, metadata, AWS SDK and HTTP instrumentation docs/tracing.md
metrics CloudWatch Embedded Metric Format; Datadog in metrics/datadog docs/metrics.md
eventhandler Routing for API Gateway REST and HTTP, ALB, Function URLs, VPC Lattice, with validation and OpenAPI; AppSync, AppSync Events and Bedrock Agents resolvers docs/eventhandler.md
batch Partial batch responses for SQS (standard and FIFO), Kinesis, DynamoDB Streams, Kafka docs/batch.md
idempotency Safe retries, with DynamoDB or Redis persistence docs/idempotency.md
circuitbreaker Stop calling an unhealthy dependency, with state shared in DynamoDB docs/circuitbreaker.md
parameters SSM Parameter Store, Secrets Manager, AppConfig, DynamoDB, with caching and transforms docs/parameters.md
featureflags Rule-based feature flags on AppConfig docs/featureflags.md
validation JSON Schema validation of events and responses docs/validation.md
parser Typed parsing of events, with envelopes docs/parser.md
eventsource The event types aws-lambda-go lacks, and helpers docs/eventsource.md
jmespath JMESPath with the Powertools decoding functions and envelopes docs/jmespath.md
streaming S3 objects larger than memory, as seekable streams with transforms docs/streaming.md
kafka Kafka events from MSK and self-managed clusters, with Avro, Protobuf and JSON docs/kafka.md
datamasking Erase or encrypt sensitive fields, with the AWS Encryption SDK in datamasking/kms docs/datamasking.md
auth, oauth2 JWT access-token verification and authorizers; client-credentials tokens docs/auth.md, docs/oauth2.md
metadata The Lambda Metadata Endpoint docs/metadata.md
middleware Your own handler middlewares docs/middleware.md

Lambda Managed Instances and durable functions: docs/lambda-features.md.

Design

The principles, the conventions every package follows, and the decisions behind the differences from Python are in docs/design.md. In short:

  • Parity, idiomatically. Every Powertools feature, with Python's defaults and POWERTOOLS_* variables; nothing that Go, aws-lambda-go or aws-sdk-go-v2 already provide (Python's typing and event data classes have no reason to exist in Go).
  • Safe under concurrency. Lambda Managed Instances run several invocations in one process, so per-invocation state lives in the context.Context.
  • Upstream bugs are fixed, not copied; each package's documentation lists where it differs from Python, and why.
  • OpenTelemetry, not the X-Ray SDK, as the AWS migration guide prescribes.

Development

go test -race ./...                 # unit tests, examples
cd integration && go test -race ./... # against Floci (AWS emulator) and Valkey, needs Docker
golangci-lint run ./...             # strict configuration, see .golangci.yml

Fuzz tests cover every parser of untrusted input: go test -run=^$ -fuzz=FuzzSearch ./jmespath/.

License

MIT, see LICENSE. Powertools for AWS Lambda (Python), which this port follows, is MIT-0. The Swagger UI assets embedded in eventhandler/swaggerui are Apache-2.0, with their own LICENSE and NOTICE.

Documentation

Overview

Package powertools is Powertools for AWS Lambda (Go): a port of Powertools for AWS Lambda (Python), the toolkit AWS maintains to implement serverless best practices, written the way Go is written today.

Every utility lives in its own package:

  • logging: structured JSON logs with Lambda context, sampling, buffering
  • tracing: OpenTelemetry traces exported to AWS X-Ray
  • metrics: CloudWatch Embedded Metric Format, and Datadog
  • eventhandler: routing for API Gateway, ALB, Function URLs, VPC Lattice, AppSync, Bedrock Agents, with validation and OpenAPI
  • batch: partial batch responses for SQS, Kinesis, DynamoDB Streams, Kafka
  • idempotency: safe retries, on DynamoDB or Redis
  • circuitbreaker: stop calling an unhealthy dependency
  • parameters: SSM Parameter Store, Secrets Manager, AppConfig, DynamoDB
  • featureflags: rule-based feature flags on AppConfig
  • validation: JSON Schema validation of events and responses
  • parser: typed parsing of events, with envelopes
  • eventsource: the event types aws-lambda-go lacks
  • jmespath: JMESPath with the Powertools decoding functions
  • streaming: S3 objects larger than memory, as seekable streams
  • kafka: Kafka events with Avro, Protobuf and JSON
  • datamasking: erase or encrypt sensitive fields
  • auth, oauth2: JWT verification and client-credentials tokens
  • metadata: the Lambda Metadata Endpoint
  • middleware: your own handler middlewares

The utilities read the same POWERTOOLS_* environment variables as the Python ones, write the same log keys, EMF documents and DynamoDB items, and are safe for the concurrent invocations of Lambda Managed Instances. They need Go 1.27, where encoding/json/v2 is enabled by default.

Index

Constants

View Source
const Version = "0.1.0"

Version is the version of this module.

Variables

This section is empty.

Functions

func ColdStart

func ColdStart(ctx context.Context) bool

ColdStart reports whether the invocation ctx belongs to is the one that paid for the execution environment's initialization. It is exact when called while a Powertools handler decorator is running; see internal/coldstart for how the cold invocation is claimed.

func ServiceName

func ServiceName() string

ServiceName returns the service the function belongs to: POWERTOOLS_SERVICE_NAME, or "service_undefined" as Powertools Python names a function without one.

Types

This section is empty.

Directories

Path Synopsis
Package auth verifies JWT access tokens in Lambda functions: Powertools for AWS Lambda (Python)'s Auth utility (auth_alpha).
Package auth verifies JWT access tokens in Lambda functions: Powertools for AWS Lambda (Python)'s Auth utility (auth_alpha).
authtest
Package authtest tests code protected by the auth package without real tokens, keys or network: the Go side of Powertools Python's mock_claims.
Package authtest tests code protected by the auth package without real tokens, keys or network: the Go side of Powertools Python's mock_claims.
Package batch processes the records of a batch event one at a time and reports to Lambda only those that failed, so that only they are retried: the partial batch response of Amazon SQS (standard and FIFO queues), Kinesis Data Streams, DynamoDB Streams, and Amazon MSK or self-managed Apache Kafka.
Package batch processes the records of a batch event one at a time and reports to Lambda only those that failed, so that only they are retried: the partial batch response of Amazon SQS (standard and FIFO queues), Kinesis Data Streams, DynamoDB Streams, and Amazon MSK or self-managed Apache Kafka.
Package circuitbreaker stops calling an unhealthy downstream dependency, giving it room to recover while you decide what happens to the rejected calls.
Package circuitbreaker stops calling an unhealthy downstream dependency, giving it room to recover while you decide what happens to the rejected calls.
Package datamasking erases, encrypts and decrypts sensitive data: the Go port of Powertools for AWS Lambda (Python) data masking utility.
Package datamasking erases, encrypts and decrypts sensitive data: the Go port of Powertools for AWS Lambda (Python) data masking utility.
kms
Package kms is the AWS Encryption SDK provider of package datamasking, with AWS KMS keys: the Go port of Powertools for AWS Lambda (Python) AWSEncryptionSDKProvider.
Package kms is the AWS Encryption SDK provider of package datamasking, with AWS KMS keys: the Go port of Powertools for AWS Lambda (Python) AWSEncryptionSDKProvider.
Package eventhandler routes the HTTP requests that reach a Lambda function through Amazon API Gateway (REST and HTTP APIs), an Application Load Balancer, a Lambda Function URL or VPC Lattice: the Go side of Powertools for AWS Lambda (Python)'s REST and HTTP event handler, with its data validation, OpenAPI document and Swagger UI.
Package eventhandler routes the HTTP requests that reach a Lambda function through Amazon API Gateway (REST and HTTP APIs), an Application Load Balancer, a Lambda Function URL or VPC Lattice: the Go side of Powertools for AWS Lambda (Python)'s REST and HTTP event handler, with its data validation, OpenAPI document and Swagger UI.
appsync
Package appsync routes the invocations of AWS AppSync GraphQL direct Lambda resolvers (and of the Amplify GraphQL Transformer @function directive) to typed Go resolvers, one per type and field.
Package appsync routes the invocations of AWS AppSync GraphQL direct Lambda resolvers (and of the Amplify GraphQL Transformer @function directive) to typed Go resolvers, one per type and field.
appsyncevents
Package appsyncevents handles the publish and subscribe operations of AWS AppSync Events channel namespaces whose handler is a Lambda function, routing each to the Go handler registered for its channel path.
Package appsyncevents handles the publish and subscribe operations of AWS AppSync Events channel namespaces whose handler is a Lambda function, routing each to the Go handler registered for its channel path.
bedrockagent
Package bedrockagent serves the action groups of Amazon Bedrock agents: the Go side of Powertools for AWS Lambda (Python)'s BedrockAgentResolver and BedrockAgentFunctionResolver.
Package bedrockagent serves the action groups of Amazon Bedrock agents: the Go side of Powertools for AWS Lambda (Python)'s BedrockAgentResolver and BedrockAgentFunctionResolver.
examples/openapimerge command
Command openapimerge writes the OpenAPI document of an API whose routes live in two Lambda functions, the Go side of Powertools Python's OpenAPIMerge.
Command openapimerge writes the OpenAPI document of an API whose routes live in two Lambda functions, the Go side of Powertools Python's OpenAPIMerge.
internal/lambdahttp
Package lambdahttp carries an HTTP request built from a Lambda event through an http.Handler and collects the response, for the event source adapters of the eventhandler packages.
Package lambdahttp carries an HTTP request built from a Lambda event through an http.Handler and collects the response, for the event source adapters of the eventhandler packages.
internal/schema
Package schema validates JSON values against the JSON Schema documents the typed operations of the event handler generate from struct tags (through github.com/swaggest/jsonschema-go): a deliberately small JSON Schema 2020-12 validator.
Package schema validates JSON values against the JSON Schema documents the typed operations of the event handler generate from struct tags (through github.com/swaggest/jsonschema-go): a deliberately small JSON Schema 2020-12 validator.
internal/schema/schematest
Package schematest generates JSON Schema documents of the subset the schema package implements, and JSON instances, from fuzzer bytes, so that tests can compare the validator with a reference implementation.
Package schematest generates JSON Schema documents of the subset the schema package implements, and JSON instances, from fuzzer bytes, so that tests can compare the validator with a reference implementation.
schemavalidation
Package schemavalidation validates the JSON bodies of the requests and responses of an eventhandler.Router against JSON Schemas, with the validation package: Powertools for AWS Lambda (Python)'s SchemaValidationMiddleware.
Package schemavalidation validates the JSON bodies of the requests and responses of an eventhandler.Router against JSON Schemas, with the validation package: Powertools for AWS Lambda (Python)'s SchemaValidationMiddleware.
swaggerui
Package swaggerui serves the Swagger UI of an eventhandler.Router's OpenAPI document: Powertools for AWS Lambda (Python)'s enable_swagger.
Package swaggerui serves the Swagger UI of an eventhandler.Router's OpenAPI document: Powertools for AWS Lambda (Python)'s enable_swagger.
Package eventsource is the Go side of Powertools for AWS Lambda (Python)'s event source data classes: the event types aws-lambda-go lacks, the members its partial types leave out, and the helpers Powertools adds on top of them.
Package eventsource is the Go side of Powertools for AWS Lambda (Python)'s event source data classes: the event types aws-lambda-go lacks, the members its partial types leave out, and the helpers Powertools adds on top of them.
codepipeline
Package codepipeline reads and writes the artifacts of a CodePipeline job, the S3 half of Powertools Python's CodePipelineJobEvent (setup_s3_client, get_artifact, put_artifact).
Package codepipeline reads and writes the artifacts of a CodePipeline job, the S3 half of Powertools Python's CodePipelineJobEvent (setup_s3_client, get_artifact, put_artifact).
Package featureflags evaluates feature flags: a small rule engine that decides, from a JSON schema and the context of a request, whether a feature is on, or which value it takes.
Package featureflags evaluates feature flags: a small rule engine that decides, from a JSON schema and the context of a request, whether a feature is on, or which value it takes.
Package idempotency makes a Lambda handler, or any function, idempotent: called again with the same input while the first call's record lasts, it returns the first call's result instead of running again.
Package idempotency makes a Lambda handler, or any function, idempotent: called again with the same input while the first call's record lasts, it returns the first call's result instead of running again.
dynamodb
Package dynamodb keeps idempotency records in Amazon DynamoDB: the persistence layer Powertools Python calls DynamoDBPersistenceLayer, with the same item schema and the same conditional writes, so that Go and Python functions can share a table.
Package dynamodb keeps idempotency records in Amazon DynamoDB: the persistence layer Powertools Python calls DynamoDBPersistenceLayer, with the same item schema and the same conditional writes, so that Go and Python functions can share a table.
redis
Package redis keeps idempotency records in Valkey, Redis OSS or any Redis-compatible cache (Amazon ElastiCache, Amazon MemoryDB): the persistence layer Powertools Python calls CachePersistenceLayer, with the same record format, so that Go and Python functions can share a cache.
Package redis keeps idempotency records in Valkey, Redis OSS or any Redis-compatible cache (Amazon ElastiCache, Amazon MemoryDB): the persistence layer Powertools Python calls CachePersistenceLayer, with the same record format, so that Go and Python functions can share a cache.
internal
authval
Package authval holds the configuration checks the auth and oauth2 packages share, written after Powertools Python's auth_alpha validation helpers so that both accept and reject the same values.
Package authval holds the configuration checks the auth and oauth2 packages share, written after Powertools Python's auth_alpha validation helpers so that both accept and reject the same values.
coldstart
Package coldstart tells the one invocation that paid for the execution environment's initialization apart from all the others.
Package coldstart tells the one invocation that paid for the execution environment's initialization apart from all the others.
debug
Package debug is where Powertools writes down what it does internally.
Package debug is where Powertools writes down what it does internally.
env
Package env reads the environment variables Powertools is configured with.
Package env reads the environment variables Powertools is configured with.
output
Package output is where Powertools writes the records Lambda collects: log lines, EMF documents, Datadog metrics.
Package output is where Powertools writes the records Lambda collects: log lines, EMF documents, Datadog metrics.
warn
Package warn is where Powertools tells the developer about a likely mistake: what Powertools Python reports through its warnings module, such as an invalid environment variable, a utility disabled for development, a metric set flushed empty, a Datadog tag that may lose data.
Package warn is where Powertools tells the developer about a likely mistake: what Powertools Python reports through its warnings module, such as an invalid environment variable, a utility disabled for development, a metric set flushed empty, a Datadog tag that may lose data.
Package jmespath extracts data from events with JMESPath expressions, plus the functions Powertools adds to decode what AWS event sources encode:
Package jmespath extracts data from events with JMESPath expressions, plus the functions Powertools adds to decode what AWS event sources encode:
Package kafka processes the events of Kafka event source mappings (Amazon MSK, MSK Serverless and self-managed Apache Kafka), decoding the key and value of every record from base64 and deserializing them from JSON, Avro, Protocol Buffers or a Kafka primitive type: the Go side of Powertools Python's Kafka consumer utility.
Package kafka processes the events of Kafka event source mappings (Amazon MSK, MSK Serverless and self-managed Apache Kafka), decoding the key and value of every record from base64 and deserializing them from JSON, Avro, Protocol Buffers or a Kafka primitive type: the Go side of Powertools Python's Kafka consumer utility.
avro
Package avro deserializes Kafka keys and values written in Apache Avro, the format Powertools recommends for Kafka: Powertools Python's value_schema_type="AVRO" (and key_schema_type).
Package avro deserializes Kafka keys and values written in Apache Avro, the format Powertools recommends for Kafka: Powertools Python's value_schema_type="AVRO" (and key_schema_type).
protobuf
Package protobuf deserializes Kafka keys and values written in Protocol Buffers: Powertools Python's value_schema_type="PROTOBUF" (and key_schema_type).
Package protobuf deserializes Kafka keys and values written in Protocol Buffers: Powertools Python's value_schema_type="PROTOBUF" (and key_schema_type).
Package logging is the Powertools structured logger for Lambda, the Go side of Powertools for AWS Lambda (Python)'s Logger: JSON records with the Lambda context, cold start, correlation ids, debug sampling, per-invocation keys and log buffering, built on log/slog.
Package logging is the Powertools structured logger for Lambda, the Go side of Powertools for AWS Lambda (Python)'s Logger: JSON records with the Lambda context, cold start, correlation ids, debug sampling, per-invocation keys and log buffering, built on log/slog.
Package metadata reads the Lambda Metadata Endpoint: what Lambda knows about the execution environment a function runs in, such as the ID of its Availability Zone.
Package metadata reads the Lambda Metadata Endpoint: what Lambda knows about the execution environment a function runs in, such as the ID of its Availability Zone.
Package metrics creates custom CloudWatch metrics asynchronously, by writing them to standard output in the CloudWatch Embedded Metric Format (EMF), the way Powertools for AWS Lambda (Python) does.
Package metrics creates custom CloudWatch metrics asynchronously, by writing them to standard output in the CloudWatch Embedded Metric Format (EMF), the way Powertools for AWS Lambda (Python) does.
datadog
Package datadog sends the metrics of package metrics to Datadog, as the Datadog provider of Powertools for AWS Lambda (Python) does: to the Datadog Lambda Extension when the function has it, or as JSON lines on standard output that the Datadog Forwarder picks up from the function's log group.
Package datadog sends the metrics of package metrics to Datadog, as the Datadog provider of Powertools for AWS Lambda (Python) does: to the Datadog Lambda Extension when the function has it, or as JSON lines on standard output that the Datadog Forwarder picks up from the function's log group.
internal/pyjson
Package pyjson writes JSON the way Python's json.dumps does with the arguments Powertools Python passes it, so that the documents a Go function writes are byte for byte those a Python function writes for the same calls.
Package pyjson writes JSON the way Python's json.dumps does with the arguments Powertools Python passes it, so that the documents a Go function writes are byte for byte those a Python function writes for the same calls.
Package middleware builds handler middlewares: logic that runs before and after each invocation of a Lambda handler, the Go side of Powertools' middleware factory.
Package middleware builds handler middlewares: logic that runs before and after each invocation of a Lambda handler, the Go side of Powertools' middleware factory.
Package oauth2 acquires and caches OAuth 2.0 client-credentials access tokens for a Lambda function that calls an API on its own behalf: Powertools for AWS Lambda (Python)'s OAuth2 client (auth_alpha.oauth2).
Package oauth2 acquires and caches OAuth 2.0 client-credentials access tokens for a Lambda function that calls an API on its own behalf: Powertools for AWS Lambda (Python)'s OAuth2 client (auth_alpha.oauth2).
Package parameters reads configuration and secrets with a cache in front: the Go side of Powertools' Parameters utility.
Package parameters reads configuration and secrets with a cache in front: the Go side of Powertools' Parameters utility.
appconfig
Package appconfig reads AWS AppConfig configuration profiles through AppConfigData sessions, with the cache and the transforms of package parameters.
Package appconfig reads AWS AppConfig configuration profiles through AppConfigData sessions, with the cache and the transforms of package parameters.
dynamodb
Package dynamodb reads parameters from an Amazon DynamoDB table, with the cache and the transforms of package parameters.
Package dynamodb reads parameters from an Amazon DynamoDB table, with the cache and the transforms of package parameters.
internal/core
Package core is the machinery the parameters packages share: the options of one read, the transforms, the conversion of a value into the Go type the caller names, the cache and the registry of default providers.
Package core is the machinery the parameters packages share: the options of one read, the transforms, the conversion of a value into the Go type the caller names, the cache and the registry of default providers.
secrets
Package secrets reads and writes AWS Secrets Manager secrets, with the cache and the transforms of package parameters.
Package secrets reads and writes AWS Secrets Manager secrets, with the cache and the transforms of package parameters.
ssm
Package ssm reads and writes AWS Systems Manager Parameter Store parameters, with the cache and the transforms of package parameters.
Package ssm reads and writes AWS Systems Manager Parameter Store parameters, with the cache and the transforms of package parameters.
Package parser parses Lambda events, or the payload an event source wraps, into typed Go models and validates them: the Go side of Powertools for AWS Lambda (Python)'s parser utility, without Pydantic.
Package parser parses Lambda events, or the payload an event source wraps, into typed Go models and validates them: the Go side of Powertools for AWS Lambda (Python)'s parser utility, without Pydantic.
Package streaming processes S3 objects larger than the function's memory as streams: the Go side of Powertools Python's streaming utility.
Package streaming processes S3 objects larger than the function's memory as streams: the Go side of Powertools Python's streaming utility.
Package tracing is the Tracer of Powertools for AWS Lambda: an opinionated layer over OpenTelemetry that traces a Lambda function to AWS X-Ray, the way the AWS X-Ray SDK migration guide prescribes now that the X-Ray SDKs are in maintenance mode.
Package tracing is the Tracer of Powertools for AWS Lambda: an opinionated layer over OpenTelemetry that traces a Lambda function to AWS X-Ray, the way the AWS X-Ray SDK migration guide prescribes now that the X-Ray SDKs are in maintenance mode.
Package validation validates events and responses against JSON Schemas, optionally after unwrapping the payload of an event source with a JMESPath envelope: the Go side of Powertools for AWS Lambda (Python)'s validation utility.
Package validation validates events and responses against JSON Schemas, optionally after unwrapping the payload of an event source with a JMESPath envelope: the Go side of Powertools for AWS Lambda (Python)'s validation utility.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL