Python support in Workers enters open beta today: applications can be written in Python and deployed with no additional build steps or external toolchains. The approach differs from earlier non-JavaScript language support because a Python implementation is integrated directly into workerd, the open-source Workers runtime. All bindings — Vectorize, Workers AI, R2, Durable Objects and others — are available on day one, and Python Workers can import a subset of popular packages, including FastAPI, Langchain and Numpy.

Delivering this required changes across the runtime, the deployment system and the contents of the Worker bundle published across the network. The sections below follow the lifecycle of a Python Worker through those systems.

Why WebAssembly support alone was not enough

Workers have supported WebAssembly since 2018, and every Worker runs as a V8 isolate, powered by the same JavaScript engine as Chrome. In principle, any language that compiles to WebAssembly or JavaScript could already be used for Workers, Python included. In practice, showing how to compile code with external toolchains falls well short of platform support: real applications depend on an ecosystem of packages that developers expect to build with.

Runtime flow of a Python Worker

With Pyodide built into workerd, a Worker is written as usual, with a wrangler.toml file that points to a .py file:

name = "hello-world-python-worker"
main = "src/entry.py"
compatibility_date = "2024-03-18"
compatibility_flags = ["python_workers"]

Running npx wrangler@latest dev triggers three steps in the runtime:

  1. It determines which version of Pyodide is required, based on the configured compatibility date.
  2. It creates an isolate for the Worker and injects Pyodide automatically.
  3. It serves the Python code using Pyodide.

No precompilation step or extra toolchain is involved; the execution environment is supplied in the same way it is for JavaScript Workers.

Pyodide inside the runtime

CPython is the reference implementation of Python — the one most developers already use — and Pyodide is a port of CPython to WebAssembly. It interprets Python without precompiling it to another format, runs in the browser (a REPL is available), provides most of the Python Standard Library, ships popular open-source packages, and can import pure Python packages directly from PyPI. It also offers a foreign function interface (FFI) to JavaScript, covered below.

The property that made Pyodide a fit for Workers is its design: the core interpreter and each native Python module are built as separate WebAssembly modules, dynamically linked at runtime. Module code footprints are therefore shared among all Workers on the same machine instead of each Worker carrying its own copy. Because the platform runs thousands of Workers per machine, that sharing is essential — it is what makes deploying every application in every location at a reasonable price feasible.

The runtime is provided for you, as it is for JavaScript Workers:

BLOG-2384 Embedded Image - PFOnDU

Pyodide is currently the exception here: most WebAssembly-targeting languages do not yet support dynamic linking, so each application bundles its own language runtime. More languages supporting dynamic linking would allow them to be brought to Workers more effectively.

Compilation target and dynamic linking

Pyodide executes Python in WebAssembly, a sandbox separated from the host runtime. Unlike native code, every operation outside pure computation — file reads, for example — must be provided by a runtime environment and imported by the WebAssembly module. LLVM offers three WebAssembly target triples for this:

  • wasm32-unknown-unknown — no C standard library or system call interface; supporting it would mean manually rewriting every system or library call against imports defined in the runtime itself.
  • wasm32-wasi — WASI standardizes the system interface and a set of imports implemented by runtimes such as wasmtime.
  • wasm32-unknown-emscripten — Emscripten defines the needed imports and also emits a companion JavaScript library implementing the imported functions.

Pyodide uses Emscripten and supplies three components: a distribution of the CPython interpreter compiled with Emscripten, an FFI between Python and JavaScript, and a set of third-party Python packages compiled to WebAssembly with Emscripten's compiler.

Only Emscripten currently supports dynamic linking among these targets, which is why it is essential for a shared Python language runtime across isolates. Emscripten implements dlopen and dlsym, which use the companion JavaScript library to modify the WebAssembly program's table and link additional WebAssembly-compiled modules at runtime. WASI does not yet support the dlopen/dlsym abstractions used by CPython.

Crossing the language boundary with FFI

Most Workers are written in JavaScript, and most runtime engineering effort goes into JavaScript Workers. A second language risks becoming a permanent second-class citizen, never reaching feature parity. Pyodide's FFI is the mechanism that avoids this: it exposes all JavaScript functionality from Python, both to Worker code directly and to packages such as FastAPI and Langchain that depend on it.

