Every Python service eventually grows the same organ: a retry loop wrapped around a database table wrapped around a while True that tracks what already happened. The code starts as a simple async def, then acquires manual checkpoints, a status column, a reconciliation job, and a stale-lock cleaner. By the time the workflow spans three services and two days of waiting, the original business logic is buried under recovery plumbing. The hard part is not writing the steps; it is remembering exactly where the process stopped when a pod dies at 3 a.m.

Temporal takes a different stance. It records the decisions a workflow makes as an append-only event history, then replays that history after a crash so the code can rebuild its in-memory state without repeating side effects. The result is durable execution that looks like ordinary imperative code. The Temporal Python SDK is the Python-native expression of that idea, and it is unusual among official SDKs because it wraps a shared Rust core rather than reimplementing the protocol in Python.

This tour follows the real package on the main branch of temporalio/sdk-python. Every path, line number, and count below was checked against that checkout, so the shapes described here are the ones a reader will actually find rather than an idealized diagram of how a workflow engine might be built.

Overview of the Temporal Python SDK: Client and Worker API, workflow engine, Rust core bridge, data conversion, and testing tools

The public surface is small: a Client, a Worker, two decorators, and a converter. Everything else exists to make those pieces survive restarts.

Reading the overview from left to right:

Detailed architecture of the Temporal Python SDK showing client, worker loops, workflow instance, sandbox, bridge protos, converters, runtime, and testing components

The detail view separates the Python-side activation interpreter from the sandbox import machinery and the generated protobuf boundary to Rust.

What actually ships in the package

The checkout contains 388 Python files under temporalio/, and the directory layout is more opinionated than the public imports suggest. client/ holds the connection and handle logic, worker/ holds task processing, workflow/ holds the authoring API, and activity.py sits at the top level because activities are invoked from outside the workflow sandbox. runtime.py and service.py are the native and gRPC seams, while bridge/, converter/, testing/, nexus/, and contrib/ handle the edges.

Two details are worth noting because they contradict common assumptions. First, workflow.py and client.py are not files; they are packages, so the real implementation lives in workflow/_definition.py and client/_client.py. Second, contrib/ in this checkout contains only pydantic.py, reflecting how small the built-in integration surface has become now that many connectors live in separate distributions.

The project metadata is equally concrete. pyproject.toml requires Python 3.11 or newer, depends on protobuf>=4.21.12,<8.0.0, and exposes gRPC support as an optional extra with grpcio>=1.49.1,<2.

From a decorated coroutine to a replayable activation

This is the section where the design stops being abstract. A workflow author writes a class with @workflow.defn, then a method with @workflow.run. The defn decorator is not just metadata: it calls _Definition._apply_to_class, which validates the class and records the workflow name, sandbox preference, failure exception types, and versioning behavior. The run decorator marks one coroutine as the entry point and stores it on the definition.

The client surface is similarly explicit. start_workflow appears as five overloads in client/_client.py at lines 403, 435, 468, 503, and 536, narrowing from a generic signature to typed convenience forms; execute_workflow follows the same pattern beginning at line 665. This is not cosmetic. It is how the SDK preserves type information for workflow inputs and results without giving up a single runtime entry point, and it pairs with the WorkflowHandle.result signature at line 202 of client/_workflow.py, which is itself overloaded so that the return type follows the handle’s generic parameters.

At runtime, Worker.run is declared at line 803 of worker/_worker.py and drives polling. A workflow task arrives as a protobuf activation through the bridge, and worker/_workflow.py decodes it, then calls activate on a per-workflow WorkflowInstance. That instance is where the real engineering lives: temporalio/worker/_workflow_instance.py is 4,265 lines long, with _WorkflowInstanceImpl at line 282 and its activate method at line 481. It is, in effect, a small interpreter that turns activations into coroutine progress.

The instance cache is a useful mental model. The workflow worker maintains workflow instances by run, and when the server sends a remove_from_cache job, it routes that job through _handle_cache_eviction after checking the field at line 351. That eviction step is why a workflow must be deterministic: the Python object may disappear, and the only way back is replaying the activation history into a fresh instance.

The deterministic context that makes replay safe is explicit rather than magical. workflow/_context.py and workflow/_asyncio.py supply the workflow-scoped event loop, while workflow/_workflow_ops.py builds commands and worker/_command_aware_visitor.py serializes completions. Time, randomness, and side effects are funneled through these modules so that the same history produces the same decisions. Activities are deliberately outside this boundary: worker/_activity.py is 1,207 lines and manages threading, cancellation, and heartbeats instead of determinism.

The sandbox is the second half of that contract. @workflow.defn defaults to sandboxed: bool = True, and the sandbox package contains five files: _runner.py, _importer.py, _in_sandbox.py, _restrictions.py, and __init__.py. SandboxedWorkflowRunner at line 64 of _runner.py installs a custom import hook so that user modules are loaded through the restriction layer. That layer is an allowlist of modules considered safe to import inside deterministic code. It is a correctness boundary, not a security boundary, which is an important distinction for anyone tempted to run untrusted workflow code.

Crossing into the Rust core without leaving Python

The bridge is where this SDK diverges most from a pure-Python design. temporalio/bridge/Cargo.toml declares a crate named temporal-sdk-bridge, builds it as a cdylib, and exposes it as the temporalio.bridge.temporal_sdk_bridge extension module. The dependency set is not incidental: pyo3 0.29 with abi3-py311, pyo3-async-runtimes on Tokio, tonic 0.14, and prost 0.14. The sdk-core entry in the tree is a git submodule commit, so the actual connection management, polling, and retry behavior come from shared Rust crates rather than Python.

The release profile is deliberately tuned for a shipped binary: opt-level = 3, lto = true, and incremental = false. The same manifest documents a FIPS build variant that swaps the rustls provider to aws-lc-rs, which hints at how seriously the transport layer is treated.

The Python side of that boundary is narrow. bridge/worker.py exposes poll_workflow_activation and poll_activity_task, both returning protobuf messages decoded from native calls. There are 12 generated *_pb2.py modules under bridge/proto/, and bridge/proto/core_interface_pb2.py is the interface contract. Above that, service.py defines WorkflowService at line 406 on top of the generated stubs, and runtime.py warns that each new runtime creates a new internal thread pool and that a forked process should create its own runtime rather than inherit one.

What a worker actually loops on

The Worker facade hides two independent loops with different failure models. In worker/_workflow.py, the workflow loop polls an activation, finds or creates the right WorkflowInstance, calls activate, and feeds the resulting completion back through the bridge. In worker/_activity.py, _ActivityWorker at line 53 manages a pool of slots. Activities may be async def, threaded, or multiprocess; the file defines _RunningActivity at line 777 for in-flight bookkeeping and _MultiprocessingSharedStateManager at line 1111 plus SharedHeartbeatSender at line 1096 so that heartbeat and cancellation state survive a process boundary.

Because activity heartbeats are the liveness signal, the heartbeat helper at line 362 of activity.py is intentionally tiny: it reads the current activity context and raises if called outside an activity. The interesting part is that the same call flows through an interceptor chain and a shared sender, which is why heartbeats keep working even when the activity function runs in a child process.

Data conversion and testing that skips the clock

Serialization is composed rather than fixed. DataConverter at line 66 of converter/_data_converter.py bundles a payload converter, a failure converter, and an optional codec chain. PayloadConverter at line 126 of converter/_payload_converter.py is the abstract seam, with DefaultPayloadConverter at line 417 and JSONPlainPayloadConverter at line 727 handling the common JSON case. Payload codecs apply afterward, which is how compression and encryption are layered without touching workflow code.

Testing is treated as a first-class subsystem. WorkflowEnvironment at line 39 of testing/_workflow.py offers start_local at line 79 and start_time_skipping at line 202. The time-skipping server is implemented by TimeSkipper at line 101 of a 705-line _timeskipping.py, which lets a test jump over a workflow sleep instead of waiting for it. Separately, Replayer at line 40 of worker/_replayer.py feeds recorded history back through the same workflow worker, which is the practical way to catch non-deterministic changes before deployment.

If you have built orchestration with a task queue such as Celery or a graph runtime such as LangGraph, the contrast is clarifying: those systems schedule work, while this one records decisions so the work can be reconstructed. The same reasoning explains why the SDK cares so much about the event loop implementation; throughput-sensitive services often pair asyncio code with uvloop, and Temporal’s workflow loop has similar performance sensitivities even though its durability guarantees come from replay rather than from the loop itself.

Honest Limits

The SDK is powerful, but the constraints are real and visible in the source. Workflow code must be deterministic, which rules out direct I/O, raw clocks, and unseeded randomness inside @workflow.run; the sandbox enforces part of this, and replay exposes the rest. The sandbox is an import restriction mechanism, not a hardened container, so it should not be used to isolate hostile code.

The build story is heavier than a pure-Python wheel. Because the bridge is a PyO3 extension linked against a submodule of shared Rust crates, contributors need a Rust toolchain, and the FIPS path adds another TLS provider variant to test. Python 3.11 is a hard floor in this checkout. Finally, the activation interpreter is a 4,265-line module with a large number of internal classes, so debugging deep workflow behavior often means reading implementation details rather than public documentation. For teams that need durable orchestration in Python, those costs buy a programming model that keeps business logic readable while the runtime handles recovery.

Watch PyShine on YouTube

Contents