Graceful shutdown for Temporal workers

Graceful shutdown lets a Temporal worker stop taking new tasks and finish or hand back in-flight work before the process exits. This page covers the settings to align, the checks to run and the failure modes to test before a deploy.

On this page

Graceful shutdown for Temporal workers: why in-flight work depends on it

A team rolling out new worker code usually asks one question first: will the activities and workflow tasks already running survive the restart? The answer depends on whether the worker stops taking new work and gets time to finish what it holds before the platform kills it. A Temporal worker is a process that polls task queues, runs workflow and activity code, and reports results back to the Temporal Service. When Kubernetes or a host sends a termination signal, the worker must stop polling, let in-flight tasks finish within a window, and only then exit. If the window closes first, those tasks are interrupted and later retried, which is safe only if the activities were written for it.

The Temporal documentation describes this worker behavior, but the exact shutdown options, their defaults and how activities learn that a shutdown has started depend on the SDK language and version. Confirm the shutdown timeout, cancellation and drain settings in the documentation for the SDK your workers use, and pin those findings to the SDK version you deploy. Do not assume the behavior of one SDK carries over to another.

This work matters most in three situations: long-running activities that may outlast the termination window, activities with side effects such as payments, emails or writes to external systems that must not be repeated, and teams that deploy workers frequently. Each of these raises the cost of an interrupted task. Before go-live, list which activities fall into these groups and record how long the slowest one normally runs.

How a termination signal moves through the worker and its in-flight tasks

The diagram starts when the orchestrator sends a termination signal to the worker pod. The worker stops polling its task queues, so no new work arrives, and in-flight activities either finish or receive a cancellation once the worker's shutdown timeout is reached. The process then exits. The lower branch shows the risk: if the Kubernetes grace period ends first, the process is killed and unfinished activities are retried by Temporal. Confirm the worker shutdown timeout in your SDK and the terminationGracePeriodSeconds value in your pod spec, and make sure the grace period is longer than the shutdown timeout.

Termination path for a Temporal worker pod, including the kill branch that leads to retries.

Shutdown settings to align and when each fits

This table compares the five settings a team must line up so a Temporal worker can finish or hand back in-flight work during a deploy. Read each row as a dial: check the SDK and Kubernetes docs for current defaults, then decide whether raising it protects running work or lowering it speeds up rollouts.

SettingWhat it controlsWhen to raise or lower itTrade-off
Worker shutdown or drain timeout (SDK)How long the worker waits for in-flight workflow tasks and activities to finish after it stops polling. Confirm the option name and default in your SDK docs.Raise it when activities run longer than the typical pod termination window and cutting them short would force retries. Lower it when rollouts are slow and activities are short and idempotent.A longer drain protects running work but holds old pods longer. A shorter drain speeds deploys but can leave activities to be retried elsewhere.
Activity cancellation on worker shutdownWhether running activities receive a cancellation signal when the worker begins to stop. Confirm how your SDK delivers this and what the activity must do with it.Enable the activity to observe shutdown when it can checkpoint, heartbeat or stop cleanly. Keep it off or limit its scope for activities that cannot be safely interrupted.Cancellation gives activities a chance to clean up, but activities that ignore it still run until the timeout ends them.
Kubernetes termination grace periodHow long kubelet waits after sending SIGTERM before sending SIGKILL. Confirm the default in the Kubernetes pod lifecycle docs.Raise it to cover the worker drain timeout plus any preStop delay. Lower it only when the worker drains quickly and the drain timeout is also reduced.A grace period shorter than the drain timeout means the pod is killed mid-drain. A longer one lengthens each pod's stop time during rollouts.
preStop hook delayA pause before the process receives the termination signal, usually used to let endpoints or load balancers stop routing new work. Confirm the mechanism in your cluster.Add a delay when routing or service discovery lags behind pod termination. Omit it when the worker stops polling immediately and nothing else depends on the delay.The delay counts against the grace period. Set too long, it leaves less time for the drain and slows every rollout.
Rolling update max unavailable and max surgeHow many worker pods stop at once and how many new pods start beforehand in a Deployment or similar controller. Confirm defaults in the Kubernetes Deployment docs.Lower the number of pods stopping at once when long-running work is concentrated on few workers. Raise it when capacity is ample and faster rollouts matter more than per-pod drain time.Fewer pods stopping at once reduces the chance of many in-flight tasks being interrupted together, but lengthens the deploy and can reduce task throughput during it.

How shutdown options differ across Temporal SDKs

The Go SDK sets worker behavior through the worker options passed when the worker is created, so the shutdown timeout is configured alongside poller and concurrency settings in the same place. Activities learn about a stopping worker through a channel that the SDK closes during shutdown, which lets long-running code exit early and record its progress.

  • Worker options: Look for the stop timeout field in the worker options struct, which controls how long the worker waits for in-flight activities before it stops them.
  • Stop channel: Activities can obtain a worker stop channel from the activity context and select on it alongside their own work.
  • Heartbeats: Record heartbeat details before exiting so that a retried attempt can resume from a known point.
  • Cancellation reason: Distinguish a worker stop from a workflow cancellation in your activity code so retries and cleanup follow the right path.
  • Test coverage: Exercise the stop path in unit tests with a simulated stop, not only with the happy path.

Confirm the exact field and function names in the Go SDK release notes for your version, because option names have changed between releases.

Setting up graceful shutdown for Temporal workers on Kubernetes

This sequence aligns the activity inventory, the worker shutdown timeout and the Kubernetes termination settings so that a rollout lets in-flight activities finish or be retried cleanly rather than being cut off mid-run.

  1. Inventory activities and their maximum durations

    The platform or application team lists every activity type each worker runs, with the longest expected duration for each, including retries and any external calls that can stall. Flag activities that are long-running, that hold locks or that cannot be safely repeated. Confirm the list with the activity owners and record it in the repository beside the worker code. Done means every task queue has a documented maximum duration and an owner for each long activity, so the shutdown timeout in the next step has a basis. Ask the SDK team to confirm how each language runtime treats activity timeouts during shutdown before you write the number down.

  2. Set the worker shutdown timeout in the SDK

    The developer sets the graceful shutdown timeout in the worker configuration of the Temporal SDK you use, sized from the longest activity duration in the inventory. Use the setting name from the SDK documentation for your language, and do not reuse a default you have not reviewed. The worker should stop polling for new tasks and then wait up to that timeout for running tasks to complete. Check: start the worker locally, send it a termination signal during a running activity, and confirm the logs record the shutdown event and the time it began waiting for activities.

  3. Set the Kubernetes termination grace period

    The platform engineer sets terminationGracePeriodSeconds in the pod spec so it is longer than the SDK shutdown timeout plus a margin for image-level cleanup. Kubernetes sends SIGTERM when the pod is deleted and sends SIGKILL once the grace period expires, so a grace period shorter than the worker timeout ends in-flight work abruptly. Record the arithmetic in the chart values so reviewers can see how the two numbers relate. Check: describe the rendered manifest in staging and confirm the field is present and larger than the SDK timeout.

  4. Add a preStop hook only if needed

    The platform engineer adds a preStop lifecycle hook only when the base image or the load balancer or service mesh in front of the pod needs time to stop sending new traffic before SIGTERM arrives. For a pure Temporal worker that polls a task queue, the hook is often unnecessary, and adding a sleep can consume grace period without benefit. If a hook is added, the grace period must cover its duration too. Check: review the rendered spec, confirm the decision is written in the values file with a reason, and confirm the worker still receives SIGTERM in staging.

  5. Configure rolling update limits

    The platform engineer sets the Deployment rolling update strategy, including maxUnavailable and maxSurge, so only a bounded share of workers is replaced at a time and enough pollers stay available on each task queue. Very aggressive settings can remove all capacity for a queue while its old workers drain. Confirm the replica count covers the queue's throughput during a rollout. Check: run kubectl rollout status against staging and confirm the deployment completes without a drop in pollers reported by the Temporal Web UI or metrics.

  6. Test a rollout in a staging cluster

    The team deploys a new worker version to a staging cluster while a load test keeps long-running workflows active on the same task queue. The test should include at least one activity that runs close to its maximum duration, so the shutdown path is exercised. Watch for activities that are cancelled, retried after the pod disappeared, or reported as timed out by the service. Check: confirm in-flight activities finish during the rollout, the pod exits within the grace period, and the worker logs show the shutdown sequence. Record the results and repeat the test before promoting the change to production.

Detecting shutdown in Temporal activities and keeping them safe to retry

An activity learns that its worker is shutting down through cancellation, so the handling of cancellation decides whether a graceful shutdown finishes cleanly or leaves work half done. When a worker begins shutting down, it stops accepting new tasks and gives in-flight activities a window to finish. Activities that check for cancellation at safe points, such as between batches of records or before each external call, can stop early, clean up and report back. Activities that never check for cancellation run until the forced stop, which is the case most likely to produce partial results. The team should review each activity and confirm that it reacts to cancellation requests in the SDK it uses, and should confirm in the SDK documentation how heartbeat timeouts and cancellation delivery work for that language before setting any values.

