sailfork / t3code-github / .repos/ alchemy-effect/ website/ src/ content/ docs/ blog/ 2026-05-13-actions.md

You finish deploying a stack. The Worker URL changes because you switched to a custom domain. Now you want to:

  • ping Slack with the new URL,
  • invalidate a CDN cache that lives outside this stack,
  • seed a database with the latest schema version.

None of these are resources — they don't reconcile a cloud entity, they don't have a lifecycle, they don't need to track drift. They're one-shot Effects you want the deploy pipeline to run when the inputs change, and skip when they haven't.

You can hack this with an exec resource that runs a shell command on every apply. Or a CloudFormation custom resource that pretends to be CRUD-shaped just so the engine will call it. Neither is what you actually want.

What you want is a node in the same dependency graph as your resources, with the same typed Output references, but without the lifecycle machinery — just a function that runs when its input changes.

Alchemy has one. It's called an Action.

The shape

Define the Action with its type name and a body:

const Sync = Action("Sync", Effect.fn(function* (input: { table: string }) {
  yield* Effect.log(`syncing ${input.table}`);
  return { rows: 42 };
}));

Call it inside a stack to register an instance:

const rows = yield* Sync({ table: bucket.name });
//          ^ Output<{ rows: number }>
rows.rows  // Output<number>

That's the whole API. The yield does four things:

  • registers an Action instance on the stack under the logical id "Sync" (or an explicit id if you pass one)
  • captures the input as an Output<…> expression — any upstream resource references get resolved during apply
  • arranges for the body to run when the resolved input hash differs from what we persisted last time
  • returns the body's return value as an Output<…> for downstream resources or other Actions to consume

The body is just an Effect. It can yield* whatever services it needs — log, fetch, Slack, anything. Inputs are typed. The output is typed. The graph is the same graph your resources live in.

What Sync(...) actually returns

Look closely at the call site:

const rows = yield* Sync({ table: bucket.name });

rows is not a Task object with a .output field. It's an Output directly. You can pass it as input to another resource, project a field out of it (rows.rows → Output<number>), or yield it inside a Worker to materialize the value at runtime.

const Worker = yield* Cloudflare.Worker("Api", { main: "./src/api.ts" },
  Effect.gen(function* () {
    return {
      fetch: Effect.gen(function* () {
        const r = yield* rows; // Accessor<{ rows: number }>
        const n = (yield* r).rows;
        return HttpServerResponse.text(`${n} rows synced`);
      }),
    };
  }),
);

There is no separate concept to learn. An Action's output is an Output. It composes with everything else.

The diff is a hash

Resources reconcile against observed cloud state. Actions don't — there's no cloud state to read. So how do we know whether the body should run?

We hash the resolved input.

When the plan walks the stack, it evaluates the Action's input expression against the current attribute values of any upstream resources, computes a SHA-256 over the resolved JSON, and compares it to the hash we stored on the previous deploy. Match → skip. Mismatch → run. No prior state → run.

const sameInput =
  prior?.status === "ran" && prior.inputHash === inputHash;
if (sameInput && !options.force) {
  return { action: "noop", /* ... skip the body ... */ };
}
return { action: "run", /* ... run the body ... */ };

--force flips skip→run for actions, the same flag that flips noop→update for resources.

The state row that records all this is tiny — there are no provider props to track, no attributes to drift against. Just the input hash, the input we ran with, and the output:

type ActionState =
  | { kind: "action"; status: "running"; inputHash; input; … }
  | { kind: "action"; status: "ran";     inputHash; input; output; … };

Remove the Action from the stack, and the row gets dropped on the next deploy. No body invoked. No lifecycle.

Wait for the terminal upstream, not the stub

The interesting bit, the one we got wrong on the first try.

Resources have a precreate hook that lets cyclic resources publish a stub identifier — a placeholder Worker script with a reserved name — before the real reconcile runs. That's what makes Worker A ↔ Worker B cycles work (see the cycles post). Other resources can use that stub identifier early because they only need the name or ARN, not the configured resource.

Actions can't. If an Action body runs against an upstream's precreate stub, it sees a placeholder URL, hashes that, and records "I ran with this URL." Then the real reconcile fills in the actual URL, the converge phase notices the input drifted, and re-runs the body. You've now invoked the body twice — once against bad data, once against good — and emitted "running" before either of them was really running.

