Lambda Function

A Stacktape Lambda function is a serverless compute resource that runs code in response to events — HTTP requests, queues, schedules, file uploads, and more. Lambda functions scale automatically from zero, bill only for consumed compute time, and require no server management. Underneath, Stacktape deploys to AWS Lambda.

Pricing: Lambda bills per GB-second of compute time. The arm64 architecture is ~20% cheaper per GB-second than the default x86_64. Provisioned concurrency adds cost even when instances are idle.

When to use

A Lambda function is the right default for event-driven code that finishes within minutes, does not need a continuously running process, and can tolerate statelessness between invocations.

When NOT to use

  • Tasks longer than 15 minutes — the maximum timeout is 900 seconds. For processing that can exceed 15 minutes, use a batch job or worker service.
  • Always-on HTTP servers — use a web service when you need a continuously running container or a container-native web framework.
  • VPC access with heavy internet egress — joinDefaultVpc removes direct internet access (S3 and DynamoDB stay reachable via VPC endpoints). Setting stackConfig.nat gives VPC functions internet access through NAT; for a workload that pushes a lot of traffic out, a web service or worker service in the public subnets avoids the NAT entirely.
  • Persistent local state — /tmp is ephemeral per invocation. Use EFS, an S3 bucket, or a database for persistent data.
  • Custom OS or daemon requirements — Stacktape Lambda packaging builds a zip from source (js-bundle, buildpack) or uses your own zip (custom-artifact). If you need image-level control over system packages or daemons, use a container workload or web service.

Basic example

A Lambda function with an HTTP API Gateway trigger. Stacktape builds the function from entryfilePath, detects the runtime from the file extension, and auto-configures the trigger permissions.

export default defineConfig(() => {
  const apiGateway = new HttpApiGateway({});

  const getUser = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({
      entryfilePath: './src/get-user.ts'
    }),
    events: [
      {
        type: 'http-api-gateway',
        properties: {
          httpApiGatewayName: 'apiGateway',
          method: 'GET',
          path: '/users/{id}'
        }
      }
    ],
    memory: 1024,
    timeout: 30
  });

  return { resources: { apiGateway, getUser } };
});

entryfilePath points to the handler source file relative to the config file. memory: 1024 allocates 1,024 MB and proportional CPU (1,769 MB = 1 vCPU). timeout: 30 stops the invocation after 30 seconds; the default is 10 and the maximum is 900.

A minimal TypeScript handler for this route:

export async function handler(event: { pathParameters?: { id?: string } }) {
  return {
    statusCode: 200,
    body: JSON.stringify({ id: event.pathParameters?.id })
  };
}

Examples

HTTP API with DynamoDB

A complete Stacktape config for a Hono API connected to a DynamoDB table through an HTTP API Gateway. The connectTo property grants IAM permissions and injects the STP_USERS_TABLE_NAME and STP_USERS_TABLE_ARN environment variables automatically.

export default defineConfig(() => {
  const apiGateway = new HttpApiGateway({});

  const usersTable = new DynamoDbTable({
    primaryKey: { partitionKey: { name: 'userId', type: 'string' } }
  });

  const api = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({
      entryfilePath: './src/api.ts'
    }),
    events: [
      {
        type: 'http-api-gateway',
        properties: {
          httpApiGatewayName: 'apiGateway',
          method: '*',
          path: '/{proxy+}'
        }
      }
    ],
    connectTo: [usersTable],
    memory: 512,
    timeout: 30
  });

  return { resources: { apiGateway, usersTable, api } };
});

A Hono handler using the injected environment variables for read and write operations:

import { Hono } from 'hono';
import { handle } from 'hono/aws-lambda';
import { DynamoDBClient, GetItemCommand, PutItemCommand } from '@aws-sdk/client-dynamodb';

const app = new Hono();
const client = new DynamoDBClient({});
const tableName = process.env.STP_USERS_TABLE_NAME!;

app.get('/users/:id', async (c) => {
  const result = await client.send(new GetItemCommand({
    TableName: tableName,
    Key: { userId: { S: c.req.param('id') } }
  }));
  return c.json(result.Item ?? {});
});

