Architecture · Nov 26, 2026 · 12 min read

Temporal 1.23 with TypeScript: Durable Workflows for SaaS

Build fault-tolerant order processing, billing, and onboarding flows with Temporal’s TypeScript SDK. Concrete setup, retry policies, signals, testing, production patterns, and trade-offs versus queues

Temporal 1.23 with TypeScript: Durable Workflows for SaaS

Understanding the Problem Temporal Solves

Modern SaaS applications contain long-running business processes that span hours or days: onboarding sequences with external API calls, subscription billing cycles that retry on payment failures, order fulfillment that talks to multiple vendors, or KYC verification that waits for manual review. Traditional approaches using cron jobs, message queues, or background job libraries fail when a process crashes, a server restarts, or a third-party API is temporarily unavailable. The usual fixes—persistent queues, careful checkpointing, and distributed locks—quickly become complex and brittle.

Temporal solves this by providing durable execution. You write ordinary TypeScript functions that represent your entire business process. The platform guarantees that once a workflow starts, it runs to completion exactly once, even if every machine it runs on is destroyed. It achieves this by persisting every execution step as an event in a highly available log and replaying the code from the beginning, skipping already-completed deterministic parts. This eliminates the need for manual state management, idempotency keys, or complex retry loops scattered across your codebase.

The programming model feels like writing synchronous code while gaining automatic retries, timeouts, compensation logic, and visibility into every running process. For startups, this means shipping complex flows faster and sleeping better knowing that a database outage at 3 a.m. will not leave customers in inconsistent states.

Core Concepts You Must Master

Four primitives drive everything in Temporal:

  • Workflows: Deterministic TypeScript functions that orchestrate the high-level process. They can call activities, sleep for months, react to signals, and spawn child workflows.
  • Activities: Non-deterministic operations that interact with the outside world—calling databases, sending emails, charging credit cards, or invoking third-party APIs. These are the only places side effects are allowed.
  • Workers: Processes that poll the Temporal server for tasks, execute either workflows or activities, and report results back.
  • Task Queues: Named channels that route work from the server to the correct worker pool. You can have multiple queues for different priorities or bounded resource groups.

A workflow execution has a unique ID and can run for years. The Temporal server stores the full event history in its persistence store (PostgreSQL, Cassandra, or MySQL). Because workflow code must be deterministic—no direct calls to Date.now(), Math.random(), or external state—the platform can safely replay history during recovery.

Setting Up a Local Development Environment

Start by running a local Temporal cluster using Docker Compose. The official temporalio/docker-compose repository provides everything needed.

git clone https://github.com/temporalio/docker-compose.git
cd docker-compose
docker compose up

This starts the Temporal server on port 7233, the web UI on http://localhost:8080, and PostgreSQL for persistence. For production-like testing, add the Temporal CLI:

brew install temporalio/tap/temporal
temporal server start-dev --db-filename temporal.db

Next, create a new TypeScript project for your workers and workflows:

mkdir temporal-saas && cd temporal-saas
npm init -y
npm install @temporalio/client @temporalio/worker @temporalio/activity @temporalio/workflow typescript ts-node
npx tsc --init

Configure tsconfig.json with "module": "NodeNext" and "moduleResolution": "NodeNext". You now have everything to write and test workflows locally.

Your First Workflow and Activity

Let’s implement a simple “onboarding” workflow that sends a welcome email and creates a trial subscription. First, define an activity that talks to an external email service.

import { proxyActivities } from '@temporalio/workflow';
import type * as activities from './activities';

const { sendWelcomeEmail, createTrialSubscription } = proxyActivities<typeof activities>({
  startToCloseTimeout: '30 seconds',
  retry: {
    maximumAttempts: 5,
    backoffCoefficient: 2,
    initialInterval: '1s',
  },
});

export async function OnboardingWorkflow(email: string, userId: string): Promise<void> {
  await sendWelcomeEmail(email);
  await createTrialSubscription(userId);
  console.log('Onboarding completed for', userId);
}

The corresponding activity file uses the real implementation:

import { ActivityContext } from '@temporalio/activity';

export async function sendWelcomeEmail(email: string): Promise<void> {
  const { resend } = ActivityContext();
  await resend.emails.send({
    from: 'hello@yourcompany.com',
    to: email,
    subject: 'Welcome!',
    html: '<h1>Welcome to our platform</h1>',
  });
}

export async function createTrialSubscription(userId: string): Promise<void> {
  // Call Stripe or database
  console.log('Created trial for user', userId);
}

Notice that activities receive a context object automatically injected by the worker. This gives access to logging, heartbeating for long-running tasks, and cancellation handling.

Start the worker that listens on a task queue:

import { Worker } from '@temporalio/worker';
import * as activities from './activities';

async function run() {
  const worker = await Worker.create({
    workflowsPath: require.resolve('./workflows'),
    activities,
    taskQueue: 'onboarding',
  });
  await worker.run();
}

run().catch((err) => {
  console.error(err);
  process.exit(1);
});

From a client (could be a Next.js API route), start the workflow:

import { Client } from '@temporalio/client';

const client = new Client();
await client.workflow.start('OnboardingWorkflow', {
  args: ['user@example.com', 'usr_123'],
  taskQueue: 'onboarding',
  workflowId: 'onboarding-usr_123',
});

Error Handling, Retries, and Timeouts

Temporal’s retry policy is applied at the activity level. The example above used a maximum of 5 attempts with exponential backoff. You can also set nonRetryableErrorTypes for errors that should fail the workflow immediately, such as ValidationError.

Workflows themselves rarely need retries because they are replayed from history. For business-level compensation, implement the Saga pattern using a compensation stack:

export async function PurchaseWorkflow(itemId: string, customerId: string) {
  const compensations: Array<() => Promise<void>> = [];

  try {
    const reservation = await reserveInventory(itemId);
    compensations.push(() => releaseInventory(reservation.id));

    const payment = await chargeCustomer(customerId, reservation.price);
    compensations.push(() => refundPayment(payment.id));

    await shipItem(itemId, customerId);
  } catch (err) {
    for (const compensation of compensations.reverse()) {
      try {
        await compensation();
      } catch (compensationErr) {
        // Log but continue rollback
      }
    }
    throw err;
  }
}

This pattern gives explicit control over rollback while still benefiting from Temporal’s automatic retry and recovery guarantees.

Signals, Queries, and Updates

Workflows are not fire-and-forget. You can interact with a running workflow using three mechanisms:

  • Signals: Send asynchronous messages that modify workflow state (e.g., “cancel order”, “add item to cart”).
  • Queries: Read current workflow state without altering it (e.g., “what is the current order status?”).
  • Updates (new in recent SDK versions): Synchronous, validated mutations that return a response.

Example signal handler inside a workflow:

import { defineSignal, setHandler } from '@temporalio/workflow';

export const cancelOrder = defineSignal<[string]>('cancelOrder');

export async function OrderWorkflow(orderId: string) {
  let status = 'pending';
  let cancelledReason = '';

  setHandler(cancelOrder, (reason: string) => {
    status = 'cancelled';
    cancelledReason = reason;
  });

  // Rest of workflow logic that checks status
  await sleep('30 days'); // example long sleep
}

From the client you send the signal with client.workflow.signal. Queries are defined similarly with defineQuery.

Case Study: Subscription Billing Workflow

Consider a metered billing system for an AI SaaS. The workflow must:

  1. Charge the monthly base fee on the 1st of each month.
  2. Calculate usage every hour and add overage charges.
  3. Retry failed charges with increasing delays and eventually downgrade the account.
  4. Allow customer support to pause billing via signal.

Here is a simplified but realistic implementation skeleton (production version would use proper Stripe integration and usage lookup activities):

import { proxyActivities, sleep, defineSignal, setHandler } from '@temporalio/workflow';
import type * as activities from './activities';

const { chargeCustomer, calculateUsage, downgradeAccount } = proxyActivities<typeof activities>({
  startToCloseTimeout: '2 minutes',
  retry: { maximumAttempts: 10, backoffCoefficient: 1.8 },
});

export const pauseBilling = defineSignal<[]>('pauseBilling');
export const resumeBilling = defineSignal<[]>('resumeBilling');

export async function SubscriptionWorkflow(customerId: string, planId: string) {
  let isPaused = false;
  let currentPeriodEnd = Date.now() + 30 * 24 * 60 * 60 * 1000;

  setHandler(pauseBilling, () => { isPaused = true; });
  setHandler(resumeBilling, () => { isPaused = false; });

  while (true) {
    if (!isPaused) {
      const usage = await calculateUsage(customerId);
      if (usage > 0) {
        await chargeCustomer(customerId, usage * 0.12); // $0.12 per unit
      }
      await chargeCustomer(customerId, 49); // base fee
    }

    await sleep('1 hour'); // In production use calendar-based scheduling via Temporal schedules
  }
}

This workflow runs forever, sleeping between billing cycles. Temporal’s ContinueAsNew can be used after 30 days or when history grows beyond 10 000 events to keep history size manageable. The platform automatically handles the handoff.

In production we added heartbeating to the usage calculation activity because it queries a high-volume ClickHouse cluster and can take longer than the default 30-second timeout. Heartbeating also allows clean cancellation if the customer cancels their account while usage is being calculated.

Integrating Temporal with Next.js Applications

Run Temporal workers in a separate long-lived process, not inside serverless functions. For a Vercel or Netlify deployment, host workers on Fly.io, Railway, or Kubernetes. The Next.js API routes only act as clients that start workflows or send signals.

Use a singleton Temporal client instance cached with globalThis to avoid creating new connections on every request:

declare global {
  var temporalClient: Client | undefined;
}

In your API route for starting a workflow:

export async function POST(req: Request) {
  const client = globalThis.temporalClient ??= new Client();
  const { userId } = await req.json();

  await client.workflow.start('OnboardingWorkflow', {
    args: [userId],
    workflowId: `onboarding-${userId}`,
    taskQueue: 'onboarding',
    retry: { maximumAttempts: 1 }, // workflow level retry is usually not needed
  });

  return Response.json({ status: 'started' });
}

For local development, run the worker with ts-node alongside next dev using tools like concurrently.

Testing Workflows

Temporal provides first-class test utilities that mock activities and control time. A test for the billing workflow can advance time by 30 days in a single line:

import { TestWorkflowEnvironment } from '@temporalio/testing';
import { Worker } from '@temporalio/worker';

test('charges base fee after 30 days', async () => {
  const env = await TestWorkflowEnvironment.create();
  const worker = await Worker.create({
    workflowsPath: require.resolve('./workflows'),
    activities: mockActivities,
    taskQueue: 'test',
  });

  const result = await env.createWorkflowHandle(SubscriptionWorkflow)
    .execute({ customerId: 'test' });

  await env.sleep('30 days'); // instantly advances workflow time
  // assert that charge activity was called with base fee

  await env.teardown();
});

Because the test environment controls the clock, you can test monthly, yearly, or even multi-year workflows in seconds. This capability alone often justifies adopting Temporal for complex business logic.

Production Deployment Options

You have two main choices: self-host the Temporal server or use Temporal Cloud. Self-hosting requires running the server, a visibility store (Elasticsearch or PostgreSQL), and a persistence database. You must manage upgrades, backups, and multi-region replication yourself. Most startups begin with Temporal Cloud, which offers a serverless pricing model based on actions and storage. The first 10 million actions per month are free, making it inexpensive for early-stage products.

Configure mTLS between workers and the server for security. Temporal Cloud provides namespace-level isolation and automatic certificate management. Enable the Visibility feature to query running workflows with SQL-like syntax in the web UI or via the ListWorkflowExecutions API.

Observability, Metrics, and Tracing

Temporal emits OpenTelemetry traces automatically. Configure the worker to export traces to Jaeger, Grafana Tempo, or your existing observability backend. Key metrics to monitor include:

  • workflow task execution latency
  • activity execution failure rate
  • task queue backlog depth
  • history size per workflow

Use the @temporalio/opentelemetry package to add custom spans inside activities for database calls or third-party HTTP requests. This gives you end-to-end visibility from a customer clicking “Subscribe” all the way through payment, provisioning, and welcome email.

Performance Characteristics and Scaling

A single Temporal worker on a 2-vCPU machine can comfortably handle hundreds of concurrent workflow tasks per second when activities are I/O bound. For CPU-heavy activities, scale worker pools horizontally and use multiple task queues with different priorities. The server itself scales by adding frontend and history pods in Kubernetes. Temporal Cloud abstracts all of this and currently powers workflows at companies processing billions of executions per month.

History size is the main limiting factor. Workflows that exceed roughly 50 000 events should call continueAsNew to reset history while preserving business state via memo or arguments.

Common Anti-Patterns and How to Avoid Them

1. Performing non-deterministic operations inside workflows (calling external APIs, using Math.random()). Move these to activities.

2. Storing large objects in workflow variables. Keep only references and fetch data inside activities.

3. Using long-running activities without heartbeating. Any activity expected to run longer than 30 seconds must heartbeat.

4. Starting workflows from inside other workflows without using ChildWorkflow or ExternalWorkflow handles. This breaks replay.

5. Ignoring workflow IDs. Always use business-meaningful, idempotent IDs (e.g., subscription-${customerId}) so you can safely retry starting the workflow.

When to Choose Temporal vs Other Tools

BullMQ (already covered in previous articles) is excellent for simple background jobs and has lower operational cost. Use BullMQ when your processes are short, do not require complex state or human-in-the-loop steps, and you already run Redis.

Temporal shines when you need:

  • Processes that last days or months
  • Strong guarantees around exactly-once execution
  • Built-in compensation and saga support
  • Visibility and debugging of every historical run
  • Easy interaction with running processes (signals/queries)

AWS Step Functions offers similar durability but uses JSON-based state machines instead of real code, leading to vendor lock-in and poorer developer experience for complex logic. Temporal’s SDKs let you use the full power of TypeScript, including classes, modules, and testing frameworks you already know.

Many teams adopt a hybrid approach: use BullMQ for fire-and-forget jobs and Temporal for the critical customer-facing business processes that must never get stuck.

After implementing the subscription billing workflow described earlier, our hypothetical AI SaaS reduced billing-related support tickets by 87 % and eliminated all “lost subscription” incidents that previously occurred during payment provider outages. The ability to pause, inspect, and manually signal any customer’s workflow from the Temporal Web UI gave the support and finance teams superpowers they never had with scattered queue workers.

The investment in learning Temporal pays off the first time you successfully recover from a three-hour database outage without writing a single line of recovery code. Your workflows simply continue from where they left off, exactly as designed.

Keep reading

Related Articles