Skip to content
TypeScript
12.2 KB
Raw Blame
---
title: Providers
description: Providers implement the lifecycle operations for a resource type — reconcile, delete, diff, read, and more.
---

A **Provider** implements the lifecycle operations for a resource
type. When you `yield*` a resource inside a Stack, alchemy looks up
the provider for that resource's type and calls the appropriate
lifecycle method. This is what gives meaning to a
[Resource](/infrastructure-as-code/resource) declaration — the engine plans, the
provider acts.

## Provider layers

Providers are registered as Effect Layers. `Cloudflare.providers()`
and `AWS.providers()` return Layers bundling every built-in provider
for that cloud:

```typescript
Alchemy.Stack(
  "MyApp",
  { providers: Cloudflare.providers(), state: Cloudflare.state() },
  Effect.gen(function* () {
    yield* Cloudflare.R2.Bucket("Bucket");
  }),
);
```

The type system enforces this — using a Cloudflare resource without
`Cloudflare.providers()` raises a compile-time error.

## Multiple providers

A stack can use any number of providers. Because providers are
Layers, combining them is just `Layer.mergeAll`:

```typescript
import * as Layer from "effect/Layer";

Alchemy.Stack(
  "MyApp",
  {
    providers: Layer.mergeAll(Cloudflare.providers(), AWS.providers()),
  },
  Effect.gen(function* () {
    yield* Cloudflare.R2.Bucket("Bucket");
    yield* AWS.SQS.Queue("Jobs");
  }),
);
```

This works for as many providers as you need — built-in ones
(`Cloudflare`, `AWS`, `Neon`, `Planetscale`, `Docker`, …) and
[custom providers](/infrastructure-as-code/custom-provider) merge
the same way:

```typescript
providers: Layer.mergeAll(
  Cloudflare.providers(),
  AWS.providers(),
  Neon.providers(),
  StripeProviders, // your own custom provider layer
),
```

The type system tracks the requirements per resource: each resource
you `yield*` demands its own provider from the merged layer, so a
missing provider is a compile-time error, never a deploy-time
surprise.

## Lifecycle operations

A provider is an object implementing some subset of these operations.
`reconcile` and `delete` are required; the rest are optional hooks
alchemy uses for richer behavior.

### `reconcile`

Required. Called for every "make it so" intent — first-time
provisioning, routine updates, and adoption takeovers. Returns the
**output attributes** that downstream resources can reference.

A reconciler is a single observe → ensure → sync → return flow:

```typescript
reconcile: Effect.fn(function* ({ news, output }) {
  let live = yield* observe(output);          // read live cloud state
  if (!live) live = yield* create(news);      // ensure it exists
  if (drifted(live, news)) {
    live = yield* update(live.id, news);      // sync only the delta
  }
  return toAttributes(live);                  // fresh attributes
}),
```

The provider receives `output: Attributes | undefined` and
`olds: Props | undefined`:

| `output`    | `olds`      | Meaning                              |
| ----------- | ----------- | ------------------------------------ |
| `undefined` | `undefined` | Greenfield — no prior resource       |
| defined     | defined     | Routine update                       |
| defined     | `undefined` | Adoption — engine adopted via `read` |

The reconciler must work for all three combinations. **Do not
branch the body on `output === undefined`** — that just renames the
old `create`/`update` split. Trust observed cloud state, not `olds`.

`reconcile` must be **idempotent**: alchemy may retry it after a
state persistence failure. Deterministic physical names plus the
observe step ensure a retry finds the existing resource and re-syncs
any drifted fields.