app.post('/users', async (c) => {
  const body = await c.req.json();
  await client.send(new PutItemCommand({
    TableName: tableName,
    Item: {
      userId: { S: body.id },
      name: { S: body.name },
      email: { S: body.email }
    }
  }));
  return c.json({ success: true }, 201);
});

export const handler = handle(app);

Scheduled cleanup task

A Lambda function that runs every hour to delete expired records. The schedule trigger accepts rate expressions and AWS cron expressions (6-field, UTC).

export default defineConfig(() => {
  const sessionsTable = new DynamoDbTable({
    primaryKey: { partitionKey: { name: 'sessionId', type: 'string' } }
  });

  const cleanup = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({
      entryfilePath: './src/cleanup.ts'
    }),
    events: [
      {
        type: 'schedule',
        properties: { scheduleRate: 'rate(1 hour)' }
      }
    ],
    connectTo: [sessionsTable],
    timeout: 120
  });

  return { resources: { sessionsTable, cleanup } };
});

The cleanup handler scans for expired sessions and deletes them:

import { DynamoDBClient, ScanCommand, DeleteItemCommand } from '@aws-sdk/client-dynamodb';

const client = new DynamoDBClient({});
const tableName = process.env.STP_SESSIONS_TABLE_NAME!;

export async function handler() {
  const cutoff = Date.now() - 7 * 24 * 60 * 60 * 1000;
  const { Items } = await client.send(new ScanCommand({
    TableName: tableName,
    FilterExpression: 'expiresAt < :cutoff',
    ExpressionAttributeValues: { ':cutoff': { N: String(cutoff) } }
  }));

  for (const item of Items ?? []) {
    await client.send(new DeleteItemCommand({
      TableName: tableName,
      Key: { sessionId: item.sessionId }
    }));
  }

  return { deleted: Items?.length ?? 0 };
}

Packaging

Stacktape supports three Lambda packaging types: js-bundle, buildpack and custom-artifact.

TypeBest for
js-bundle (JavaScript, TypeScript)Point to a source file. Stacktape bundles, minifies and source-maps the code, moves code shared between functions into a shared layer, and uploads the package.
buildpack (Python, Java, Go, Ruby, .NET, Rust)Point to a source file. Stacktape installs dependencies and compiles the code in Docker on the Lambda build image of the function's runtime.
custom-artifactProvide a pre-built zip. Use when your CI already produces a deployment package or when you need a build step Stacktape does not support.

js-bundle and buildpack are the better defaults: they detect the runtime from the file extension, build for the selected architecture and skip unchanged packages. Use custom artifact only when you own the build outside Stacktape.

JS bundle

JsBundleLambdaPackaging options such as nodeVersion, outputModuleFormat, disableSourceMaps and minify are direct properties next to entryfilePath. See JS Bundle for Lambda for all options.

export default defineConfig(() => {
  const api = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({
      entryfilePath: './src/api.ts',
      nodeVersion: 22,
      outputModuleFormat: 'esm'
    })
  });

  return { resources: { api } };
});

nodeVersion selects the Node.js major version for the build; keep it aligned with the function's runtime. outputModuleFormat switches between 'cjs' (CommonJS) and 'esm' (ES Modules, enables top-level await). Node.js 24 and later use ESM output automatically; earlier versions default to CommonJS. Some npm packages do not support ESM.

Buildpack

BuildpackLambdaPackaging builds Python, Java, Go, Ruby, .NET and Rust functions. The function's runtime selects the language version. Language options are grouped under python, java and dotnet. See Buildpack for Lambda for all options.

export default defineConfig(() => {
  const processor = new LambdaFunction({
    runtime: 'python3.13',
    packaging: new BuildpackLambdaPackaging({
      entryfilePath: './src/process.py',
      python: { packageManagerFile: './pyproject.toml' }
    })
  });

  return { resources: { processor } };
});

Custom artifact