An FFI calls functions implemented in one language from another; typically a higher-level language calls into a systems language, often C, as with Python's ctypes module, and such interfaces are often hard to use because of the nature of C APIs. Pyodide's FFI instead joins Python and JavaScript, two high-level object-oriented languages with substantial design similarities. Immutable types such as strings and numbers are translated transparently when passed across; mutable objects are wrapped in an appropriate proxy.

For a JavaScript object entering Python, Pyodide inspects which JavaScript protocols the object supports and dynamically constructs a Python class implementing the matching Python protocols. An object supporting the JavaScript iteration protocol yields a proxy supporting the Python iteration protocol; a Promise or other thenable becomes an awaitable.

from js import JSON

js_array = JSON.parse("[1,2,3]")

for entry in js_array:
   print(entry)

Request handling relies on the same mechanism. The incoming JavaScript Request object is wrapped in a JsProxy accessible from Python, and the value returned by the Python Worker's handler is converted into a JavaScript Response delivered to the client:

BLOG-2384 Embedded Image - 7A3DY1

Dynamic vs. static linking for native libraries

Python exposes a C FFI, and many packages rely on it to load native libraries. Those libraries are usually written in C and must be compiled to WebAssembly before they can run on the Workers runtime. Because Pyodide is built with Emscripten, Python's C FFI is overridden: when a package tries to load a native library, the library is instead loaded from a WebAssembly module supplied by the Workers runtime. Dynamic linking is what enables that override, and it is the reason Pyodide can support a substantial set of Python packages that depend on native libraries.

The trade-off is one of timing: dynamic linking is "pay as you go," while static linking is "pay upfront." Code that is statically linked into a binary must be loaded before that binary can run, whether or not the code is ever used.

BLOG-2384 Embedded Image - PqTIoA

Dynamic linking also lets the runtime share the underlying WebAssembly modules of packages across multiple Workers on the same machine.

In Emscripten, the runtime fetches WebAssembly modules from a filesystem abstraction provided in JavaScript. For each Worker, the runtime generates a filesystem whose structure mirrors a Python distribution with the Worker's dependencies installed, but whose underlying files are shared between Workers. Python and WebAssembly files can therefore be shared among Workers importing the same dependency. Today those files are shared but still copied into each new isolate; the team believes it can go further using copy-on-write techniques to share the underlying resource across many Workers.

HTTP client libraries in the Workers runtime

Popular Python HTTP clients — httpx, urllib3, requests and others — do not work out of the box in Pyodide, and supporting them has been one of the longest-running requests for the project. These libraries work with raw sockets, which the browser security model and CORS forbid, so a different approach is needed on the Workers runtime.

Asynchronous clients

Libraries that can issue requests asynchronously, such as aiohttp and httpx, are handled through the Fetch API. The library is patched to use JavaScript's Fetch API via Pyodide's FFI. The httpx patch comes to fewer than 100 lines; simplified further, it looks like this:

from js import Headers, Request, fetch

def py_request_to_js_request(py_request):
    js_headers = Headers.new(py_request.headers)
    return Request.new(py_request.url, method=py_request.method, headers=js_headers)

def js_response_to_py_response(js_response):
  ... # omitted

async def do_request(py_request):
  js_request = py_request_to_js_request(py_request)
    js_response = await fetch(js_request)
    py_response = js_response_to_py_response(js_response)
    return py_response

Synchronous clients

Many Python APIs are synchronous, and the Fetch API cannot be used directly for them because it is asynchronous. Joe Marshall recently contributed Pyodide support to urllib3 for web browsers by:

  1. Checking whether blocking with Atomics.wait() is possible:
    1. If so, starting a fetch worker thread;
    2. Delegating the fetch to the worker thread and serializing the response into a SharedArrayBuffer;
    3. In the Python thread, using Atomics.wait to block for the response in the SharedArrayBuffer.
  2. If Atomics.wait() doesn't work, falling back to a synchronous XMLHttpRequest.

