Functions



Functions are Stacktape's abstraction for AWS Lambda, a serverless compute service that lets you run code without managing servers. You can write code in multiple languages and trigger it to run in response to events like HTTP requests, file uploads to an S3 bucket, or messages in an SQS queue.

This allows you to build and deploy web applications, process data, and automate workflows while only paying for the compute time you use.

Example function

resources:
  myLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: path/to/my-lambda.ts

Stacktape configuration for a basic Lambda function.

// Stacktape will automatically package any library for you
import anyLibrary from 'any-library';
import { initializeDatabaseConnection } from './database';

// Everything outside of the handler function will be executed only once (on every cold-start).
// You can execute any code that should be "cached" here (such as initializing a database connection)
const myDatabaseConnection = initializeDatabaseConnection();

// handler will be executed on every function invocation
const handler = async (event, context) => {
  // This log will be published to a CloudWatch log group
  console.log(event, context);

  const posts = myDatabaseConnection.query('SELECT * FROM posts');

  return { result: posts };
};

export default handler;

Example function code written in TypeScript.

Under the hood

Stacktape Functions are built on top of AWS Lambda, a production-ready, pay-per-request service suitable for a wide range of use cases.

When to use

Lambda functions are a great choice for many applications, including HTTP APIs, scheduled tasks, and event-driven integrations. However, they are not suitable for long-running processes or tasks that require fine-grained control over the execution environment.

Advantages

  • Pay-per-use: You are billed only for the compute time you consume, rounded to the nearest millisecond.
  • Massive & fast scaling: Functions can scale to thousands of parallel executions in milliseconds.
  • High availability: AWS Lambda automatically runs your function in multiple Availability Zones to ensure high availability.
  • Secure by default: The underlying environment is securely managed by AWS.
  • Lots of integrations: Functions can be triggered by a wide variety of services.

Disadvantages

  • Limited execution time: A function can run for a maximum of 15 minutes.
  • Limited configuration: You can only configure memory (from 128MB to 10GB), and CPU power scales proportionally.
  • More expensive for certain tasks: For continuous or predictable workloads, batch jobs or container workloads can be more cost-effective.
  • Cold starts: The first invocation of a function after a period of inactivity can experience a slight delay.

Packaging

In the packaging section, you specify the path to your code and how it should be built. For more details, see the packaging documentation.

resources:
  myLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: path/to/my-lambda.ts
      timeout: 10
      memory: 2048

Computing resources

The function's execution environment is fully managed. You can set the memory from 128MB to 10,240MB. CPU power is allocated proportionally to the memory, with 1,797MB corresponding to one virtual CPU and a maximum of six vCPUs at 10,240MB.

resources:
  myLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: path/to/my-lambda.ts
      memory: 1024

Runtime

Auto-detected from your source file extension when using stacktape-lambda-buildpack. Override only if you need a specific version.

Timeout

Sets the maximum execution time for the function in seconds. The default is 3 seconds, and the maximum is 900 seconds (15 minutes).

resources:
  myLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: path/to/my-lambda.ts
      timeout: 300

Environment variables

A list of environment variables to pass to the script or command.

Values can be:

environment:
  - name: STATIC_ENV_VAR
    value: my-env-var
  - name: DYNAMICALLY_SET_ENV_VAR
    value: $MyCustomDirective('input-for-my-directive')
  - name: DB_HOST
    value: $ResourceParam('myDatabase', 'host')
  - name: DB_PASSWORD
    value: $Secret('dbSecret.password')

Logging

Any output to stdout or stderr is captured and stored in an AWS CloudWatch log group. You can view logs through the Stacktape Console, the stacktape stack-info command, or by streaming them with the stacktape logs command.

To manage costs, you can configure retentionDays to automatically delete old logs.

LambdaFunctionLoggingAPI referenceParent:LambdaFunction
disabled

Disable CloudWatch logging entirely.

Type: boolean

retentionDaysDefault: 180

How many days to keep logs. Longer retention = higher storage cost.

Type: number ENUM

Possible values: 13571430609012015018036540054573118273653

logForwarding

Forward logs to an external service (Datadog, Highlight.io, or any HTTP endpoint).

Type: HttpEndpointLogForwarding or HighlightLogForwarding or DatadogLogForwarding

Uses Kinesis Data Firehose (~$0.03/GB). Failed deliveries go to a backup S3 bucket.

Forwarding logs

You can forward logs to third-party services. For more information, see the Log Forwarding documentation.

Storage

Each function has access to 512MB of temporary, ephemeral storage at /tmp. This storage is not shared between concurrent executions but can be used for caching data within a single execution environment. For persistent storage, use Buckets.

Trigger events

Functions are invoked in response to events. Stacktape automatically creates the necessary integrations and permissions for your specified triggers. A single function can have multiple event integrations, and the payload it receives will vary based on the event source.

HTTP API event

Triggers the function when a request is made to a specified HTTP API Gateway.

resources:
  myHttpApi:
    type: http-api-gateway

  myLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: path/to/my-lambda.ts
      events:
        - type: http-api-gateway
          properties:
            httpApiGatewayName: myHttpApi
            path: /hello
            method: GET
HttpApiIntegrationAPI referenceParent:LambdaFunction
typeRequired
No description

Type: string "http-api-gateway"

properties.httpApiGatewayNameRequired

The name of the HTTP API Gateway.

Type: string

properties.methodRequired

The HTTP method that will trigger this integration.

Type: string ENUM

Possible values: *DELETEGETHEADOPTIONSPATCHPOSTPUT

You can specify an exact method (e.g., GET) or use * to match any method.

properties.pathRequired

The URL path that will trigger this integration.

Type: string

  • Exact path: /users
  • Path with parameter: /users/{id}. The id will be available in event.pathParameters.id.
  • Greedy path: /files/{proxy+}. This will match any path starting with /files/.
properties.authorizer

An authorizer to protect this route.

Type: StpAuthorizer

Unauthorized requests will be rejected with a 401 Unauthorized response.

properties.payloadFormatDefault: '1.0'

The payload format version for the Lambda integration.

Type: string ENUM

Possible values: 1.02.0

For details on the differences between formats, see the AWS documentation.

Cognito authorizer

Restricts access to users authenticated with a User Pool.

resources:
  myGateway:
    type: http-api-gateway

  myUserPool:
    type: user-auth-pool
    properties:
      userVerificationType: email-code

  myLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: src/my-lambda.ts
      events:
        - type: http-api-gateway
          properties:
            httpApiGatewayName: myGateway
            path: /some-path
            method: '*'
            authorizer:
              type: cognito
              properties:
                userPoolName: myUserPool
import { CognitoIdentityProvider } from '@aws-sdk/client-cognito-identity-provider';

const cognito = new CognitoIdentityProvider({});

const handler = async (event, context) => {
  const userData = await cognito.getUser({ AccessToken: event.headers.authorization });
  // do something with your user data
};

export default handler;
CognitoAuthorizerAPI reference
typeRequired

Cognito JWT authorizer

Type: string "cognito"

Configures an HTTP API authorizer that validates JSON Web Tokens (JWTs) issued by a Cognito user pool. This is the simplest way to protect routes when your users sign in via user-auth-pool.

Stacktape turns this into an API Gateway v2 authorizer of type JWT that checks the token's issuer and audience.

properties.userPoolNameRequired

Name of the user pool to protect the API

Type: string

The Stacktape name of the user-auth-pool resource whose tokens should be accepted by this HTTP API authorizer. Stacktape uses this to:

  • Set the expected audience to the user pool client ID.
  • Build the expected issuer URL based on the user pool and AWS region.

In practice this means only JWTs issued by this pool (and its client) will be considered valid.

properties.identitySources

Where to read the JWT from in the request

Type: Array of string

A list of identity sources that tell API Gateway where to look for the bearer token, using the $request.* syntax from API Gateway (for example '$request.header.Authorization').

If you omit this, Stacktape defaults to reading the token from the Authorization HTTP header, using a JWT authorizer as described in the API Gateway v2 authorizer docs (AWS::ApiGatewayV2::Authorizer).


Lambda authorizer

Uses another Lambda function to authorize incoming requests.

LambdaAuthorizerAPI reference
typeRequired

Lambda-based HTTP API authorizer

Type: string "lambda"

Configures an API Gateway request authorizer that runs a Lambda function to decide whether a request is allowed. This is useful when your authorization logic can't be expressed as simple JWT validation – for example when you check API keys, look up permissions in a database, or integrate with a non-JWT identity system.

Stacktape creates an AWS::ApiGatewayV2::Authorizer of type REQUEST and wires it up to your Lambda.

properties.functionNameRequired

Name of the authorizer function

Type: string

The Stacktape name of a function resource that should run for each authorized request. API Gateway calls this Lambda, passes request details, and uses its response to allow or deny access.

properties.iamResponse

Use IAM-style (v1) authorizer responses

Type: boolean

  • If true, your Lambda must return a full IAM policy document (the "v1" format).
  • If false or omitted, Stacktape enables simple responses (the HTTP API v2 payload format) so your Lambda can return a small JSON object with an isAuthorized flag and optional context.

This flag is wired to EnableSimpleResponses on the underlying AWS::ApiGatewayV2::Authorizer.

properties.identitySources

Where to read identity data from

Type: Array of string

A list of request fields API Gateway should pass into your Lambda authorizer (for example headers, query parameters, or stage variables) using the $request.* syntax.

When left empty, no specific identity sources are configured and your Lambda must inspect the incoming event directly.

properties.cacheResultSeconds

Cache authorizer results

Type: number

Number of seconds API Gateway should cache the result of the Lambda authorizer for a given identity. While cached, repeated requests skip calling your authorizer function and reuse the previous result.

This value is applied to AuthorizerResultTtlInSeconds. If omitted, Stacktape sets it to 0 (no caching).


Schedule event

Triggers the function on a fixed rate or cron schedule.

resources:
  myLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: path/to/my-lambda.ts
      events:
        # invoke function every two hours
        - type: schedule
          properties:
            scheduleRate: rate(2 hours)
        # invoke function at 10:00 UTC every day
        - type: schedule
          properties:
            scheduleRate: cron(0 10 * * ? *)
ScheduleIntegrationAPI referenceParent:LambdaFunction
typeRequired
No description

Type: string "schedule"

properties.scheduleRateRequired

The schedule rate or cron expression.

Type: string

Examples: rate(2 hours), cron(0 10 * * ? *)

properties.input
No description

Type: UNSPECIFIED

properties.inputPath

A JSONPath expression to extract a portion of the event to pass to the target.

Type: string

This is useful for forwarding only a specific part of the event payload. You can only use one of input, inputPath, or inputTransformer.

Example:

inputPath: '$.detail'
properties.inputTransformer

Customizes the event payload sent to the target.

Type: EventInputTransformer

This allows you to extract values from the original event and use them to construct a new payload. You can only use one of input, inputPath, or inputTransformer.

Example:

inputTransformer:
  inputPathsMap:
    eventTime: '$.time'
  inputTemplate:
    message: 'This event occurred at <eventTime>.'

Event Bus event

Triggers the function when a matching event is received by an event bus.

