Skip to main content

Build Your First Workflow

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
Part 1: Build Your First Workflow
Part 2: Failure Simulation

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

Quickstart Guide

Run through the Quickstart to get your set up complete.

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.

Money Transfer Application Flow

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.

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.

git clone https://github.com/temporalio/money-transfer-project-template-go
cd money-transfer-project-template-go
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.

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.
Temporal Application Components
Your Temporal Application
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.

info

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

Workflow Definition

A Workflow Definition in Python uses the @workflow.defn decorator on the Workflow class to identify a Workflow.

This is what the Workflow Definition looks like for this kind of process:

workflows.py

from datetime import timedelta
from temporalio import workflow
from temporalio.common import RetryPolicy
from temporalio.exceptions import ActivityError

with workflow.unsafe.imports_passed_through():
from activities import BankingActivities
from shared import PaymentDetails

@workflow.defn
class MoneyTransfer:
@workflow.run
async def run(self, payment_details: PaymentDetails) -> str:
retry_policy = RetryPolicy(
maximum_attempts=3,
maximum_interval=timedelta(seconds=2),
non_retryable_error_types=["InvalidAccountError", "InsufficientFundsError"],
)

# Withdraw money
withdraw_output = await workflow.execute_activity_method(
BankingActivities.withdraw,
payment_details,
start_to_close_timeout=timedelta(seconds=5),
retry_policy=retry_policy,
)

# Deposit money
try:
deposit_output = await workflow.execute_activity_method(
BankingActivities.deposit,
payment_details,
start_to_close_timeout=timedelta(seconds=5),
retry_policy=retry_policy,
)

result = f"Transfer complete (transaction IDs: {withdraw_output}, {deposit_output})"
return result
except ActivityError as deposit_err:
# Handle deposit error
workflow.logger.error(f"Deposit failed: {deposit_err}")
# Attempt to refund
try:
refund_output = await workflow.execute_activity_method(
BankingActivities.refund,
payment_details,
start_to_close_timeout=timedelta(seconds=5),
retry_policy=retry_policy,
)
workflow.logger.info(
f"Refund successful. Confirmation ID: {refund_output}"
)
raise deposit_err
except ActivityError as refund_error:
workflow.logger.error(f"Refund failed: {refund_error}")
raise refund_error

Activity Definition

Activities handle the business logic. Each activity method calls an external banking service:

activities.py

import asyncio
from temporalio import activity
from shared import PaymentDetails

class BankingActivities:
@activity.defn
async def withdraw(self, data: PaymentDetails) -> str:
reference_id = f"{data.reference_id}-withdrawal"
try:
confirmation = await asyncio.to_thread(
self.bank.withdraw, data.source_account, data.amount, reference_id
)
return confirmation
except InvalidAccountError:
raise
except Exception:
activity.logger.exception("Withdrawal failed")
raise

Step 2: Set the Retry Policy

Temporal makes your software durable and fault tolerant by default. If an Activity fails, Temporal automatically retries it, but you can customize this behavior through a Retry Policy.

Retry Policy Configuration

In the MoneyTransfer Workflow, you'll see a Retry Policy that controls this behavior:

workflows.py

# ...
retry_policy = RetryPolicy(
maximum_attempts=3, # Stop after 3 tries
maximum_interval=timedelta(seconds=2), # Don't wait longer than 2s
non_retryable_error_types=[ # Never retry these errors
"InvalidAccountError",
"InsufficientFundsError"
],
)

What Makes Errors Non-Retryable?

Without retry policies, a temporary network glitch could cause your entire money transfer to fail. With Temporal's intelligent retries, your workflow becomes resilient to these common infrastructure issues.

Don't Retry

  • InvalidAccountError - Wrong account number
  • InsufficientFundsError - Not enough money

These are business logic errors that won't be fixed by retrying.

Retry Automatically

  • Network timeouts - Temporary connectivity
  • Service unavailable - External API down
  • Rate limiting - Too many requests

These are temporary issues that often resolve themselves.

This is a Simplified Example

This tutorial shows core Temporal features and is not intended for production use. A real money transfer system would need additional logic for edge cases, cancellations, and error handling.

Step 3: Create a Worker file

A Worker is responsible for executing your Workflow and Activity code. It:

  • Can only execute Workflows and Activities registered to it
  • Knows which piece of code to execute based on Tasks from the Task Queue
  • Only listens to the Task Queue that it's registered to
  • Returns execution results back to the Temporal Server

run_worker.py

import asyncio

from temporalio.client import Client
from temporalio.worker import Worker

from activities import BankingActivities
from shared import MONEY_TRANSFER_TASK_QUEUE_NAME
from workflows import MoneyTransfer


async def main() -> None:
client: Client = await Client.connect("localhost:7233", namespace="default")
# Run the worker
activities = BankingActivities()
worker: Worker = Worker(
client,
task_queue=MONEY_TRANSFER_TASK_QUEUE_NAME,
workflows=[MoneyTransfer],
activities=[activities.withdraw, activities.deposit, activities.refund],
)
await worker.run()


if __name__ == "__main__":
asyncio.run(main())

Step 4: Define the Task Queue

A Task Queue is where Temporal Workers look for Tasks about Workflows and Activities to execute. Each Task Queue is identified by a name, which you will specify when you configure the Worker and again in the code that starts the Workflow Execution. To ensure that the same name is used in both places, this project follows the recommended practice of specifying the Task Queue name in a constant referenced from both places.

Set Your Task Queue Name

To ensure your Worker and Workflow starter use the same queue, define the Task Queue name as a constant:

shared.py

# Task Queue name - used by both Worker and Workflow starter
MONEY_TRANSFER_TASK_QUEUE_NAME = "MONEY_TRANSFER_TASK_QUEUE"
Why Use Constants?

Using a shared constant prevents typos that would cause your Worker to listen to a different Task Queue than where your Workflow tasks are being sent. It's a common source of "Why isn't my Workflow running?" issues.

Step 5: Execute the Workflow

Now you'll create a client program that starts a Workflow execution. This code connects to the Temporal Service and submits a Workflow execution request:

start_workflow.py

import asyncio
from temporalio.client import Client
from workflows import MoneyTransfer
from shared import MONEY_TRANSFER_TASK_QUEUE_NAME

async def main():
# Create the Temporal Client to connect to the Temporal Service
client = await Client.connect("localhost:7233", namespace="default")

# Define the money transfer details
details = {
"source_account": "A1001",
"target_account": "B2002",
"amount": 100,
"reference_id": "12345"
}

# Start the Workflow execution
handle = await client.start_workflow(
MoneyTransfer.run,
details,
id=f"money-transfer-{details['reference_id']}",
task_queue=MONEY_TRANSFER_TASK_QUEUE_NAME,
)

print(f"Started Workflow {handle.id}")
print(f"Transferring ${details['amount']} from {details['source_account']} to {details['target_account']}")

# Wait for the result
result = await handle.result()
print(f"Workflow result: {result}")

if __name__ == "__main__":
asyncio.run(main())

This code uses a Temporal Client to connect to the Temporal Service, calling its workflow start method to request execution. This returns a handle, and calling result on that handle will block until execution is complete, at which point it provides the result.

Run Your Money Transfer

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.

Workflow Status: EXECUTING
Withdraw Activity: RUNNING
Deposit Activity: RUNNING
Transaction: COMPLETED
Terminal 1 - Start the Temporal server:
temporal server start-dev
Terminal 2 - Start the Worker:
python run_worker.py
Terminal 3 - Start the Workflow:
python run_workflow.py
Expected Success Output:
Result: Transfer complete (transaction IDs: Withdrew $250 from account 85-150. ReferenceId: 12345, Deposited $250 into account 43-812. ReferenceId: 12345)

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.

Money Transfer Web UI

Ready for Part 2?

Continue to Part 2: Simulate Failures

Simulate crashes, fix bugs in running workflows, and experience Temporal's reliability superpowers