Skip to content
zapierPublic

About

Durable execution for TypeScript and Node.js. Write workflows as plain async code with replayable steps, callbacks, and waits that survive restarts. Powers Zaps. Runs on Zapier or your own compute.

Topics

Resources

Code of conduct

Security policy

Stars

70 stars

Watchers

0 watching

Forks

Repository files navigation

@zapier/zapier-durable

Durable execution for the Zapier SDK. Pluggable adapter model for different runtimes.

Pre-1.0: This package is published on the latest dist-tag while the API stabilises. Expect breaking changes between minor versions until 1.0.

Features

  • Clean ergonomics: Two consistent call styles everywhere (({ name, run, ...options }) or (name, run))
  • Optional schemas: zod schemas for the input, a step's result and a callback's payload. Input and step schemas take any zod version; callback payload schemas need zod 4.2 or later. Schemas are always optional; without one, the input is typed Record<string, unknown>
  • Adapter-based: Pluggable for different runtimes

Installation

pnpm add @zapier/zapier-durable

Quick Start

import { defineDurable } from "@zapier/zapier-durable";
import { z } from "zod";

const myDurable = defineDurable({
  name: "my-durable",
  description: "My durable example",
  inputSchema: z.object({ userId: z.string() }),
  run: async (ctx, input) => {
    // Steps are durable - they only run once even if the execution replays
    const result = await ctx.step("fetch-data", async () => {
      const response = await fetch("https://api.example.com/data");
      return response.json();
    });

    // Create a callback for external approval
    const [approvalPromise, callbackUrl] = await ctx.createCallback({
      name: "wait-for-approval",
      payloadSchema: z.object({ approved: z.boolean() }),
    });

    // Send the callback URL (wrapped in a step so it only runs once)
    await ctx.step("notify-approver", async () => {
      await notifyApprover(callbackUrl);
    });

    // Wait for the callback to be delivered
    const approval = await approvalPromise;

    if (!approval.approved) {
      throw new Error("Not approved");
    }

    return { approved: true, userId: input.userId };
  },
});

const response = await myDurable({ userId: "123" });

// Technically, we'd wait for an approval callback, and resume with the execution ID:
//   await myDurable(response.executionId)
// ...but imagine we had instant approval!

if (response.done) {
  console.log(response.result);
  // { approved: true, userId: "123" }
} else {
  console.log(response.error);
  // { message: "Not approved", name: "Error", stack?: string }
}

CLI

