@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
mdx 420 lines 14 KB
Raw
1 ---
2 title: Lambda
3 description: Stand up an AWS Lambda Function from a single Effect, expose it over a Function URL, and call it from a test.
4 ---
5
6 **Lambda** is Alchemy's default AWS runtime: a class that bundles
7 an Effect program into a zip, deploys it as a Lambda Function,
8 and generates its IAM execution role from the bindings you
9 actually use. Serve HTTP over a public **Function URL**, or
10 consume events — every building block in this section plugs in
11 through the same pattern: S3 notifications
12 (`Lambda.BucketEventSource`), SQS queues
13 (`Lambda.QueueEventSource`), Kinesis streams
14 (`Lambda.StreamEventSource`), and DynamoDB Streams
15 (`Lambda.TableEventSource`).
16
17 :::tip
18 For an API or web app, use a
19 [Lambda Web Function](/aws/compute/web-functions). It serves many
20 requests per environment and streams responses. Use a Lambda Function
21 for event sources.
22 :::
23
24 This page stands up the smallest possible function — a public
25 HTTP endpoint — which the [S3](/aws/data/s3),
26 [DynamoDB](/aws/data/dynamodb), [SQS](/aws/messaging/sqs), and
27 [Kinesis](/aws/messaging/kinesis) pages then grow into a small
28 event-driven system.
29
30 ## Prerequisites
31
32 Install Alchemy and connect your AWS account — see
33 [Setup](/aws/setup).
34
35 ## Create the Stack
36
37 Every Alchemy app has an `alchemy.run.ts` at the root that
38 declares the resources to deploy. Create one with the AWS
39 providers wired in:
40
41 ```typescript
42 // alchemy.run.ts
43 import * as Alchemy from "alchemy";
44 import * as AWS from "@alchemy.run/aws";
45 import * as Effect from "effect/Effect";
46
47 export default Alchemy.Stack(
48 "MyApp",
49 {
50 providers: AWS.providers(),
51 state: AWS.state(),
52 },
53 Effect.gen(function* () {
54 return {};
55 }),
56 );
57 ```
58
59 `Alchemy.Stack` is the root of every app. The first argument
60 (`"MyApp"`) doubles as a logical id and as the prefix Alchemy
61 uses when AWS asks for physical resource names.
62
63 `providers: AWS.providers()` registers every AWS resource and
64 IAM policy binding that ships with Alchemy, and resolves
65 credentials from your Alchemy profile — SSO, console login,
66 or stored keys, whichever you picked in
67 [Setup](/aws/setup).
68
69 `state: AWS.state()` stores deploy state in an account-regional
70 S3 bucket (`alchemy-state-{accountId}-{region}-an`), created
71 lazily on the first deploy. Because the state lives in your AWS
72 account rather than on disk, the same configuration works
73 locally and in CI. (For purely local iteration you can use
74 `Alchemy.localState()` instead, which writes state under
75 `.alchemy/` next to your code.)
76
77 The trailing `Effect.gen` block is where you'll declare the
78 resources to deploy. It's empty for now.
79
80 ## Declare a Lambda Function
81
82 A Lambda Function in Alchemy is a class. Create `src/api.ts`
83 with the smallest possible declaration — just the class
84 ceremony, an entrypoint, and an empty runtime:
85
86 ```typescript
87 // src/api.ts
88 import * as AWS from "@alchemy.run/aws";
89 import * as Effect from "effect/Effect";
90
91 export default class Api extends AWS.Lambda.Function<Api>()(
92 "Api",
93 { main: import.meta.url },
94 Effect.gen(function* () {
95 return {};
96 }),
97 ) {}
98 ```
99
100 The `<Api>` type argument plus the empty `()` is a one-time bit
101 of ceremony — it lets TypeScript reason about `Api` as a typed
102 handle that other resources can later bind against. The rest of
103 your code looks completely normal.
104
105 `main: import.meta.url` tells Alchemy this same file is the
106 bundle entrypoint. At deploy time it'll be bundled with Rolldown
107 into a zip and uploaded as the function's code.
108
109 ## Serve HTTP from a Function URL
110
111 The empty function compiles, but it doesn't do anything yet.
112 Add a `fetch` field — Alchemy treats anything returned from the
113 `Effect.gen` block as the runtime API, and `fetch` specifically
114 is wired up to handle incoming HTTP requests:
115
116 ```diff lang="typescript"
117 // src/api.ts
118 import * as AWS from "@alchemy.run/aws";
119 import * as Effect from "effect/Effect";
120 +import * as HttpServerResponse from "effect/http/HttpServerResponse";
121
122 export default class Api extends AWS.Lambda.Function<Api>()(
123 "Api",
124 { main: import.meta.url },
125 Effect.gen(function* () {
126 - return {};
127 + return {
128 + fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")),
129 + };
130 }),
131 ) {}
132 ```
133
134 `HttpServerResponse.text(...)` is the same `effect/http`
135 API used everywhere else — Alchemy adapts it to the Lambda event
136 envelope under the hood, so your handler never sees the raw
137 `APIGatewayProxyEvent` shape.
138
139 ## Expose a public URL
140
141 Every Lambda Function gets a public **Function URL** by default:
142 `functionUrl` defaults to `true`, which creates an unauthenticated HTTPS
143 endpoint (`authType: "NONE"`) and lets anyone invoke it. Spell it out
144 so the access level is visible in the code:
145
146 ```diff lang="typescript"
147 export default class Api extends AWS.Lambda.Function<Api>()(
148 "Api",
149 - { main: import.meta.url },
150 + { main: import.meta.url, functionUrl: true },
151 Effect.gen(function* () {
152 return {
153 fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")),
154 };
155 }),
156 ) {}
157 ```
158
159 The resolved `Api` resource exposes a `functionUrl`
160 field carrying that endpoint — we'll surface it from the Stack
161 in a moment.
162
163 `functionUrl` takes three access choices. `false` creates no URL,
164 `true` creates a public one, and `{ authType: "AWS_IAM" }` requires
165 SigV4-signed requests.
166
167 :::caution
168 Omitting `functionUrl` gives you a public URL. A Function that only
169 consumes events (SQS, SNS, EventBridge, Kinesis, S3) should set
170 `functionUrl: false`.
171 :::
172
173 ## Customize per stage
174
175 Lambda has knobs you'll want to tune per stage — memory,
176 timeout, log retention. Swap the static props object for
177 `Stack.useSync`, which gives you a synchronous accessor for any
178 value in the surrounding Effect context:
179
180 ```diff lang="typescript"
181 // src/api.ts
182 import * as AWS from "@alchemy.run/aws";
183 +import { Stack } from "alchemy/Stack";
184 import * as Effect from "effect/Effect";
185 import * as HttpServerResponse from "effect/http/HttpServerResponse";
186
187 export default class Api extends AWS.Lambda.Function<Api>()(
188 "Api",
189 - { main: import.meta.url, functionUrl: true },
190 + Stack.useSync((stack) => ({
191 + main: import.meta.url,
192 + functionUrl: true,
193 + memory: stack.stage === "prod" ? 1024 : 512,
194 + })),
195 Effect.gen(function* () {
196 return {
197 fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")),
198 };
199 }),
200 ) {}
201 ```
202
203 `Stack.useSync` is the synchronous accessor for any value in the
204 surrounding Effect context — handy for stack-level config like
205 `stage`, `appName`, or anything else you'd want to vary per
206 environment.
207
208 Lambda creates the function's log group on its first invocation
209 and keeps events forever. Set `logging: { retention: "2 weeks" }`
210 to have Alchemy create the group up front with that retention (the
211 duration is rounded up to the nearest value CloudWatch Logs
212 supports; `"forever"` clears an existing policy). The group is
213 deleted with the function.
214
215 ## Wire the function into the Stack
216
217 The `Api` class is just a typed identifier — yielding it inside
218 the Stack's Effect is what registers the resource and starts the
219 deploy:
220
221 ```diff lang="typescript"
222 // alchemy.run.ts
223 import * as Alchemy from "alchemy";
224 import * as AWS from "@alchemy.run/aws";
225 import * as Effect from "effect/Effect";
226 +import Api from "./src/api.ts";
227
228 export default Alchemy.Stack(
229 "MyApp",
230 {
231 providers: AWS.providers(),
232 state: AWS.state(),
233 },
234 Effect.gen(function* () {
235 + const api = yield* Api;
236 + return { url: api.functionUrl };
237 - return {};
238 }),
239 );
240 ```
241
242 Yielding `Api` returns the resolved Lambda outputs — the function
243 ARN, role ARN, log group, and the public Function URL we asked
244 for with `functionUrl: true`. We surface `functionUrl` as the Stack's
245 `url` so the test harness can find it.
246
247 ## Deploy
248
249 ```sh
250 bun alchemy deploy
251 ```
252
253 Alchemy bundles `src/api.ts` with Rolldown, packages it into a
254 zip, creates the IAM execution role, uploads the function, and
255 provisions the Function URL. The first deploy takes a moment
256 because of role propagation; subsequent deploys are seconds.
257
258 ## Verify
259
260 Drop a quick integration test that hits the Function URL and
261 checks the body:
262
263 ```typescript
264 // test/integ.test.ts
265 import * as AWS from "@alchemy.run/aws";
266 import * as Test from "@alchemy.run/test/Bun";
267 import { expect } from "bun:test";
268 import * as Effect from "effect/Effect";
269 import * as HttpClient from "effect/http/HttpClient";
270 import Stack from "../alchemy.run.ts";
271
272 const { test, beforeAll, deploy } = Test.make({
273 providers: AWS.providers(),
274 state: AWS.state(),
275 });
276
277 const stack = beforeAll(deploy(Stack));
278
279 test(
280 "Api responds over Function URL",
281 Effect.gen(function* () {
282 const { url } = yield* stack;
283 const response = yield* HttpClient.get(url);
284 expect(yield* response.text).toBe("Hello from Lambda!");
285 }),
286 );
287 ```
288
289 ```sh
290 bun test test/integ.test.ts
291 ```
292
293 You now have a deployable Lambda with a public URL.
294
295 ## Sandbox scope vs invocation scope
296
297 The constructor runs **once per sandbox**, at cold start —
298 everything it builds (bindings, SDK clients) is reused by every
299 invocation. Each invocation then runs with a **fresh `Scope`** that
300 is settled *inline* before the handler returns — so
301 `Effect.addFinalizer` in a handler runs before the response leaves,
302 and request finalizers should be fast (closing a pool is
303 milliseconds).
304
305 :::caution[There is no `waitUntil` on Lambda — request finalizers block the response]
306 No mechanism delivers post-response work reliably on Lambda. A
307 buffered invocation's response is not released to the caller until
308 the entire Invoke phase completes, so deferring cleanup past the
309 handler (we measured an extension-held post-response window) still
310 shows up as response latency — and environments whose invoke phase
311 is held open this way get recycled. Dangling promises resume on a
312 later thaw at best: TCP connections rarely survive the freeze, and a
313 crash or timeout reset drops the work entirely — silent data loss
314 for anything that mattered.
315
316 The contract is blocking and honest: request finalizers run before
317 the response, keep them cheap, and anything that must not be lost
318 gets written durably (a queue, a table) inside the handler itself.
319 :::
320
321 ### Timeouts interrupt the handler
322
323 When an invocation runs past its `timeout`, the runtime interrupts the
324 handler, the same way `runMain` handles `SIGTERM`. Its `acquireRelease`,
325 `ensuring` and scope finalizers run, and every open span ends, so the
326 trace shows the call that hung. The root span ends with an
327 `AWS.Lambda.InvocationTimeoutError`.
328
329 Lambda itself is configured with `timeout + timeoutMargin`, so the
330 finalizers and the telemetry flush run in that margin. A handler that
331 finishes inside its `timeout` is never cut short.
332
333 Once cleanup is done, the runtime holds the invocation until Lambda's own
334 timeout ends it. Lambda still logs `Task timed out`, counts a timeout and
335 retries it like any other, and it resets the sandbox, so work that ignored
336 the interruption, like a promise without an `AbortSignal`, can never resume
337 in the next invocation. The unused rest of the margin is billed, but only
338 on invocations that time out. If cleanup is still
339 running 500 ms before Lambda's own timeout, the runtime ends the root
340 span, marks it `aws.lambda.timeout.imminent`, and drains the exporters
341 before Lambda kills the process.
342
343 The margin defaults to one second. Size it for your finalizers plus one
344 export round-trip to your telemetry backend:
345
346 ```typescript
347 // src/api.ts
348 import * as AWS from "@alchemy.run/aws";
349 import * as Duration from "effect/Duration";
350 import * as Effect from "effect/Effect";
351 import * as HttpServerResponse from "effect/http/HttpServerResponse";
352
353 export default class Api extends AWS.Lambda.Function<Api>()(
354 "Api",
355 {
356 main: import.meta.url,
357 functionUrl: true,
358 // interrupt the handler after 30 s; Lambda kills it at 32 s
359 timeout: Duration.seconds(30),
360 timeoutMargin: Duration.seconds(2),
361 },
362 Effect.gen(function* () {
363 return {
364 fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")),
365 };
366 }),
367 ) {}
368 ```
369
370 `timeout + timeoutMargin` must fit in Lambda's 900-second maximum. Set
371 `timeoutMargin` to `Duration.zero` to never interrupt the handler; Lambda
372 then kills it at `timeout`, and the runtime only flushes telemetry 500 ms
373 before that. Durable functions are never interrupted, since their
374 invocations replay from checkpoints.
375
376 Construction-level finalizers run at **sandbox shutdown**. A Lambda sandbox
377 with no registered extensions is killed with no signal at all, so
378 the generated entry registers an internal extension with the
379 Extensions API — that makes Lambda send `SIGTERM` and allow 500 ms
380 before `SIGKILL`, and the entry uses the window to close the
381 instance scope:
382
383 ```typescript
384 Effect.gen(function* () {
385 // Construction: runs once per sandbox
386 yield* Effect.addFinalizer(() =>
387 // runs in the 500 ms SIGTERM window at sandbox spin-down
388 flushTelemetry().pipe(Effect.ignore),
389 );
390 return { fetch: /* per-invocation */ };
391 });
392 ```
393
394 Treat instance-level cleanup as best-effort: half a second, and not
395 delivered on hard failures (a timeout reset kills the runtime
396 without the signal). Flush caches and close connections there;
397 anything that *must* happen belongs in the handler, scoped to the
398 invocation. See
399 [Instance scope vs request scope](/infrastructure-as-effects/runtime#instance-scope-vs-request-scope)
400 for the model across all runtimes.
401
402 ## Where next
403
404 - [Drizzle + Aurora PostgreSQL](/aws/data/drizzle-aurora) — private database access,
405 IAM authentication, verified TLS, and deployment-time schema setup.
406 - [Drizzle + Aurora DSQL](/aws/data/drizzle-dsql) — the separate serverless database,
407 with an IAM-authenticated endpoint and non-admin application role.
408
409 - [S3](/aws/data/s3) — add a bucket and bind read/write operations
410 into this function; IAM policies generated from the call
411 sites, no policy JSON to hand-write.
412 - [Secrets & env](/aws/security/secrets-env) — API keys from .env and
413 Secrets Manager credentials for this function.
414 - [REST API (API Gateway v1)](/aws/apis/api-gateway) — put an
415 API Gateway REST API with stages and custom domains in front
416 instead of a Function URL.
417 - [Choosing a runtime](/aws/compute/choosing-a-runtime) — when ECS,
418 EKS, or EC2 fits better than Lambda.
419 - [`Function` reference](/providers/aws/lambda/function) — every
420 prop and attribute.