The CustomArtifactLambdaPackaging class takes a packagePath pointing to a pre-built deployment package. If the path points to a directory or a non-zip file, Stacktape zips it before upload. With custom-artifact, there is no source file for runtime auto-detection, so you must set runtime on the resource and handler in the packaging. The handler file must be at the artifact root; see custom-artifact limitations. If you use architecture: 'arm64', pre-compile any native dependencies for that architecture yourself.

export default defineConfig(() => {
  const processor = new LambdaFunction({
    packaging: new CustomArtifactLambdaPackaging({
      packagePath: './dist/processor.zip',
      handler: 'index.js:handler'
    }),
    runtime: 'nodejs22.x'
  });

  return { resources: { processor } };
});

handler follows the format filepath:functionName and tells Lambda which exported function to invoke.

Triggers

A Lambda function receives work through its events array. Stacktape supports 13 trigger types and auto-configures the permissions for each.

Trigger typeEvent discriminatorDocs
HTTP API Gatewayhttp-api-gatewayHTTP triggers
WebSocket API Gatewaywebsocket-api-gatewayWebSocket API Gateway
Application Load Balancerapplication-load-balancerHTTP triggers
SchedulescheduleSchedule triggers
S3s3S3 events
SQSsqsSQS events
SNSsnsSNS events
DynamoDB streamdynamo-db-streamDynamoDB streams
Kinesis streamkinesis-streamKinesis events
EventBridgeevent-busEventBridge events
CloudWatch logcloudwatch-logCloudWatch logs
CloudWatch alarmcloudwatch-alarmAlarms as triggers
Kafka topickafka-topicKafka topics

For queue and stream triggers (sqs, kinesis-stream, dynamo-db-stream), batchSize and maxBatchWindowSeconds control how many records the function receives per invocation. Keep handlers idempotent. By default, failed batches retry records that already succeeded. Enable reportBatchItemFailures and return batchItemFailures for partial failure handling; see SQS, Kinesis and DynamoDB streams.

export default defineConfig(() => {
  const jobs = new SqsQueue({});

  const worker = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/worker.ts' }),
    events: [
      {
        type: 'sqs',
        properties: {
          sqsQueueName: 'jobs',
          batchSize: 10,
          maxBatchWindowSeconds: 30
        }
      }
    ]
  });

  return { resources: { jobs, worker } };
});

batchSize controls the maximum number of records delivered to one invocation and defaults to 10. The maximum batchSize varies by trigger type (for example, DynamoDB streams cap at 1,000 while SQS and Kinesis accept up to 10,000). maxBatchWindowSeconds waits up to the configured seconds before invoking with a partial batch (maximum 300). The function is also invoked when the batch reaches the 6 MB payload limit.

A schedule trigger runs the function on a cron expression or fixed rate. scheduleRate accepts rate expressions like rate(5 minutes) and cron expressions like cron(0 18 ? * MON-FRI *) (6-field AWS cron, UTC). See schedule triggers for full syntax.

Function URLs

A Lambda function URL gives one function its own HTTPS endpoint (https://{id}.lambda-url.{region}.on.aws) without requiring an API Gateway resource. Use function URLs for single-function endpoints, webhooks, or internal tools where the routing configuration of a full gateway is unnecessary.

When to use a function URL: the function handles all paths itself (e.g., a Hono or Express app behind handle()), or you have exactly one function serving a narrow purpose like a webhook receiver.

When to use an HTTP API Gateway instead: you need route-level method/path matching or a shared API surface across multiple functions.

export default defineConfig(() => {
  const webhook = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/webhook.ts' }),
    url: {
      enabled: true,
      authMode: 'NONE',
      cors: {
        enabled: true,
        allowedOrigins: ['https://app.example.com'],
        allowedMethods: ['POST']
      }
    }
  });

  return { resources: { webhook } };
});

authMode defaults to 'NONE' (public — anyone can call the URL). Set authMode: 'AWS_IAM' to restrict access to authenticated AWS users and roles with invoke permission. cors.enabled: true without additional settings uses permissive defaults (* for origins and methods). allowedOrigins and allowedMethods narrow CORS to specific browser origins and HTTP methods. Function URL CORS settings override any CORS headers returned by your function code.