Neither approach applies to Python Workers today: Cloudflare Workers support neither worker threads nor synchronous XMLHttpRequest. Synchronous requests are therefore unsupported for now, though there is a path forward.

Stack switching in WebAssembly

WebAssembly has a stage 3 proposal for stack switching, for which v8 has an implementation. Pyodide contributors have worked on adding stack switching support to Pyodide since September 2022, and it is almost ready. With it, Pyodide exposes a function called run_sync that can block until an awaitable completes:

from pyodide.ffi import run_sync

def sync_fetch(py_request):
   js_request = py_request_to_js_request(py_request)
   js_response  = run_sync(fetch(js_request))
   return js_response_to_py_response(js_response)

FastAPI without patches

FastAPI applications follow the Asynchronous Server Gateway Interface (ASGI), which means FastAPI never reads from or writes to a socket itself. An ASGI application expects to be attached to an ASGI server — typically uvicorn — that handles raw sockets on its behalf. As a result, FastAPI runs in Cloudflare Workers with no patches or changes to FastAPI itself; only uvicorn must be replaced with an ASGI server that runs inside a Worker. The initial implementation lives in the maintained Pyodide fork, at src/pyodide/internal/asgi.py. The plan is to broaden its feature set and add test coverage before upstreaming it to Pyodide.

To try it, clone cloudflare/python-workers-examples and run npx wrangler@latest dev in the directory of the FastAPI example.

Package support and the Pyodide fork

Python Workers support a subset of Python packages provided directly by Pyodide, including numpy, httpx, FastAPI, Langchain and more. Pinning package versions to Pyodide versions ensures compatibility with the runtime and lets Pyodide patch internal implementations, as with httpx above.

Importing a package means adding it to requirements.txt without a version number; Pyodide supplies a specific version. Packages can be used in local development today, and deployment of Workers that declare dependencies in a requirements.txt file will follow in the coming weeks. A separate, maintained fork of Pyodide allows patches specific to the Workers runtime and rapid expansion of package support, with a commitment to upstreaming changes so the wider ecosystem benefits.

Python packages tend to be large, memory-hungry, and capable of doing substantial work at import time, which raises the question of how to keep cold starts short.

Cold starts and memory snapshots

Pyodide itself is 6.4 MB, and packages can be large as well. Simply uploading Pyodide inside a Worker would produce a large Worker to load into each new isolate, making cold starts slow. In a browser on a fast machine with a good connection, Pyodide takes about two seconds to initialize — roughly one second of network time and one second of CPU time — and paying that cost on every code update in every isolate across Cloudflare's network would not be acceptable.

When you run npx wrangler@latest deploy, the following happens instead:

  1. Wrangler uploads your Python code and requirements.txt to the Workers API.
  2. The code and requirements.txt go to the Workers runtime for validation.
  3. A new isolate is created for the Worker, with Pyodide and the packages named in requirements.txt injected automatically.
  4. The Worker's code is scanned for import statements, those imports are executed, and a snapshot of the Worker's WebAssembly linear memory is taken — moving the expensive package-import work to deploy time.
  5. The snapshot is deployed alongside the Worker's Python code to Cloudflare's network.
  6. The Worker's top-level scope executes, just as in a JavaScript Worker.

When a request arrives, the snapshot is loaded to bootstrap the Worker in an isolate, avoiding expensive initialization:

BLOG-2384 Embedded Image - q70QKd

This brings cold starts for a basic Python Worker below 1 second, which the team does not consider good enough.

Toward shared, pre-warmed snapshots

Each uploaded Python Worker currently gets a single snapshot covering its top-level imports, Pyodide and dependencies. That snapshot is specific to the Worker and cannot be shared, even though most of its contents match those of other Python Workers. The alternative is to create one shared snapshot ahead of time and preload it into a pool of pre-warmed isolates that already have the Pyodide runtime loaded. A Python Worker would then behave like a JavaScript Worker: the runtime supplies the interpreter and execution environment on demand, with the difference that for Python the interpreter runs in WebAssembly inside the Worker.

