Skip to content

[Feature Request] Default heartbeat timeout for every plugin's own activities #491

Open
12 of 12 issues completed

Description

@campoy

Is your feature request related to a problem? Please describe.

A running activity only hears about a cancel when it heartbeats. Most of our plugins heartbeat only if you set a heartbeat_timeout, and almost none set one for you. Many activities, like most MCP ones, never heartbeat at all.

So by default:

@JasonSteving99 found that this makes the fix in #228 do nothing with the defaults: the Workflow records the cancel, but the activity never hears it.

Why not heartbeat without a timeout? Then the SDK sends at most one heartbeat every 30 seconds, so the cancel can arrive 30 seconds late. @DABH found this on #228.

And why not set a timeout yourself? On an activity that never heartbeats, every call longer than the timeout fails and retries. #465 fixed that for the Vercel AI SDK model calls. Most MCP activities still have it.

Describe the solution you'd like

  1. Every activity a plugin defines heartbeats on a timer, at half the timeout, for as long as it runs. Not per chunk: a model can be quiet for a long time before its first token.
  2. Those activities get a 10-second heartbeat_timeout by default. A timeout you set wins, and you can turn it off.
  3. Your own activities (activity_as_tool, activity_node, LangGraph nodes) stay as they are.

Why 10 seconds? The SDK sends at most one heartbeat every 0.8 × the timeout, so the timeout sets how fast a cancel arrives. Here's what I measured (Python 3.13, temporalio 1.35.0, Temporal CLI 1.10.0 dev server):

heartbeat_timeout=  30s  trip at  1.0s  cancel reached the activity after  14.0s
heartbeat_timeout=  30s  trip at 16.0s  cancel reached the activity after  23.0s
heartbeat_timeout=  10s  trip at  1.0s  cancel reached the activity after   4.0s
heartbeat_timeout=  10s  trip at  6.0s  cancel reached the activity after   7.0s
heartbeat_timeout=   5s  trip at  1.0s  cancel reached the activity after   1.5s
heartbeat_timeout=   5s  trip at  3.5s  cancel reached the activity after   3.0s

At 30 seconds, many answers finish before the cancel lands. At 5, a Worker that stalls for 5 seconds times out, and we pay for the call twice. The Claude Agent SDK and Codex plugins already use 10.

It needs no version gate: replay only compares an activity's ID and type, and a run I recorded with no heartbeat timeout replayed fine with one.

What does it cost? In Temporal Cloud, a heartbeat is an Action only when it reaches the server: at most one every 8 seconds here. A 30-second streamed answer already sends up to about 300 Signals, and heartbeats add about 4. A 30-second call that doesn't stream goes from 1 Action to about 5, or $0.0002. If that matters to you, turn it off.

What each plugin needs, from reading main:

Plugin Needs only the default Needs a timer first
Python OpenAI Agents model calls, stateful MCP session MCP operations, sandbox
TypeScript OpenAI Agents model calls, stateful MCP session MCP operations, sandbox
Python Deep Agents everything (#350 adds 30 s)
Python Strands model calls, sandbox model config read, MCP
TypeScript Strands model calls model config read, MCP
Python Google ADK stateful MCP session model calls (per chunk at best), MCP operations
TypeScript Google ADK model calls, MCP
Go Google ADK everything (today 30 s, for streamed model calls only)
Java Google ADK MCP model calls: the timer starts only after the model is built
Java Spring AI chat model, MCP
TypeScript Vercel AI SDK model and embedding calls MCP
Python google-genai all 16 call types, MCP
Python MCP (temporalio-mcp, used by OpenAI Agents and Strands) all 7 operations
Python Claude Agent SDK, Codex nothing: they already use 10 s

I left out Python typesafe (its calls are short, and it skips heartbeats on purpose) and Python LangGraph (every activity is your own node or task).

Where it stands (November 14):

Where a released version's activities don't heartbeat (Python Google ADK, google-genai, Vercel AI SDK, temporalio-mcp), a call that a new Workflow schedules fails on an older Worker after 10 seconds. So each one gets upgrade steps: in #520, #551 and #552, and in the temporalio-mcp 0.4.0 release notes.

Additional context

The script behind the numbers
"""How long does a cancel take to reach a heartbeating activity, for each heartbeat_timeout?

The activity heartbeats every heartbeat_timeout / 2, like the plugin's heartbeating().
The workflow cancels it after `trip_after` seconds. The latency is the time between
ActivityTaskCancelRequested and ActivityTaskCanceled in History.
"""

import asyncio
import uuid
from datetime import timedelta

from temporalio import activity, workflow
from temporalio.client import Client
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker


@activity.defn
async def stream() -> None:
    timeout = activity.info().heartbeat_timeout
    delay = timeout.total_seconds() / 2 if timeout else None

    async def beat() -> None:
        while True:
            await asyncio.sleep(delay)
            activity.heartbeat()

    task = asyncio.create_task(beat()) if delay else None
    try:
        await asyncio.sleep(300)
    finally:
        if task:
            task.cancel()


@workflow.defn
class Trip:
    @workflow.run
    async def run(self, heartbeat_s: float, trip_after: float) -> None:
        handle = workflow.start_activity(
            stream,
            start_to_close_timeout=timedelta(seconds=300),
            heartbeat_timeout=timedelta(seconds=heartbeat_s),
            cancellation_type=workflow.ActivityCancellationType.WAIT_CANCELLATION_COMPLETED,
        )
        await asyncio.sleep(trip_after)
        handle.cancel()
        try:
            await handle
        except Exception:
            pass


async def case(client: Client, heartbeat_s: float, trip_after: float) -> str:
    handle = await client.start_workflow(
        Trip.run, args=[heartbeat_s, trip_after], id=str(uuid.uuid4()), task_queue="tq"
    )
    await handle.result()
    times = {}
    async for e in handle.fetch_history_events():
        name = e.WhichOneof("attributes")
        if name in ("activity_task_cancel_requested_event_attributes", "activity_task_canceled_event_attributes"):
            times[name] = e.event_time.ToDatetime()
    latency = (
        times["activity_task_canceled_event_attributes"]
        - times["activity_task_cancel_requested_event_attributes"]
    ).total_seconds()
    return f"heartbeat_timeout={heartbeat_s:>4}s  trip at {trip_after:>4}s  cancel reached the activity after {latency:5.1f}s"


async def main() -> None:
    async with await WorkflowEnvironment.start_local() as env:
        async with Worker(
            env.client,
            task_queue="tq",
            workflows=[Trip],
            activities=[stream],
            workflow_runner=UnsandboxedWorkflowRunner(),
        ):
            cases = []
            for t in (30, 10, 5):
                # Early in the call, and just after the first heartbeat went out.
                cases += [(t, 1.0), (t, t / 2 + 1)]
            for line in await asyncio.gather(*(case(env.client, t, a) for t, a in cases)):
                print(line)


asyncio.run(main())

Sub-issues

Sub-issues

12 of 12 Issues completed
Loading 12 sub-issues

Activity

  1. added
    enhancement
    on Nov 12, 2026
  2. changed the title [-][Feature Request] Default heartbeat timeout for streaming model activities in every plugin[/-] [+][Feature Request] Default heartbeat timeout for every plugin's own activities[/+] on Nov 12, 2026
  3. campoy commented on Nov 12, 2026

    @campoy
    ContributorAuthor

    I widened this from streaming model calls to every activity a plugin defines. A survey of all the plugins showed the same problem in non-streaming model calls, MCP and sandbox activities. Many of them never heartbeat at all, so they need a timer before they can take a default. I also added what it costs in Temporal Cloud Actions, and the plugins left out on purpose.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions