workers-multi-lang

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Multi-Language Workers Development

多语言Workers开发

Build Cloudflare Workers using Rust, Python, or WebAssembly for performance-critical operations.
使用Rust、Python或WebAssembly构建Cloudflare Workers,用于性能敏感型操作。

Language Comparison

语言对比

FeatureJavaScript/TSRustPython
StartupFastFastest (WASM)Moderate
CPU PerfGoodExcellentGood
MemoryHigherLowerHigher
Bundle SizeSmallerMediumLarger
Type SafetyOptional (TS)StrictOptional
Best ForGeneral appsCPU-intensiveData/ML
特性JavaScript/TSRustPython
启动速度最快(WASM)中等
CPU性能良好极佳良好
内存占用较高较低较高
包体积较小中等较大
类型安全性可选(TS)严格可选
适用场景通用应用CPU密集型任务数据/机器学习

Quick Decision

快速决策

Need maximum performance? → Rust/WASM
Heavy computation (crypto, image processing)? → Rust/WASM
Data processing, ML inference? → Python
General web apps? → JavaScript/TypeScript
Need maximum performance? → Rust/WASM
Heavy computation (crypto, image processing)? → Rust/WASM
Data processing, ML inference? → Python
General web apps? → JavaScript/TypeScript

Top 10 Multi-Lang Errors

十大多语言开发常见错误

ErrorLanguageCauseSolution
WebAssembly.instantiate() failed
RustInvalid WASMCheck wasm-pack build output
Module parse failed: Unexpected token
RustESM/CJS mismatchUse
--target bundler
Cannot find module
PythonMissing depAdd to pyproject.toml
Out of memory
AllLarge WASMEnable streaming instantiation
Exceeded CPU time limit
AllLong computationChunk processing
wasm-bindgen version mismatch
RustDep conflictAlign versions in Cargo.toml
RuntimeError: unreachable
RustPanic in WASMAdd proper error handling
TypeError: not a function
RustMissing exportAdd
#[wasm_bindgen]
attribute
Python worker startup timeout
PythonSlow initMinimize imports
SharedArrayBuffer not supported
AllSecurityAdd COOP/COEP headers
错误语言原因解决方案
WebAssembly.instantiate() failed
Rust无效WASM模块检查wasm-pack构建输出
Module parse failed: Unexpected token
RustESM/CJS不兼容使用
--target bundler
Cannot find module
Python依赖缺失添加至pyproject.toml
Out of memory
所有语言WASM模块过大启用流式实例化
Exceeded CPU time limit
所有语言计算耗时过长拆分任务处理
wasm-bindgen version mismatch
Rust依赖版本冲突统一Cargo.toml中的版本
RuntimeError: unreachable
RustWASM中发生panic添加完善的错误处理
TypeError: not a function
Rust缺少导出添加
#[wasm_bindgen]
属性
Python worker startup timeout
Python初始化缓慢减少导入依赖
SharedArrayBuffer not supported
所有语言安全限制添加COOP/COEP头

Rust Quick Start

Rust快速入门

bash
undefined
bash
undefined

Install tools

Install tools

cargo install wasm-pack
cargo install wasm-pack

Create project

Create project

cargo new --lib my-worker cd my-worker
cargo new --lib my-worker cd my-worker

Add to Cargo.toml

Add to Cargo.toml

cat >> Cargo.toml << 'EOF' [lib] crate-type = ["cdylib"]
[dependencies] wasm-bindgen = "0.2" worker = "0.3" console_error_panic_hook = "0.1"
[profile.release] opt-level = "s" lto = true EOF

```rust
// src/lib.rs
use worker::*;

#[event(fetch)]
async fn fetch(req: Request, env: Env, _ctx: Context) -> Result<Response> {
    console_error_panic_hook::set_once();

    Router::new()
        .get("/", |_, _| Response::ok("Hello from Rust!"))
        .get("/compute", |_, _| {
            // CPU-intensive computation
            let result = heavy_computation();
            Response::ok(format!("Result: {}", result))
        })
        .run(req, env)
        .await
}

fn heavy_computation() -> u64 {
    (1..1_000_000).filter(|n| is_prime(*n)).count() as u64
}

fn is_prime(n: u64) -> bool {
    if n < 2 { return false; }
    (2..=(n as f64).sqrt() as u64).all(|i| n % i != 0)
}
cat >> Cargo.toml << 'EOF' [lib] crate-type = ["cdylib"]
[dependencies] wasm-bindgen = "0.2" worker = "0.3" console_error_panic_hook = "0.1"
[profile.release] opt-level = "s" lto = true EOF

```rust
// src/lib.rs
use worker::*;

#[event(fetch)]
async fn fetch(req: Request, env: Env, _ctx: Context) -> Result<Response> {
    console_error_panic_hook::set_once();

    Router::new()
        .get("/", |_, _| Response::ok("Hello from Rust!"))
        .get("/compute", |_, _| {
            // CPU-intensive computation
            let result = heavy_computation();
            Response::ok(format!("Result: {}", result))
        })
        .run(req, env)
        .await
}

fn heavy_computation() -> u64 {
    (1..1_000_000).filter(|n| is_prime(*n)).count() as u64
}

fn is_prime(n: u64) -> bool {
    if n < 2 { return false; }
    (2..=(n as f64).sqrt() as u64).all(|i| n % i != 0)
}

Python Quick Start (Workers for Platforms)

Python快速入门(Workers for Platforms)

toml
undefined
toml
undefined

pyproject.toml

pyproject.toml

[project] name = "my-worker" version = "0.1.0" requires-python = ">=3.12" dependencies = []
[build-system] requires = ["hatchling"] build-backend = "hatchling.build"

```python
[project] name = "my-worker" version = "0.1.0" requires-python = ">=3.12" dependencies = []
[build-system] requires = ["hatchling"] build-backend = "hatchling.build"

```python

src/entry.py

src/entry.py

from js import Response, Headers
async def on_fetch(request, env): url = request.url
if "/compute" in url:
    result = heavy_computation()
    return Response.new(f"Result: {result}")

return Response.new("Hello from Python!")
def heavy_computation(): """CPU-intensive computation""" return sum(1 for n in range(2, 100000) if is_prime(n))
def is_prime(n): if n < 2: return False return all(n % i != 0 for i in range(2, int(n**0.5) + 1))
undefined
from js import Response, Headers
async def on_fetch(request, env): url = request.url
if "/compute" in url:
    result = heavy_computation()
    return Response.new(f"Result: {result}")

return Response.new("Hello from Python!")
def heavy_computation(): """CPU-intensive computation""" return sum(1 for n in range(2, 100000) if is_prime(n))
def is_prime(n): if n < 2: return False return all(n % i != 0 for i in range(2, int(n**0.5) + 1))
undefined

WASM Module Integration

WASM模块集成

typescript
// Load and use WASM module in TypeScript Worker
import wasmModule from './pkg/my_lib_bg.wasm';
import { init, process_data } from './pkg/my_lib';

let wasmInstance: WebAssembly.Instance;

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // Initialize WASM once
    if (!wasmInstance) {
      wasmInstance = await WebAssembly.instantiate(wasmModule);
      init();
    }

    // Use WASM function
    const result = process_data(inputData);

    return Response.json({ result });
  },
};
typescript
// Load and use WASM module in TypeScript Worker
import wasmModule from './pkg/my_lib_bg.wasm';
import { init, process_data } from './pkg/my_lib';

let wasmInstance: WebAssembly.Instance;

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // Initialize WASM once
    if (!wasmInstance) {
      wasmInstance = await WebAssembly.instantiate(wasmModule);
      init();
    }

    // Use WASM function
    const result = process_data(inputData);

    return Response.json({ result });
  },
};

When to Load References

参考文档加载时机

ReferenceLoad When
references/rust-workers.md
Building Workers with Rust/WASM
references/python-workers.md
Using Python on Workers for Platforms
references/wasm-integration.md
Integrating WASM modules in any Worker
参考文档加载场景
references/rust-workers.md
使用Rust/WASM构建Workers时
references/python-workers.md
在Workers for Platforms上使用Python时
references/wasm-integration.md
在任意Worker中集成WASM模块时

Performance Tips

性能优化技巧

  1. WASM Initialization: Cache instance, use streaming
  2. Memory: Use typed arrays for data transfer
  3. Bundle Size: Enable LTO, strip debug info
  4. Cold Starts: Keep WASM modules small
  5. Data Transfer: Minimize JS/WASM boundary crossings
  1. WASM初始化:缓存实例,使用流式加载
  2. 内存管理:使用类型化数组进行数据传输
  3. 包体积优化:启用LTO,移除调试信息
  4. 冷启动优化:保持WASM模块体积小巧
  5. 数据传输:减少JS与WASM之间的边界交互

See Also

相关链接

  • workers-performance
    - General optimization techniques
  • workers-testing
    - Testing multi-language Workers
  • cloudflare-worker-base
    - Basic Workers setup
  • workers-performance
    - 通用优化技巧
  • workers-testing
    - 多语言Workers测试
  • cloudflare-worker-base
    - Workers基础配置