resources:
  myLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: path/to/my-lambda.ts
      events:
        - type: event-bus
          properties:
            useDefaultBus: true
            eventPattern:
              source:
                - 'aws.autoscaling'
              region:
                - 'us-west-2'
resources:
  myEventBus:
    type: event-bus

  myLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: path/to/my-lambda.ts
      events:
        - type: event-bus
          properties:
            eventBusName: myEventBus
            eventPattern:
              source:
                - 'mycustomsource'
EventBusIntegrationAPI referenceParent:LambdaFunction
typeRequired
No description

Type: string "event-bus"

properties.eventPatternRequired

A pattern to filter events from the event bus.

Type: EventBusIntegrationPattern

Only events that match this pattern will trigger the target. For details on the syntax, see the AWS EventBridge documentation on event patterns.

properties.eventBusArn

The ARN of an existing event bus.

Type: string

Use this to subscribe to an event bus that is not managed by your stack. You must specify only one of eventBusArn, eventBusName, or useDefaultBus.

properties.eventBusName

The name of an event bus defined in your stack's resources.

Type: string

You must specify only one of eventBusArn, eventBusName, or useDefaultBus.

properties.useDefaultBus

Uses the default AWS event bus.

Type: boolean

You must specify only one of eventBusArn, eventBusName, or useDefaultBus.

properties.onDeliveryFailure

A destination for events that fail to be delivered to the target.

Type: EventBusOnDeliveryFailure

In rare cases, an event might fail to be delivered. This property specifies an SQS queue where failed events will be sent.

properties.input
No description

Type: UNSPECIFIED

properties.inputPath

A JSONPath expression to extract a portion of the event to pass to the target.

Type: string

This is useful for forwarding only a specific part of the event payload. You can only use one of input, inputPath, or inputTransformer.

Example:

inputPath: '$.detail'
properties.inputTransformer

Customizes the event payload sent to the target.

Type: EventInputTransformer

This allows you to extract values from the original event and use them to construct a new payload. You can only use one of input, inputPath, or inputTransformer.

Example:

inputTransformer:
  inputPathsMap:
    instanceId: '$.detail.instance-id'
    instanceState: '$.detail.state'
  inputTemplate:
    message: 'Instance <instanceId> is now in state <instanceState>.'

Kafka Topic event

Triggers the function when messages are available in a Kafka topic.

resources:
  # is triggered when there are records in custom configured kafka topic
  myConsumer:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: consumer.ts
      events:
        - type: kafka-topic
          properties:
            customKafkaConfiguration:
              bootstrapServers:
                - my-kafka-broker-1.my-domain.com:9092
                - my-kafka-broker-2.my-domain.com:9092
              topicName: myTopic
              authentication:
                type: SASL_SCRAM_256_AUTH
                properties:
                  authenticationSecretArn: arn:aws:secretsmanager:eu-west-1:xxxxxxxxxxx:secret:mySecret
KafkaTopicIntegrationAPI referenceParent:LambdaFunction
typeRequired
No description

Type: string "kafka-topic"

properties.customKafkaConfiguration

The details of your Kafka cluster.

Type: CustomKafkaEventSource

Specifies the bootstrap servers and topic name.

properties.batchSizeDefault: 100

The maximum number of records to process in a single batch.

Type: number

The function will be invoked with up to this many records. Maximum is 10,000.

properties.maxBatchWindowSecondsDefault: 0.5

The maximum time (in seconds) to wait before invoking the function with a batch of records.

Type: number

The function will be triggered when either the batchSize is reached or this time window expires. Maximum is 300 seconds.


SNS event

Triggers the function when a message is published to an SNS topic.

resources:
  myLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: path/to/my-lambda.ts
      events:
        - type: sns
          properties:
            snsTopicName: mySnsTopic

  mySnsTopic:
    type: sns-topic
SnsIntegrationAPI referenceParent:LambdaFunction
typeRequired
No description

Type: string "sns"

properties.snsTopicName

The name of an SNS topic defined in your stack's resources.

Type: string

You must specify either snsTopicName or snsTopicArn.

properties.snsTopicArn

The ARN of an existing SNS topic.

Type: string

Use this to subscribe to a topic that is not managed by your stack. You must specify either snsTopicName or snsTopicArn.

properties.filterPolicy
No description

Type: UNSPECIFIED

properties.onDeliveryFailure

A destination for messages that fail to be delivered to the target.

Type: SnsOnDeliveryFailure

In rare cases (e.g., if the target function cannot scale fast enough), a message might fail to be delivered. This property specifies an SQS queue where failed messages will be sent.


SQS event

Triggers the function when messages are available in an SQS queue.

resources:
  myLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: path/to/my-lambda.ts
      events:
        - type: sqs
          properties:
            sqsQueueName: mySqsQueue

  mySqsQueue:
    type: sqs-queue
SqsIntegrationAPI referenceParent:LambdaFunction
typeRequired
No description

Type: string "sqs"

properties.sqsQueueName

The name of an SQS queue defined in your stack's resources.

Type: string

You must specify either sqsQueueName or sqsQueueArn.

properties.sqsQueueArn

The ARN of an existing SQS queue.

Type: string

Use this to consume messages from a queue that is not managed by your stack. You must specify either sqsQueueName or sqsQueueArn.

properties.batchSizeDefault: 10

The maximum number of records to process in a single batch.

Type: number

Maximum is 10,000.

properties.maxBatchWindowSeconds

The maximum time (in seconds) to wait before invoking the function with a batch of records.

Type: number

Maximum is 300 seconds. If not set, the function is invoked as soon as messages are available.


Kinesis stream event

Triggers the function when records are available in a Kinesis Data Stream.

