diff --git a/docs/build-your-first-basic-workflow/build-your-first-workflow.mdx b/docs/build-your-first-basic-workflow/build-your-first-workflow.mdx
new file mode 100644
index 0000000000..9f9eb27114
--- /dev/null
+++ b/docs/build-your-first-basic-workflow/build-your-first-workflow.mdx
@@ -0,0 +1,2101 @@
+---
+id: build-your-first-workflow
+title: Build Your First Workflow
+sidebar_label: "Part 1: Build Your First Workflow"
+hide_table_of_contents: true
+description: Learn Temporal's core concepts by building a money transfer Workflow. Experience reliability, failure handling, and live debugging in a short tutorial.
+keywords:
+ - temporal
+ - workflow
+ - tutorial
+ - money transfer
+ - reliability
+tags:
+ - Getting Started
+ - Tutorial
+---
+
+import { SetupSteps, SetupStep, CodeSnippet } from "@site/src/components/elements/SetupSteps";
+import { CallToAction } from "@site/src/components/elements/CallToAction";
+import { TemporalProgress } from "@site/src/components/TemporalProgress";
+import { StatusIndicators } from "@site/src/components/StatusIndicators";
+import { RetryPolicyComparison } from "@site/src/components/RetryPolicyComparison";
+import { NextButton } from "@site/src/components/TutorialNavigation";
+import SdkTabs from "@site/src/components/elements/SdkTabs";
+import { FaPython, FaJava } from 'react-icons/fa';
+import { SiGo, SiTypescript, SiPhp, SiDotnet, SiRuby } from 'react-icons/si';
+
+export const TUTORIAL_LANGUAGE_ORDER = [
+ { key: 'py', label: 'Python', icon: FaPython },
+ { key: 'go', label: 'Go', icon: SiGo },
+ { key: 'java', label: 'Java', icon: FaJava },
+ { key: 'ts', label: 'TypeScript', icon: SiTypescript },
+ { key: 'php', label: 'PHP', icon: SiPhp },
+ { key: 'dotnet', label: '.NET', icon: SiDotnet },
+ { key: 'rb', label: 'Ruby', icon: SiRuby },
+];
+
+In this tutorial, you'll build and run your first Temporal application.
+You'll understand the core building blocks of Temporal and learn how Temporal helps you build crash proof applications through durable execution.
+
+
+
+ Temporal beginner
+
+
+
+
+
+## Introduction
+
+
+### Prerequisites
+
+Before starting this tutorial:
+
+- **Set up a local development environment** for developing Temporal applications
+- **Ensure you have Git installed** to clone the project
+
+
+
+### What You'll Build
+
+You’ll build a basic money transfer app from the ground up, learning how to handle essential transactions like deposits, withdrawals, and refunds using Temporal.
+
+**Why This Application?:**
+Most applications require multiple coordinated steps - processing payments, sending emails, updating databases.
+This tutorial uses money transfers to demonstrate how Temporal ensures these multi-step processes complete reliably, resuming exactly where they left off even after any failure.
+
+
+
+
+
+In this sample application, money comes out of one account and goes into another.
+However, there are a few things that can go wrong with this process.
+If the withdrawal fails, then there is no need to try to make a deposit.
+But if the withdrawal succeeds, but the deposit fails, then the money needs to go back to the original account.
+
+One of Temporal's most important features is its ability to **maintain the application state when something fails**.
+When failures happen, Temporal recovers processes where they left off or rolls them back correctly.
+This allows you to focus on business logic, instead of writing application code to recover from failure.
+
+
+
+
+
+
+ git clone https://github.com/temporalio/money-transfer-project-template-python
+
+
+ cd money-transfer-project-template-python
+
+
+
+
+ git clone https://github.com/temporalio/money-transfer-project-template-go
+
+
+ cd money-transfer-project-template-go
+
+
+
+
+ git clone https://github.com/temporalio/money-transfer-project-java
+
+
+ cd money-transfer-project-java
+
+
+
+
+ git clone https://github.com/temporalio/money-transfer-project-template-ts
+
+
+ cd money-transfer-project-template-ts
+
+
+
+
+ git clone https://github.com/temporalio/money-transfer-project-template-dotnet
+
+
+ cd money-transfer-temporal-template-dotnet
+
+
+
+
+ git clone https://github.com/temporalio/money-transfer-project-template-ruby
+
+
+ cd money-transfer-project-template-ruby
+
+
+
+
+ git clone https://github.com/temporalio/money-transfer-project-template-php
+
+
+ cd money-transfer-project-template-php
+
+
+ composer install
+
+
+
+}>
+
+### Download the example application
+
+The application you'll use in this tutorial is available in a GitHub repository.
+
+Open a new terminal window and use `git` to clone the repository, then change to the project directory.
+
+Now that you've downloaded the project, let's dive into the code.
+
+
+
+
+:::tip
+The repository for this tutorial is a GitHub Template repository, which means you could clone it to your own account and use it as the foundation for your own Temporal application.
+:::
+
+
+
+ Temporal Application Components
+
+
+
+
+
+
+
+}>
+
+
+
+### Let's Recap: Temporal's Application Structure
+
+The Temporal Application will consist of the following pieces:
+
+1. **A Workflow** written in your programming language of choice and your installed Temporal SDK in that language. A Workflow defines the overall flow of the application.
+2. **An Activity** is a function or method that does specific operation - like withdrawing money, sending an email, or calling an API. Since these operations often depend on external services that can be unreliable, Temporal automatically retries Activities when they fail.
+In this application, you'll write Activities for withdraw, deposit, and refund operations.
+3. **A Worker**, provided by the Temporal SDK, which runs your Workflow and Activities reliably and consistently.
+
+
+
+
+
+
+What You'll Build and Run
+
+The project in this tutorial mimics a "money transfer" application.
+It is implemented with a single Workflow, which orchestrates the execution of three Activities (Withdraw, Deposit, and Refund) that move money between the accounts.
+
+To perform a money transfer, you will do the following:
+
+1. **Launch a Worker**: Since a Worker is responsible for executing the Workflow and Activity code, at least one Worker must be running for the money transfer to make progress.
+
+2. **Submit a Workflow Execution request** to the Temporal Service: After the Worker communicates with the Temporal Service, the Worker will begin executing the Workflow and Activity code. It reports the results to the Temporal Service, which tracks the progress of the Workflow Execution.
+
+
+
+:::important
+None of your application code runs on the Temporal Server. Your Worker, Workflow, and Activity run on your infrastructure, along with the rest of your applications.
+:::
+
+## Step 1: Build your Workflow and Activities
+
+
+
+
+
+
+In the Temporal Go SDK, a Workflow Definition is a Go function that accepts a Workflow Context and input parameters.
+
+This is what the Workflow Definition looks like for the money transfer process:
+
+**workflow.go**
+
+```go
+func MoneyTransfer(ctx workflow.Context, input PaymentDetails) (string, error) {
+ // RetryPolicy specifies how to automatically handle retries if an Activity fails.
+ retrypolicy := &temporal.RetryPolicy{
+ InitialInterval: time.Second,
+ BackoffCoefficient: 2.0,
+ MaximumInterval: 100 * time.Second,
+ MaximumAttempts: 500, // 0 is unlimited retries
+ NonRetryableErrorTypes: []string{"InvalidAccountError", "InsufficientFundsError"},
+ }
+
+ options := workflow.ActivityOptions{
+ // Timeout options specify when to automatically timeout Activity functions.
+ StartToCloseTimeout: time.Minute,
+ // Optionally provide a customized RetryPolicy.
+ // Temporal retries failed Activities by default.
+ RetryPolicy: retrypolicy,
+ }
+
+ // Apply the options.
+ ctx = workflow.WithActivityOptions(ctx, options)
+
+ // Withdraw money.
+ var withdrawOutput string
+ withdrawErr := workflow.ExecuteActivity(ctx, Withdraw, input).Get(ctx, &withdrawOutput)
+ if withdrawErr != nil {
+ return "", withdrawErr
+ }
+
+ // Deposit money.
+ var depositOutput string
+ depositErr := workflow.ExecuteActivity(ctx, Deposit, input).Get(ctx, &depositOutput)
+ if depositErr != nil {
+ // The deposit failed; put money back in original account.
+ var result string
+ refundErr := workflow.ExecuteActivity(ctx, Refund, input).Get(ctx, &result)
+ if refundErr != nil {
+ return "",
+ fmt.Errorf("Deposit: failed to deposit money into %v: %v. Money could not be returned to %v: %w",
+ input.TargetAccount, depositErr, input.SourceAccount, refundErr)
+ }
+ return "", fmt.Errorf("Deposit: failed to deposit money into %v: Money returned to %v: %w",
+ input.TargetAccount, input.SourceAccount, depositErr)
+ }
+
+ result := fmt.Sprintf("Transfer complete (transaction IDs: %s, %s)", withdrawOutput, depositOutput)
+ return result, nil
+}
+```
+
+The `MoneyTransfer` function takes in the details about the transaction, executes Activities to withdraw and deposit the money, and returns the results of the process. The `PaymentDetails` type is defined in `shared.go`:
+
+**shared.go**
+
+```go
+type PaymentDetails struct {
+ SourceAccount string
+ TargetAccount string
+ Amount int
+ ReferenceID string
+}
+```
+
+
Activity Definition
+
+Activities handle the business logic. Each Activity function calls an external banking service:
+
+**activity.go**
+
+```go
+func Withdraw(ctx context.Context, data PaymentDetails) (string, error) {
+ log.Printf("Withdrawing $%d from account %s.\n\n",
+ data.Amount,
+ data.SourceAccount,
+ )
+
+ referenceID := fmt.Sprintf("%s-withdrawal", data.ReferenceID)
+ bank := BankingService{"bank-api.example.com"}
+ confirmation, err := bank.Withdraw(data.SourceAccount, data.Amount, referenceID)
+ return confirmation, err
+}
+
+func Deposit(ctx context.Context, data PaymentDetails) (string, error) {
+ log.Printf("Depositing $%d into account %s.\n\n",
+ data.Amount,
+ data.TargetAccount,
+ )
+
+ referenceID := fmt.Sprintf("%s-deposit", data.ReferenceID)
+ bank := BankingService{"bank-api.example.com"}
+ confirmation, err := bank.Deposit(data.TargetAccount, data.Amount, referenceID)
+ return confirmation, err
+}
+```
+
+
+
+
+
+
+
+Activities handle the business logic. Each Activity method calls an external banking service:
+
+**AccountActivity.java**
+
+```java
+@ActivityInterface
+public interface AccountActivity {
+ @ActivityMethod
+ void withdraw(String accountId, String referenceId, int amount);
+
+ @ActivityMethod
+ void deposit(String accountId, String referenceId, int amount);
+
+ @ActivityMethod
+ void refund(String accountId, String referenceId, int amount);
+}
+```
+
+**AccountActivityImpl.java**
+
+```java
+public class AccountActivityImpl implements AccountActivity {
+ @Override
+ public void withdraw(String accountId, String referenceId, int amount) {
+ System.out.printf("\nWithdrawing $%d from account %s.\n[ReferenceId: %s]\n",
+ amount, accountId, referenceId);
+ }
+
+ @Override
+ public void deposit(String accountId, String referenceId, int amount) {
+ System.out.printf("\nDepositing $%d into account %s.\n[ReferenceId: %s]\n",
+ amount, accountId, referenceId);
+ }
+
+ @Override
+ public void refund(String accountId, String referenceId, int amount) {
+ System.out.printf("\nRefunding $%d to account %s.\n[ReferenceId: %s]\n",
+ amount, accountId, referenceId);
+ }
+}
+```
+
+
+
+
+
+
Workflow Definition
+
+In the Temporal TypeScript SDK, a Workflow Definition is a regular TypeScript function that accepts some input values.
+
+This is what the Workflow Definition looks like for the money transfer process:
+
+**workflows.ts**
+
+```typescript
+import { proxyActivities } from '@temporalio/workflow';
+import { ApplicationFailure } from '@temporalio/common';
+
+import type * as activities from './activities';
+import type { PaymentDetails } from './shared';
+
+export async function moneyTransfer(details: PaymentDetails): Promise {
+ // Get the Activities for the Workflow and set up the Activity Options.
+ const { withdraw, deposit, refund } = proxyActivities({
+ // RetryPolicy specifies how to automatically handle retries if an Activity fails.
+ retry: {
+ initialInterval: '1 second',
+ maximumInterval: '1 minute',
+ backoffCoefficient: 2,
+ maximumAttempts: 500,
+ nonRetryableErrorTypes: ['InvalidAccountError', 'InsufficientFundsError'],
+ },
+ startToCloseTimeout: '1 minute',
+ });
+
+ // Execute the withdraw Activity
+ let withdrawResult: string;
+ try {
+ withdrawResult = await withdraw(details);
+ } catch (withdrawErr) {
+ throw new ApplicationFailure(`Withdrawal failed. Error: ${withdrawErr}`);
+ }
+
+ //Execute the deposit Activity
+ let depositResult: string;
+ try {
+ depositResult = await deposit(details);
+ } catch (depositErr) {
+ // The deposit failed; try to refund the money.
+ let refundResult;
+ try {
+ refundResult = await refund(details);
+ throw ApplicationFailure.create({
+ message: `Failed to deposit money into account ${details.targetAccount}. Money returned to ${details.sourceAccount}. Cause: ${depositErr}.`,
+ });
+ } catch (refundErr) {
+ throw ApplicationFailure.create({
+ message: `Failed to deposit money into account ${details.targetAccount}. Money could not be returned to ${details.sourceAccount}. Cause: ${refundErr}.`,
+ });
+ }
+ }
+ return `Transfer complete (transaction IDs: ${withdrawResult}, ${depositResult})`;
+}
+```
+
+The `PaymentDetails` type is defined in `shared.ts`:
+
+**shared.ts**
+
+```typescript
+export type PaymentDetails = {
+ amount: number;
+ sourceAccount: string;
+ targetAccount: string;
+ referenceId: string;
+};
+```
+
+
Activity Definition
+
+Activities handle the business logic. Each Activity function calls an external banking service:
+
+**activities.ts**
+
+```typescript
+import type { PaymentDetails } from './shared';
+import { BankingService } from './banking-client';
+
+export async function withdraw(details: PaymentDetails): Promise {
+ console.log(
+ `Withdrawing $${details.amount} from account ${details.sourceAccount}.\n\n`
+ );
+ const bank1 = new BankingService('bank1.example.com');
+ return await bank1.withdraw(
+ details.sourceAccount,
+ details.amount,
+ details.referenceId
+ );
+}
+
+export async function deposit(details: PaymentDetails): Promise {
+ console.log(
+ `Depositing $${details.amount} into account ${details.targetAccount}.\n\n`
+ );
+ const bank2 = new BankingService('bank2.example.com');
+ return await bank2.deposit(
+ details.targetAccount,
+ details.amount,
+ details.referenceId
+ );
+}
+
+export async function refund(details: PaymentDetails): Promise {
+ console.log(
+ `Refunding $${details.amount} to account ${details.sourceAccount}.\n\n`
+ );
+ const bank1 = new BankingService('bank1.example.com');
+ return await bank1.deposit(
+ details.sourceAccount,
+ details.amount,
+ details.referenceId
+ );
+}
+```
+
+
+
+
+
+
Workflow Definition
+
+In the Temporal Ruby SDK, a Workflow Definition is a class that extends `Temporalio::Workflow::Definition`.
+
+This is what the Workflow Definition looks like for the money transfer process:
+
+**workflow.rb**
+
+```ruby
+class MoneyTransferWorkflow < Temporalio::Workflow::Definition
+ def execute(details)
+ retry_policy = Temporalio::RetryPolicy.new(
+ max_interval: 10,
+ non_retryable_error_types: [
+ 'InvalidAccountError',
+ 'InsufficientFundsError'
+ ]
+ )
+
+ Temporalio::Workflow.logger.info("Starting workflow (#{details})")
+
+ withdraw_result = Temporalio::Workflow.execute_activity(
+ BankActivities::Withdraw,
+ details,
+ start_to_close_timeout: 5,
+ retry_policy: retry_policy
+ )
+
+ begin
+ deposit_result = Temporalio::Workflow.execute_activity(
+ BankActivities::Deposit,
+ details,
+ start_to_close_timeout: 5,
+ retry_policy: retry_policy
+ )
+
+ "Transfer complete (transaction IDs: #{withdraw_result}, #{deposit_result})"
+ rescue Temporalio::Error::ActivityError => e
+ # Since the deposit failed, attempt to recover by refunding
+ begin
+ refund_result = Temporalio::Workflow.execute_activity(
+ BankActivities::Refund,
+ details,
+ start_to_close_timeout: 5,
+ retry_policy: retry_policy
+ )
+
+ "Transfer complete (transaction IDs: #{withdraw_result}, #{refund_result})"
+ rescue Temporalio::Error::ActivityError => refund_error
+ Temporalio::Workflow.logger.error("Refund failed: #{refund_error}")
+ end
+ end
+ end
+end
+```
+
+The `TransferDetails` struct is defined in `shared.rb`:
+
+**shared.rb**
+
+```ruby
+TransferDetails = Struct.new(:source_account, :target_account, :amount, :reference_id) do
+ def to_s
+ "TransferDetails { #{source_account}, #{target_account}, #{amount}, #{reference_id} }"
+ end
+end
+```
+
+
Activity Definition
+
+Activities handle the business logic. Each Activity class calls an external banking service:
+
+**activities.rb**
+
+```ruby
+module BankActivities
+ class Withdraw < Temporalio::Activity::Definition
+ def execute(details)
+ puts("Doing a withdrawal from #{details.source_account} for #{details.amount}")
+ raise InsufficientFundsError, 'Transfer amount too large' if details.amount > 1000
+
+ "OKW-#{details.amount}-#{details.source_account}"
+ end
+ end
+
+ class Deposit < Temporalio::Activity::Definition
+ def execute(details)
+ puts("Doing a deposit into #{details.target_account} for #{details.amount}")
+ raise InvalidAccountError, 'Invalid account number' if details.target_account == 'B5555'
+
+ "OKD-#{details.amount}-#{details.target_account}"
+ end
+ end
+
+ class Refund < Temporalio::Activity::Definition
+ def execute(details)
+ puts("Refunding #{details.amount} back to account #{details.source_account}")
+
+ "OKR-#{details.amount}-#{details.source_account}"
+ end
+ end
+end
+```
+
+
+
+
+
+
Workflow Definition
+
+In the Temporal PHP SDK, a Workflow Definition is a class marked with the `#[WorkflowInterface]` attribute.
+
+This is what the Workflow Definition looks like for the money transfer process:
+
+**MoneyTransfer.php**
+
+```php
+bankingActivity = Workflow::newActivityStub(
+ Banking::class,
+ ActivityOptions::new()
+ ->withStartToCloseTimeout('5 seconds')
+ ->withRetryOptions(
+ RetryOptions::new()
+ ->withMaximumAttempts(3)
+ ->withMaximumInterval('2 seconds')
+ ->withNonRetryableExceptions([InvalidAccount::class, InsufficientFunds::class]),
+ ),
+ );
+ }
+
+ #[WorkflowMethod('money_transfer')]
+ #[ReturnType(Type::TYPE_STRING)]
+ public function handle(PaymentDetails $paymentDetails): \Generator
+ {
+ # Withdraw money
+ $withdrawOutput = yield $this->bankingActivity->withdraw($paymentDetails);
+
+ # Deposit money
+ try {
+ $depositOutput = yield $this->bankingActivity->deposit($paymentDetails);
+ return "Transfer complete (transaction IDs: {$withdrawOutput}, {$depositOutput})";
+ } catch (\Throwable $depositError) {
+ # Handle deposit error
+ Workflow::getLogger()->error("Deposit failed: {$depositError->getMessage()}");
+
+ # Attempt to refund
+ try {
+ $refundOutput = yield $this->bankingActivity->refund($paymentDetails);
+ Workflow::getLogger()->info('Refund successful. Confirmation ID: ' . $refundOutput);
+ } catch (ActivityFailure $refundError) {
+ Workflow::getLogger()->error("Refund failed: {$refundError->getMessage()}");
+ throw $refundError;
+ }
+
+ # Re-raise deposit error if refund was successful
+ throw $depositError;
+ }
+ }
+}
+```
+
+
+ Expected Success Output:
+
+
+ Result: Transfer complete (transaction IDs: Withdrew $250 from account 85-150. ReferenceId: 12345, Deposited $250 into account 43-812. ReferenceId: 12345)
+
+
+ Starting transfer from account 85-150 to account 43-812 for 250
+2022/11/14 10:52:20 WorkflowID: pay-invoice-701 RunID: 3312715c-9fea-4dc3-8040-cf8f270eb53c
+Transfer complete (transaction IDs: W1779185060, D1779185060)
+
+
+ Worker is running and actively polling the Task Queue.
+To quit, use ^C to interrupt.
+
+Withdrawing $62 from account 249946050.
+[ReferenceId: 1480a22d-d0fc-4361]
+Depositing $62 into account 591856595.
+[ReferenceId: 1480a22d-d0fc-4361]
+[1480a22d-d0fc-4361] Transaction succeeded.
+
+
+ Transfer complete (transaction IDs: W3436600150, D9270097234)
+
+
+ Workflow result: Transfer complete (transaction IDs: W-caa90e06-3a48-406d-86ff-e3e958a280f8, D-1910468b-5951-4f1d-ab51-75da5bba230b)
+
+
+ Initiated transfer of $100 from A1001 to B2002
+Workflow ID: moneytransfer-2926a650-1aaf-49d9-bf87-0e3a09ef7b32
+Workflow result: Transfer complete (transaction IDs: OKW-100-A1001, OKD-100-B2002)
+
+
+ Result: Transfer complete (transaction IDs: W12345, D12345)
+
+
+
+
+}>
+
+Now that your Worker is running and polling for tasks, you can start a Workflow Execution.
+
+**In Terminal 3, start the Workflow:**
+
+The workflow starter script starts a Workflow Execution. Each time you run it, the Temporal Server starts a new Workflow Execution.
+
+
+
+
+
+## Check the Temporal Web UI
+
+
+}>
+
+The Temporal Web UI lets you see details about the Workflow you just ran.
+
+**What you'll see in the UI:**
+- List of Workflows with their execution status
+- Workflow summary with input and result
+- History tab showing all events in chronological order
+- Query, Signal, and Update capabilities
+- Stack Trace tab for debugging
+
+**Try This:** Click on a Workflow in the list to see all the details of the Workflow Execution.
+
+
+
+
+
+
+
+
+
+## Ready for Part 2?
+
+
+ Continue to Part 2: Simulate Failures
+
diff --git a/docs/build-your-first-basic-workflow/failure-simulation.mdx b/docs/build-your-first-basic-workflow/failure-simulation.mdx
new file mode 100644
index 0000000000..5d8791357f
--- /dev/null
+++ b/docs/build-your-first-basic-workflow/failure-simulation.mdx
@@ -0,0 +1,1126 @@
+---
+id: failure-simulation
+title: Simulate Failures with Temporal
+sidebar_label: "Part 2: Failure Simulation"
+description: Learn how Temporal handles failures, recovers from crashes, and enables live debugging of your Workflows.
+hide_table_of_contents: true
+keywords:
+ - temporal
+ - python
+ - failure simulation
+ - crash recovery
+ - live debugging
+ - reliability
+tags:
+ - Getting Started
+ - Tutorial
+---
+
+import { CallToAction } from "@site/src/components/elements/CallToAction";
+import { TemporalProgress } from "@site/src/components/TemporalProgress";
+import { StatusIndicators } from "@site/src/components/StatusIndicators";
+import { WorkflowDiagram } from "@site/src/components/WorkflowDiagram";
+import { RetryCounter } from "@site/src/components/RetryCounter";
+import { TemporalCheckbox } from "@site/src/components/TemporalCheckbox";
+import SdkTabs from "@site/src/components/elements/SdkTabs";
+import { FaPython, FaJava } from 'react-icons/fa';
+import { SiGo, SiTypescript, SiPhp, SiDotnet, SiRuby } from 'react-icons/si';
+
+export const TUTORIAL_LANGUAGE_ORDER = [
+ { key: 'py', label: 'Python', icon: FaPython },
+ { key: 'go', label: 'Go', icon: SiGo },
+ { key: 'java', label: 'Java', icon: FaJava },
+ { key: 'ts', label: 'TypeScript', icon: SiTypescript },
+ { key: 'php', label: 'PHP', icon: SiPhp },
+ { key: 'dotnet', label: '.NET', icon: SiDotnet },
+ { key: 'rb', label: 'Ruby', icon: SiRuby },
+];
+import { SetupSteps, SetupStep, CodeSnippet } from "@site/src/components/elements/SetupSteps";
+import { CodeComparison } from "@site/src/components/CodeComparison";
+import { AnimatedTerminal } from "@site/src/components/AnimatedTerminal";
+
+export const getTodayDate = () => {
+ const now = new Date();
+ const year = now.getFullYear();
+ const month = String(now.getMonth() + 1).padStart(2, '0');
+ const day = String(now.getDate()).padStart(2, '0');
+ const hours = String(now.getHours()).padStart(2, '0');
+ const minutes = String(now.getMinutes()).padStart(2, '0');
+ const seconds = String(now.getSeconds()).padStart(2, '0');
+ return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
+};
+
+export const getTodayDateISO = () => {
+ return new Date().toISOString();
+};
+
+# Part 2: Simulate Failures
+In this part, you'll simulate failures to see how Temporal handles them.
+This demonstrates why Temporal is particularly useful for building reliable systems.
+
+
+
+Systems fail in unpredictable ways. A seemingly harmless deployment can bring down production, a database connection can time out during peak traffic, or a third-party service can decide to have an outage.
+Despite our best efforts with comprehensive testing and monitoring, systems are inherently unpredictable and complex.
+Networks fail, servers restart unexpectedly, and dependencies we trust can become unavailable without warning.
+
+Traditional systems aren't equipped to handle these realities.
+When something fails halfway through a multi-step process, you're left with partial state, inconsistent data, and the complex task of figuring out where things went wrong and how to recover.
+Most applications either lose progress entirely or require you to build extensive checkpointing and recovery logic.
+
+In this tutorial, you'll see Temporal's durable execution in action by running two tests: crashing a server while it's working and fixing code problems on the fly without stopping your application.
+
+## Recover from a server crash
+
+Unlike other solutions, Temporal is designed with failure in mind.
+In this part of the tutorial, you'll simulate a server crash mid-transaction and watch Temporal helps you recover from it.
+
+**Here's the challenge:** Kill your Worker process while money is being transferred.
+In traditional systems, this would corrupt the transaction or lose data entirely.
+
+
+
+### Before You Start
+
+
+ Worker is currently stopped
+
+
+
+ You have terminals ready (Terminal 2 for Worker, Terminal 3 for Workflow)
+
+
+
+ Web UI is open at `http://localhost:8233`
+
+
+
+What's happening behind the scenes?
+
+Unlike many modern applications that require complex leader election processes and external databases to handle failure, Temporal automatically preserves the state of your Workflow even if the server is down.
+You can test this by stopping the Temporal Service while a Workflow Execution is in progress.
+
+No data is lost once the Temporal Service went offline.
+When it comes back online, the work picked up where it left off before the outage.
+Keep in mind that this example uses a single instance of the service running on a single machine.
+In a production deployment, the Temporal Service can be deployed as a cluster, spread across several machines for higher availability and increased throughput.
+
+
+
+### Instructions
+
+
+
+
+
+ Terminal 2 - Worker
+
+
+
+ python run_worker.py
+
+
+ go run worker/main.go
+
+
+ mvn compile exec:java -Dexec.mainClass="moneytransferapp.MoneyTransferWorker"
+
+
+ npm run worker
+
+
+ dotnet run --project MoneyTransferWorker
+
+
+ bundle exec ruby worker.rb
+
+
+ ./rr serve
+
+
+
+}>
+
+### Step 1: Start Your Worker
+
+First, stop any running Worker (`Ctrl+C`) and start a fresh one in Terminal 2.
+
+
+
+
+
+
+
+ Terminal 3 - Workflow
+
+
+
+ python run_workflow.py
+
+
+ go run start/main.go
+
+
+ mvn compile exec:java -Dexec.mainClass="moneytransferapp.TransferApp"
+
+
+ npm run client
+
+
+ dotnet run --project MoneyTransferClient
+
+
+ bundle exec ruby starter.rb
+
+
+ php src/transfer.php
+
+
+
+}>
+
+### Step 2: Start the Workflow
+
+Now in Terminal 3, start the Workflow. Check the Web UI - you'll see your Worker busy executing the Workflow and its Activities.
+
+
+
+
+
+
+ The Crash Test
+
Go back to Terminal 2 and kill the Worker with Ctrl+C
+
+} style={{background: 'transparent'}}>
+
+### Step 3: Simulate the Crash
+
+**The moment of truth!** Kill your Worker while it's processing the transaction.
+
+**Jump back to the Web UI** and refresh. Your Workflow is still showing as "Running"!
+
+That's the magic! The Workflow keeps running because Temporal saved its state, even though we killed the Worker.
+
+
+
+
+
+
+
+ Terminal 2 - Recovery
+
+
+
+ python run_worker.py
+
+
+ go run worker/main.go
+
+
+ mvn compile exec:java -Dexec.mainClass="moneytransferapp.MoneyTransferWorker"
+
+
+ npm run worker
+
+
+ dotnet run --project MoneyTransferWorker
+
+
+ bundle exec ruby worker.rb
+
+
+ ./rr serve
+
+
+
+}>
+
+### Step 4: Bring Your Worker Back
+
+Restart your Worker in Terminal 2. Watch Terminal 3 - you'll see the Workflow finish up and show the result!
+
+
+
+
+
+
+
+
+:::tip **Try This Challenge**
+
+Try killing the Worker at different points during execution. Start the Workflow, kill the Worker during the withdrawal, then restart it. Kill it during the deposit. Each time, notice how Temporal maintains perfect state consistency.
+
+Check the Web UI while the Worker is down and you'll see the Workflow is still "Running" even though no code is executing.
+:::
+
+## Recover from an unknown error
+
+In this part of the tutorial, you will inject a bug into your production code, watch Temporal retry automatically, then fix the bug while the Workflow is still running.
+This demo application makes a call to an external service in an Activity.
+If that call fails due to a bug in your code, the Activity produces an error.
+
+To test this out and see how Temporal responds, you'll simulate a bug in the Deposit Activity function or method.
+
+
+
+### Before You Start
+
+
+ Worker is stopped
+
+
+
+ Code editor open with the Activities file
+
+
+
+ Ready to uncomment the failure line
+
+
+
+ Web UI open to watch the retries
+
+
+
+## Instructions
+
+### Step 1: Stop Your Worker
+
+Before we can simulate a failure, we need to stop the current Worker process. This allows us to modify the Activity code safely.
+
+In Terminal 2 (where your Worker is running), stop it with `Ctrl+C`.
+
+**What's happening?** You're about to modify Activity code to introduce a deliberate failure. The Worker process needs to restart to pick up code changes, but the Workflow execution will continue running in Temporal's service - this separation between execution state and code is a core Temporal concept.
+
+### Step 2: Introduce the Bug
+
+Now we'll intentionally introduce a failure in the deposit Activity to simulate real-world scenarios like network timeouts, database connection issues, or external service failures. This demonstrates how Temporal handles partial failures in multi-step processes.
+
+
+
+
+Find the `deposit()` method and **uncomment the failing line** while **commenting out the working line**:
+
+**activities.py**
+```python
+@activity.defn
+async def deposit(self, data: PaymentDetails) -> str:
+ reference_id = f"{data.reference_id}-deposit"
+ try:
+ # Comment out this working line:
+ # confirmation = await asyncio.to_thread(
+ # self.bank.deposit, data.target_account, data.amount, reference_id
+ # )
+
+ # Uncomment this failing line:
+ confirmation = await asyncio.to_thread(
+ self.bank.deposit_that_fails,
+ data.target_account,
+ data.amount,
+ reference_id,
+ )
+ return confirmation
+ except InvalidAccountError:
+ raise
+ except Exception:
+ activity.logger.exception("Deposit failed")
+ raise
+```
+
+Save your changes. You've now created a deliberate failure point in your deposit Activity. This simulates a real-world scenario where external service calls might fail intermittently.
+
+
+
+
+
+Find the `Deposit()` function and **uncomment the failing line** while **commenting out the working line**:
+
+**activity.go**
+```go
+func Deposit(ctx context.Context, data PaymentDetails) (string, error) {
+ log.Printf("Depositing $%d into account %s.\n\n",
+ data.Amount,
+ data.TargetAccount,
+ )
+
+ referenceID := fmt.Sprintf("%s-deposit", data.ReferenceID)
+ bank := BankingService{"bank-api.example.com"}
+
+ // Uncomment this failing line:
+ confirmation, err := bank.DepositThatFails(data.TargetAccount, data.Amount, referenceID)
+ // Comment out this working line:
+ // confirmation, err := bank.Deposit(data.TargetAccount, data.Amount, referenceID)
+
+ return confirmation, err
+}
+```
+
+Save your changes. You've now created a deliberate failure point in your deposit Activity. This simulates a real-world scenario where external service calls might fail intermittently.
+
+
+
+
+
+Find the `deposit()` method and **change `activityShouldSucceed` to `false`**:
+
+**AccountActivityImpl.java**
+```java
+public String deposit(PaymentDetails details) {
+ // Change this to false to simulate failure:
+ boolean activityShouldSucceed = false;
+
+ // ... rest of your method
+}
+```
+
+Save your changes. You've now created a deliberate failure point in your deposit Activity. This simulates a real-world scenario where external service calls might fail intermittently.
+
+
+
+
+
+Find the `deposit()` function and **uncomment the failing line** while **commenting out the working line**:
+
+**activities.ts**
+```typescript
+export async function deposit(details: PaymentDetails): Promise {
+ // Comment out this working line:
+ // return await bank.deposit(details.targetAccount, details.amount, details.referenceId);
+
+ // Uncomment this failing line:
+ return await bank.depositThatFails(details.targetAccount, details.amount, details.referenceId);
+}
+```
+
+Save your changes. You've now created a deliberate failure point in your deposit Activity. This simulates a real-world scenario where external service calls might fail intermittently.
+
+
+
+
+
+Find the `DepositAsync()` method and **uncomment the failing line** while **commenting out the working block**:
+
+**MoneyTransferWorker/Activities.cs**
+```csharp
+[Activity]
+public static async Task DepositAsync(PaymentDetails details)
+{
+ var bankService = new BankingService("bank2.example.com");
+ Console.WriteLine($"Depositing ${details.Amount} into account {details.TargetAccount}.");
+
+ // Uncomment this failing line:
+ return await bankService.DepositThatFailsAsync(details.TargetAccount, details.Amount, details.ReferenceId);
+
+ // Comment out this working block:
+ /*
+ try
+ {
+ return await bankService.DepositAsync(details.TargetAccount, details.Amount, details.ReferenceId);
+ }
+ catch (Exception ex)
+ {
+ throw new ApplicationFailureException("Deposit failed", ex);
+ }
+ */
+}
+```
+
+Save your changes. You've now created a deliberate failure point in your deposit Activity. This simulates a real-world scenario where external service calls might fail intermittently.
+
+
+
+
+
+Find the `deposit` method and **uncomment the failing line** that causes a divide-by-zero error:
+
+**activities.rb**
+```ruby
+def deposit(details)
+ # Uncomment this line to introduce the bug:
+ result = 100 / 0 # This will cause a divide-by-zero error
+
+ # Your existing deposit logic here...
+end
+```
+
+Save your changes. You've now created a deliberate failure point in your deposit Activity. This simulates a real-world scenario where external service calls might fail intermittently.
+
+
+
+
+
+Find the `deposit()` method in `BankingActivity.php` and **uncomment the failing line** while **commenting out the working line**:
+
+**BankingActivity.php**
+
+```php
+#[\Override]
+public function deposit(PaymentDetails $data): string
+{
+ $referenceId = $data->referenceId . "-deposit";
+ try {
+ // Comment out this working line:
+ // $confirmation = $this->bank->deposit(
+ // $data->targetAccount,
+ // $data->amount,
+ // $referenceId,
+ // );
+
+ // Uncomment this failing line:
+ $confirmation = $this->bank->depositThatFails(
+ $data->targetAccount,
+ $data->amount,
+ $referenceId,
+ );
+ return $confirmation;
+ } catch (InvalidAccount $e) {
+ throw $e;
+ } catch (\Throwable $e) {
+ $this->logger->error("Deposit failed", ['exception' => $e]);
+ throw $e;
+ }
+}
+```
+
+Save your changes. You've now created a deliberate failure point in your deposit Activity. This simulates a real-world scenario where external service calls might fail intermittently.
+
+
+
+
+### Step 3: Start Worker & Observe Retry Behavior
+
+Now let's see how Temporal handles this failure. When you start your Worker, it will execute the withdraw Activity successfully, but hit the failing deposit Activity. Instead of the entire Workflow failing permanently, Temporal will retry the failed Activity according to your retry policy.
+
+
+
+
+```bash
+python run_worker.py
+```
+
+**Here's what you'll see:**
+- The `withdraw()` Activity completes successfully
+- The `deposit()` Activity fails and retries automatically
+
+
+
+
+
+
+
+```bash
+go run worker/main.go
+```
+
+**Here's what you'll see:**
+- The `Withdraw()` Activity completes successfully
+- The `Deposit()` Activity fails and retries automatically
+
+
+
+
+
+
+
+Make sure your Workflow is still running in the Web UI, then start your Worker:
+
+```bash
+mvn clean install -Dorg.slf4j.simpleLogger.defaultLogLevel=info 2>/dev/null
+mvn compile exec:java -Dexec.mainClass="moneytransferapp.MoneyTransferWorker" -Dorg.slf4j.simpleLogger.defaultLogLevel=warn
+```
+
+**Here's what you'll see:**
+- The `withdraw()` Activity completes successfully
+- The `deposit()` Activity fails and retries automatically
+
+
+
+
+
+
+
+```bash
+npm run worker
+```
+
+**Here's what you'll see:**
+- The `withdraw()` Activity completes successfully
+- The `deposit()` Activity fails and retries automatically
+
+
+
+
+
+
+
+```bash
+dotnet run --project MoneyTransferWorker
+```
+
+**Here's what you'll see:**
+- The `WithdrawAsync()` Activity completes successfully
+- The `DepositAsync()` Activity fails and retries automatically
+
+
+
+
+
+
+
+```bash
+bundle exec ruby worker.rb
+```
+
+In another terminal, start a new Workflow:
+
+```bash
+bundle exec ruby starter.rb
+```
+
+**Here's what you'll see:**
+- The `withdraw` Activity completes successfully
+- The `deposit` Activity fails and retries automatically
+
+
+
+Check the Web UI - click on your Workflow to see the failure details and retry attempts.
+
+
+
+
+
+```bash
+./rr serve
+```
+
+**Here's what you'll see:**
+- The `withdraw()` Activity completes successfully
+- The `deposit()` Activity fails and retries automatically
+
+Check the Web UI - click on your Workflow to see the failure details and retry attempts.
+
+
+
+
+**Key observation:** Your Workflow isn't stuck or terminated. Temporal automatically retries the failed Activity according to your configured retry policy, while maintaining the overall Workflow state. The successful withdraw Activity doesn't get re-executed - only the failed deposit Activity is retried.
+
+### Step 4: Fix the Bug
+
+Here's where Temporal really shines - you can fix bugs in production code while Workflows are still executing. The Workflow state is preserved in Temporal's durable storage, so you can deploy fixes and let the retry mechanism pick up your corrected code.
+
+
+
+
+Go back to `activities.py` and **reverse the comments** - comment out the failing line and uncomment the working line:
+
+**activities.py**
+```python
+@activity.defn
+async def deposit(self, data: PaymentDetails) -> str:
+ reference_id = f"{data.reference_id}-deposit"
+ try:
+ # Uncomment this working line:
+ confirmation = await asyncio.to_thread(
+ self.bank.deposit, data.target_account, data.amount, reference_id
+ )
+
+ # Comment out this failing line:
+ # confirmation = await asyncio.to_thread(
+ # self.bank.deposit_that_fails,
+ # data.target_account,
+ # data.amount,
+ # reference_id,
+ # )
+ return confirmation
+ except InvalidAccountError:
+ raise
+ except Exception:
+ activity.logger.exception("Deposit failed")
+ raise
+```
+
+
+
+
+
+Go back to `activity.go` and **reverse the comments** - comment out the failing line and uncomment the working line:
+
+**activity.go**
+```go
+func Deposit(ctx context.Context, data PaymentDetails) (string, error) {
+ log.Printf("Depositing $%d into account %s.\n\n",
+ data.Amount,
+ data.TargetAccount,
+ )
+
+ referenceID := fmt.Sprintf("%s-deposit", data.ReferenceID)
+ bank := BankingService{"bank-api.example.com"}
+
+ // Comment out this failing line:
+ // confirmation, err := bank.DepositThatFails(data.TargetAccount, data.Amount, referenceID)
+ // Uncomment this working line:
+ confirmation, err := bank.Deposit(data.TargetAccount, data.Amount, referenceID)
+
+ return confirmation, err
+}
+```
+
+
+
+
+
+Go back to `AccountActivityImpl.java` and **change `activityShouldSucceed` back to `true`**:
+
+**AccountActivityImpl.java**
+```java
+public String deposit(PaymentDetails details) {
+ // Change this back to true to fix the bug:
+ boolean activityShouldSucceed = true;
+
+ // ... rest of your method
+}
+```
+
+
+
+
+
+Go back to `activities.ts` and **reverse the comments** - comment out the failing line and uncomment the working line:
+
+**activities.ts**
+```typescript
+export async function deposit(details: PaymentDetails): Promise {
+ // Uncomment this working line:
+ return await bank.deposit(details.targetAccount, details.amount, details.referenceId);
+
+ // Comment out this failing line:
+ // return await bank.depositThatFails(details.targetAccount, details.amount, details.referenceId);
+}
+```
+
+
+
+
+
+Go back to `Activities.cs` and **reverse the comments** - comment out the failing line and uncomment the working block:
+
+**MoneyTransferWorker/Activities.cs**
+```csharp
+[Activity]
+public static async Task DepositAsync(PaymentDetails details)
+{
+ var bankService = new BankingService("bank2.example.com");
+ Console.WriteLine($"Depositing ${details.Amount} into account {details.TargetAccount}.");
+
+ // Comment out this failing line:
+ // return await bankService.DepositThatFailsAsync(details.TargetAccount, details.Amount, details.ReferenceId);
+
+ // Uncomment this working block:
+ try
+ {
+ return await bankService.DepositAsync(details.TargetAccount, details.Amount, details.ReferenceId);
+ }
+ catch (Exception ex)
+ {
+ throw new ApplicationFailureException("Deposit failed", ex);
+ }
+}
+```
+
+
+
+
+
+Go back to `activities.rb` and **comment out the failing line**:
+
+**activities.rb**
+```ruby
+def deposit(details)
+ # Comment out this problematic line:
+ # result = 100 / 0 # This will cause a divide-by-zero error
+
+ # Your existing deposit logic here...
+end
+```
+
+
+
+
+
+Go back to `BankingActivity.php` and **reverse the comments** - comment out the failing line and uncomment the working line:
+
+**BankingActivity.php**
+
+```php
+#[\Override]
+public function deposit(PaymentDetails $data): string
+{
+ $referenceId = $data->referenceId . "-deposit";
+ try {
+ // Uncomment this working line:
+ $confirmation = $this->bank->deposit(
+ $data->targetAccount,
+ $data->amount,
+ $referenceId,
+ );
+
+ // Comment out this failing line:
+ // $confirmation = $this->bank->depositThatFails(
+ // $data->targetAccount,
+ // $data->amount,
+ // $referenceId,
+ // );
+ return $confirmation;
+ } catch (InvalidAccount $e) {
+ throw $e;
+ } catch (\Throwable $e) {
+ $this->logger->error("Deposit failed", ['exception' => $e]);
+ throw $e;
+ }
+}
+```
+
+
+
+
+Save your changes. You've now restored the working implementation. The key insight here is that you can deploy fixes to Activities while Workflows are still executing - Temporal will pick up your changes on the next retry attempt.
+
+### Step 5: Restart Worker
+
+To apply your fix, you need to restart the Worker process so it picks up the code changes. Since the Workflow execution state is stored in Temporal's servers (not in your Worker process), restarting the Worker won't affect the running Workflow.
+
+
+
+
+```bash
+# Stop the current Worker
+Ctrl+C
+
+# Start it again with the fix
+python run_worker.py
+```
+
+**On the next retry attempt,** your fixed `deposit()` Activity will succeed, and you'll see the completed transaction in Terminal 3:
+
+```
+Transfer complete.
+Withdraw: {'amount': 250, 'receiver': '43-812', 'reference_id': '1f35f7c6-4376-4fb8-881a-569dfd64d472', 'sender': '85-150'}
+Deposit: {'amount': 250, 'receiver': '43-812', 'reference_id': '1f35f7c6-4376-4fb8-881a-569dfd64d472', 'sender': '85-150'}
+```
+
+
+
+
+
+```bash
+# Stop the current Worker
+Ctrl+C
+
+# Start it again with the fix
+go run worker/main.go
+```
+
+**On the next retry attempt,** your fixed `Deposit()` Activity will succeed, and you'll see the completed transaction in your starter terminal:
+
+```
+Transfer complete (transaction IDs: W1779185060, D1779185060)
+```
+
+
+
+
+
+```bash
+# Stop the current Worker
+Ctrl+C
+
+# Start it again with the fix
+mvn clean install -Dorg.slf4j.simpleLogger.defaultLogLevel=info 2>/dev/null
+mvn compile exec:java -Dexec.mainClass="moneytransferapp.MoneyTransferWorker" -Dorg.slf4j.simpleLogger.defaultLogLevel=warn
+```
+
+**On the next retry attempt,** your fixed `deposit()` Activity will succeed:
+
+```
+Depositing $32 into account 872878204.
+[ReferenceId: d3d9bcf0-a897-4326]
+[d3d9bcf0-a897-4326] Transaction succeeded.
+```
+
+
+
+
+
+```bash
+# Stop the current Worker
+Ctrl+C
+
+# Start it again with the fix
+npm run worker
+```
+
+**On the next retry attempt,** your fixed `deposit()` Activity will succeed, and you'll see the completed transaction in your client terminal:
+
+```
+Transfer complete (transaction IDs: W3436600150, D9270097234)
+```
+
+
+
+
+
+```bash
+# Stop the current Worker
+Ctrl+C
+
+# Start it again with the fix
+dotnet run --project MoneyTransferWorker
+```
+
+**On the next retry attempt,** your fixed `DepositAsync()` Activity will succeed, and you'll see the completed transaction in your client terminal:
+
+```
+Workflow result: Transfer complete (transaction IDs: W-caa90e06-3a48-406d-86ff-e3e958a280f8, D-1910468b-5951-4f1d-ab51-75da5bba230b)
+```
+
+
+
+
+
+```bash
+# Stop the current Worker
+Ctrl+C
+
+# Start it again with the fix
+bundle exec ruby worker.rb
+```
+
+**On the next retry attempt,** your fixed `deposit` Activity will succeed, and you'll see the Workflow complete successfully.
+
+
+
+
+
+```bash
+# Stop the current Worker
+Ctrl+C
+
+# Start it again with the fix
+./rr serve
+```
+
+**On the next retry attempt,** your fixed `deposit()` Activity will succeed, and you'll see the completed transaction:
+
+```
+Result: Transfer complete (transaction IDs: W12345, D12345)
+```
+
+
+
+
+Check the Web UI - your Workflow shows as completed. You've just demonstrated Temporal's key differentiator: the ability to fix production bugs in running applications without losing transaction state or progress. This is possible because Temporal stores execution state separately from your application code.
+
+**Mission Accomplished.** You have just fixed a bug in a running application without losing the state of the Workflow or restarting the transaction.
+
+
+
+
+
+
+:::tip Advanced Challenge
+
+Try this advanced scenario of compensating transactions.
+
+
+1. **Modify the retry policy** in `workflows.py` to only retry 1 time
+2. **Force the deposit to fail permanently**
+3. **Watch the automatic refund** execute
+
+:::
+
+
+## Knowledge Check
+
+Test your understanding of what you just experienced:
+
+
+Q: What are four of Temporal's value propositions that you learned about in this tutorial?
+
+**Answer**:
+1. Temporal automatically maintains the state of your Workflow, despite crashes or even outages of the Temporal Service itself.
+2. Temporal's built-in support for retries and timeouts enables your code to overcome transient and intermittent failures.
+3. Temporal provides full visibility in the state of the Workflow Execution and its Web UI offers a convenient way to see the details of both current and past executions.
+4. Temporal makes it possible to fix a bug in a Workflow Execution that you've already started. After updating the code and restarting the Worker, the failing Activity is retried using the code containing the bug fix, completes successfully, and execution continues with what comes next.
+
+
+
+Q: Why do we use a shared constant for the Task Queue name?
+
+**Answer**: Because the Task Queue name is specified in two different parts of the code (the first starts the Workflow and the second configures the Worker). If their values differ, the Worker and Temporal Service would not share the same Task Queue, and the Workflow Execution would not progress.
+
+
+
+
+
+Q: What do you have to do if you make changes to Activity code for a Workflow that is running?
+
+**Answer**: Restart the Worker.
+
+
+
+
+## Continue Your Learning
+
+