Orchestration

Agents that can wait three days: a durable refund workflow on Temporal

A refund agent that waits days for human approval and survives restarts. The workflow, the code and what Temporal's UI shows, from a run on our machines.

Most agent demos finish in seconds. Real business processes don't. A refund needs a person to approve it, and that person might reply in ten minutes or on Monday. If the waiting lives in a Python loop or a chat session, a deploy or a crash in between loses the work.

We build those processes on Temporal. To show what that looks like, we wrote a small refund workflow and ran it on a local Temporal server. Everything below, including the screenshots, comes from that run.

The shape of the workflow

A support request comes in for order 4821. The workflow classifies it, looks up the order, checks the refund policy, and then stops to wait for a reviewer. Only after an approval does it call the payment API.

In Temporal there are two kinds of code. The workflow is the orchestration. It must be deterministic, because Temporal rebuilds its state by replaying recorded history. Activities do everything with side effects: model calls, database lookups, payments. Each activity gets its own timeout and retry policy, so a flaky API is retried without re-running the steps before it.

temporal_refund.pyDurable refund workflow with retries and a 3-day approval wait
"""Durable refund workflow on Temporal, used for the vithupro.in Temporal page.
Each LLM/tool call is an activity with its own retries; the workflow waits for a human approval signal
for up to 3 days before escalating. Run against `temporal server start-dev`."""
import asyncio
from datetime import timedelta

from temporalio import activity, workflow
from temporalio.client import Client
from temporalio.common import RetryPolicy
from temporalio.worker import Worker

RETRY = RetryPolicy(initial_interval=timedelta(seconds=2), maximum_attempts=5)


@activity.defn
async def classify_request(text: str) -> str:
    return "refund_request"  # LLM call in production


@activity.defn
async def get_order(order_id: str) -> dict:
    return {"id": order_id, "status": "delivered", "damaged": True, "amount": 2499}  # MCP tool in production


@activity.defn
async def check_policy(order: dict) -> str:
    return "Damaged on arrival: full refund within 7 days [policy.pdf p.3]"  # GraphRAG lookup in production


@activity.defn
async def issue_refund(order_id: str) -> str:
    return f"refund-{order_id}-ok"  # payment API in production


@workflow.defn
class RefundWorkflow:
    def __init__(self) -> None:
        self.decision: str | None = None

    @workflow.signal
    def review(self, decision: str) -> None:
        self.decision = decision

    @workflow.query
    def status(self) -> str:
        return self.decision or "waiting for approval"

    @workflow.run
    async def run(self, order_id: str, text: str) -> str:
        opts = dict(start_to_close_timeout=timedelta(seconds=30), retry_policy=RETRY)
        await workflow.execute_activity(classify_request, text, **opts)
        order = await workflow.execute_activity(get_order, order_id, **opts)
        await workflow.execute_activity(check_policy, order, **opts)
        try:  # durable wait: survives worker restarts and deploys
            await workflow.wait_condition(lambda: self.decision is not None, timeout=timedelta(days=3))
        except asyncio.TimeoutError:
            return "escalated to support lead"
        if self.decision != "approve":
            return "refund rejected by reviewer"
        return await workflow.execute_activity(issue_refund, order_id, **opts)


async def main() -> None:
    client = await Client.connect("localhost:7233")
    activities = [classify_request, get_order, check_policy, issue_refund]
    async with Worker(client, task_queue="support", workflows=[RefundWorkflow], activities=activities):
        done = await client.start_workflow(RefundWorkflow.run, args=["4821", "Order #4821 arrived damaged."], id="refund-order-4821", task_queue="support")
        await asyncio.sleep(2)
        await done.signal(RefundWorkflow.review, "approve")
        print("4821:", await done.result())
        for oid in ("4907", "5133"):  # left waiting for a reviewer
            await client.start_workflow(RefundWorkflow.run, args=[oid, f"Order #{oid} arrived damaged."], id=f"refund-order-{oid}", task_queue="support")
        await asyncio.sleep(4)
        h = client.get_workflow_handle("refund-order-4907")
        print("4907:", await h.query(RefundWorkflow.status))


if __name__ == "__main__":
    asyncio.run(main())
Output of this run
4821: refund-4821-ok
4907: waiting for approval

Waiting is a first-class step

The line that matters is workflow.wait_condition(..., timeout=timedelta(days=3)). The workflow sleeps until a review signal arrives or three days pass, and then escalates. No thread is held open and no cron job polls a table. If the worker process dies during those three days, a new worker picks the workflow up and continues from its recorded history.

Temporal Web UI timeline of a completed refund workflow
Real Temporal Web UI: each activity, the 3-day approval wait and the human signal, from the code below.

This is Temporal's own UI for the approved request. You can see the three activities, the approval timer, the review signal and the final refund. Temporal recorded 35 events for the run. It took about two seconds only because we approved straight away; in production that gap is however long the reviewer takes.

A reviewer queue for free

We started two more refunds and did not approve them. They stay in the Running state, durably, until someone acts.

Temporal Web UI workflow list: two running, one completed
Two refunds durably waiting for a reviewer, one completed after approval.

Each one answers a status query ("waiting for approval"), so a support dashboard can list pending reviews straight from Temporal instead of keeping a separate table in sync.

Where the LLM fits

In this sample the activities return fixed values so the run is reproducible. In a real system classify_request is a model call, get_order is a narrow tool exposed through an MCP server, and check_policy is a GraphRAG lookup with citations. Because each is an activity, a timeout from the model provider is retried on its own, and every call is in the workflow history.

We often pair this with LangGraph. LangGraph handles the reasoning loop of a single agent; Temporal makes the overall business process durable.

When you don't need Temporal

  • Short requests that finish inside one HTTP call.
  • Scheduled batch pipelines, where Airflow is the better fit.
  • Early prototypes, where a checkpointed LangGraph graph is enough until approvals and long waits appear.

Rule of thumb: once a process has a human step, a wait longer than a request timeout, or a side effect that must not run twice, it belongs in a durable workflow.

Vithupro Engineering

The engineering team at Vithupro Infotech, Pune. We build agents, GraphRAG and ML systems for production, and write up what we learn along the way.

Have an AI system to build?

Tell us what it needs to do. We reply within one business day with questions, a rough plan and the next step.

Book a call
  • Free 30-minute architecture call
  • NDA before you share details
  • You own all code and IP
  • Reply within one business day