resources:
  myLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: 'path/to/my-lambda.ts'
      events:
        - type: kinesis-stream
          properties:
            autoCreateConsumer: true
            maxBatchWindowSeconds: 30
            batchSize: 200
            streamArn: $CfResourceParam('myKinesisStream', 'Arn')
            onFailure:
              arn: $CfResourceParam('myOnFailureSqsQueue', 'Arn')
              type: sqs

cloudformationResources:
  myKinesisStream:
    Type: AWS::Kinesis::Stream
    Properties:
      ShardCount: 1

  myOnFailureSqsQueue:
    Type: AWS::SQS::Queue
KinesisIntegrationAPI referenceParent:LambdaFunction
typeRequired
No description

Type: string "kinesis-stream"

properties.kinesisStreamName

The name of a Kinesis stream defined in your stack's resources.

Type: string

You must specify either kinesisStreamName or streamArn.

properties.streamArn

The ARN of an existing Kinesis stream to consume records from.

Type: string

Use this to consume from a stream that is not managed by your stack. You must specify either kinesisStreamName or streamArn.

properties.consumerArn

The ARN of a specific stream consumer to use.

Type: string

This cannot be used with autoCreateConsumer.

properties.autoCreateConsumer

Automatically creates a dedicated stream consumer for this integration.

Type: boolean

This is recommended for minimizing latency and maximizing throughput. For more details, see the AWS documentation on stream consumers. This cannot be used with consumerArn.

properties.maxBatchWindowSeconds

The maximum time (in seconds) to wait before invoking the function with a batch of records.

Type: number

Maximum is 300 seconds.

properties.batchSizeDefault: 10

The maximum number of records to process in a single batch.

Type: number

Maximum is 10,000.

properties.startingPositionDefault: TRIM_HORIZON

The position in the stream from which to start reading records.

Type: string ENUM

Possible values: LATESTTRIM_HORIZON

  • LATEST: Read only new records.
  • TRIM_HORIZON: Read all available records from the beginning of the stream.
properties.maximumRetryAttempts

The number of times to retry a failed batch of records.

Type: number

Important: If an error occurs, the entire batch is retried, including records that were processed successfully. Your function should be idempotent to handle this.

properties.onFailure

A destination (SQS queue or SNS topic) for batches that fail after all retry attempts.

Type: DestinationOnFailure

properties.parallelizationFactor

The number of batches to process concurrently from the same shard.

Type: number

properties.bisectBatchOnFunctionError

Splits a failed batch in two before retrying.

Type: boolean

This can be useful if a failure is caused by a batch being too large.


DynamoDB stream event

Triggers the function in response to item-level changes in a DynamoDB table.

resources:
  myDynamoDbTable:
    type: dynamo-db-table
    properties:
      primaryKey:
        partitionKey:
          name: id
          type: string
      streamType: NEW_AND_OLD_IMAGES

  myLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: path/to/my-lambda.ts
      events:
        - type: dynamo-db-stream
          properties:
            streamArn: $ResourceParam('myDynamoDbTable', 'streamArn')
            # OPTIONAL
            batchSize: 200
DynamoDbIntegrationAPI referenceParent:LambdaFunction
typeRequired
No description

Type: string "dynamo-db-stream"

properties.streamArnRequired

The ARN of the DynamoDB table stream.

Type: string

properties.maxBatchWindowSeconds

The maximum time (in seconds) to wait before invoking the function with a batch of records.

Type: number

Maximum is 300 seconds.

properties.batchSizeDefault: 100

The maximum number of records to process in a single batch.

Type: number

Maximum is 1,000.

properties.startingPositionDefault: TRIM_HORIZON

The position in the stream from which to start reading records.

Type: string

  • LATEST: Read only new records.
  • TRIM_HORIZON: Read all available records from the beginning of the stream.
properties.maximumRetryAttempts

The number of times to retry a failed batch of records.

Type: number

Important: If an error occurs, the entire batch is retried, including records that were processed successfully. Your function should be idempotent to handle this.

properties.onFailure

A destination (SQS queue or SNS topic) for batches that fail after all retry attempts.

Type: DestinationOnFailure

properties.parallelizationFactor

The number of batches to process concurrently from the same shard.

Type: number

properties.bisectBatchOnFunctionError

Splits a failed batch in two before retrying.

Type: boolean

This can be useful if a failure is caused by a batch being too large.


S3 event

Triggers the function in response to events in an S3 bucket.

resources:
  myBucket:
    type: bucket

  myLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: path/to/my-lambda.ts
      events:
        - type: s3
          properties:
            bucketArn: $ResourceParam('myBucket', 'arn')
            s3EventType: 's3:ObjectCreated:*'
            filterRule:
              prefix: order-
              suffix: .jpg
S3IntegrationAPI referenceParent:LambdaFunction
typeRequired
No description

Type: string "s3"

properties.bucketArnRequired

The ARN of the S3 bucket to monitor for events.

Type: string

properties.s3EventTypeRequired

The type of S3 event that will trigger the function.

Type: string ENUM

Possible values: s3:ObjectCreated:*s3:ObjectCreated:CompleteMultipartUploads3:ObjectCreated:Copys3:ObjectCreated:Posts3:ObjectCreated:Puts3:ObjectRemoved:*s3:ObjectRemoved:Deletes3:ObjectRemoved:DeleteMarkerCreateds3:ObjectRestore:*s3:ObjectRestore:Completeds3:ObjectRestore:Posts3:ReducedRedundancyLostObjects3:Replication:*s3:Replication:OperationFailedReplications3:Replication:OperationMissedThresholds3:Replication:OperationNotTrackeds3:Replication:OperationReplicatedAfterThreshold