responseStreamEnabled streams the response progressively instead of buffering, improving Time to First Byte and increasing the maximum response size from 6 MB to 20 MB. Your handler must use the AWS streaming handler pattern.

Runtime resources

Lambda function runtime resources are controlled by runtime, architecture, memory, timeout, and storage. These properties determine the language version, CPU allocation, execution limits, and ephemeral disk available to each invocation.

runtime is auto-detected from the source file extension when using js-bundle or buildpack packaging. Supported runtime identifiers are nodejs18.x, nodejs20.x, nodejs22.x, nodejs24.x, python3.8, python3.9, python3.10, python3.11, python3.12, python3.13, python3.14, ruby3.3, ruby3.4, ruby4.0, java8, java8.al2, java11, java17, java21, java25, dotnet6, dotnet7, dotnet8, dotnet10, provided.al2, and provided.al2023. With buildpack, runtime also selects the language version used for the build. Set it when you need a specific version, for Rust functions (provided.al2023), and with custom-artifact packaging, where there is no source file for auto-detection.

memory accepts 128 to 10,240 MB and determines CPU power proportionally: 1,769 MB equals 1 vCPU, 3,538 MB equals 2 vCPUs. For CPU-bound functions, increasing memory often reduces total cost because shorter execution time offsets the higher per-millisecond rate.

export default defineConfig(() => {
  const imageProcessor = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/image-processor.ts' }),
    runtime: 'nodejs22.x',
    architecture: 'arm64',
    memory: 2048,
    timeout: 120,
    storage: 2048
  });

  return { resources: { imageProcessor } };
});

architecture is 'x86_64' by default. 'arm64' (AWS Graviton) is ~20% cheaper per GB-second and often works without code changes. When using js-bundle or buildpack, Stacktape builds for the selected architecture automatically; with a custom artifact, you must pre-compile for the target.

storage controls the ephemeral /tmp directory size from 512 (default) to 10,240 MB. This space is only available during one invocation and is not shared. Use it for temporary downloads or intermediate files, not persistent data.

A Lambda function is stopped when it exceeds timeout. The default is 10 seconds and the maximum is 900 seconds (15 minutes). For processing that can exceed 15 minutes, use a batch job or worker service.

Concurrency

Lambda concurrency controls protect downstream systems and manage cold-start behavior. Two independent knobs control scaling limits and warm instances.

  • reservedConcurrency — caps and reserves execution slots for this function. Other functions in the account cannot use these slots, and this function cannot exceed the cap. No additional cost.
  • provisionedConcurrency — keeps a configured number of instances pre-warmed. Eliminates cold starts but bills for those instances even when idle and adds ~2–5 minutes to deploy time.

Use reservedConcurrency when a database, third-party API, or queue consumer must not receive unlimited parallel traffic. Use provisionedConcurrency for latency-sensitive user-facing paths where cold starts are unacceptable. Skip provisioned concurrency for background jobs, cron tasks, and data pipelines where occasional cold starts are tolerable.

export default defineConfig(() => {
  const checkout = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/checkout.ts' }),
    reservedConcurrency: 25,
    provisionedConcurrency: 3
  });

  return { resources: { checkout } };
});

reservedConcurrency: 25 means this function cannot scale beyond 25 concurrent instances, and those 25 slots are reserved exclusively for it. provisionedConcurrency: 3 keeps three instances warm and ready to handle requests instantly.

Networking

A Lambda function does not need VPC attachment by default. Set joinDefaultVpc: true only when the function must reach VPC-only resources such as a relational database with accessibilityMode: 'vpc', a Redis cache, or an EFS filesystem.

The main tradeoff: when joinDefaultVpc is enabled, the function loses direct outbound internet access. Stacktape creates VPC endpoints for S3 and DynamoDB, but calls to external APIs (payment providers, AI services, SaaS webhooks) will fail.

To give VPC functions internet access, set stackConfig.nat. Once it is set, every function with joinDefaultVpc is placed in the private subnets and reaches the internet through the NAT. Three kinds are available: ec2 (one small Stacktape-managed instance, about $7 per month, no failover), ha-ec2 (one instance per availability zone with automatic failover, about $7 per month per zone) and gateway (managed NAT Gateways, about $32 per month per zone plus $0.045 per GB). See VPC and networking for how to choose. Without it, stacktape deploy prints a warning for every VPC function that has no internet access. If you need VPC access and push a lot of traffic to the internet, a web service or worker service in the public subnets avoids NAT costs.

Connecting to resources

The connectTo property grants IAM permissions, opens network access (security group rules for databases and Redis), and injects environment variables with connection details using the STP_[RESOURCE_NAME]_[PARAM] pattern. See connecting resources for the full list of injected variables per resource type.

Use the environment property for explicit runtime variables such as LOG_LEVEL or feature flags. Values can be strings, numbers, or booleans. For secrets, use $Secret() directives rather than hard-coded values. Variables from connectTo are added automatically alongside any environment entries.

export default defineConfig(() => {
  const database = new RelationalDatabase({
    engine: new RdsEnginePostgres({
      version: '16',
      primaryInstance: { instanceSize: 'db.t4g.micro' }
    }),
    credentials: { masterUserPassword: $Secret('database', 'password') }
  });

  const api = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/api.ts' }),
    connectTo: [database],
    joinDefaultVpc: true,
    environment: { LOG_LEVEL: 'info' },
    memory: 1024,
    timeout: 30
  });

  return { resources: { database, api } };
});

For a resource named database, Stacktape follows the STP_[RESOURCE_NAME]_[PARAM] pattern — for example, the connection string variable is STP_DATABASE_CONNECTION_STRING, the host is STP_DATABASE_HOST, and the port is STP_DATABASE_PORT. The LOG_LEVEL environment variable is available alongside the auto-injected connectTo variables.

Use iamRoleStatements for AWS services not covered by connectTo (e.g., Rekognition, Bedrock, Textract):

export default defineConfig(() => {
  const analyzer = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/analyzer.ts' }),
    iamRoleStatements: [
      {
        Effect: 'Allow',
        Action: ['rekognition:DetectLabels', 'rekognition:DetectText'],
        Resource: ['*']
      }
    ]
  });

  return { resources: { analyzer } };
});

Storage

A Lambda function has two storage paths: ephemeral /tmp and persistent volume mounts via the volumeMounts property.

Ephemeral /tmp is controlled by the storage property (512–10,240 MB, default 512). The contents exist only for the current invocation and are not shared across instances. Use /tmp for temporary downloads, intermediate processing files, or cached assets within a single invocation.

Volume mounts attach persistent file systems through the volumeMounts property. Stacktape supports two volume mount types: efs (EFS filesystem) and s3files (S3 Files access point). EFS mounts are the common path for persistent, shared file storage across Lambda invocations. The s3files mount type accepts an existing S3 Files access point ARN; this is an advanced path for teams that already manage S3 Files access points outside Stacktape. Both volume mount types require joinDefaultVpc: true, and the mountPath must start with /mnt/.

Use EFS when files must persist across invocations, be shared across multiple functions, or exceed the /tmp size limit. Skip EFS when an S3 bucket or database is a better fit for the data access pattern — EFS adds VPC attachment overhead and cost.

export default defineConfig(() => {
  const sharedFiles = new EfsFilesystem({});

  const renderer = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/renderer.ts' }),
    joinDefaultVpc: true,
    storage: 2048,
    volumeMounts: [
      {
        type: 'efs',
        properties: {
          efsFilesystemName: 'sharedFiles',
          rootDirectory: '/renders',
          mountPath: '/mnt/renders'
        }
      }
    ]
  });

  return { resources: { sharedFiles, renderer } };
});

efsFilesystemName references an EFS resource defined in the same config. rootDirectory restricts the mount to a subdirectory of the filesystem (defaults to '/'). mountPath is the path inside the function where the volume appears — it must start with /mnt/.

CDN

A Lambda function can be placed behind a CDN by setting the cdn property. CloudFront caches responses at edge locations worldwide, reducing function invocations and bandwidth costs for cacheable content.

When to enable: The function serves public, repeatable responses (product catalogs, generated pages, static API data) to a geographically distributed audience. CDN reduces both latency and cost.

When the default is fine: Functions that return personalized data, handle write operations, or need every request to execute function code should skip CDN.

Tradeoff: Adds CloudFront distribution propagation time on first deploy, and stale-cache risk if cache rules are too broad.

export default defineConfig(() => {
  const catalog = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/catalog.ts' }),
    url: { enabled: true },
    cdn: {
      enabled: true
    }
  });

  return { resources: { catalog } };
});

cdn.enabled: true places CloudFront in front of the Lambda function with default caching behavior. The cdn property uses the shared CDN configuration; see CDN for cache and routing options.

Deployments

Lambda deployment strategies control how traffic shifts from the previous function version to the new one. Use deployment.strategy when you want Stacktape to manage Lambda traffic shifting with canary, linear, or all-at-once behavior. Gradual deployments are most valuable for production functions where an all-at-once failure would affect users.

When to enable: Production-facing APIs, payment handlers, or any function where rolling back quickly matters more than deployment speed.

When the default is fine: Development stages, internal tools, and batch processors where a brief disruption is acceptable.

Available strategies:

Strategy familyVariantsBehavior
CanaryCanary10Percent5Minutes, Canary10Percent10Minutes, Canary10Percent15Minutes, Canary10Percent30MinutesSend 10% of traffic to the new version, then all traffic after the wait period.
LinearLinear10PercentEvery1Minute, Linear10PercentEvery2Minutes, Linear10PercentEvery3Minutes, Linear10PercentEvery10MinutesShift 10% of traffic at regular intervals until 100%.
AllAtOnceAllAtOnceInstant switch, no gradual rollout.
export default defineConfig(() => {
  const api = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/api.ts' }),
    deployment: {
      strategy: 'Canary10Percent5Minutes'
    }
  });

  return { resources: { api } };
});

Canary10Percent5Minutes sends 10% of traffic to the new version and waits 5 minutes before shifting the remaining 90%. Optional beforeAllowTrafficFunction and afterTrafficShiftFunction run Lambda-based validation hooks before and after the traffic shift. beforeAllowTrafficFunction must signal success or failure to CodeDeploy; if it fails, the deployment rolls back.

For the full deployment lifecycle, see gradual deployments.

Destinations

Lambda destinations route the result of an asynchronous invocation to another service — an SQS queue, SNS topic, EventBridge event bus, or another Lambda function. Use onSuccess to chain successful results into a downstream workflow and onFailure to capture errors for dead-letter processing or alerting.

When to use destinations: You invoke the function asynchronously (via aws lambda invoke --invocation-type Event, or from SNS/EventBridge/S3 triggers) and need to route results without polling. Destinations are the simplest way to wire a function into a multi-step event pipeline without adding a state machine.

When to skip destinations: Synchronous triggers like API Gateway and Application Load Balancer return the function's response directly to the caller — destinations have no effect on synchronous invocations. Kinesis and DynamoDB stream integrations expose their own onFailure destination for failed batches, which handles retries and batch-level failure separately from Lambda destinations. The SQS integration does not expose an onFailure property in the Lambda event source configuration.

Destinations vs. in-function error handling: With destinations, AWS routes the full invocation result (including error details) to the target automatically. This keeps the function code focused on its own logic. Without destinations, the function would need to catch errors internally and publish to SQS or SNS in application code.

export default defineConfig(() => {
  const deadLetterQueue = new SqsQueue({});

  const processor = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/processor.ts' }),
    destinations: {
      onFailure: "$ResourceParam('deadLetterQueue', 'arn')"
    }
  });

  return { resources: { deadLetterQueue, processor } };
});

onSuccess and onFailure each accept an ARN string. Use $ResourceParam() to reference a resource defined in the same config.

Observability

Lambda function logs from stdout and stderr are sent to CloudWatch Logs automatically. View logs with stacktape logs or in the Stacktape Console.

logging.retentionDays defaults to 90. Set a shorter retention for high-volume functions when old logs are not needed; keep longer retention for audit-heavy production paths. Setting logging.disabled: true disables CloudWatch logging entirely — use this only when another observability path captures the same data.

Lambda functions also support log forwarding to external services (HTTP endpoints, Datadog, Highlight.io) through the logging.logForwarding property. See log forwarding for configuration details.

Alarms

Lambda function alarms support lambda-error-rate and lambda-duration triggers. Define alarms in the function config and deploy to apply changes. Existing legacy Console rules can be exported into config; disabledGlobalAlarms excludes named legacy rules during migration.

export default defineConfig(() => {
  const api = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/api.ts' }),
    logging: {
      retentionDays: 30
    },
    alarms: [
      {
        trigger: {
          type: 'lambda-error-rate',
          properties: { thresholdPercent: 5 }
        }
      },
      {
        trigger: {
          type: 'lambda-duration',
          properties: { thresholdMilliseconds: 5000 }
        }
      }
    ]
  });

  return { resources: { api } };
});

thresholdPercent: 5 fires the error-rate alarm when more than 5% of invocations fail. thresholdMilliseconds: 5000 fires the duration alarm when execution time exceeds 5 seconds. Alarm evaluation settings (period, evaluated periods, breached periods) and notificationChannels are configurable on each alarm. See alarms for notification target types and setup.

Layers

Lambda layers are zip archives with additional code or data that get mounted into the function at runtime. Set layers to an array of Lambda layer ARNs to attach shared libraries, custom runtimes, or large datasets that multiple functions need without duplicating them in each deployment package. Stacktape supports up to 5 layer ARNs per function.

Most teams do not need layers. js-bundle and buildpack handle dependencies automatically. Use layers when you need a binary dependency too large for the zip package, a shared custom runtime, or a public layer maintained by a third party.

Lambda Function FAQ

Does a Stacktape Lambda function scale to zero?

Yes. A Lambda function only runs when invoked, so idle functions do not consume compute. The exception is provisionedConcurrency: those instances stay warm and bill even when idle. Most teams start without provisioned concurrency and add it only for latency-sensitive paths.

Should I use a function URL or an HTTP API Gateway?

Use url.enabled: true (a function URL) when the function handles all routing itself — a Hono/Express app behind handle(), a webhook receiver, or a single narrow-purpose endpoint. Use an HTTP API Gateway when you need route-level method/path matching or a shared API surface across multiple functions. Note that a function URL defaults to authMode: 'NONE', meaning anyone can call it — set authMode: 'AWS_IAM' to restrict access.

How do I connect a Lambda function to a database?

Use connectTo to reference the database resource — Stacktape grants IAM permissions, opens network access, and injects connection-string environment variables. If the database is VPC-only, set joinDefaultVpc: true. The tradeoff: the function loses direct outbound internet access. See connecting resources.

When should I use a Lambda function instead of a web service?

Use a Lambda function for short-lived, event-driven work that finishes within 15 minutes and does not need a persistent process. Use a web service for always-on containers, workloads needing both VPC and internet access, or tasks requiring more than 10,240 MB of memory. Lambda scales to zero and bills per invocation; a web service bills per running container-hour.

How much memory should I allocate, and how do I lower cost?

Lambda CPU scales proportionally with memory: 1,769 MB equals 1 vCPU (range 128–10,240 MB). Start with the smallest memory that meets your latency target, then raise it for CPU-bound work — higher memory often reduces total cost because faster execution offsets the higher per-millisecond rate. For an additional ~20% saving per GB-second, set architecture: 'arm64' (AWS Graviton), which usually works without code changes.

Why are records being processed more than once from my SQS or stream trigger?

For queue and stream triggers (sqs, kinesis-stream, dynamo-db-stream), a failed batch is retried in full by default, including records that already succeeded. For partial failure handling, enable reportBatchItemFailures and return batchItemFailures; see SQS, Kinesis and DynamoDB streams. Keep handlers idempotent so reprocessing a record is safe. batchSize (default 10) and maxBatchWindowSeconds (max 300) control how many records each invocation receives.

API Reference

LambdaFunctionProps
Click a property in the tree to see its description, default value, and full type.

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')