Why Temporal Python workflows need a sandbox and an event loop plan
The workflow sandbox decides which Python code runs deterministically inside a workflow, and the asyncio versus pool choice decides where slow I/O and CPU-bound work runs. Get both wrong and the failures appear later: a workflow that replays differently after a deploy, or a worker that stops polling because one blocking call holds the event loop. Teams should settle these decisions before writing the first workflow, because changing them later usually means reworking every workflow and activity that depends on them.
Design work is needed before coding when a Python team will call slow external APIs, run CPU-heavy transforms, or import third-party libraries that read clocks, randomness or environment state. Each of those touches the determinism rules that replay depends on. The team should inventory which modules workflow code will import, decide which must be passed through the sandbox unchanged, and decide which work moves into activities that run on asyncio, a thread pool or a process pool. Ask whoever will own the workers to confirm the concurrency model and the Python version they will support.
This Python SDK work sits on top of a Temporal Service that someone has to run. Whether that is self-hosted Temporal, with its persistence and visibility stores, or Temporal Cloud, the worker design depends on the service's namespaces, authentication and task queue behavior, so the two decisions should be made together. The pillar covers the service side, while this page covers the Python code and worker choices that sit inside it.
Before committing, confirm three things with your team: which modules workflow code may import, which blocking calls must never run on the worker event loop, and how your tests will exercise replay. The Temporal documentation on the Python SDK is the natural next read for the exact sandbox rules, and the rest of this page works through each decision in turn.
Choosing asyncio, thread pool or process pool for activities
Async activities are async def functions that run on the worker's asyncio event loop. They suit I/O-bound work where every network call uses an async client, such as an async HTTP client or an async database driver. Many activities can wait on I/O at once without a thread per call, which makes this model economical when the library ecosystem supports it.
- What blocks the loop: any synchronous call inside an async activity, such as a blocking
requestscall, atime.sleep, or a CPU-heavy loop. One blocked coroutine stalls heartbeats and task polling for every other activity on that worker. - Worker sizing: concurrency is governed by the SDK's activity slot settings. Confirm the maximum concurrent activity values in the Python SDK documentation and set them from your load tests, not from defaults.
- Cancellation: cancellation arrives as an
asyncio.CancelledErrorat the next await point. Code that swallows this exception or runs long synchronous sections cannot be cancelled promptly. - Heartbeats: call heartbeat from the coroutine itself. A loop that never yields cannot send heartbeats, so long-running async work needs regular awaits.
Before relying on this model, check that every library in the activity path is async and that the team has a rule for detecting blocking calls in review.
Thread pool activities are synchronous functions executed in a worker thread pool. They fit blocking I/O, such as synchronous database drivers, legacy SDKs, or vendor clients that offer no async interface. Threads let these calls wait without freezing the event loop that serves the rest of the worker.
- What blocks the loop: less of the loop is at risk, but the thread pool itself becomes the bottleneck. Once every thread is busy, further activity tasks queue, and their start-to-close timers keep running.
- Libraries that hold the GIL: threads help with I/O waits, but pure-Python CPU work in threads still competes for the global interpreter lock. Libraries that release the GIL during native calls benefit most.
- Worker sizing: the thread pool size and activity slot limits must be set together. Confirm the relevant settings in the Python SDK documentation and check them under realistic concurrency.
- Cancellation: a running thread cannot be forcibly stopped. Cancellation depends on the activity checking for cancellation requests during heartbeats, so long blocking calls should use timeouts.
- Heartbeats: heartbeat from inside the synchronous function at a regular interval, and set heartbeat timeouts that match the slowest expected step.
Confirm how your chosen client library behaves under cancellation before assuming a stalled call will stop.
Process pool activities run in separate worker processes. They fit CPU-bound work such as parsing large files, compression, scoring models or cryptographic operations in pure Python, where threads would contend for the GIL. Each process has its own interpreter, so the work does not block the event loop or other threads.
- What blocks the loop: the main process should only coordinate. Large arguments and results are serialized between processes, so payload size and serialization cost can dominate the work itself.
- Memory and process count: each process carries its own memory footprint. Size the pool against the host's memory and core count, and confirm the process pool settings in the SDK documentation.
- Cancellation: stopping a process is more abrupt than stopping a coroutine. Design the work in chunks that check for cancellation, so the parent can end a run cleanly.
- Heartbeats: heartbeats are sent from the activity context, so the work should report progress at chunk boundaries. Set heartbeat timeouts to cover the longest chunk.
- Operational fit: process pools complicate logging, tracing and crash handling. Test what happens when a child process dies mid-activity and confirm the retry behavior your workflows expect.
Validate pool sizing with a load test that mirrors production payloads before going live.
Configuration options and when each fits
This table compares the worker and activity settings that decide how Python code runs in a Temporal worker, and when each one fits. Read each row as a decision: what the option controls, when it suits your activities, and what it costs you in complexity or risk. Confirm default values and option names in the Python SDK reference for your exact SDK version before you set them.
| Option | When it fits | Trade-off to weigh |
|---|---|---|
| Async activities on the event loop | Activities that await network I/O with async client libraries and never run CPU-heavy code | Any blocking call inside an async activity stalls the whole worker, including heartbeats and other tasks |
| Thread pool activity executor | Activities that call blocking, thread-safe libraries such as synchronous database or HTTP clients | Threads share memory and the GIL limits CPU-bound speedup, so shared state needs locking |
| Process pool activity executor | CPU-bound activities such as parsing, compression or heavy computation | Arguments and results cross process boundaries by serialization, and activity code must be importable and picklable |
| Activity executor pool size | Sizing parallel blocking work to the cores or I/O capacity of the worker host | Too large a pool exhausts memory or CPU, too small queues tasks and inflates schedule-to-start latency |
| Worker activity and workflow task slot limits | Capping concurrent activities or workflow tasks so one worker does not overload its host or downstream systems | Lower limits protect the host but reduce throughput, and they must match the pool sizes above |
| Sandbox passthrough modules | Third-party or standard library modules that workflow code imports and that the sandbox would otherwise reload, slowing or breaking execution | Passing through a module skips sandbox isolation for it, so it must not hold non-deterministic state or I/O |
| Heartbeat timeout and heartbeat calls | Long-running activities that need to report progress so the server can detect a stalled or lost worker quickly | Heartbeats add calls and payload traffic, and a loop that blocks the event loop cannot send them on time |
| Heartbeat details for resumption | Activities that can checkpoint progress and resume from the last recorded point after a retry | Stored details must be serializable and small, and activities must handle resuming from partial state |
Mistakes that block the event loop in Temporal Python code
Most stalled Temporal Python workers trace back to a small set of habits: blocking calls on an asyncio loop, heavy computation in the wrong place, and state or data handled in ways the sandbox and the Temporal service do not expect. Each card below names the symptom, the cause and the check that catches it before production.
Blocking HTTP and database clients in async activities
Symptom: an async activity stops heartbeating, other activities on the same worker start timing out, and the worker logs show long gaps between task starts. Cause: a synchronous client such as requests, a blocking database driver or a plain file read runs directly inside an async def activity, so it holds the single event loop thread. Fix: use an async client library, or move the blocking call into a thread or process pool through the activity executor. Check every async activity for calls that do not await.
Using time.sleep in async code
Symptom: a worker that looks idle still processes tasks slowly, and sibling activities finish late after one activity pauses. Cause: time.sleep blocks the thread that runs the event loop, so no other coroutine runs during the pause. Fix: replace it with await asyncio.sleep inside async code. For waits that must survive a worker restart, use a Temporal timer in the workflow rather than sleeping in an activity. A lint rule that flags time.sleep in async modules catches most cases.
CPU-heavy work on the event loop
Symptom: heartbeats for long-running activities are missed, tasks queue up behind a single slow computation, and the worker reports task timeouts for work that would have finished on time. Cause: parsing large files, compression, hashing or model scoring runs on the loop thread, which cannot serve other coroutines while it computes. Fix: send CPU-bound functions to a process pool, sized to the cores the worker container actually has, and keep the activity coroutine free to heartbeat. Measure with a load test on realistic input sizes before choosing thread or process pools.
Non-deterministic calls in workflow code
Symptom: a workflow fails with a non-determinism error during replay after a deploy, even though it ran correctly before. Cause: workflow code reads the clock, generates random values or UUIDs, performs I/O, or imports libraries that do so, and replay produces different commands from the recorded history. Fix: use workflow.now(), workflow.random() and workflow.uuid4() or move the work into an activity. Run the sandbox with pass-through modules only for libraries you have reviewed. Replay tests against real histories catch these before rollout.
Mutating shared state across tasks
Symptom: two concurrent activities or handlers produce results that depend on timing, and counters or lists in a workflow hold values that differ between the original run and a replay. Cause: module-level variables, shared dictionaries or class attributes are read and written by several coroutines or threads with no ordering guarantee. Fix: keep per-execution state on the workflow instance, guard shared resources in activities with explicit locks or a single owner, and let the workflow coordinate through signals, updates and workflow.wait_condition rather than polling shared flags.
Oversized payloads in arguments and results
Symptom: activity inputs or results fail with a payload size error, or workflow histories grow until the execution becomes slow to load and replay. Cause: full documents, large dataframes or entire API responses are passed as arguments or return values instead of being referenced. Fix: pass object-store keys or database IDs, have the activity fetch and process the data, and return only the summary the workflow needs. Confirm the payload size limits for your Temporal Server version and deployment, since they are configurable and can change between releases.
Temporal releasesHow to set up a Python worker that runs safely
This sequence takes a Temporal Python project from pinned dependencies to a worker that has passed determinism checks, so workflow code stays safe to change. Each step ends with a check the team can run before promoting code.
Pin the Python SDK version
The engineering lead chooses one temporalio SDK version and pins it in the project's lock file, then records the matching Temporal Server version the team targets. Workflow code is sensitive to SDK behavior, so every worker and every test environment must install the same pinned release. Done means a clean install in CI and on developer machines resolves to the same version, and the version is written in the team's runbook next to the server version.
Separate workflow and activity modules
The developers split the code into a workflow module that holds only orchestration logic and an activity module that holds I/O such as HTTP calls, database access and file work. Workflow modules import only what they need to decide, and activities import the client libraries. Done means a reviewer can open the workflow file and find no network, file or clock calls, and the worker entry point imports both modules explicitly.
Configure the sandbox and pass-through modules
The developers set the workflow sandbox restrictions and list any third-party libraries that must bypass re-import inside the sandbox using the pass-through configuration for modules that are safe to share. Each pass-through entry should be a library the team has reviewed for determinism. Done means the workflow module imports without sandbox errors in a local test, and the pass-through list is short, documented and reviewed in code review.
Choose the activity executor
The engineers decide whether async activities run on the event loop, in a thread pool or in a process pool, based on whether each activity is async I/O, blocking I/O or CPU-bound work. Synchronous blocking calls inside async activities will stall the worker, so blocking work belongs in a configured executor. Done means each activity is mapped to one executor in a written table, and no blocking call sits directly inside an async activity.
Start the worker against a development server
The developer starts a Temporal development server and launches the worker with the chosen executor and the task queue name that the client uses. The worker startup log should show the expected task queue and the configured activity executor, and a test workflow should run end to end. Done means a sample execution completes and the worker logs confirm the executor type the team selected.
Run replay tests before promotion
The team collects real or representative workflow histories and replays them against the new code in CI before any deployment. A replay failure indicates a non-deterministic change, such as a reordered command or a new call in workflow code without versioning. Done means the replay suite passes on the candidate build, and a failing replay blocks promotion until the change is versioned or reverted.
Promote the worker with a documented check
The release owner promotes the worker build only after the pinned SDK, sandbox configuration, executor mapping and replay results are all recorded for that build. The promotion record should name the Temporal Server version the worker connects to, so operators can trace a failure back to a known pairing. Done means the release record contains each check result and a rollback path is written down.
How workflow tasks and activity tasks flow through a Python worker
The diagram starts at the Temporal Service, which hands workflow tasks to the Python worker. Those tasks run deterministic workflow code inside the workflow sandbox, where pass-through modules decide which imports load normally. Activity tasks leave that boundary and run in an asyncio event loop, a thread pool or a process pool, where side effects such as network calls are allowed. Check that no blocking call sits in the sandbox or on the event loop, because either one stalls every other task on that worker.
Workflow tasks run in the sandbox, while activity tasks run outside it.
Security and operational considerations for Python workers
Python workers sit between your workflow code and the data it touches, so the security questions cover what is stored, who can call the server, and what runs on the worker. The cards below cover the controls to decide before go-live and the checks to repeat when dependencies or services change.
Encrypt activity payloads with codecs
Activity inputs and results are recorded in workflow history as payloads. A custom payload codec encrypts them before they reach the server, and a codec server lets the Web UI decode them for authorized users. Decide which keys hold the data, who can read them, and how keys rotate, then confirm that every worker and client uses the same codec chain.
Self-hosted security docsKeep secrets out of history
Workflow history is durable and readable by anyone with history access, so API tokens and passwords should not be passed as workflow arguments or returned from activities. Have activities fetch credentials from your secrets manager at run time, and confirm that logs and exception messages do not echo them back into history.
Set authorization on the server
If no Authorizer is configured, self-hosted Temporal uses the default noopAuthorizer, which allows every API request with no authentication or access control. Before any worker connects, configure an Authorizer and a ClaimMapper so that namespace roles map to your identity claims, and test that a worker without the right role is refused.
Security settingsKeep services off the public internet
Temporal's deployment guidance says services should run on hosts that are not reachable from the public internet, with network access limited to trusted internal networks. Check that the frontend, internode and database endpoints are private, that Python workers reach the frontend over a controlled path, and that mTLS covers both internode and frontend traffic.
Deployment guidePin dependencies used in the sandbox
The workflow sandbox restricts which modules workflow code can import, and pass-through modules decide which third-party packages load unchanged. Pin exact versions of the SDK and every library imported by workflow code, and rebuild the worker image from the lockfile. A silent upgrade can change behavior during replay, so test it against recorded histories before rollout.
Instrument workers for logs and metrics
A worker that blocks its event loop or exhausts its thread pool shows up first as rising schedule-to-start latency and slow activity completions. Export SDK and worker metrics, send structured logs with workflow and activity IDs, and alert on task queue backlog and activity failure rates. Confirm that logs redact payload contents and secrets.
Questions teams ask before building Temporal Python workflows
Can a Python team build Temporal workflows on its own?
Yes, a Python team can build Temporal workflows with its own engineers, and many do. The Python SDK gives you the workflow sandbox, asyncio and worker pools, but the design choices are where teams usually need help: which code belongs in workflows, which library imports must be passed through the sandbox, and where CPU-bound work runs. A useful test is whether at least two engineers can explain why a workflow is deterministic, read a replay failure and size a worker pool for their workload. If not, a fixed-scope review of your first workflows is a lower-risk way to learn those rules before the pattern spreads across the codebase.
What drives the effort of a Temporal Python build?
Effort scales with the shape of the workload more than with line count. The main drivers are:
- The number of activity types and how many external systems each one calls
- The library mix, since libraries that do I/O or hold global state need sandbox pass-through decisions and checks
- How much CPU-bound work runs in activities, which determines whether thread or process pools are needed
- How much replay test coverage you want before the first deployment, and whether real event histories will be collected for it
Each driver adds design, test and review work. Ask any partner to break its quote down by these items.
What does the work need from our engineers and infrastructure?
You need named engineers who own the Python codebase, a person who can approve changes to workflow code, and access to a Temporal Service in a test environment. On the infrastructure side, workers need to reach the Temporal frontend over the network, and the Temporal Service should run on hosts that are not reachable from the public internet, according to the Temporal deployment documentation. Your team should also confirm which persistence and visibility stores the service uses, how secrets reach workers, and where worker logs and metrics go. Write these dependencies into the scope so that delays in access do not show up later as schedule slips.
How long does it take to reach a first production worker?
It depends on scope, and the duration should be quoted in writing against that scope. The main variables are the number of workflows and activity types in the first release, the external systems each activity touches, whether replay tests are part of the first release, and how quickly your environments and access are ready. Ask for a milestone plan that shows when the first workflow runs in a test environment, when replay tests are in CI, and when a worker is deployed to production with monitoring in place. A plan without those milestones is hard to check later.
How is cost split between the one-time build and ongoing operations?
The one-time build covers design of workflows and activities, Python worker implementation, replay and integration tests, deployment, and handover documentation. Recurring costs cover running the Temporal Service or paying for Temporal Cloud, operating workers, upgrading the SDK and server, and keeping replay tests current as workflow code changes. Self-hosted costs also include the databases and visibility store that Temporal depends on. Ask any quote to separate these lines, state who pays the infrastructure vendor, and say which upgrades and test maintenance are included in a retainer and which are billed separately.
When does Temporal Cloud change the Python worker work?
Temporal Cloud changes the worker work mostly in what you no longer run. You still write and deploy the Python workers, so the sandbox rules, activity pool choices and determinism checks stay the same. What moves is the operation of the Temporal Service itself: server upgrades, persistence, and frontend exposure. Cloud pricing is usage-based, with pay-as-you-go pricing starting at 50 US dollars per million actions according to Temporal's pricing page, so action volume from retries, timers and child workflows becomes a cost driver to model. Confirm identity, network connectivity and data residency requirements before choosing between the two options.
Which Python worker mistakes cause the most production problems?
The most common problems are blocking calls inside async workflow or activity code, which stall the event loop and delay every task on that worker, and non-deterministic calls such as reading the clock or random values inside workflow code. Teams also import heavy libraries into workflows without declaring pass-through modules, which can fail at startup or slow sandbox loading. Using a thread or process pool for CPU-bound activities without sizing it against the worker's slots is another frequent cause of timeouts. Replay tests and code review of workflow files catch many of these before release.
How DeployOpen works on this
DeployOpen scopes Temporal Python work in writing before any code changes, starting from which workflows run in the sandbox, which activities block, and where your workers run. The build then covers workflow code, activity execution model, tests and handover for infrastructure you control.
How we scope
- Inventory existing workflows and activities to mark which imports need sandbox pass-through and which code runs outside workflows.
- Classify each activity as async I/O, thread pool, or process pool work, based on its blocking calls and CPU profile.
- Agree in writing the deliverables, exclusions and timeline for the Python workflow and worker changes before work starts.
How we build
- Move non-deterministic calls such as I/O, clocks and randomness into activities, and keep workflow code inside the sandbox rules.
- Configure worker thread and process pool sizes and check that no synchronous call blocks the asyncio event loop.
- Add replay tests against recorded event histories so changes to workflow code are checked before deployment.
How we hand over
- Document the sandbox pass-through list, activity execution model and the reasons behind each workflow design decision.
- Deliver a runbook covering worker startup, shutdown, event loop blocking symptoms and how to check them in logs and metrics.
- Walk your engineers through the code and tests so your team can change workflows safely after the engagement ends.
How we support
- Ongoing support, upgrades and continuous testing are available as retainers once the initial build is handed over.
- Retainers can cover Python SDK upgrades, new workflow versions and retesting after changes to activity code.
- Ask any quote to name the Temporal server version, SDK version and the infrastructure where workers will run.