properties.filterRule

A filter to apply to objects, so the function is only triggered for relevant objects.

Type: S3FilterRule

S3FilterRuleAPI referenceParent:S3Integration
prefix

The prefix that an object's key must have to trigger the function.

Type: string

suffix

The suffix that an object's key must have to trigger the function.

Type: string


Cloudwatch Log event

Triggers the function when a log record is added to a CloudWatch log group.

resources:
  myLogProducingLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: lambdas/log-producer.ts
  myLogConsumingLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: lambdas/log-consumer.ts
      events:
        - type: cloudwatch-log
          properties:
            logGroupArn: $ResourceParam('myLogProducingLambda', 'arn')
CloudwatchLogIntegrationAPI referenceParent:LambdaFunction
typeRequired
No description

Type: string "cloudwatch-log"

properties.logGroupArnRequired

The ARN of the log group to watch for new records.

Type: string

properties.filter

A filter pattern to apply to the log records.

Type: string

Only logs that match this pattern will trigger the function. For details on the syntax, see the AWS documentation on filter and pattern syntax.


Alarm event

Triggers the function when a CloudWatch alarm enters the ALARM state. You can reference alarms created in the Stacktape Console or directly in your configuration file.

resources:
  myDatabase:
    type: relational-database
    properties:
      engine:
        type: aurora-mysql-serverless
      credentials:
        masterUserPassword: my-master-password
      alarms:
        # alarm fires when cpu utilization is higher than 80%
        - trigger:
            type: database-cpu-utilization
            properties:
              thresholdPercent: 80

  myFunction:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: 'lambdas/cleanup-function.js'
      events:
        - type: cloudwatch-alarm
          properties:
            alarmName: myDatabase.alarms.0
resources:
  myDatabase:
    type: relational-database
    properties:
      engine:
        type: aurora-mysql-serverless
      credentials:
        masterUserPassword: my-master-password

  myFunction:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: 'lambdas/cleanup-function.js'
      events:
        - type: cloudwatch-alarm
          properties:
            alarmName: myDatabase.alarms.CpuUtilization

Application Load Balancer event

Triggers the function when an Application Load Balancer receives a request matching specified rules.

resources:
  # load balancer which routes traffic to the function
  myLoadBalancer:
    type: application-load-balancer

  myLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: path/to/my-lambda.ts
      events:
        - type: application-load-balancer
          properties:
            # referencing load balancer defined above
            loadBalancerName: myLoadBalancer
            priority: 1
            paths:
              - /invoke-my-lambda
              - /another-path
ApplicationLoadBalancerIntegrationAPI referenceParent:LambdaFunction
typeRequired

Triggers a function when an Application Load Balancer receives a matching HTTP request.

Type: string "application-load-balancer"

You can route requests based on HTTP method, path, headers, query parameters, and source IP address.

properties.loadBalancerNameRequired

The name of the Application Load Balancer.

Type: string

This must reference a load balancer defined in your Stacktape configuration.

properties.priorityRequired

The priority of this integration rule.

Type: number

Load balancer rules are evaluated in order from the lowest priority to the highest. The first rule that matches an incoming request will handle it.

properties.listenerPort

The port of the load balancer listener to attach to.

Type: number

You only need to specify this if the load balancer uses custom listeners.

properties.paths

A list of URL paths that will trigger this integration.

Type: Array of string

The request will be routed if its path matches any of the paths in this list. The comparison is case-sensitive and supports * and ? wildcards.