Snapshots are a familiar pattern: Node.js uses V8 snapshots to speed startup, and Firecracker microVMs can be snapshotted and resumed in a different process. More can be done here — not only for Python Workers but for JavaScript Workers too, caching snapshots of compiled top-level code and isolate state. Workers have been fast enough that this hasn't been necessary to date, but the team sees significant performance gains remaining. Reusing memory snapshots is the biggest lever for reducing cold start times over the rest of 2024.

Keeping old Workers running as Pyodide moves forward

A Worker deployed to Cloudflare is expected to keep running indefinitely, even if it is never touched again; Workers deployed in 2018 are still in production. That guarantee rests on Compatibility Dates and Compatibility Flags, which let developers explicitly opt in to new behavior and potentially backwards-incompatible changes without affecting existing Workers. The model mirrors the web itself: a page published with some JavaScript is expected to work forever, and Workers carries the same stability commitment.

Python complicates this, because both Pyodide and CPython are versioned. New releases ship regularly and can contain breaking changes, and Pyodide bundles a set of built-in packages, each pinned to a version. That raises the question of how a Worker should move to a newer Pyodide.

Again the answer is Compatibility Dates and Flags. A new Python release arrives every August, with a new Pyodide following six (6) months later. Each new Pyodide is added to Workers behind a Compatibility Flag that is only enabled after a specified Compatibility Date, so updates can ship continuously without breaking changes and the same commitment made for JavaScript extends to Python.

Every Python release has a five (5) year support window; once it closes, security patches stop and the version is unsafe to rely on. To limit that risk while holding to long-term support, a Python Worker still on a release outside its support window is automatically moved forward to the next oldest Python release after five years. Python is mature and stable, so most Workers should keep running unchanged, but updating a Worker's compatibility date regularly keeps it inside the support window.

Between Python releases, Python packages can also be updated and added through the same opt-in mechanism. A Compatibility Flag combines the Python version with the release date of a package set, for example python_3.17_packages_2025_03_01.

Bindings and the JavaScript object model

Pyodide's foreign function interface (FFI) to JavaScript lets Python code use JavaScript objects, methods and functions directly. As a result, every binding API to other Cloudflare resources has worked from day one. The env object handed to handlers in Python Workers is a JavaScript object behind a proxy API, with type translations handled automatically across the two languages.

Reading from and writing to a KV namespace from a Python Worker looks like this:

from js import Response

async def on_fetch(request, env):
    await env.FOO.put("bar", "baz")
    bar = await env.FOO.get("bar")
    return Response.new(bar) # returns "baz"

Web APIs work the same way: Response is imported from the js module, and any JavaScript global can be imported this way.

Towards Pythonic and ecosystem-friendly APIs

from js import Response is not Pythonic, and the team has addressed this problem before for another language. workers-rs, launched in 2021, made it possible to write Workers in Rust; for each JavaScript API in Workers, Cloudflare and open-source contributors wrote bindings exposing a more idiomatic Rust API.

Python Workers will follow that path, starting with bindings to Workers AI and Vectorize. Unlike workers-rs, which requires using and updating an external dependency, the APIs provided with Python Workers will be built into the Workers runtime directly: updating the compatibility date brings the latest, most Pythonic APIs.

The goal extends to ecosystem compatibility. Just as workers-rs was recently converted to use types from the http crate, which makes the axum crate easy to use for routing, Python Workers should interoperate with existing Python code. The standard library's raw socket API, for instance, is a dependency of many Python packages, and Workers already provides connect(), a JavaScript API for raw sockets. At least a subset of the Python socket API could plausibly be provided in Workers, letting a broader set of packages run with fewer patches. Longer term, the aim is to kick start a standardized serverless API for Python that is easy for any Python developer to use and matches JavaScript's capabilities.

What comes next

True support for a language is a large investment that goes well beyond making "hello world" work. Python was chosen deliberately — it is the second most popular programming language after JavaScript — and work continues on performance and on widening package support. Feedback is welcome in the Python Workers channel of the Cloudflare Developers Discord, or in a Github discussion about which packages should be supported next.

BLOG-2384 Embedded Image - tIemKe