The fix is a separate signal per node: readyStable. It fires only after the real reconcile completes. Resources keep both signals (so they can still consume each other's precreate stubs); Actions wait on readyStable only. The body never runs against placeholder data.

// resources.ts — keeps two signals
yield* signalReady;        // fires after precreate (early)
// ... reconcile ...
yield* signalReadyStable;  // fires only after reconcile (terminal)

// actions.ts — only waits on terminal
yield* waitForStableDeps(upstreamFqns);

The plan log lines up with what actually happened:

[Bucket]         creating
[Api]            creating
[Api]            Uploading worker (280.32 KB) ...
[Api]            Enabling workers.dev subdomain...
[AnnounceDeploy] running         ← only here, after Api's reconcile
[AnnounceDeploy] ran

Pulling in dependencies

The runner signature so far is plain: (input) => Effect<Out, _, _>. But sometimes the runner itself needs a service — a database handle, a logger, an HTTP client. You don't want to construct those every time the body runs.

Action accepts a constructor form. The second argument is an Effect that yields its dependencies and returns the runner:

const Sync = Action("Sync", Effect.gen(function* () {
  const db = yield* Database;
  const logger = yield* Logger;
  return Effect.fn(function* (input: { table: string }) {
    yield* logger.info(`syncing ${input.table}`);
    return { rows: yield* db.count(input.table) };
  });
}));

The init Effect's Req bubbles to the call site:

const rows = yield* Sync({ table: bucket.name });
//          ^ Effect.Effect<Output<…>, never, Database | Logger | Stack>

The init runs once per process — Effect.cached memoizes it — and every Action instance reuses the resolved runner. Dependencies show up in your stack's R, your stack's providers satisfy them, the body gets a fully-constructed closure to call.

This is the same pattern as Effect's Layer construction. You yield what you need, return what you produce. Most Alchemy features follow it; Actions are no different.

Tag form for splitting contract and implementation

If you want the contract — "there is an Action called Sync with this input shape and this output shape" — to live in a different file from the implementation, use the class form:

class Sync extends Action<Sync, { table: string }, { rows: number }>()
  ("Sync") {}

const SyncLive = Sync.make(
  Effect.gen(function* () {
    const db = yield* Database;
    return Effect.fn(function* (input) {
      return { rows: yield* db.count(input.table) };
    });
  }),
);

Same pattern as Cloudflare.Worker's class form — the class is a Tag carrying the input/output types; .make() binds an implementation Layer that resolves the Tag. Stack providers include SyncLive, the constructor's Req picks up Sync, the planner has a runner to call.

.make() accepts either a direct runner or an init Effect.

In the plan

In the terraform-style preview, Actions get their own symbol — λ for a run, · for a skip:

Plan: 1 to create | 1 to update | 1 to run

~ Api (Cloudflare.Worker)
+ BucketA (Cloudflare.R2.Bucket)
λ AnnounceDeploy (AnnounceDeploy) [action]
· DbMigrate (DbMigrate) [action]

The [action] tag distinguishes them from resources without moving them out of the namespace tree — they sort alongside the resources they're related to. During apply λ swaps in a spinner; on success it switches to ✓ (cyan).

What this is not

An Action is not a runtime function. To run code from inside a deployed Worker or Lambda, use a Platform. Actions run at deploy time, once per input change, never on a request.

An Action is not a Resource. It has no read, no reconcile, no drift detection. If you need lifecycle management of a cloud entity, model that entity as a Resource.

An Action is not idempotent for free. The engine guarantees the body runs only when the input hash changes, but the body itself has to be safe to retry if the run is interrupted before it commits — its running state is persisted, the side effect inside the body is your responsibility.

Where this fits

Resources are the right shape when you're modeling a cloud entity that needs to converge to a desired state. Actions are the right shape for everything else that wants to participate in the same graph — deploy-time scripts, notifications, one-shot migrations, derived values computed from resource outputs.

The same graph means: upstream Outputs flow in as typed inputs, downstream resources can read outputs back, cycles are detected at plan time, --force works, removal drops state cleanly. The same graph means: Actions don't sit alongside your stack — they live inside it, one node among the others.

Where to go next