Example: /users, /articles/*

properties.methods

A list of HTTP methods that will trigger this integration.

Type: Array of string

Example: GET, POST, DELETE

properties.hosts

A list of hostnames that will trigger this integration.

Type: Array of string

The hostname is parsed from the Host header of the request. Wildcards (* and ?) are supported.

Example: api.example.com, *.myapp.com

properties.headers

A list of header conditions that the request must match.

Type: Array of LbHeaderCondition

All header conditions must be met for the request to be routed.

properties.queryParams

A list of query parameter conditions that the request must match.

Type: Array of LbQueryParamCondition

All query parameter conditions must be met for the request to be routed.

properties.sourceIps

A list of source IP addresses (in CIDR format) that are allowed to trigger this integration.

Type: Array of string

Note: If the client is behind a proxy, this will be the IP address of the proxy.

Sync vs. Async invocations

Functions can be invoked synchronously or asynchronously, depending on the trigger.

Synchronous invocation

The caller waits for the function to complete and returns its result. This is used by API Gateway, Application Load Balancer, and direct SDK calls.

Asynchronous invocation

The caller queues the function for execution and does not wait for the result. This is used by SNS, SQS, EventBridge, S3, and others. If an asynchronously invoked function fails, AWS Lambda will automatically retry it up to two times.

Lambda Destinations

For asynchronous invocations, you can configure destinations to handle the results. You can send the output of a function to another service (like SQS, SNS, or another Lambda) on success or failure.

resources:
  myEventBus:
    type: event-bus

  mySuccessLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: lambdas/success-handler.ts

  myLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: path/to/my-lambda.ts
      destinations:
        # if function succeeds, invoke the mySuccessLambda with the result data
        onSuccess: $ResourceParam('mySuccessLambda', 'arn')
        # if the function fails, send the result to "myEventBus"
        onFailure: $ResourceParam('myEventBus', 'arn')
LambdaFunctionDestinationsAPI referenceParent:LambdaFunction
onSuccess

ARN to receive the result when the function succeeds (SQS, SNS, EventBus, or Lambda ARN).

Type: string

onFailure

ARN to receive error details when the function fails. Useful for dead-letter processing.

Type: string

Accessing other resources

By default, functions cannot access other AWS resources. You must grant permissions explicitly using IAM.

Using connectTo

The connectTo property is a simplified way to grant access to other Stacktape-managed resources.

resources:
  myLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: path/to/my-lambda.ts
      environment:
        - name: MY_BUCKET_NAME
          value: $ResourceParam('myBucket', 'name')
      connectTo:
        # access to the bucket
        - myBucket
        # access to AWS SES
        - aws:ses

  myBucket:
    type: bucket

List the names of resources this workload needs to communicate with. Stacktape automatically:

  • Grants IAM permissions (e.g., S3 read/write, SQS send/receive)
  • Opens network access (security group rules for databases, Redis)
  • Injects environment variables with connection details: STP_[RESOURCE_NAME]_[PARAM]

Example: connectTo: ["myDatabase", "myBucket"] gives this workload full access to both resources and injects STP_MY_DATABASE_CONNECTION_STRING, STP_MY_BUCKET_NAME, etc.

Using iamRoleStatements

For fine-grained control, you can provide raw IAM role statements.

resources:
  myFunction:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: path/to/my-lambda.ts
      environment:
        - name: TOPIC_ARN
          value: $CfResourceParam('NotificationTopic', 'Arn')
      iamRoleStatements:
        - Resource:
            - $CfResourceParam('NotificationTopic', 'Arn')
          Effect: 'Allow'
          Action:
            - 'sns:Publish'

cloudformationResources:
  NotificationTopic:
    Type: AWS::SNS::Topic

Deployment strategies

Instead of switching all traffic to the new version instantly, shift it gradually (canary or linear). If issues arise, traffic rolls back automatically.

LambdaDeploymentConfigAPI referenceParent:LambdaFunction
strategyRequired

How traffic shifts from the old version to the new one.

Type: string ENUM

Possible values: AllAtOnceCanary10Percent10MinutesCanary10Percent15MinutesCanary10Percent30MinutesCanary10Percent5MinutesLinear10PercentEvery10MinutesLinear10PercentEvery1MinuteLinear10PercentEvery2MinutesLinear10PercentEvery3Minutes

  • Canary: Send 10% of traffic first, then all traffic after a wait period.
  • Linear: Shift 10% of traffic at regular intervals.
  • AllAtOnce: Instant switch (no gradual rollout).
beforeAllowTrafficFunction

Function to run before traffic shifting begins (e.g., smoke tests).

Type: string

Must signal success/failure to CodeDeploy. If it fails, the deployment rolls back.

afterTrafficShiftFunction

Function to run after all traffic has shifted (e.g., post-deploy validation).

Type: string

Must signal success/failure to CodeDeploy.

resources:
  myLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: path/to/my-lambda.ts
      deployment:
        strategy: Linear10PercentEvery1Minute

Hook functions

You can use hook functions to perform checks during deployment.

resources:
  myLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: path/to/my-lambda.ts
      deployment:
        strategy: Linear10PercentEvery1Minute
        beforeAllowTrafficFunction: validateDeployment

  validateDeployment:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: validate.ts
import { CodeDeployClient, PutLifecycleEventHookExecutionStatusCommand } from '@aws-sdk/client-codedeploy';

const client = new CodeDeployClient({});

export default async (event) => {
  // read DeploymentId and LifecycleEventHookExecutionId from payload
  const { DeploymentId, LifecycleEventHookExecutionId } = event;

  // performing validations here

  await client.send(
    new PutLifecycleEventHookExecutionStatusCommand({
      deploymentId: DeploymentId,
      lifecycleEventHookExecutionId: LifecycleEventHookExecutionId,
      status: 'Succeeded' // status can be 'Succeeded' or 'Failed'
    })
  );
};

Cold starts

A cold start is the latency experienced on the first invocation of a function after a period of inactivity. This happens because AWS needs to provision a new container to run your code. Subsequent invocations are much faster until the container is terminated due to inactivity.

The duration of a cold start depends on the runtime, the size of your function package, and the amount of code that runs outside your main handler.

Default VPC connection

Functions are not connected to a VPC by default. If your function needs to access resources inside a VPC (like a Relational Database), you must explicitly connect it.

Connecting a function to a VPC will cut off its access to the public internet. Restoring internet access requires a NAT Gateway, which can be complex and costly.

resources:
  myLambda:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: path/to/my-lambda.ts
      joinDefaultVpc: true

Function connected to the default VPC.

Pricing

You are charged for:

  • Total compute: A combination of memory allocated and execution time.
  • Number of requests: A flat rate per million invocations.

AWS offers a generous free tier for Lambda. For details, see the AWS pricing page.

Referenceable parameters

The following parameters can be easily referenced using $ResourceParam directive directive.

To learn more about referencing parameters, refer to referencing parameters.

arn
  • Arn of the function

  • Usage: $ResourceParam('<<resource-name>>', 'arn')
logGroupArn
  • Arn of the log group aggregating logs from the function

  • Usage: $ResourceParam('<<resource-name>>', 'logGroupArn')

API reference

LambdaFunctionAPI reference
typeRequired
No description

Type: string "function"

properties.packagingRequired

How your code is built and packaged for deployment.

Type: LambdaPackaging

  • stacktape-lambda-buildpack (recommended): Point to your source file and Stacktape builds, bundles, and uploads it automatically.
  • custom-artifact: Provide a pre-built zip file. Stacktape handles the upload.
properties.events

What triggers this function: HTTP requests, file uploads, queues, schedules, etc.

Type: Array of ApplicationLoadBalancerIntegration or KafkaTopicIntegration or SnsIntegration or SqsIntegration or KinesisIntegration or DynamoDbIntegration or S3Integration or ScheduleIntegration or AlarmIntegration or CloudwatchLogIntegration or HttpApiIntegration or EventBusIntegration

Stacktape auto-configures permissions for each trigger. The event payload your function receives depends on the trigger type.

properties.environment

Environment variables available to the function at runtime.

Type: Array of EnvironmentVar

Variables from connectTo (e.g., STP_MY_DATABASE_CONNECTION_STRING) are added automatically.

properties.runtime

The language runtime (e.g., nodejs22.x, python3.13).

Type: string ENUM

Possible values: dotnet6dotnet7dotnet8java11java17java8java8.al2nodejs18.xnodejs20.xnodejs22.xnodejs24.xprovided.al2provided.al2023python3.10python3.11python3.12python3.13python3.8python3.9ruby3.3

Auto-detected from your source file extension when using stacktape-lambda-buildpack. Override only if you need a specific version.

properties.architectureDefault: x86_64

Processor architecture: x86_64 (default) or arm64 (Graviton, ~20% cheaper).

Type: string ENUM

Possible values: arm64x86_64

arm64 is cheaper per GB-second and often faster. Works with most code out of the box. If using stacktape-lambda-buildpack, Stacktape builds for the selected architecture automatically. With custom-artifact, you must pre-compile for the target architecture.

properties.memory

Memory in MB (128 - 10,240). Also determines CPU power.

Type: number

Lambda scales CPU proportionally to memory: 1,769 MB = 1 vCPU, 3,538 MB = 2 vCPUs, etc. If your function is slow, increasing memory gives it more CPU, which often makes it faster and cheaper overall (less execution time).

properties.timeoutDefault: 10

Max execution time in seconds. Function is killed if it exceeds this.

Type: number

Maximum: 900 seconds (15 minutes). For longer tasks, use a batch-job or worker-service.

properties.joinDefaultVpc

Connects the function to your VPC so it can reach databases, Redis, and other VPC-only resources.

Type: boolean

You usually don't need to set this manually. Stacktape will tell you if a resource in your connectTo requires it (e.g., a database with accessibilityMode: 'vpc', or any Redis cluster).

Tradeoff: The function loses direct internet access. It can still reach S3 and DynamoDB (Stacktape auto-creates VPC endpoints), but calls to external APIs (Stripe, OpenAI, etc.) will fail. If you need both VPC access and internet, use a web-service or worker-service instead.

Required when using volumeMounts (EFS).

properties.tags

Additional tags for this function (on top of stack-level tags). Max 50.

Type: Array of CloudformationTag

properties.destinations

Route async invocation results to another service (SQS, SNS, EventBus, or another function).

Type: LambdaFunctionDestinations

Useful for building event-driven workflows: send successful results to one destination and failures to another for error handling.

properties.logging

Logging configuration (retention, forwarding).

Type: LambdaFunctionLogging

Logs (stdout/stderr) are auto-sent to CloudWatch. View with stacktape logs or in the Stacktape Console.

properties.provisionedConcurrency

Eliminates cold starts by keeping function instances warm and ready.

Type: number

When a function hasn't been called recently, the first request can take 1-5+ seconds ("cold start"). This setting pre-warms the specified number of instances so they respond instantly.

When to use: User-facing APIs, web/mobile backends, or any function where response time matters. Skip this for background jobs, cron tasks, or data pipelines.

Cost: You pay for each provisioned instance even when idle. Also increases deploy time by ~2-5 minutes.

properties.reservedConcurrency

Cap the maximum number of concurrent instances for this function.

Type: number

Reserves this many execution slots exclusively for this function — other functions can't use them, and this function can't scale beyond it. No additional cost.

Common uses:

  • Prevent overwhelming a database with too many connections
  • Guarantee capacity for critical functions
  • Throttle expensive downstream API calls
properties.layers

Lambda Layer ARNs to attach (shared libraries, custom runtimes, etc.).

Type: Array of string

Layers are zip archives with additional code/data mounted into the function. Provide the layer ARN (e.g., from AWS console or another stack). Max 5 layers per function.

properties.deployment

Gradual traffic shifting for safe deployments.

Type: LambdaDeploymentConfig

Instead of switching all traffic to the new version instantly, shift it gradually (canary or linear). If issues arise, traffic rolls back automatically.

properties.alarms

Alarms for this function (merged with global alarms from the Stacktape Console).

Type: Array of LambdaAlarm

properties.disabledGlobalAlarms

Global alarm names to exclude from this function.

Type: Array of string

properties.url

Give this function its own HTTPS URL (no API Gateway needed).

Type: LambdaUrlConfig

Simpler and cheaper than an API Gateway for single-function endpoints. URL format: https://{id}.lambda-url.{region}.on.aws

properties.cdn

Put a CDN (CloudFront) in front of this function for caching and lower latency.

Type: CdnConfiguration

Caches responses at edge locations worldwide. Reduces function invocations and bandwidth costs.

properties.storageDefault: 512

Size of the /tmp directory in MB (512 - 10,240). Ephemeral per invocation.

Type: number

Increase if your function downloads/processes large files temporarily.

properties.volumeMounts

Persistent EFS storage shared across invocations and functions.

Type: Array of LambdaEfsMount

Unlike /tmp, EFS data persists indefinitely and can be shared across multiple functions. Requires joinDefaultVpc: true (Stacktape will remind you if you forget).

properties.connectTo

Give this resource access to other resources in your stack.

Type: Array of string

List the names of resources this workload needs to communicate with. Stacktape automatically:

  • Grants IAM permissions (e.g., S3 read/write, SQS send/receive)
  • Opens network access (security group rules for databases, Redis)
  • Injects environment variables with connection details: STP_[RESOURCE_NAME]_[PARAM]

Example: connectTo: ["myDatabase", "myBucket"] gives this workload full access to both resources and injects STP_MY_DATABASE_CONNECTION_STRING, STP_MY_BUCKET_NAME, etc.

properties.iamRoleStatements

Raw IAM policy statements for permissions not covered by connectTo.

Type: Array of StpIamRoleStatement

Added as a separate policy alongside auto-generated permissions. Use this for accessing AWS services directly (e.g., Rekognition, Textract, Bedrock).

overrides

Escape hatch to modify the underlying CloudFormation resources Stacktape creates.

Type: Object

Use dot-notation paths to override specific properties on any child resource. Find resource logical IDs with stacktape stack-info --detailed.

overrides:
  MyDbInstance:
    Properties.StorageEncrypted: true
EventInputTransformerAPI referenceParent:EventBusIntegration or ScheduleIntegration
inputTemplateRequired
No description

Type: UNSPECIFIED

inputPathsMap
No description

Type: UNSPECIFIED

EventBusIntegrationPatternAPI referenceParent:EventBusIntegration
version
No description

Type: UNSPECIFIED

detail-type
No description

Type: UNSPECIFIED

source
No description

Type: UNSPECIFIED

account
No description

Type: UNSPECIFIED

region
No description

Type: UNSPECIFIED

resources
No description

Type: UNSPECIFIED

detail
No description

Type: UNSPECIFIED

replay-name
No description

Type: UNSPECIFIED

CustomKafkaEventSourceAPI referenceParent:KafkaTopicIntegration
bootstrapServersRequired

A list of host:port addresses for your Kafka brokers.

Type: Array of string

topicNameRequired

The name of the Kafka topic to consume messages from.

Type: string

authenticationRequired

The authentication method for connecting to the Kafka cluster.

Type: KafkaSASLAuth or KafkaMTLSAuth

  • SASL: Authenticate using a username and password (PLAIN or SCRAM).
  • MTLS: Authenticate using a client-side TLS certificate.
KafkaSASLAuthAPI referenceParent:CustomKafkaEventSource
typeRequired

The SASL authentication protocol.

Type: string ENUM

Possible values: BASIC_AUTHSASL_SCRAM_256_AUTHSASL_SCRAM_512_AUTH

  • BASIC_AUTH: SASL/PLAIN
  • SASL_SCRAM_256_AUTH: SASL SCRAM-256
  • SASL_SCRAM_512_AUTH: SASL SCRAM-512
properties.authenticationSecretArnRequired

The ARN of a secret containing the Kafka credentials.

Type: string

The secret must be a JSON object with username and password keys. You can create secrets using the stacktape secret:create command.

KafkaMTLSAuthAPI referenceParent:CustomKafkaEventSource
typeRequired

The authentication protocol.

Type: string "MTLS"

MTLS: Mutual TLS authentication.

properties.clientCertificateRequired

The ARN of a secret containing the client certificate.

Type: string

This secret should contain the certificate chain (X.509 PEM), private key (PKCS#8 PEM), and an optional private key password. You can create secrets using the stacktape secret:create command.

properties.serverRootCaCertificate

The ARN of a secret containing the server's root CA certificate.

Type: string

You can create secrets using the stacktape secret:create command.

EventInputTransformerAPI referenceParent:EventBusIntegration or ScheduleIntegration
inputTemplateRequired
No description

Type: UNSPECIFIED

inputPathsMap
No description

Type: UNSPECIFIED

SnsOnDeliveryFailureAPI referenceParent:SnsIntegration
sqsQueueArn

The ARN of the SQS queue for failed messages.

Type: string

sqsQueueName

The name of an SQS queue (defined in your Stacktape configuration) for failed messages.

Type: string

DestinationOnFailureAPI referenceParent:DynamoDbIntegration or KinesisIntegration
arnRequired

The ARN of the SNS topic or SQS queue for failed batches.

Type: string

typeRequired

The type of the destination.

Type: string ENUM

Possible values: snssqs

LbHeaderConditionAPI referenceParent:ApplicationLoadBalancerIntegration
headerNameRequired

The name of the HTTP header.

Type: string

valuesRequired

A list of allowed values for the header.

Type: Array of string

The condition is met if the header's value in the incoming request matches any of the values in this list. The comparison is case-insensitive.

LbQueryParamConditionAPI referenceParent:ApplicationLoadBalancerIntegration
paramNameRequired

The name of the query parameter.

Type: string

valuesRequired

A list of allowed values for the query parameter.

Type: Array of string

The condition is met if the query parameter's value in the incoming request matches any of the values in this list. The comparison is case-insensitive.

EnvironmentVarAPI referenceParent:LambdaFunction
nameRequired

Environment variable name (e.g., DATABASE_URL, API_KEY).

Type: string

valueRequired

Environment variable value. Numbers and booleans are converted to strings.

Type: string or number or boolean

CloudformationTagAPI referenceParent:LambdaFunction
nameRequired

Tag name (1-128 characters).

Type: string

valueRequired

Tag value (1-256 characters).

Type: string

StpIamRoleStatementAPI referenceParent:LambdaFunction
ResourceRequired

ARNs of the AWS resources this statement applies to. Use "*" for all resources.

Type: Array of string

Sid

Optional identifier for this statement (for readability).

Type: string

EffectDefault: Allow

Whether to allow or deny the specified actions.

Type: string

Action

AWS actions to allow or deny (e.g., s3:GetObject, sqs:SendMessage).

Type: Array of string

Condition
No description

Type: UNSPECIFIED