Skip to content

stevewallone/temporal-order-processing-poc

Repository files navigation

Order Processing Workflow - Temporal.io

Test License: MIT Node.js Version TypeScript

A production-ready order processing system built with Temporal.io that demonstrates the Saga pattern for distributed transaction management.

Table of Contents

Overview

This workflow orchestrates a complete order processing flow including:

  • Inventory reservation
  • Payment processing
  • Shipment creation
  • Automatic compensation on failures (Saga pattern)
  • Order cancellation support via signals
  • Real-time status queries

Architecture

Workflow: orderProcessingWorkflow

Orchestrates the order processing with automatic compensation:

  1. Reserve Inventory → Compensate: Release inventory
  2. Process Payment → Compensate: Refund payment
  3. Create Shipment → Compensate: Cancel shipment
  4. Complete Order

Activities

All external I/O operations are implemented as activities:

  • reserveInventory - Reserve stock for order items
  • releaseInventory - Release reserved inventory (compensation)
  • processPayment - Process payment through payment gateway
  • refundPayment - Refund payment (compensation)
  • createShipment - Create shipment with shipping provider
  • cancelShipment - Cancel shipment (compensation)
  • notifyCustomer - Send notifications (email/SMS)
  • updateOrderStatus - Update order status in database

Signals & Queries

  • Signal: cancelOrder - Cancel an in-progress order
  • Query: orderStatus - Get real-time order status

Setup

Prerequisites

  • Node.js 16+
  • Temporal Server running locally or Temporal Cloud account

Install Dependencies

npm install

Start Temporal Server (Local)

temporal server start-dev

Or use Docker:

docker run -p 7233:7233 -p 8233:8233 temporalio/auto-setup:latest

Running the Application

1. Build the Project

npm run build

2. Start the Worker

The worker processes workflows and activities:

npm run worker

3. Run the Client

Start an order:

npm run client start

Cancel an order:

npm run client cancel ORD-1234567890 "Customer requested cancellation"

Check order status:

npm run client status ORD-1234567890

4. Run the Web Server (Optional)

For a browser-based interface, start the web server:

npm run web

The web interface will be available at http://localhost:3000

Web Interface Features

  • Create Orders: Submit new orders through a web form
  • View Order Status: Check the status of any order by ID
  • Cancel Orders: Send cancellation signals to running workflows
  • List Orders: View all recent orders

API Endpoints

The web server exposes a REST API:

  • POST /api/orders - Create a new order
  • GET /api/orders/:orderId - Get order status
  • POST /api/orders/:orderId/cancel - Cancel an order
  • GET /api/orders - List recent orders
  • GET /health - Health check

Example: Create an order via API

curl -X POST http://localhost:3000/api/orders \
  -H "Content-Type: application/json" \
  -d '{
    "customerId": "CUST-123",
    "items": [
      {"productId": "PROD-001", "quantity": 2, "price": 29.99}
    ],
    "paymentDetails": {
      "paymentMethodId": "pm_test_123",
      "amount": 59.98,
      "currency": "USD"
    },
    "shippingAddress": {
      "street": "123 Main St",
      "city": "San Francisco",
      "state": "CA",
      "zipCode": "94105",
      "country": "USA"
    }
  }'

Testing

Run the test suite:

npm test

Tests cover:

  • Successful order processing
  • Payment failure compensation
  • Order cancellation via signal
  • Status queries

Configuration

Environment Variables

  • TEMPORAL_ADDRESS - Temporal server address (default: localhost:7233)
  • TEMPORAL_NAMESPACE - Temporal namespace (default: default)

Retry Policies

Activities are configured with exponential backoff:

retry: {
  initialInterval: '1s',
  backoffCoefficient: 2,
  maximumInterval: '1 minute',
  maximumAttempts: 3,
}

Timeouts

  • Activity timeout: 5 minutes
  • Worker shutdown grace time: 30 seconds

Key Features

Saga Pattern

Automatic compensation ensures data consistency:

try {
  await reserveInventory();
  await processPayment();
  await createShipment();
} catch (error) {
  // Compensate in reverse order
  await cancelShipment();
  await refundPayment();
  await releaseInventory();
}

Idempotency

All activities are designed to be idempotent using order IDs as idempotency keys.

Determinism

Workflow code is deterministic:

  • Uses workflow.now() instead of Date.now()
  • All I/O in activities
  • No random values or external dependencies

Error Handling

  • Non-retryable errors for business logic failures
  • Retryable errors for transient failures
  • Graceful degradation with notifications

Production Considerations

TODO: Implement Real Integrations

Current activities contain placeholder implementations. Replace with:

  1. Inventory Management

    • Database queries for stock levels
    • Distributed locking for reservations
    • Reservation expiration handling
  2. Payment Gateway

    • Stripe/PayPal/Square integration
    • 3DS authentication flows
    • PCI compliance considerations
  3. Shipping Provider

    • FedEx/UPS/USPS API integration
    • Address validation
    • Label generation
  4. Notifications

    • Email service (SendGrid, SES)
    • SMS service (Twilio)
    • Push notifications
  5. Database

    • PostgreSQL/MySQL for order storage
    • Transaction management
    • Audit logging

Monitoring

  • Enable Temporal Web UI: http://localhost:8233
  • Add custom metrics and logging
  • Set up alerts for workflow failures

Scaling

  • Run multiple workers for horizontal scaling
  • Configure worker concurrency based on load
  • Use task queue partitioning for high throughput

Security

  • Use TLS for Temporal Cloud connections
  • Encrypt sensitive data in workflow state
  • Implement authentication/authorization
  • Audit trail for all transactions

Deployment

Docker

FROM node:16-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --production
COPY dist ./dist
CMD ["node", "dist/worker.js"]

Kubernetes

Deploy workers as separate deployments:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: order-processing-worker
spec:
  replicas: 3
  template:
    spec:
      containers:
      - name: worker
        image: your-registry/order-worker:latest
        env:
        - name: TEMPORAL_ADDRESS
          value: "temporal-frontend:7233"

Resources

License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors