sailfork / t3code-github / .repos/ alchemy-effect/ website/ src/ content/ docs/ blog/ 2026-04-30-bindings.md

You're writing a Cloudflare Worker (or an AWS Lambda — same story). It needs to read an object from an S3 bucket. In Alchemy it looks like this:

Effect.gen(function* () {
  const getPhoto = yield* S3.GetObject(Photos);
  return {
    fetch: Effect.gen(function* () {
      const photo = yield* getPhoto({ Key: "cover.jpg" });
      return HttpServerResponse.raw(photo.Body);
    }),
  };
});

The shape is "bind and use" — the standard Layer constructor pattern from Effect. yield* your dependencies at the top, then return a fetch Effect that uses them. Bind runs once; fetch runs per request.

Focus on the S3.GetObject(Photos) call. Two things have to happen for it to work.

  • At deploy time, the Worker's IAM role needs s3:GetObject on the Photos bucket. If it doesn't, the call fails at runtime with AccessDenied.
  • At runtime, the Worker process needs a real S3 SDK client that knows how to talk to AWS, signs the request, and gets back bytes.

These are very different jobs. The first is infrastructure authoring — IAM policy documents, role attachments, deploy orchestration. The second is application code — SDK calls, retries, response parsing. Most frameworks make you write them in two separate places: the IAM in your IaC config, the SDK call in your handler. You're responsible for keeping the two in sync.

Alchemy lets you write one line for both, then arranges for each half to run in the right phase — and crucially, arranges for the deploy-side half to never end up in your runtime bundle.

Capabilities have two halves

Every capability in Alchemy — S3.GetObject, S3.PutObject, SQS.SendMessage, DynamoDB.GetItem, and so on — is implemented as a pair of Effect Services:

// AWS/S3/GetObject.ts
export class GetObject extends Binding.Service<GetObject, ...>()
  ("AWS.S3.GetObject") {}

export class GetObjectPolicy extends Binding.Policy<GetObjectPolicy, ...>()
  ("AWS.S3.GetObject") {}

The Binding.Service is the runtime half — an Effect service whose Live layer wraps the actual SDK client. When you yield* it, you get back a typed callable that takes a bucket and a request and gives you back the response.

The Binding.Policy is the deploy-time half — an Effect service whose Live layer doesn't do any I/O at all. It takes the bucket your handler referenced and records a policy statement onto the calling Worker's role:

yield* host.bind`Allow(${host}, AWS.S3.GetObject(${bucket}))`({
  policyStatements: [{
    Effect: "Allow",
    Action: ["s3:GetObject", "s3:GetObjectVersion"],
    Resource: [Output.interpolate`${bucket.bucketArn}/*`],
  }, /* + s3:ListBucket so 404s aren't 403s */],
});

Two services, one capability name (AWS.S3.GetObject). One gets bundled into your Worker; one runs only during plan.

The TypeScript trick

The interesting bit is how Alchemy distinguishes "this service must be provided" from "this service is allowed to be absent."

When you yield* S3.GetObject(Photos) inside a Worker, the Effect's R channel picks up GetObject (the runtime service) as a hard requirement. If you forget to attach the GetObjectLive layer to the Worker, the compiler tells you:

Argument of type 'Effect<…, …, GetObject>' is not assignable to
parameter of type 'Effect<…, …, never>'.

GetObjectPolicy (the deploy-time service) is also referenced by the same line. But it doesn't show up in R, because the framework resolves it via Effect.serviceOption — it's optional at the type level.

The relevant snippet is the comment right in Binding.ts:

// we use a service option because at runtime (e.g. in a Lambda
// Function or Cloudflare Worker) the Policy Layer is not provided
// and this becomes a no-op

The runtime layer must be provided or TypeScript breaks your build. The policy layer is allowed to be missing — and at runtime, it is. The same S3.GetObject(...) expression is a real SDK-client construction at runtime and a no-op at runtime for the policy half.

What happens if the policy is needed but missing

If you forget to provide GetObjectPolicyLive at deploy time, you don't want a silent no-op — you want a loud failure that tells you the role won't get the right IAM.

Alchemy checks the deploy phase explicitly. From Binding.ts:

service
  ? Effect.succeed(service)
  : Effect.all([CurrentStack, ALCHEMY_PHASE]).pipe(
      Effect.flatMap(([stack, phase]) =>
        stack && phase === "plan"
          ? Effect.die(
              `Binding.Policy provider 'Policy<${Identifier}>' was not provided at Plan Time in Stack '${stack.name}'`,
            )
          : Effect.succeed((() => Effect.void) as any as Shape),
      ),
    ),

In plan phase + with a Stack in scope, missing the policy layer dies with a clear message. Outside plan (e.g. inside the deployed Worker), it falls through to Effect.void and is invisible. Same expression, different behavior, scoped to the phase that needs each half.

The Stack is where policies live

A Cloudflare.Worker (or Lambda.Function) lets you provide the runtime layers it needs on the Worker itself:

const Photos = yield* Cloudflare.R2.Bucket("Photos");
const Api = yield* Cloudflare.Worker("Api", { main: "./src/api.ts" },
  Effect.gen(function* () {
    return { fetch: handler };
  }).pipe(
    Effect.provide(GetObjectLive),     // ← Binding.Service: bundled
  ),
);

GetObjectLive (the runtime service) gets bundled into the Worker. Nothing else here mentions IAM.

The Stack is where the Policy layers live:

export default Alchemy.Stack(
  "MyApp",
  { providers: AWS.providers() },        // ← Binding.Policy layers: NOT bundled
  Effect.gen(function* () {
    const photos = yield* Photos;
    const api = yield* Api;
    return { url: api.url };
  }),
);

AWS.providers() is a Layer that bundles every Binding.Policy AWS exposes — GetObjectPolicyLive, PutObjectPolicyLive, SendMessagePolicyLive, etc. The Stack runs your generator in plan phase with those provided. When the planner walks into your Worker's generator and reaches S3.GetObject(Photos), the policy lookup succeeds, the role gets the right statement, the deploy proceeds.

Then the planner walks back out. Your Worker bundle is written. The bundle has GetObjectLive (runtime SDK) but not GetObjectPolicyLive (IAM logic) — because the Worker's R never required it.

What ends up in your bundle

The mental model is: the Worker bundle is whatever its Effect's R channel demands, and nothing else.

In the bundle:

  • Your handler.
  • Binding.Service runtime layers (SDK wrappers) — every getObject/putObject/sendMessage you actually call.
  • Resource data structures — { LogicalId: "Photos", ... } is all the runtime needs to identify a bucket. The output values (bucket name, ARN) get resolved at deploy time and inlined as constants by the bundler.

Not in the bundle:

  • Binding.Policy layers — they're optional services, so the Worker's R never required them.
  • Provider implementations — the code that knows how to reconcile a Bucket lives in AWS.providers(), which is provided to the Stack, not the Worker.
  • Other Workers' handlers — same reasoning, different resource type. Worker A binding Worker B only needs B's Tag (its LogicalId and binding contract), not B's handler code.

The tree-shake property falls out of the type system. You didn't have to opt in; you'd have to opt out to leak deploy-time code into a runtime bundle, by explicitly providing the Policy layer where it isn't needed.

Inline and Tag forms produce the same bundle

There are two ways to author a Worker. The inline form, for when nothing else references this Worker:

export const Api = Cloudflare.Worker("Api", { main: "./src/api.ts" },
  Effect.gen(function* () {
    const getPhoto = yield* S3.GetObject(Photos);
    return {
      fetch: Effect.gen(function* () {
        const photo = yield* getPhoto({ Key: "cover.jpg" });
        /* ... */
      }),
    };
  }),
);

The Tag-and-Layer form, for when this Worker has to be referenced before its implementation is in scope (a cycle, self-reference, or just a Worker exported across files):

export class Api extends Cloudflare.Worker<Api>()("Api", {
  main: import.meta.filename,
}) {}

export default Api.make(
  Effect.gen(function* () {
    const getPhoto = yield* S3.GetObject(Photos);
    return {
      fetch: Effect.gen(function* () {
        const photo = yield* getPhoto({ Key: "cover.jpg" });
        /* ... */
      }),
    };
  }),
);

Both produce the same runtime bundle. The Tag form just splits identity (the class declaration) from implementation (the .make() call), so other files can import the Tag without pulling in the handler. See Circular references, without the deadlock for the full story on when each form pays off.

Composable units of infrastructure

The same shape — Binding.Service required, Binding.Policy optional — is what makes pieces of infrastructure composable as Effect Layers. A "feature" can be a Layer that brings its own Workers, Tables, and bindings, with all the internal cross-references already wired. The Stack that consumes the feature provides providers() and gets the IAM right for free; the Workers inside the feature bundle exactly their own runtime code, nothing else.

We'll get into that pattern in a separate post. For now, the takeaway is: the line you write — yield* S3.GetObject(Photos) — is a complete specification of what your Worker needs. The framework handles the rest, in the right phase, without mixing the two phases' code together.

Where to go next