Triamorph Systems

Architecture · 13 min read · Sep 05, 2024

Resilient Microservices with Temporal: Workflow Orchestration & The Saga Pattern

Master distributed workflow orchestration with Temporal: implementing the Saga pattern for multi-service transactions, handling long-running workflows, and durable execution.

By Aman Aslam

Core Engineering Takeaways

  • Temporal records every workflow state transition to an event log, allowing workflows to resume immediately across server crashes without loss of state.
  • The Saga pattern ensures that if any downstream step fails, matching compensating activities (e.g. RefundPayment, ReleaseInventory) execute automatically in reverse order.
  • Workflows can sleep or wait for human approval for months without consuming active CPU threads or memory.

In a microservice architecture, a single business action like "Fulfill Customer Order" requires charging a credit card in Stripe, reserving inventory in a warehouse database, and scheduling courier dispatch. When service 3 fails after service 1 has charged the card, traditional databases lack distributed rollback primitives. Temporal solves this with durable code execution and the Saga compensation pattern.

1. The Fallacy of 2-Phase Commit in Microservices

Why distributed database locks cripple scalability and availability

Two-Phase Commit (2PC) locks database tables across multiple servers until all participants acknowledge completion. If any single network node stalls, the entire cluster freezes. In modern distributed systems, we adopt eventual consistency and compensating transactions.

2. How Temporal Achieves Durable Execution

Event-driven history replay that makes code execution invincible

Temporal executes code deterministically. If a worker pod crashes mid-function, a new worker spins up, replays past activity outcomes from the temporal event store, and resumes code execution from the exact line that failed without repeating completed work.

3. Implementing the Saga Pattern in TypeScript

Automating compensation activities upon downstream service errors

Below is a robust Temporal workflow executing an order checkout saga with automatic refund handlers.

workflows/order_checkout_saga.ts (typescript)
import { proxyActivities } from '@temporalio/workflow';
import type * as activities from './activities';

const { chargeCreditCard, reserveInventory, scheduleCourier, refundCreditCard, releaseInventory } =
  proxyActivities<typeof activities>({
    startToCloseTimeout: '1 minute',
    retry: { initialInterval: '1s', maximumAttempts: 5 }
  });

export async function orderCheckoutSaga(orderId: string, amount: number, items: string[]): Promise<void> {
  const compensations: (() => Promise<void>)[] = [];

  try {
    // Step 1: Charge Card
    await chargeCreditCard(orderId, amount);
    compensations.push(async () => await refundCreditCard(orderId, amount));

    // Step 2: Reserve Inventory
    await reserveInventory(orderId, items);
    compensations.push(async () => await releaseInventory(orderId, items));

    // Step 3: Schedule Courier (Simulate Failure)
    await scheduleCourier(orderId);

  } catch (err) {
    // Execute all registered compensations in reverse order
    for (const compensate of compensations.reverse()) {
      await compensate();
    }
    throw new Error(`Order checkout failed and was safely compensated: ${err}`);
  }
}

4. Operational Monitoring & Failure Recovery

Visualizing live workflows in the Temporal Web UI

Engineering teams gain real-time visibility into every inflight workflow, inspecting call stacks, activity retry counters, and variable states directly in a graphical dashboard.

Tags: temporal workflow orchestrationsaga pattern distributed transactionslong running microservice workflowsfault tolerant distributed systemsMicroservices

Related Engineering Practice & Case Studies

Engineering Practice Blueprint

Custom Web Development & SaaS Platforms →

Next.js & React web platforms engineered for sub-1.5s load times and 98+ Lighthouse scores.

View Practice Blueprint & Capabilities →
Production Client System

Portfolix Developer Portfolio Builder →

Modern developer portfolio builder platform delivering sub-5 minute deployments with 98+ Lighthouse scores and 100% clean code export.

Read Deployed Case Study (Sub-5 minute edge deployment with 100% clean code export) →

Related Engineering Articles & Guides

Explore all technical guides in our Articles & Guides Index → or discuss your architecture with our engineers via Technical Discovery →