Quick answer
Temporal is a workflow engine that remembers where a long-running job stopped and picks it up after a crash. You write the order flow as normal code, and the steps that touch the outside world, charging a card, reserving stock, sending a text, become activities. Temporal records every completed step, so a worker that dies halfway through an order is replaced by a new one that resumes it instead of starting over.
A customer in Karachi orders two embroidered lawn suits for Rs 4,900. The shop's code charges the card, reserves the stock, then sends a confirmation text: three steps, each calling a different service, and any of them can fail. The payment gateway times out, the stock service is slow, the text provider is down. The usual answer is retries plus a status column, and a nightly job that hunts for orders stuck halfway. That holds until the server restarts during step two and nobody can tell whether the card was charged. Temporal exists for exactly this shape of problem: work that must finish, step by step, even when machines die in the middle of it.
What I would check before using it
My first check is whether the work lasts long enough to need remembering. Temporal earns its place when a job spans minutes or hours and touches several services. If the whole job finishes in a second inside one request, a plain function and a retry loop are simpler. The Celery Tutorial: Background Jobs in Python That Just Work post covers the lighter end: Celery runs background tasks well, but it forgets a multi-step job halfway.
My second check is who runs the server. Temporal needs a server that stores the event history, and someone to run it and back it up. The dev server is one binary, but production is a real service with a database. If nobody owns that, a managed cloud account or a simpler queue is the alternative. The RabbitMQ Tutorial: An Order Queue That Never Loses Work post covers the queue-only shape, enough when messages stand alone.
My third check is whether every step can safely run twice. Temporal retries a failed activity, and a retried payment can charge a card twice unless the activity is idempotent, keyed by the order id. I would not adopt Temporal until each activity can re-run without side effects.
My verdict, as judgement: adopt Temporal when an order, a signup, or a payout must finish across several services and a crash halfway is a matter of when, not if. The recommendation flips for a single quick task, for a team with nobody to run the server, or for steps that cannot be made idempotent.
One shop order, a dead worker, and a finished sale
The demo is a small Karachi shop. Order ORD-2001, from Ayesha Khan: two lawn suits at Rs 2,450 each, Rs 4,900, paid by card. The workflow charges the card, reserves two units of SKU LAWN-EMB-014, then sends a confirmation text.
Everything runs locally: the Temporal CLI bundles server, UI, and command line in one binary, and temporal server start-dev starts it all.
$ ./temporal --version
temporal version 1.10.1 (Server 1.32.2, UI 2.56.4)
$ ./temporal server start-dev --db-filename temporal.db
$ ./temporal operator cluster health
SERVING
The Python SDK installs with pip:
$ pip install temporalio
$ python -c "import temporalio; print(temporalio.__version__)"
1.37.0
The activities in activities.py touch the outside world. The payment pretends the gateway is flaky: it waits six seconds, heartbeating so a dead worker is noticed, then fails twice before succeeding.
"""Activities for the Karachi shop order workflow."""
import asyncio
import time
from temporalio import activity
from temporalio.exceptions import ApplicationError
@activity.defn
async def charge_payment(order: dict) -> str:
"""Charge the customer. The mock gateway times out on the first
two attempts, then succeeds, so Temporal's retry policy is exercised."""
attempt = activity.info().attempt
activity.logger.info("charge_payment attempt %s for %s", attempt, order["order_id"])
# Heartbeat so a dead worker is noticed quickly, not only at the
# start-to-close timeout.
for _ in range(6):
activity.heartbeat("waiting on payment gateway")
await asyncio.sleep(1)
if attempt < 3:
raise ApplicationError(
f"Payment gateway timed out after 6s (attempt {attempt})",
non_retryable=False,
)
return f"charged Rs {order['total_pkr']:,.2f} to card ending 4242"
@activity.defn
async def reserve_stock(order: dict) -> str:
await asyncio.sleep(1)
items = ", ".join(
f"{i['qty']}x {i['sku']}" for i in order["items"]
)
return f"reserved {items} at Karachi warehouse"
@activity.defn
async def send_confirmation(order: dict) -> str:
await asyncio.sleep(1)
return (
f"confirmation SMS sent to {order['customer']} "
f"for order {order['order_id']}"
)
@activity.defn
async def refund_payment(order: dict) -> str:
"""Compensation step, run only if a later step fails."""
return f"refunded Rs {order['total_pkr']:,.2f} to card ending 4242"
The workflow in workflows.py reads like the plain order flow. No retry code, no status column: Temporal provides that.
"""Order workflow: charge, reserve stock, confirm. Durable by design:
if the worker dies mid-order, Temporal replays the workflow from its
event history and the order continues where it stopped."""
from datetime import timedelta
from temporalio import workflow
with workflow.unsafe.imports_passed_through():
from activities import (
charge_payment,
refund_payment,
reserve_stock,
send_confirmation,
)
@workflow.defn
class OrderWorkflow:
@workflow.run
async def run(self, order: dict) -> dict:
payment = await workflow.execute_activity(
charge_payment,
order,
start_to_close_timeout=timedelta(seconds=15),
heartbeat_timeout=timedelta(seconds=5),
)
try:
stock = await workflow.execute_activity(
reserve_stock,
order,
start_to_close_timeout=timedelta(seconds=30),
)
confirmation = await workflow.execute_activity(
send_confirmation,
order,
start_to_close_timeout=timedelta(seconds=30),
)
except Exception:
await workflow.execute_activity(
refund_payment,
order,
start_to_close_timeout=timedelta(seconds=30),
)
raise
return {
"order_id": order["order_id"],
"status": "completed",
"payment": payment,
"stock": stock,
"confirmation": confirmation,
}
A worker listens on the shop-orders task queue, and a client starts one workflow for ORD-2001. Then the real test: kill the worker mid-payment and start a fresh one. Started 03:06:13; first worker died 03:06:17; second started 03:06:19.
$ python shop_orders/worker.py
Worker started on task queue 'shop-orders'
$ python shop_orders/client.py
Starting workflow for order ORD-2001 ...
Workflow started: shop-order-ORD-2001
Two things went wrong. The worker died mid-payment, so the first attempt never reported back: scheduled at 03:06:14, recorded start 03:06:29, fifteen seconds later. Then the new worker hit the gateway and failed once:
Completing activity as failed ({'activity_id': '1', 'activity_type': 'charge_payment', 'attempt': 2, ...})
temporalio.exceptions.ApplicationError: Payment gateway timed out after 6s (attempt 2)
Temporal retried it, the third attempt succeeded, and the order moved on. Finished at 03:06:38, twenty-five seconds after it started:
Workflow completed:
{
"confirmation": "confirmation SMS sent to Ayesha Khan for order ORD-2001",
"order_id": "ORD-2001",
"payment": "charged Rs 4,900.00 to card ending 4242",
"status": "completed",
"stock": "reserved 2x LAWN-EMB-014 at Karachi warehouse"
}
The event history is the proof: 23 events, from WorkflowExecutionStarted to WorkflowExecutionCompleted, stored on the server, not in the worker's memory. The NATS Tutorial: Messaging Your Shop Orders Can Trust post covers the messaging half; Temporal adds the memory of where the job stopped.
Common mistakes and how to fix them
First, starting a workflow with no worker on the task queue. The symptom is a workflow stuck in Running, its history showing WorkflowExecutionStarted and nothing after. The fix is a worker on the same task queue, shop-orders here, confirmed polling first.
Second, a payment activity that is not idempotent. The symptom is a customer charged twice, because Temporal retried a payment that went through. The fix is to key every side effect by the order id, so a retry finds the first charge.
Third, calling time.sleep or random inside workflow code. The symptom is a runtime error, because workflow code must be deterministic: Temporal replays it from the event history, and a different result on replay breaks it. The fix is to keep workflow code pure and put anything non-deterministic in activities, or use workflow.sleep.
Fourth, leaving timeouts unset. The symptom is an order that hangs forever when a service stops responding, because nothing declares the activity dead. The fix is a start_to_close_timeout on every activity, plus a heartbeat_timeout for long ones, so a stuck step is retried.
Frequently Asked Questions
Do I need a server to try Temporal? No. The dev server is one binary: temporal server start-dev gives you a server, a database file, and a web UI. Production needs a real database and an owner.
How is Temporal different from Celery? Celery runs background tasks that are independent of each other, so if a chain breaks halfway, your code has to work out what already ran. Temporal keeps the whole workflow and its history, so a crashed worker resumes the job. The Kafka Explained: The Event Backbone of Big Systems post covers the event-log shape behind it.
What happens if the Temporal server itself restarts? The event history lives in the server's database, so a restart loses nothing: workflows resume from their last recorded event. The dev server keeps its history in a local file; production uses a managed database.
What to remember
- A workflow is ordinary code; activities touch the outside world.
- Temporal stores an event history, so a dead worker is replaced.
- Activities retry by default, so make each safe to run twice.
- Timeouts and heartbeats decide how fast a dead worker is noticed.
- The dev server is one binary; production needs a database and an owner.
Where this leaves you
The order started as three calls that could each fail, and ended as one workflow that survived a dead worker and a timed-out payment gateway without any recovery code of its own. That is the case for Temporal: the durability lives in the platform, not in a status column and a nightly cleanup job. If you have a job that must finish across several services, install the CLI, run temporal server start-dev, and rewrite your riskiest multi-step flow as a workflow with one activity per step.
Further reading
- Temporal workflows
- Temporal activities
- Temporal CLI
- Celery Tutorial: Background Jobs in Python That Just Work
- RabbitMQ Tutorial: An Order Queue That Never Loses Work
- NATS Tutorial: Messaging Your Shop Orders Can Trust
- Kafka Explained: The Event Backbone of Big Systems
- Python asyncio: Running Jobs at the Same Time Without Threads
Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.
Originally published at https://practicaldevblog.blogspot.com/2026/11/temporal-shop-orders-workflow.html

Top comments (0)