TypeScript
---
title: Lambda
description: Stand up an AWS Lambda Function from a single Effect, expose it over a Function URL, and call it from a test.
---
**Lambda** is Alchemy's default AWS runtime: a class that bundles
an Effect program into a zip, deploys it as a Lambda Function,
and generates its IAM execution role from the bindings you
actually use. Serve HTTP over a public **Function URL**, or
consume events — every building block in this section plugs in
through the same pattern: S3 notifications
(`Lambda.BucketEventSource`), SQS queues
(`Lambda.QueueEventSource`), Kinesis streams
(`Lambda.StreamEventSource`), and DynamoDB Streams
(`Lambda.TableEventSource`).
:::tip
For an API or web app, use a
[Lambda Web Function](/aws/compute/web-functions). It serves many
requests per environment and streams responses. Use a Lambda Function
for event sources.
:::
This page stands up the smallest possible function — a public
HTTP endpoint — which the [S3](/aws/data/s3),
[DynamoDB](/aws/data/dynamodb), [SQS](/aws/messaging/sqs), and
[Kinesis](/aws/messaging/kinesis) pages then grow into a small
event-driven system.
## Prerequisites
Install Alchemy and connect your AWS account — see
[Setup](/aws/setup).
## Create the Stack
Every Alchemy app has an `alchemy.run.ts` at the root that
declares the resources to deploy. Create one with the AWS
providers wired in:
```typescript
// alchemy.run.ts
import * as Alchemy from "alchemy";
import * as AWS from "@alchemy.run/aws";
import * as Effect from "effect/Effect";
export default Alchemy.Stack(
"MyApp",
{
providers: AWS.providers(),
state: AWS.state(),
},
Effect.gen(function* () {
return {};
}),
);
```
`Alchemy.Stack` is the root of every app. The first argument
(`"MyApp"`) doubles as a logical id and as the prefix Alchemy
uses when AWS asks for physical resource names.
`providers: AWS.providers()` registers every AWS resource and
IAM policy binding that ships with Alchemy, and resolves
credentials from your Alchemy profile — SSO, console login,
or stored keys, whichever you picked in
[Setup](/aws/setup).
`state: AWS.state()` stores deploy state in an account-regional
S3 bucket (`alchemy-state-{accountId}-{region}-an`), created
lazily on the first deploy. Because the state lives in your AWS
account rather than on disk, the same configuration works
locally and in CI. (For purely local iteration you can use
`Alchemy.localState()` instead, which writes state under
`.alchemy/` next to your code.)
The trailing `Effect.gen` block is where you'll declare the
resources to deploy. It's empty for now.
## Declare a Lambda Function
A Lambda Function in Alchemy is a class. Create `src/api.ts`
with the smallest possible declaration — just the class
ceremony, an entrypoint, and an empty runtime:
```typescript
// src/api.ts
import * as AWS from "@alchemy.run/aws";
import * as Effect from "effect/Effect";
export default class Api extends AWS.Lambda.Function<Api>()(
"Api",
{ main: import.meta.url },
Effect.gen(function* () {
return {};
}),
) {}
```
The `<Api>` type argument plus the empty `()` is a one-time bit
of ceremony — it lets TypeScript reason about `Api` as a typed
handle that other resources can later bind against. The rest of
your code looks completely normal.
`main: import.meta.url` tells Alchemy this same file is the
bundle entrypoint. At deploy time it'll be bundled with Rolldown
into a zip and uploaded as the function's code.
## Serve HTTP from a Function URL
The empty function compiles, but it doesn't do anything yet.
Add a `fetch` field — Alchemy treats anything returned from the
`Effect.gen` block as the runtime API, and `fetch` specifically
is wired up to handle incoming HTTP requests:
```diff lang="typescript"
// src/api.ts
import * as AWS from "@alchemy.run/aws";
import * as Effect from "effect/Effect";
+import * as HttpServerResponse from "effect/http/HttpServerResponse";
export default class Api extends AWS.Lambda.Function<Api>()(
"Api",
{ main: import.meta.url },
Effect.gen(function* () {
- return {};
+ return {
+ fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")),
+ };
}),
) {}
```
`HttpServerResponse.text(...)` is the same `effect/http`
API used everywhere else — Alchemy adapts it to the Lambda event
envelope under the hood, so your handler never sees the raw
`APIGatewayProxyEvent` shape.
## Expose a public URL
Every Lambda Function gets a public **Function URL** by default:
`functionUrl` defaults to `true`, which creates an unauthenticated HTTPS
endpoint (`authType: "NONE"`) and lets anyone invoke it. Spell it out
so the access level is visible in the code:
```diff lang="typescript"
export default class Api extends AWS.Lambda.Function<Api>()(
"Api",
- { main: import.meta.url },
+ { main: import.meta.url, functionUrl: true },
Effect.gen(function* () {
return {
fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")),
};
}),
) {}
```
The resolved `Api` resource exposes a `functionUrl`
field carrying that endpoint — we'll surface it from the Stack
in a moment.
`functionUrl` takes three access choices. `false` creates no URL,
`true` creates a public one, and `{ authType: "AWS_IAM" }` requires
SigV4-signed requests.
:::caution
Omitting `functionUrl` gives you a public URL. A Function that only
consumes events (SQS, SNS, EventBridge, Kinesis, S3) should set
`functionUrl: false`.
:::
## Customize per stage
Lambda has knobs you'll want to tune per stage — memory,
timeout, log retention. Swap the static props object for
`Stack.useSync`, which gives you a synchronous accessor for any
value in the surrounding Effect context:
```diff lang="typescript"
// src/api.ts
import * as AWS from "@alchemy.run/aws";
+import { Stack } from "alchemy/Stack";
import * as Effect from "effect/Effect";
import * as HttpServerResponse from "effect/http/HttpServerResponse";
export default class Api extends AWS.Lambda.Function<Api>()(
"Api",
- { main: import.meta.url, functionUrl: true },
+ Stack.useSync((stack) => ({
+ main: import.meta.url,
+ functionUrl: true,
+ memory: stack.stage === "prod" ? 1024 : 512,
+ })),
Effect.gen(function* () {
return {
fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")),
};
}),
) {}
```
`Stack.useSync` is the synchronous accessor for any value in the
surrounding Effect context — handy for stack-level config like
`stage`, `appName`, or anything else you'd want to vary per
environment.
Lambda creates the function's log group on its first invocation
and keeps events forever. Set `logging: { retention: "2 weeks" }`
to have Alchemy create the group up front with that retention (the
duration is rounded up to the nearest value CloudWatch Logs
supports; `"forever"` clears an existing policy). The group is
deleted with the function.
## Wire the function into the Stack
The `Api` class is just a typed identifier — yielding it inside
the Stack's Effect is what registers the resource and starts the
deploy:
```diff lang="typescript"
// alchemy.run.ts
import * as Alchemy from "alchemy";
import * as AWS from "@alchemy.run/aws";
import * as Effect from "effect/Effect";
+import Api from "./src/api.ts";
export default Alchemy.Stack(
"MyApp",
{
providers: AWS.providers(),
state: AWS.state(),
},
Effect.gen(function* () {
+ const api = yield* Api;
+ return { url: api.functionUrl };
- return {};
}),
);
```
Yielding `Api` returns the resolved Lambda outputs — the function
ARN, role ARN, log group, and the public Function URL we asked
for with `functionUrl: true`. We surface `functionUrl` as the Stack's
`url` so the test harness can find it.
## Deploy
```sh
bun alchemy deploy
```
Alchemy bundles `src/api.ts` with Rolldown, packages it into a
zip, creates the IAM execution role, uploads the function, and
provisions the Function URL. The first deploy takes a moment
because of role propagation; subsequent deploys are seconds.
## Verify
Drop a quick integration test that hits the Function URL and
checks the body:
```typescript
// test/integ.test.ts
import * as AWS from "@alchemy.run/aws";
import * as Test from "@alchemy.run/test/Bun";
import { expect } from "bun:test";
import * as Effect from "effect/Effect";
import * as HttpClient from "effect/http/HttpClient";
import Stack from "../alchemy.run.ts";
const { test, beforeAll, deploy } = Test.make({
providers: AWS.providers(),
state: AWS.state(),
});
const stack = beforeAll(deploy(Stack));
test(
"Api responds over Function URL",
Effect.gen(function* () {
const { url } = yield* stack;
const response = yield* HttpClient.get(url);
expect(yield* response.text).toBe("Hello from Lambda!");
}),
);
```
```sh
bun test test/integ.test.ts
```
You now have a deployable Lambda with a public URL.
## Sandbox scope vs invocation scope
The constructor runs **once per sandbox**, at cold start —
everything it builds (bindings, SDK clients) is reused by every
invocation. Each invocation then runs with a **fresh `Scope`** that
is settled *inline* before the handler returns — so
`Effect.addFinalizer` in a handler runs before the response leaves,
and request finalizers should be fast (closing a pool is
milliseconds).
:::caution[There is no `waitUntil` on Lambda — request finalizers block the response]
No mechanism delivers post-response work reliably on Lambda. A
buffered invocation's response is not released to the caller until
the entire Invoke phase completes, so deferring cleanup past the
handler (we measured an extension-held post-response window) still
shows up as response latency — and environments whose invoke phase
is held open this way get recycled. Dangling promises resume on a
later thaw at best: TCP connections rarely survive the freeze, and a
crash or timeout reset drops the work entirely — silent data loss
for anything that mattered.
The contract is blocking and honest: request finalizers run before
the response, keep them cheap, and anything that must not be lost
gets written durably (a queue, a table) inside the handler itself.
:::
### Timeouts interrupt the handler
When an invocation runs past its `timeout`, the runtime interrupts the
handler, the same way `runMain` handles `SIGTERM`. Its `acquireRelease`,
`ensuring` and scope finalizers run, and every open span ends, so the
trace shows the call that hung. The root span ends with an
`AWS.Lambda.InvocationTimeoutError`.
Lambda itself is configured with `timeout + timeoutMargin`, so the
finalizers and the telemetry flush run in that margin. A handler that
finishes inside its `timeout` is never cut short.
Once cleanup is done, the runtime holds the invocation until Lambda's own
timeout ends it. Lambda still logs `Task timed out`, counts a timeout and
retries it like any other, and it resets the sandbox, so work that ignored
the interruption, like a promise without an `AbortSignal`, can never resume
in the next invocation. The unused rest of the margin is billed, but only
on invocations that time out. If cleanup is still
running 500 ms before Lambda's own timeout, the runtime ends the root
span, marks it `aws.lambda.timeout.imminent`, and drains the exporters
before Lambda kills the process.
The margin defaults to one second. Size it for your finalizers plus one
export round-trip to your telemetry backend:
```typescript
// src/api.ts
import * as AWS from "@alchemy.run/aws";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as HttpServerResponse from "effect/http/HttpServerResponse";
export default class Api extends AWS.Lambda.Function<Api>()(
"Api",
{
main: import.meta.url,
functionUrl: true,
// interrupt the handler after 30 s; Lambda kills it at 32 s
timeout: Duration.seconds(30),
timeoutMargin: Duration.seconds(2),
},
Effect.gen(function* () {
return {
fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")),
};
}),
) {}
```
`timeout + timeoutMargin` must fit in Lambda's 900-second maximum. Set
`timeoutMargin` to `Duration.zero` to never interrupt the handler; Lambda
then kills it at `timeout`, and the runtime only flushes telemetry 500 ms
before that. Durable functions are never interrupted, since their
invocations replay from checkpoints.
Construction-level finalizers run at **sandbox shutdown**. A Lambda sandbox
with no registered extensions is killed with no signal at all, so
the generated entry registers an internal extension with the
Extensions API — that makes Lambda send `SIGTERM` and allow 500 ms
before `SIGKILL`, and the entry uses the window to close the
instance scope:
```typescript
Effect.gen(function* () {
// Construction: runs once per sandbox
yield* Effect.addFinalizer(() =>
// runs in the 500 ms SIGTERM window at sandbox spin-down
flushTelemetry().pipe(Effect.ignore),
);
return { fetch: /* per-invocation */ };
});
```
Treat instance-level cleanup as best-effort: half a second, and not
delivered on hard failures (a timeout reset kills the runtime
without the signal). Flush caches and close connections there;
anything that *must* happen belongs in the handler, scoped to the
invocation. See
[Instance scope vs request scope](/infrastructure-as-effects/runtime#instance-scope-vs-request-scope)
for the model across all runtimes.
## Where next
- [Drizzle + Aurora PostgreSQL](/aws/data/drizzle-aurora) — private database access,
IAM authentication, verified TLS, and deployment-time schema setup.
- [Drizzle + Aurora DSQL](/aws/data/drizzle-dsql) — the separate serverless database,
with an IAM-authenticated endpoint and non-admin application role.
- [S3](/aws/data/s3) — add a bucket and bind read/write operations
into this function; IAM policies generated from the call
sites, no policy JSON to hand-write.
- [Secrets & env](/aws/security/secrets-env) — API keys from .env and
Secrets Manager credentials for this function.
- [REST API (API Gateway v1)](/aws/apis/api-gateway) — put an
API Gateway REST API with stages and custom domains in front
instead of a Function URL.
- [Choosing a runtime](/aws/compute/choosing-a-runtime) — when ECS,
EKS, or EC2 fits better than Lambda.
- [`Function` reference](/providers/aws/lambda/function) — every
prop and attribute.