Temporal TypeScript SDK Samples

repository·main·Indexed 19 days ago

https://github.com/temporalio/samples-typescript

A collection of sample projects demonstrating patterns and API usage with the Temporal TypeScript SDK. Examples include activity cancellation and heartbeating, dependency injection, AI SDK integration with streaming model output, the Batch Sliding Window pattern, child workflows, continue-as-new, and cron workflows.

Tokens
103.7K
Snippets
333
Records
406
Agent score
66%

What's inside samples-typescript

  1. Overview of Lambda Worker sample

    main

    This sample demonstrates how to run a Temporal Worker inside an AWS Lambda function using the @temporalio/lambda-worker package.

    Key features include:

    • Serverless Execution: Running Temporal Workflows and Activities in AWS Lambda.
    • Observability: Optional OpenTelemetry (OTel) instrumentation that exports traces and metrics via AWS Distro for OpenTelemetry (ADOT).
    • Structured Logging: Automatic detection and use of @aws-lambda-powertools/logger to produce JSON logs for CloudWatch.
    • Optimized Bundling: Uses a pre-bundling script to prepare Workflow code with OTel interceptors to improve Lambda cold start performance.
  2. Overview of MCP scenarios in openai-agents

    main

    This sample demonstrates how to use stateless and stateful Model Context Protocol (MCP) servers with a Temporal-backed OpenAI agent via the @temporalio/openai-agents plugin. All MCP servers are bundled and run locally (either in-process or as a localhost/subprocess server) so no external MCP service is required.

    Included scenarios:

    • filesystem: Stateless MCP over stdio. Uses a bundled server (src/mcp/servers/filesystem-server.ts) to expose listFiles and readFile operations on src/mcp/servers/sample-files/.
    • streamable-http: Stateless MCP over a localhost Streamable-HTTP server (src/mcp/servers/tools-server.ts) providing add, getWeather, and getSecret tools.
    • sse: Stateless MCP over a localhost SSE server (src/mcp/servers/sse-server.ts) providing add, getWeather, and getSecret tools.
    • prompt-server: Stateless MCP server (src/mcp/servers/prompt-server.ts) exposing a summarize prompt. The workflow fetches this prompt to use as the agent's instructions.
    • stateful-memory: A stateful server using StatefulMCPServerProvider (src/mcp/servers/notes-server.ts) with saveNote, listNotes, and readNote. The workflow manages the server lifecycle by calling connect() and cleanup() to preserve state during the run.
  3. Overview of the Food Delivery App sample

    main

    The Food Delivery App is a comprehensive sample application demonstrating reliable distributed systems using Temporal. It is structured as a Turborepo monorepo containing shared packages and three distinct applications.

    Key features demonstrated include:

    • Workflow Logic: Located in packages/workflows/order.ts, it showcases activity retries, non-retryable failures, Signals, Queries, and state change timeouts using condition().
    • List Workflow API: Demonstrated in the getOrders API route handler within the driver app.
    • Architecture:
      • apps/menu/: Customer-facing app (Next.js, Tailwind, tRPC).
      • apps/driver/: Driver portal for meal pickup and delivery.
      • apps/worker/: The Temporal Worker.
      • packages/: Shared logic and workflow definitions.
  4. Available OpenAI Agent samples

    main

    The openai-agents/ repository contains several specialized samples demonstrating different orchestration patterns:

    • basic: Single agent with core building blocks (Activity-backed tools, inline tools, agent context, structured output, etc.).
    • handoffs: Triage agent routing to specialists using Agent[] or handoff().
    • agent-patterns: Multi-agent orchestration (chaining, parallelization, LLM-as-judge, guardrails).
    • sessions: Conversation history using WorkflowSafeMemorySession and continueAsNew.
    • human-approval: Human-in-the-loop patterns using Signals and state rehydration.
    • tools: Server-side hosted tools (web search, image generation, code interpreter).
    • tracing: Tracing implementations (Custom TracingProcessor, OpenAI exporter, OpenTelemetry).
    • model-providers: Using custom ModelProvider for OpenAI-compatible endpoints.
    • reasoning-content: Accessing reasoning_content via direct SDK calls in Activities.
    • mcp: Local Model Context Protocol (MCP) servers (stdio, HTTP, SSE).
    • hosted-mcp: Using HostedMCPTool with Signal-driven approval.
    • multi-agent: Planner/Writer patterns (fan-out/fan-in).
    • stateful-conversation: Long-running workflows using Updates and Queries.
    • nexus-tools: Exposing Nexus Operations via nexusOperationAsTool.
    • streaming: Experimental streaming of agent events over a Workflow Stream.
  5. Execute Nexus Operations directly from client code

    main

    This sample demonstrates how to use Nexus to execute Operations directly from a Temporal Client without wrapping them in a caller Workflow. It covers:

    • Synchronous Operations: Executing an operation that returns a result immediately (e.g., an echo operation).
    • Workflow-backed Operations: Executing an operation that triggers a Workflow in a different namespace (e.g., a hello operation).
    • Management: Listing and counting standalone Nexus Operation executions.

    Note: Support for Standalone Nexus Operations in the Temporal TypeScript SDK is currently in Pre-release and APIs are experimental. You must use a Temporal server version that supports this feature (e.g., the dev server build v1.7.4-standalone-nexus-operations).

    # This sample demonstrates how to execute Nexus Operations directly from client code, without wrapping them in a caller Workflow.
  6. LangSmith Tracing Sample Scenarios

    main

    The langsmith/ directory contains several scenarios demonstrating different tracing patterns:

    • activity-tracing: Demonstrates a traceable model call inside an Activity, nested under the Workflow and Activity runs.
    • workflow-tracing: Demonstrates replay-safe traceable calls in a Workflow body. These are emitted exactly once and are not duplicated during workflow replay.
    • agent-pipeline: Demonstrates a multi-step agent where the trace threads through Activities and a child Workflow.
    • message-handlers: Demonstrates traceable calls inside Signal and Update handlers, nested under each handler's specific run.
  7. Activity usage patterns in Activities Examples

    main

    This sample demonstrates three specific patterns for using Activities:

    • External HTTP requests: Using axios within an activity (see makeHTTPRequest in src/activities/index.ts).
    • Cancellable HTTP requests: Using cancellationSignal to make an HTTP request cancellable (see cancellableFetch in src/activities/cancellable-fetch.ts).
    • Asynchronous Activity completion: Using the AsyncCompletionClient to complete an activity asynchronously (see doSomethingAsync in src/activities/async-completion.ts).
  8. Nexus RPC Sample Structure

    main

    The nexus-hello sample is organized as follows:

    • src/api.ts: Defines the Nexus Service, including its input and output types.
    • src/caller/: Contains sample Workflows that invoke Nexus Operations.
    • src/service/: Contains the Nexus Service handler implementation and the Workflows used by the Nexus Operations.
    • src/starter.ts: Entry point to trigger the caller Workflows.
  9. Explore Temporal TypeScript Samples

    main

    The samples-typescript repository provides a comprehensive collection of examples for building with the Temporal TypeScript SDK. Samples are categorized by complexity and use case:

    Basic

    • Hello World: Simple Workflow and Activity definitions.
    • mTLS: Connecting to Temporal Cloud using mTLS authentication.
    • Pure ESM: Configuring Temporal with TypeScript and Pure ES Modules.
    • JavaScript: Hello World implementation in vanilla JavaScript.

    API Demos

    • Activity APIs: Includes patterns for HTTP requests (makeHTTPRequest), cancellable fetches (cancellableFetch), async completion (doSomethingAsync), dependency injection, and worker-specific task queues.
    • Nexus APIs: Demonstrates defining Nexus Services, implementing Operation handlers, and calling Operations from Workflows or standalone Clients.
    • Workflow APIs: Covers Timers (sleep), Signals, Queries, Mutexes, State management, Schedules, Child Workflows, and the continueAsNew API for infinite workflows.

    Production & Advanced

    • Production Readiness: Build optimization, environment configuration via TOML, custom logging (Winston), Sinks, and Worker Versioning.
    • Advanced Features: Interceptors (OpenTelemetry), raw gRPC calls, and LangSmith tracing.

    AI / LLM Integration

    • OpenAI Agents: Integration with the OpenAI Agents SDK, covering multi-agent orchestration, human-in-the-loop approval, MCP (Model Context Protocol) servers, and streaming agent responses over Workflow Streams.
  10. Expose Temporal workflows as Nexus operations

    main

    This sample demonstrates how to expose a long-running Temporal workflow's queries, updates, and signals as Nexus operations. It provides two distinct architectural patterns for integrating Temporal with Nexus, depending on whether the caller needs to manage the workflow lifecycle or if the workflow is managed by a handler worker.

    Patterns for Nexus Integration

    1. Caller Pattern (callerpattern/): Used when you want to signal an existing workflow.

      • Workflow Creation: The handler worker starts the workflow automatically on boot.
      • Workflow ID Management: Only the handler knows the workflow ID.
      • Nexus Service: Uses NexusGreetingService.
      • Use Case: When the workflow is a long-running background process and the caller only needs to interact with it via signals/queries.
    2. On-Demand Pattern (ondemandpattern/): Used when you want to create and run workflows on demand and then signal them.

      • Workflow Creation: The caller starts the workflow via a Nexus operation.
      • Workflow ID Management: The caller chooses and passes the workflow ID in every operation.
      • Nexus Service: Uses NexusRemoteGreetingService.
      • Use Case: When the caller requires full lifecycle control and needs to specify which workflow instance to target.
  11. Understand the Batch Sliding Window pattern

    main

    The Batch Sliding Window pattern is used for high-throughput batch processing while maintaining a bounded history size.

    Key components:

    • SlidingWindowWorkflow: The parent workflow that manages the window. It starts a configured number of RecordProcessorWorkflow children in parallel. To prevent the workflow history from growing indefinitely, it uses the continue-as-new pattern after processing a preconfigured number of children.
    • RecordProcessorWorkflow: A child workflow that processes a single record. Upon completion, it sends a signal to the parent SlidingWindowWorkflow to notify it that a slot in the window has opened.
    • Scaling: Because a single SlidingWindowWorkflow has limited throughput due to its window size, you can scale horizontally by running multiple instances of SlidingWindowWorkflow in parallel.

    In this specific sample, the workflow processes 90 records using a sliding window of 10 parallel workers across 3 partitions, with a page size of 5 records per continue-as-new iteration.

  12. Architectural patterns for Next.js and Temporal integration

    main

    When integrating Next.js with Temporal, this sample follows two specific architectural patterns:

    1. Client-side vs. Workflow Timeout Modeling

    This sample models timeouts on both the client-side and within the Temporal workflow. This is a UX tradeoff to provide immediate feedback to the user.

    • Alternative: If a single source of truth is critical, the frontend can poll an API endpoint that executes a Query on the workflow.
    • Alternative: For instantaneous updates, a long-polling or WebSocket subscription model can be used.

    2. Next.js API Routes as a Proxy to Temporal

    Instead of the browser talking to Temporal directly, the Next.js frontend communicates with Next.js API routes, which then interact with Temporal.

    • Reasoning: Temporal Clients use gRPC to communicate with the Temporal Server. It is significantly easier and more secure to manage gRPC connections and authentication secrets on the server-side (Next.js API routes) than in the browser.
    • Alternative: For direct browser-to-Temporal communication, you can use grpc-web on the frontend combined with an ambassador router/Envoy proxy for backend authorization.