Stacktape
Stacktape


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

Stacktape automatically detects the programming language and selects the latest appropriate runtime. For example, .ts and .js files will use a recent Node.js runtime. For a full list of available runtimes, see the AWS Lambda runtimes documentation.

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.

LambdaFunctionLogging  API reference
disabled
retentionDays
Default: 180
logForwarding

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
HttpApiIntegration  API reference
type
Required
properties.httpApiGatewayName
Required
properties.method
Required
properties.path
Required
properties.authorizer
properties.payloadFormat
Default: '1.0'

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;
CognitoAuthorizer  API reference
type
Required
properties.userPoolName
Required
properties.identitySources

Lambda authorizer

Uses another Lambda function to authorize incoming requests.

LambdaAuthorizer  API reference
type
Required
properties.functionName
Required
properties.iamResponse
properties.identitySources
properties.cacheResultSeconds

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 * * ? *)
ScheduleIntegration  API reference
type
Required
properties.scheduleRate
Required
properties.input
properties.inputPath
properties.inputTransformer

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'
EventBusIntegration  API reference
type
Required
properties.eventPattern
Required
properties.eventBusArn
properties.eventBusName
properties.useDefaultBus
properties.onDeliveryFailure
properties.input
properties.inputPath
properties.inputTransformer

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
KafkaTopicIntegration  API reference
type
Required
properties.customKafkaConfiguration
properties.batchSize
Default: 100
properties.maxBatchWindowSeconds
Default: 0.5

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
SnsIntegration  API reference
type
Required
properties.snsTopicName
properties.snsTopicArn
properties.filterPolicy
properties.onDeliveryFailure

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
SqsIntegration  API reference
type
Required
properties.sqsQueueName
properties.sqsQueueArn
properties.batchSize
Default: 10
properties.maxBatchWindowSeconds

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
KinesisIntegration  API reference
type
Required
properties.streamArn
Required
properties.consumerArn
properties.autoCreateConsumer
properties.maxBatchWindowSeconds
properties.batchSize
Default: 10
properties.startingPosition
Default: TRIM_HORIZON
properties.maximumRetryAttempts
properties.onFailure
properties.parallelizationFactor
properties.bisectBatchOnFunctionError

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
DynamoDbIntegration  API reference
type
Required
properties.streamArn
Required
properties.maxBatchWindowSeconds
properties.batchSize
Default: 100
properties.startingPosition
Default: TRIM_HORIZON
properties.maximumRetryAttempts
properties.onFailure
properties.parallelizationFactor
properties.bisectBatchOnFunctionError

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
S3Integration  API reference
type
Required
properties.bucketArn
Required
properties.s3EventType
Required
properties.filterRule
S3FilterRule  API reference
prefix
suffix

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')
CloudwatchLogIntegration  API reference
type
Required
properties.logGroupArn
Required
properties.filter

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
ApplicationLoadBalancerIntegration  API reference
type
Required
properties.loadBalancerName
Required
properties.priority
Required
properties.listenerPort
properties.paths
properties.methods
properties.hosts
properties.headers
properties.queryParams
properties.sourceIps

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')
LambdaFunctionDestinations  API reference
onSuccess
onFailure

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

Configures access to other resources in your stack and AWS services. By specifying resources here, Stacktape automatically:

  • Configures IAM role permissions.
  • Sets up security group rules to allow network traffic.
  • Injects environment variables with connection details into the compute resource.

Environment variables are named STP_[RESOURCE_NAME]_[VARIABLE_NAME] (e.g., STP_MY_DATABASE_CONNECTION_STRING).

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

This allows for safe, gradual deployments. Instead of instantly replacing the old version, traffic is shifted to the new version over time. This provides an opportunity to monitor for issues and roll back if necessary.

Supported strategies include:

  • Canary: A percentage of traffic is shifted to the new version for a specified time before routing all traffic.
  • Linear: Traffic is shifted in equal increments over a specified period.
  • AllAtOnce: All traffic is shifted to the new version immediately.
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

LambdaFunction  API reference
type
Required
properties.packaging
Required
properties.events
properties.environment
properties.runtime
properties.architecture
Default: x86_64
properties.memory
properties.timeout
Default: 10
properties.joinDefaultVpc
properties.tags
properties.destinations
properties.logging
properties.provisionedConcurrency
properties.reservedConcurrency
properties.layers
properties.deployment
properties.alarms
properties.disabledGlobalAlarms
properties.url
properties.cdn
properties.storage
Default: 512
properties.volumeMounts
properties.connectTo
properties.iamRoleStatements
overrides
EventInputTransformer  API reference
Parent:EventBusIntegrationorScheduleIntegration
inputTemplate
Required
inputPathsMap
EventBusIntegrationPattern  API reference
version
detail-type
source
account
region
resources
detail
replay-name
CustomKafkaEventSource  API reference
bootstrapServers
Required
topicName
Required
authentication
Required
KafkaSASLAuth  API reference
type
Required
properties.authenticationSecretArn
Required
KafkaMTLSAuth  API reference
type
Required
properties.clientCertificate
Required
properties.serverRootCaCertificate
EventInputTransformer  API reference
inputTemplate
Required
inputPathsMap
SnsOnDeliveryFailure  API reference
sqsQueueArn
sqsQueueName
DestinationOnFailure  API reference
arn
Required
type
Required
LbHeaderCondition  API reference
headerName
Required
values
Required
LbQueryParamCondition  API reference
paramName
Required
values
Required
EnvironmentVar  API reference
name
Required
value
Required
CloudformationTag  API reference
name
Required
value
Required
StpIamRoleStatement  API reference
Resource
Required
Sid
Effect
Default: Allow
Action
Condition

Contents