Long-running activities should heartbeat so that progress and cancellation become visible to the Temporal service. A heartbeat records progress details that the next attempt can read, so a retried activity can resume from a checkpoint rather than start over. Heartbeats also carry cancellation back to the worker, so an activity that heartbeats regularly learns about a shutdown or a cancelled workflow promptly. The heartbeat timeout must be longer than the gap between heartbeats under normal load, or the service will treat a healthy activity as lost. Teams should confirm the heartbeat timeout semantics, the throttling behavior of heartbeat calls and the exact cancellation types in their SDK documentation, then write those values into the activity configuration rather than relying on defaults.

Temporal can retry an activity after a forced stop, so any activity with external side effects must be idempotent. A payment, email, ticket or file write that runs twice because the first attempt was interrupted during shutdown causes real harm unless the target system can recognize the repeat. Teams should pass a stable idempotency key derived from the workflow and activity identifiers, check whether the external operation already completed before repeating it, and record results in a system the activity can query on retry. For each activity, the review should record the side effect, the idempotency key, the check performed on retry and the test that interrupts the activity mid-run and confirms the outcome is correct.

Failure modes that cost in-flight work during deploys

Each failure mode below shows up during a worker deploy as lost progress, duplicated side effects or slow recovery. Most trace back to a mismatch between how long the worker needs to stop and how long the platform allows it. Check the symptom first, then review the setting or code path that produces it.

Grace period ends before activities finish

The worker process receives a termination signal and stops accepting new tasks, but activities already running get only the time the platform allows. If the Kubernetes terminationGracePeriodSeconds is shorter than the worker's graceful shutdown timeout, the kubelet sends SIGKILL while activities are still executing. Symptom: activity attempts end with no completion and the same activity retries on another worker. Review: the worker shutdown timeout and the pod termination grace period together.

Self-hosted deployment docs

Long activity without heartbeat handling

An activity that runs for minutes without heartbeating cannot learn that its worker is shutting down or that the attempt has been cancelled. It keeps working until the platform kills the process. Activities that send heartbeats can receive cancellation and stop cleanly. Symptom: activities killed mid-loop with no cleanup logged. Review: heartbeat calls inside long loops, the heartbeat timeout, and how the activity reacts to cancellation.

Non-idempotent activity runs twice

When a worker is force-stopped after starting an activity but before reporting its result, Temporal retries the attempt on another worker. An activity that charges a card, sends an email or creates a record without a stable key may run twice. Symptom: duplicate side effects that match a deploy window. Review: whether each side-effecting activity uses an idempotency key derived from the workflow and activity identifiers.

Pre-stop delay shorter than traffic drain

A preStop hook delays SIGTERM so that the pod leaves the service endpoints and the worker stops polling before shutdown begins. If that delay is shorter than the time the load balancer or polling takes to stop, new tasks arrive after shutdown has started. Symptom: tasks picked up during the final seconds of termination and then cancelled. Review: the preStop sleep, the endpoint removal timing, and the worker shutdown timeout that follows it.

Rolling update drains one task queue

A rolling update that replaces most pods of a single deployment at once can leave a task queue with no pollers while the new pods start. Work then waits in the queue, and schedule-to-start latency rises for every workflow that depends on it. Symptom: a backlog on one task queue that clears only after new pods register. Review: the deployment strategy's maxUnavailable and maxSurge values and the minimum pod count for each queue.

Restart empties the workflow cache

A restarted worker starts with an empty workflow cache, so each workflow running on it must be replayed from history on its next task. Replay cost rises across the fleet during the deploy and can slow recovery of active workflows. Symptom: a spike in replay activity and workflow task latency right after rollout. Review: the cache size setting, the number of workers replaced per interval, and whether sticky queue fallback behavior is expected in the rollout plan.

Verifying that a deploy drains workers cleanly

Test the drain before production traffic depends on it. Run a rollout of the worker deployment while long-running test workflows are in progress, using a dedicated namespace and task queue so the test does not touch real business work. Start workflows whose activities run longer than the shutdown window you plan to configure, and include some that call the cancellation path, some that heartbeat, and some that are expected to finish quickly. Before the rollout, write down what each one should do: an activity that is allowed to finish should complete on the old pod, an activity that should stop should observe shutdown and report cancellation, and a workflow should either finish or be retried on a new worker without a visible gap.

Watch the Temporal Web UI or CLI during the rollout. Look for activities that show failed or retried attempts, for workflows stuck waiting on a task queue with no pollers, and for attempts that were interrupted and then re-run. Check each retried activity against its idempotency design: a payment, email or file write that ran twice is a defect in the activity, not in the drain. Then review the worker logs from the terminated pods for shutdown events and compare the timestamps with the Kubernetes termination events. The metric names for shutdown, poller and slot behavior differ between SDKs and server versions, so confirm the exact names in the SDK and server documentation before you build dashboards or alerts on them.

Record the result and repeat the test after every change. Keep the test workflows, the rollout command and the expected outcomes in version control so the same drill runs after each change to the shutdown timeout, the termination grace period or the SDK version. A pass means every test workflow reached a terminal state or a documented retry, no activity ran a side effect twice, and the logs show each pod exited after its work was drained or deliberately cancelled. Ask the team that owns the Temporal deployment to sign off on the results, and keep the run record as evidence for release reviews.

What to confirm in your SDK, cluster and workloads

Graceful shutdown depends on several layers agreeing: the Temporal SDK, the workload's longest activity, the Kubernetes termination behavior and any network layer in front of the pod. Each card below is a value to confirm in your own environment rather than assume from defaults. The Temporal server and Kubernetes documentation are the places to check each one.

SDK shutdown and cancellation behavior

Confirm how the SDK version you run handles worker shutdown: whether it stops polling first, how long it waits for in-flight activities, and how it delivers cancellation to running activities. Behavior differs between SDKs and between releases, so read the release notes for the exact version in your lockfile. Test a rollout in a non-production namespace and watch for activities that were cancelled or retried when they should have finished. Confirm the SDK version before setting any timeout.

Temporal deployment docs

Longest activity runtime

List every activity type that runs on the workers being deployed and record its worst-case duration, including retries and heartbeat intervals. The graceful shutdown window must be long enough for the longest activity you expect to be running at the moment a pod receives its termination signal. Activities that exceed the window are interrupted and retried from their last state. Ask the owners of long-running activities such as file processing or external batch calls for these figures rather than estimating them.

Kubernetes version and termination behavior

Identify the Kubernetes minor version your clusters run and confirm how it sends termination signals, runs preStop hooks and applies the grace period before force-killing a container. Check the terminationGracePeriodSeconds value in each worker pod spec and compare it with the longest activity window. Kubernetes support windows also change over time, so confirm your cluster version is still maintained before you rely on its behavior.

Kubernetes version skew policy

Mesh and ingress delay before traffic stops

Determine whether a service mesh sidecar, ingress controller or load balancer adds its own drain delay, and whether it stops sending traffic to a pod before or after the pod begins shutting down. Worker shutdown and sidecar shutdown can race, which may leave the worker without a network path while it still holds tasks. Test the order of events in your cluster with a deliberately slow activity and record the result.

Self-hosted or Temporal Cloud

Confirm whether your workers connect to a self-hosted Temporal Service or to Temporal Cloud, since the connection, namespace and endpoint settings differ between the two. Check whether the server version you run affects how task routing and worker shutdown behave during a deployment. Also confirm which team owns the Temporal side of a rollout, because a worker that drains cleanly still needs the server to reassign its pending tasks.

Serverless worker platform limits

If any workers run on serverless compute, confirm the platform's own limits on invocation duration, idle shutdown and forced termination, and whether those limits can end a worker before its activities finish. Check the current support status of the platform with Temporal, since serverless worker support is described in Temporal's documentation as having maturity constraints. Serverless workers may need shorter activities or checkpointing that a long-lived pod does not.

How long does graceful shutdown work take and what does it cost

How much effort does it take to set up graceful shutdown in-house?

Effort depends on the shape of your worker fleet, so no single figure applies to every team. A team with one worker image, one task queue and a small set of activities can usually make the change in a normal sprint, mostly in Kubernetes manifests, worker startup code and one test pass. The larger cost is learning how your SDK stops pollers, finishes in-flight tasks and signals shutdown to activities, then proving the behavior under load. Most of that work is one-time engineering time. Recurring effort starts later, when new task queues, new activity types or SDK upgrades change the behavior and someone must retest. Ask your engineers to estimate each worker deployment separately and to list which parts they have already done.

What makes graceful shutdown work take longer?

The main factors that move the effort are the scope of your fleet and the behavior of your activities. Each one adds design, code and test work:

  • The number of task queues, since each queue's pollers and in-flight work must drain and be tested.
  • The language mix, because each SDK exposes shutdown and activity cancellation differently.
  • Activity duration, since long activities need heartbeats and a termination window long enough to finish or hand off cleanly.
  • Non-idempotent side effects, such as payments, emails or writes to external systems, which need retry-safe design before a worker can stop mid-task without creating duplicates.
  • The number of environments, since each one needs its own settings and its own test run.

A smaller, uniform fleet with short, idempotent activities takes the least effort.

What does graceful shutdown work need from my team before it starts?

The work needs access to your deployment definitions, a staging environment and people who can make decisions about code. The specific inputs are:

  • The Kubernetes manifests for every worker Deployment, including termination grace period, lifecycle hooks and any autoscaling settings.
  • The SDK and version for each worker, plus the Temporal Server version it connects to.
  • An activity inventory listing each activity type, its typical duration, whether it heartbeats and whether its side effects are idempotent.
  • A staging cluster with a Temporal Service and representative load, where restarts can be triggered safely.
  • A named owner who can approve changes to workflow and activity code.

Without the inventory, the scope cannot be fixed in writing, so it should be settled before anyone requests a quote.

Can my own engineers set up graceful shutdown without a partner?

Yes, for simple workers. A single service with one task queue, short activities and idempotent side effects is a reasonable first project for an in-house team that already runs Kubernetes and has SDK experience. Before changing anything, the team should write a test plan: trigger rollouts during load, confirm that in-flight activities complete or retry as designed, check that workflows resume on new workers and record the termination behavior in the runbook. Teams with many queues, mixed languages or long side effects often benefit from outside help on the design, even if they run the rollout themselves. Confirm the shutdown options in the documentation for your SDK version, because the behavior is set per SDK.

What does a fixed-scope graceful shutdown engagement cover?

DeployOpen's engagements are generally fixed-scope, with scope, deliverables and timelines agreed in writing before work starts. For graceful shutdown, a typical written scope can cover:

  • A review of worker deployments, SDK versions and the activity inventory.
  • A design of shutdown timeouts, Kubernetes termination settings and activity behavior during shutdown, set out per task queue.
  • Code or configuration changes listed in the scope, with review of activity idempotency where it affects safe retries.
  • A test plan run in staging, including rollouts under load, with recorded results.
  • Runbook and alert guidance for shutdown-related failures, handed to your team.
  • Knowledge transfer so your engineers can run future changes.

DeployOpen does not publish a price list. A quote follows from the written scope, and ongoing support and upgrade testing are available as retainers.

What should I ask for in a written quote for this work?

Ask for a quote that names what is in scope, what is excluded and what you must provide. Useful items to request:

  • A list of worker deployments, task queues and environments covered.
  • The SDK and Temporal Server versions covered, and any upgrades excluded.
  • Activity inventory review, with activities needing code changes listed separately from configuration changes.
  • The staging environment, load conditions and pass criteria for the rollout tests.
  • Named deliverables: manifests, code changes, runbooks and test records.
  • Assumptions about access, staging availability and your team's time, with the impact if any of them change.
  • Which costs are one-time and which recur, such as retainer support and retests after upgrades.

Compare quotes on these points before comparing totals.

Which costs recur after graceful shutdown is in place?

The initial build is mostly one-time, but several changes in your fleet bring the work back. New task queues, new activity types and new environments each need the shutdown settings reviewed and tested. SDK upgrades can change shutdown behavior, so they need a retest before they reach production. Kubernetes upgrades matter too: the version skew policy says kube-apiserver must be upgraded one minor version at a time, before the other control plane components and kubelets, so worker termination should be retested as part of the cluster upgrade plan. Your on-call team also carries a recurring cost in reviewing shutdown-related alerts. Ask any partner which of these are covered by a retainer and which are billed as new work.

How DeployOpen works on this

DeployOpen treats graceful shutdown for Temporal workers as part of the wider worker deployment, scoped against your own Kubernetes termination settings, activity timeouts and release process. Engagements are fixed-scope, with scope, deliverables and timelines agreed in writing before work starts.

How we scope

  • Inventory every worker deployment, its task queues, SDK language and current termination settings.
  • Record the longest expected activity and how long in-flight workflows may run during a rollout.
  • Agree in writing which workers, environments and Kubernetes clusters the shutdown work covers.

How we build

  • Configure worker shutdown timeouts and activity cancellation handling in your own codebase and manifests.
  • Align the Kubernetes termination grace period, preStop behavior and rollout settings with the worker timeouts.
  • Test rollouts and forced restarts in a non-production environment before any change reaches production.

How we hand over

  • Deliver the configuration, a shutdown runbook and the test results for each worker deployment.
  • Document which settings must change together so future tuning does not reintroduce failed in-flight work.
  • Walk your platform and application teams through the rollout procedure and the alerts that confirm it.

How we support

  • Offer ongoing support, upgrades and continuous testing as a retainer after handover.
  • Re-check shutdown behavior when Temporal SDK, Kubernetes or worker configuration versions change.
  • Confirm with your team the support hours and escalation path before the engagement starts.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.