For a real reconciler built up step by step — observe, ensure,
sync, return, against the Stripe API — see the
[custom provider guide](/infrastructure-as-code/custom-provider#implement-reconcile).

### `delete`

Required. Called when a resource is removed from code, replaced, or
when running `alchemy destroy`. Like `reconcile`, must be **idempotent**
— treat "already deleted" as success.

```typescript
delete: ({ output }) =>
  Effect.promise(() => stripe.products.del(output.productId));
```

### `diff`

Optional. Called during planning to decide what kind of change is
needed when properties differ. Returns a tagged `Diff` describing
the action:

```typescript
diff: Effect.fn(function* ({ news, olds }) {
  if (news.region !== olds.region) {
    return { action: "replace" } as const;
  }
  if (news.name !== olds.name) {
    return { action: "update" } as const;
  }
  return { action: "noop" } as const;
}),
```

The shape is one of:

- **`{ action: "noop" }`** — properties differ trivially; don't
  call `update`.
- **`{ action: "update", stables?: [...] }`** — apply an in-place
  update. `stables` lists props that are guaranteed not to change
  during this update.
- **`{ action: "replace", deleteFirst?: boolean }`** — destroy and
  recreate (see [Resource Lifecycle › Replace](/infrastructure-as-code/resource-lifecycle#replace)).
  Set `deleteFirst: true` for resources that can't coexist with
  their replacement (e.g. unique-name constraints).
- **`void` / `undefined`** — fall back to the default behavior
  (treat the change as an `update`).

A provider can also declare top-level `stables` for attributes that
are immutable across all updates (e.g. ARNs, resource IDs).

For comparing nested objects, use the `deepEqual` and
`anyPropsAreDifferent` helpers from `alchemy/Diff`. If any input
might still be unresolved when `diff` runs (an unresolved `Output`),
guard with `isResolved` first and return `undefined` to let the
default path handle it.

### `read`

Optional. The engine consults `read` whenever a resource has no prior
state — both for **state recovery** (state lost between create and
persist) and for **adoption** (a fresh state store deploying against
existing cloud infrastructure). It is the single source of truth for
"does this resource exist, and is it ours?".

```typescript
read: Effect.fn(function* ({ id, olds, output }) {
  const stripe = yield* StripeClient;
  if (!output?.productId) return undefined;
  const product = yield* Effect.tryPromise(() =>
    stripe.products.retrieve(output.productId),
  ).pipe(Effect.catchAll(() => Effect.succeed(undefined)));
  if (!product) return undefined;
  return { productId: product.id, name: product.name };
}),
```

`read` returns one of three values:

- **`undefined`** — the resource doesn't exist. The engine will
  drive a normal `create`.
- **plain attributes** — the resource exists and we own it.
  The engine silently adopts: it persists the attributes as the
  initial `created` state and lets ordinary `diff` decide whether
  the next deploy is a noop or update.
- **`Unowned(attributes)`** — the resource exists but we *don't*
  own it. By default the engine fails with `OwnedBySomeoneElse`
  so you don't accidentally clobber a production resource.
  Re-running with `--adopt` (or scoping the effect with
  `adopt(true)`) unlocks a takeover.

`Unowned` is a brand from `alchemy/AdoptPolicy` — there's no wrapper
to unwrap, just a hidden symbol on the attributes object:

```typescript
import { Unowned } from "alchemy/AdoptPolicy";

read: Effect.fn(function* ({ id, olds }) {
  const live = yield* lookup(olds.name);
  if (!live) return undefined;
  const attrs = { productId: live.id, name: live.name };
  return ownsResource(id, live.tags) ? attrs : Unowned(attrs);
}),
```

**Inputs.** `read` may be called for an existence/adoption probe with
`output: undefined` (no prior state). Resources whose live lookup
requires a previously-persisted ID (e.g. `output.productId`) should
return `undefined` in that case — they have no way to find the
resource without it.

**Ownership detection.** Resources with no notion of ownership (e.g.
"the cloud API just gives us a single global object by name") should
always return plain attributes. The engine treats them as owned and
silent adoption is the default, so `--adopt` is unnecessary.
Resources with tag-based or naming-based ownership (most cloud
resources) should brand foreign-owned attributes with `Unowned`.

> **Lifecycle methods don't gate on ownership.** Once `read` clears a
> resource for write, `reconcile` can assume it's safe to proceed.
> Don't repeat the ownership check inside `reconcile` — that just
> hides the policy decision from the engine.

### `precreate`

Optional. Reserves a physical name (or stub resource) before
`create` runs. This is what enables [circular
bindings](/infrastructure-as-effects/circular-bindings) — Worker A can know Worker B's
URL before either is fully created.

### `observe`

Optional, and only useful next to `precreate`. A cycle precreates on
raw props before they resolve, so `read` can't check ownership yet.
`observe` gets the same raw props and reports what exists at the
identity `precreate` would claim, without writing:

```typescript
observe: Effect.fn(function* ({ id, news }) {
  if (!isResolved(news.name)) return Unresolved;
  const live = yield* lookup(news.name);
  if (!live) return undefined;
  const attrs = { productId: live.id, name: live.name };
  return ownsResource(id, live.tags) ? attrs : Unowned(attrs);
}),
```

The engine refuses an `Unowned` result before `precreate` runs, unless
adoption is allowed. Implement it whenever `precreate` can write to a
resource that already exists.

Return `Unresolved` when the identity isn't known yet. `undefined` would
say nothing exists there. The engine checks the resolved identity before
`reconcile` claims it. It refuses a delete-first replacement outright,
since it can't check the target before deleting the old resource.
`precreate` must not write to an identity it can't resolve.

During a replacement, `observe` and `read` also get `previous`, the
attributes of the generation being replaced. A provider that can't tell
its own resource apart by tags, like an explicitly named Container
application, reports that generation as owned:

```typescript
read: Effect.fn(function* ({ olds, previous }) {
  const live = yield* lookup(olds.name);
  if (!live) return undefined;
  const attrs = { productId: live.id, name: live.name };
  return live.id === previous?.productId ? attrs : Unowned(attrs);
}),
```

### `list`

Enumerates every existing resource of this type in the ambient
scope (account, region, or zone), returning the same `Attributes`
shape `read` produces — so each item is directly usable with
`delete`. This powers account-wide operations like
[`alchemy unsafe nuke`](/cli/nuke). It must paginate exhaustively;
resources with no enumeration API (singletons, existence-only
resources) return an empty array. Providers can opt out of nuke
with `nuke.singleton` (delete only resets always-present config)
or `nuke.skip` (the resource can never actually be deleted).

### `tail` / `logs`

Optional. Powers `alchemy logs --tail` (live log streaming) and
`alchemy logs` (historical fetch). Each returns a `Stream` or
`Effect` of `LogLine` values respectively.

## Plan and apply

Alchemy combines every provider's lifecycle operations into a single
**plan**, then **applies** it.

- **Plan** — for each declared resource, alchemy compares the
  desired props against persisted state and uses `diff` to decide
  whether it's a `create`, `update`, `replace`, or `noop`. Anything
  in state but no longer declared is marked for `delete`.
- **Apply** — alchemy walks the plan in dependency order and calls
  the matching lifecycle operation on each provider, surfacing the
  results as `Output`s for downstream resources.

See [Resource Lifecycle](/infrastructure-as-code/resource-lifecycle) for how a
resource moves through these phases over time.

## Authoring a custom provider

Providers are just Layers, so adding a new cloud or third-party API
is "declare a [Resource type](/infrastructure-as-code/resource), implement a
Layer" — and merge it alongside `Cloudflare.providers()` or
`AWS.providers()`. The [custom provider guide](/infrastructure-as-code/custom-provider)
builds a Stripe `Product` provider end-to-end.

## Where next

- [Custom Provider](/infrastructure-as-code/custom-provider) — step-by-step
  walkthrough of a Stripe `Product` provider.
- [Actions](/infrastructure-as-code/action) — deploy-time work that isn't a
  resource.
- [Resource lifecycle](/infrastructure-as-code/resource-lifecycle) — when each
  operation fires.