Generate and deploy verified, production-ready software

Model your business with domain-driven design and your infrastructure as code, in one typed program. Stories and proofs verify the business logic, the type checker verifies the infrastructure, and Layers ground it in any platform.

One program, from the business rule to the cloud resource

You or your agent declare the software against contracts: the business as a model, its behavior as stories and rules, and everything it needs from outside. Layers ground each contract in a real platform. Every step then proves the program works before the next one starts: types, stories and proofs answer in milliseconds, emulated tests in seconds, and the real cloud in about 20 seconds. CI deploys a preview, tests it, and ships it on merge.

See the example app and benchmark on GitHub

StagedThe agent's typing is staged. A story runs in memory, with nothing deployed.
bank — test/Account.story.test.ts
1 
agent · bankSTORY
›

Declare · the model

Declare the whole system in its own language

Alchemy Domain gives the words your business already uses a place in the code. A command declares what it asks for and every way it can end, an aggregate decides it in a pure function, and an event records what happened. What the model needs from outside, a payment provider or a database, it declares as a contract and nothing more. You, your agent and the type checker all read the same program.

src/WithdrawMoney.command.ts
export class WithdrawMoney extends Domain.Command("WithdrawMoney", {
  target: AccountId,
  input: { amount: Schema.Int },
  events: [MoneyWithdrawn],
  rejects: [NotOpen, InsufficientFunds],
  reply: { balance: Schema.Int },
}) {}
src/Account.aggregate.ts
decide: {
  WithdrawMoney: (account, cmd) =>
    account._tag !== "Open"
      ? new NotOpen()
      : cmd.amount > account.balance
        ? new InsufficientFunds({
            balance: account.balance,
            requested: cmd.amount,
          })
        : [
            new MoneyWithdrawn({
              amount: cmd.amount,
              balanceAfter: account.balance - cmd.amount,
            }),
          ],
},

Specify · stories

Specify behavior as stories, in the words of the business

A story is a test written in the model's own terms: given this history, when this command, then these events. It reads like the requirement it came from, so the person who asked for the behavior can check it. It runs the real model in memory in milliseconds, policies and sagas included, and fails if anything happens that it doesn't account for. Write the story first, and let your agent change the model until it passes.

test/Account.test.ts
it.effect("an overdraft is rejected with the evidence", () =>
  story(
    Story.given(
      account,
      new AccountOpened({ owner: "sam" }),
      new MoneyDeposited({ amount: 50, balanceAfter: 50 }),
    ),
    Story.when(account, new WithdrawMoney({ amount: 80 })),
    Story.rejected(
      new InsufficientFunds({ balance: 50, requested: 80 }),
    ),
  ),
);
test/Fraud.test.ts
it.effect("a risky withdrawal freezes the account", () =>
  story(
    Story.given(
      account,
      new AccountOpened({ owner: "sam" }),
      new MoneyDeposited({ amount: 90_000, balanceAfter: 90_000 }),
    ),
    Story.when(account, new WithdrawMoney({ amount: 60_000 })),
    Story.then(
      account,
      new MoneyWithdrawn({ amount: 60_000, balanceAfter: 30_000 }),
    ),
    // the fraud policy asks the scoring service; the story answers
    Story.call(FraudCheck.score, {
      accountId: account.id,
      amount: 60_000,
    }),
    Story.succeed(FraudCheck.score, { risk: 0.95 }),
    Story.then(
      account,
      new AccountFrozen({
        reason: "fraud risk 0.95",
        by: system("FraudReview"),
      }),
    ),
  ),
);

Prove · invariants

State an invariant and have it proved

A story tests the cases you thought of. An invariant is a predicate that must hold in every case, and nobody writes a case for it. One test proves each aggregate's invariants for every state and every input, then explores every short sequence of commands across the model for one that breaks a rule. A broken invariant fails with the shortest sequence that breaks it, written as a story.

src/Account.aggregate.ts
// rules sit on the aggregate, beside decide
invariants: {
  NeverOverdrawn: (account) =>
    account._tag !== "Open" || account.balance >= 0,
},
transitions: {
  AClosedAccountStaysClosed: ({ before, after }) =>
    before._tag !== "Closed" || after._tag === "Closed",
},

// one test verifies every rule in the model
it.effect("the bank keeps its promises", () =>
  Verify.model(Bank, { apis: [CustomerApi, SupportApi], story }),
);
pnpm test
Proved: for every state and every input,
after any number of commands
  ✓ Account.NeverOverdrawn
  ✓ Account.WithinDailyLimit
  ✓ Account.AClosedAccountStaysClosed

Checked: every sequence of up to 2 commands,
each event delivered twice, each saga step run
twice, every answer FraudCheck can give
19,641 sequences, 10,648 states
  ✓ Bank.TransfersLoseNoMoney
  ✓ Bank.NoTransferLeftPending
  ✓ Bank.EveryTransferEnds

Sampled: 200 longer sequences, of up to
12 commands picked at random (seed 1)
  ✓ none breaks a rule

Ground · Layers

A Layer grounds it in a real platform

A specified and proved model still knows nothing about the cloud. A Layer answers each contract with a real platform, and owns the resources and the access that takes: Durable Objects for the aggregates, a database for the ledger, a vendor for payments. Swap a Layer and the same program runs in memory, on your machine, or on another platform.

Agents
harnesses, coming soon
src/BankWorker.ts
const BankLive = Bank.layer(BankHandlers).pipe(
  // the ledger projection writes to a D1 database
  Layer.provideMerge(D1LedgerStore),
  Layer.provide(
    Layer.mergeAll(
      // one Durable Object per aggregate
      DomainCloudflare.layerDurableObjects(),
      // Payments and FraudCheck, answered by vendors
      StripePayments,
      SiftFraudCheck,
      Cloudflare.D1.QueryDatabaseBinding,
    ),
  ),
);

Guarantee least-privilege IAM at compile time

Each binding grants one permission and returns a client that can only make that call. The policy is inferred from the bindings, so it grants exactly what the code uses: nothing broader slips in, and nothing the code needs is left out. Reach for an operation you didn't bind and the code doesn't compile, so a missing permission shows up in your editor, not as an AccessDenied in production.

Run · on your machine

Run the whole system on your machine

alchemy dev grounds the same program in local Layers: Workers, Durable Objects, queues and buckets run on emulated services on your machine, and the frontend reloads as you type. Set dev: true in a test and the same suite runs against those services in seconds, with nothing deployed.

alchemy.run.ts
import Api from "./src/api.ts";

export default Alchemy.Stack(
  "my-app",
  { providers: Cloudflare.providers() },
  Effect.gen(function* () {
    // backend: a Cloudflare Worker, run locally in workerd
    const api = yield* Api;
    // frontend: a Vite app that calls it
    const web = yield* Cloudflare.Website.Vite("Web", {
      env: { VITE_API_URL: api.url },
    });
    return { web: web.url, api: api.url };
  }),
);
~/my-appDEV

Test · live cloud

Test against a live cloud deployment

Once it works locally, run the same test without LOCAL=1. It deploys the app to a stage of its own, runs against real Workers, buckets and permissions, and destroys the stage afterwards, in about 20 seconds.

test/api.test.ts
const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
  providers: Cloudflare.providers(),
  dev: !!process.env.LOCAL, // emulated, or the real cloud
});

const stack = beforeAll(deploy(Stack)); // its own stage
afterAll(destroy(Stack));

test("PUT + GET round-trips through R2", Effect.gen(function* () {
  const { url } = yield* stack;
  const res = yield* HttpClient.get(`${url}/object/hello.txt`);
  expect(yield* res.text).toBe("hi!");
}));
CI · pr-1729TEST
$

Ship · preview per PR

Every pull request gets its own deployment

CI deploys each pull request to its own stage, runs the same tests, and comments a link to try it. The comment is a resource in the same program, so it is updated on every push and deleted with the preview. Merging deploys to production.

alchemy.run.ts
const api = yield* Api;const pr = yield* Config.option(Config.Int("PULL_REQUEST"));const sha = yield* Config.String("GITHUB_SHA"); if (Option.isSome(pr)) {  yield* GitHub.Comment("Preview", {    owner: "acme",    repository: "my-app",    issueNumber: pr.value,    body: Output.interpolate`Preview: ${api.url} (${sha})`,    allowDelete: true,  });}

Observe · trace the model

Production traces speak the model's language

The model gives telemetry a shape. Every command, event, policy, view and saga records an OpenTelemetry span named after itself and the resource it ran on, and the spans join into one trace from a click to everything it caused. Provide one Layer to export them. Its datasets, dashboards and alert monitors are resources in the same program, so monitoring ships with the app.

trace · Account.WithdrawMoney
Domain.send Account.WithdrawMoney          the Worker
└─ Domain.decide Account.WithdrawMoney     the account's Durable Object
   │   event MoneyWithdrawn
   ├─ Domain.view AccountSummary
   ├─ Domain.view DailyOutflow
   └─ Domain.policy FraudReview
      ├─ Domain.external FraudCheck.score
      └─ Domain.send Account.FreezeAccount
         └─ Domain.decide Account.FreezeAccount

Loved by the people shipping with it

What builders say after putting Alchemy in front of their agents, their Cloudflare apps, and their production infrastructure.

Get started.

  1. Installpnpm add https://pkg.alchemy.run/alchemy/pr:3743:5915225 effect
  2. Paste this into your coding agent
    Help me build an Alchemy app on Cloudflare. Start by reading https://alchemy.run/getting-started and follow it exactly: scaffold a fresh project, install the dependencies, create the `alchemy.run.ts` Stack with a single Cloudflare R2 Bucket (no Worker yet), and run `alchemy deploy` so I sign in to Cloudflare and provision the Bucket. Confirm the Bucket is live before moving on. Then STOP and ASK ME what I want to build. From there, consult only the docs you need for what I asked for — don't march me through every tutorial. A Worker only gets added later if what I want to build needs one (the tutorial covers that in part-2). Tutorial — foundations, work through whichever parts I haven't touched: https://alchemy.run/cloudflare/tutorial/part-1 First Stack (state store + first resource) https://alchemy.run/cloudflare/tutorial/part-2 Add a Worker https://alchemy.run/cloudflare/tutorial/part-3 Testing https://alchemy.run/cloudflare/tutorial/part-4 Local Dev (`alchemy dev`) https://alchemy.run/cloudflare/tutorial/part-5 CI/CD (per-PR previews from GitHub Actions) For everything else (Cloudflare deep-dives, guides, concepts), fetch https://alchemy.run/llms.txt — it's the index of the guide and concept docs. Use it to look up the specific page you need instead of guessing URLs. The per-resource API reference is indexed separately in https://alchemy.run/llms-full.txt — it's large, so only fetch it when you need a specific resource's reference page. Important: - Confirm with me before each deploy. Don't batch. - Do NOT instruct me to export CLOUDFLARE_ACCOUNT_ID or CLOUDFLARE_API_TOKEN. Alchemy stores credentials in profiles — `alchemy profile edit` (or the first `alchemy deploy`) prompts interactively for OAuth or an API token and saves it to ~/.alchemy/profiles.json. - Use pnpm: `pnpm add` to install packages and `pnpm alchemy deploy` to deploy. - If I'm migrating from Alchemy v1 (async/await), find the v1 migration guide via llms.txt and read it first.
  3. Shippnpm alchemy deploy