Durable runs are executed remotely on code-substrate-runner via the Zapier SDK CLI, gated behind the experimental stability tier: run-durable, get-durable-run, list-durable-runs, and cancel-durable-run. Opt in with --stability experimental, or ZAPIER_STABILITY=experimental in the environment. See the CLI reference for the full command list and options, or run --help for any command (the opt-in is required even for --help, since these commands aren't registered on the stable CLI surface):

npx zapier-sdk run-durable --help --stability experimental

Running outside Zapier

defineDurable is a library, and it runs anywhere Node.js runs. You can run it in three ways:

  • On Zapier. Zapier's hosted runner runs your code, keeps the journal, and resumes each execution for you. This is how Next Gen Zaps run: a Next Gen Zap's code is a defineDurable workflow, and the runner runs it with a pinned version of this package. See Create your first Next Gen Zap.
  • Bring your own compute (push mode). Zapier's runner keeps the journal and tells your servers when to resume. Your code runs on your servers. See Bring your own compute.
  • Fully on your own. Your process runs the code and keeps the journal. This needs no Zapier account. See Fully on your own.

Bring your own compute (push mode)

Zapier's runner keeps the journal and schedules each wake. Your code runs on your servers. Use a RestClient with a Zapier SDK token, and set notificationUrl to a public URL on your servers:

import { RestClient } from "@zapier/zapier-durable";
import { resolveAuthToken } from "@zapier/zapier-sdk";

// Reads the token that `npx zapier-sdk login` stores, or ZAPIER_CREDENTIALS.
const token = await resolveAuthToken();
const client = new RestClient({
  token: token!,
  notificationUrl: "https://my-app.example.com/durable/resume",
});

const first = await myDurable({ userId: "u_123" }, { client });
await myExecutions.add(first.executionId!);

myExecutions stands for the store where your app keeps the IDs of the executions it started.

When a wait ends or a callback arrives, the runner POSTs { "execution_id": "..." } to the notification URL. The POST can arrive up to a minute later. Resume the execution in that handler:

// In the handler for POST /durable/resume:
const { execution_id } = JSON.parse(body);
// The POST is unauthenticated: only resume IDs your app recorded when it started them.
if (
  typeof execution_id !== "string" ||
  !(await myExecutions.has(execution_id))
) {
  return; // reply 2xx and do nothing
}
await myDurable(execution_id, { client });
  • The notification URL must be public. The runner does not follow redirects.
  • Reply with a 2xx status. After 5 failed deliveries in a row, the runner fails the execution. A 410 reply stops the wakes.
  • The POST carries no credentials. Treat it as a signal, and check that execution_id is an execution you started.
  • Zapier's runner must be enabled for your Zapier account.

Fully on your own

Your process runs the code, as in push mode. It also does the runner's part: it keeps the journal and decides when to resume each execution. This needs no Zapier account.

Storage. Pass a client to choose where the journal lives:

  • FilesystemClient keeps each execution's journal in a directory on local disk. Use it from a single process: it always grants the lease, so it does not stop two workers from running the same execution.
  • MemoryClient keeps the journal in memory. Use it in tests.
  • For production, keep the journal in Postgres, MySQL, or SQLite. Write a DurableClient for your database: the callbackBaseUrl property and the create, checkout, checkpoint, release, and callback methods. The interface is small, and MemoryClient and FilesystemClient implement the same one. checkout must return each operation with its current status: a wait whose time has passed is completed, and a callback whose timeout has passed is expired. It also takes a lease. Return { leased: false } while another worker holds an unexpired lease, so several workers can share one store without running the same execution at the same time.

Running. Call a durable with input to start an execution. It runs until it completes or suspends. Call it with the execution ID to resume it:

import { FilesystemClient } from "@zapier/zapier-durable";

const client = new FilesystemClient({ baseDir: "/var/lib/my-app/durable" });

const first = await myDurable({ userId: "u_123" }, { client });
// Later, after a wait ends or a callback arrives:
const next = await myDurable(first.executionId!, { client });
console.log(next.done ? next.result : "still waiting");

Scheduling. The library does not include a scheduler. Your process keeps the IDs of suspended executions. It resumes each one when its wait ends (the journal records each wait's resume_at) or after it delivers a callback with client.callback(token, payload). On Zapier and in push mode, Zapier's runner decides when to resume.

API

defineDurable

Define a durable execution with optional input/output schemas.

// Object signature, preferred
defineDurable({ name, inputSchema?, run, description?, outputSchema? })

// Positional signature
defineDurable(name, run)

Options:

  • inputSchema? - Optional zod schema for the input, from any zod version. It types input in run, and Zapier reads it to find the workflow's input fields, so write it with zod in the workflow's file. It is checked only when you call the workflow directly with an input object, not when Zapier starts a run, and run gets the input as passed. Parse it in run when you need validation, defaults or transforms
  • outputSchema? - Optional zod schema for output validation, from any zod version
  • description?: string - Optional description for the durable

ctx.step

Execute a durable step. Steps are memoized - they only execute once even if the execution replays.

// Simple signature
await ctx.step(name, run)

// Object signature with options
await ctx.step({ name, run, outputSchema?, maxAttempts?, retryDelaySeconds? })

Options:

  • outputSchema? - Optional zod schema for the step's result, from any zod version. It types the result; it is not checked at runtime
  • maxAttempts?: number - Optional max retry attempts on failure
  • retryDelaySeconds?: number - Optional base delay between retries (backs off exponentially)

ctx.createCallback

Create a callback that can be awaited later. Returns [promise, callbackUrl].

// Simple signature - awaiting resolves the delivered payload
const [promise, callbackUrl] = await ctx.createCallback("my-callback");

// With a payload schema (edge validation + typing), no deadline
const [promise, callbackUrl] = await ctx.createCallback({
  name: "my-callback",
  payloadSchema: z.object({ result: z.string() }),
});

// Send callbackUrl somewhere, then await the promise
const result = await promise;

payloadSchema needs zod 4.2 or later: the callback sends the schema to the server as JSON Schema, using the schema's toJSONSchema method.

With a deadline (timeoutSeconds): the callback gets a server-enforced expiry, and awaiting it resolves a CallbackResult - exactly one journaled outcome, delivered in time or expired:

const [promise, callbackUrl] = await ctx.createCallback({
  name: "approval",
  timeoutSeconds: 24 * 60 * 60, // 24h SLA
  payloadSchema: z.object({ approved: z.boolean() }),
});

const result = await promise;
if (result.status === "delivered") {
  // result.value is the delivered payload, typed from payloadSchema;
  // result.at is the server-journaled delivery time
} else {
  // result.status === "expired": the deadline elapsed and result.at is
  // the server-journaled deadline. The outcome is decided once: a late
  // delivery to the callback URL cannot flip it back to delivered.
}

The outcome is decided once by the server and read back from the journal on replay - the SDK's clock never participates in deadlines. Without timeoutSeconds the callback never expires and awaiting resolves the bare payload, as in the simple signature.

Racing durable operations is unsupported. Do not use Promise.race over steps, waits, or callbacks; express deadline patterns with timeoutSeconds and branch on result.status instead. (Promise.all over durable operations is supported.)

ctx.wait

Wait for a specified duration.

// Simple signature
await ctx.wait("delay-step", 60);

// Object signature
await ctx.wait({ name: "delay-step", seconds: 60 });

Configuration

Configuration is via environment variables:

Variable Default Description
ZAPIER_DURABLE_ADAPTER "filesystem" Adapter type: "filesystem", "zapier", or "memory"
ZAPIER_DURABLE_FS_DIR ~/.config/zapier-sdk/durable Directory for filesystem adapter
ZAPIER_DURABLE_DETERMINISM_GUARD "on" Enable determinism checking ("on" or "off")
ZAPIER_DURABLE_API_URL https://sdkapi.zapier.com/api/v0/sdk/code-substrate-runner Base URL for the API (when adapter=zapier)
ZAPIER_DURABLE_API_JWT (auto for localhost) JWT token for API authentication
ZAPIER_DURABLE_DEBUG "false" Enable debug logging ("true" or "false")
ZAPIER_DURABLE_WAIT_INPROCESS_THRESHOLD_SECONDS 0 (disabled) Waits at or below the remaining threshold at first await complete in-process instead of suspending
ZAPIER_DURABLE_WAIT_INPROCESS_BUDGET_SECONDS 120 Cap on total in-process wait seconds per tick

Test Mode (Integration Tests)

For faster integration tests, these env vars cap durations:

Variable Default Description
ZAPIER_DURABLE_TEST_MAX_WAIT_SECONDS (none) Cap ctx.wait() durations
ZAPIER_DURABLE_TEST_MAX_RETRY_DELAY_MILLISECONDS (none) Cap retry backoff delays (deprecated alias: ..._MS)

Example:

ZAPIER_DURABLE_TEST_MAX_WAIT_SECONDS=2 \
ZAPIER_DURABLE_TEST_MAX_RETRY_DELAY_MILLISECONDS=500 \
pnpm test

Contributing

The GitHub repository for this package is a read-only mirror. Zapier does not accept outside pull requests or other code contributions. To report a problem, contact Zapier support.

License

This SDK's source code is licensed under the MIT License (see LICENSE). The MIT License covers the code only. Using the Zapier service and APIs through this SDK is governed separately by the Zapier Terms of Service (https://zapier.com/legal/terms-of-service) or your other agreement with Zapier for use of the Zapier service, which apply regardless of the code license.

About

Durable execution for TypeScript and Node.js. Write workflows as plain async code with replayable steps, callbacks, and waits that survive restarts. Powers Zaps. Runs on Zapier or your own compute.

Topics

Resources

Code of conduct

Security policy

Stars

70 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages