Short answer
Use Python for the workflow — queues, browsers, APIs, CRMs, and operator tools — and Rust for the tight loop that must be fast, memory-safe, and easy to run as a small binary: parsing, checksums, audio or byte-level work, and CPU-heavy validation. Keep a clear boundary: Python calls a Rust CLI or shared library with structured input and structured output (JSON or a simple binary protocol). Do not rewrite the whole service in Rust, and do not hide a slow Python loop behind a Rust wrapper that still does the heavy work in Python.
Why split the work at all?
A lot of operations automation starts in Python because the ecosystem is strong: Playwright and Selenium, HTTP clients, pandas or openpyxl for lead files, FastAPI for a control panel, and PyQt or a web UI for staff. That is the right default for glue.
The same process often grows a hot path: normalizing tens of thousands of phone numbers, walking every byte of a recording, hashing files, or validating records before they hit a CRM. Python can do all of that, but when that loop is tight and well-defined, Rust is a good fit: one compiled binary, no GIL in the inner loop, and a type system that catches a class of bugs before the job runs unattended.
The useful design is a pipeline, not a rewrite.
A practical boundary
Give each language a job it is good at:
| Layer | Prefer | Examples |
|---|---|---|
| Operator UI, job queue, CRM and HTTP APIs | Python | FastAPI, Playwright, spreadsheet import, webhook handlers |
| Tight, deterministic transforms | Rust | E.164-style digit normalization, file hashing, CSV field cleaning, codec or DSP work |
| Glue between them | A stable contract | argv + stdin/stdout JSON, or a cffi / PyO3 module with a small API |
Rules that keep the split honest:
- The Rust side should not open the CRM, the browser, or the mailbox. It should not know about API tokens.
- The Python side should not reimplement the inner loop “just this once.” If the contract exists, call it.
- Input and output must be documented and tested from both sides (a fixture file is enough).
A minimal contract: Python calls a Rust CLI
A command-line tool is the simplest boundary. It is easy to test, easy to log, and easy to replace later with a library if you need to.
Rust (concept sketch):
use serde::{Deserialize, Serialize}; use std::io::{self, Read}; #[derive(Deserialize)] struct InRec { phone: Option<String>, email: Option<String> } #[derive(Serialize)] struct OutRec { phone_e164: Option<String>, email: Option<String>, ok: bool, error: Option<String>, } fn normalize_us_phone(raw: &str) -> Option<String> { let digits: String = raw.chars().filter(|c| c.is_ascii_digit()).collect(); let digits = if digits.len() == 10 { format!("1{digits}") } else { digits }; if digits.len() == 11 && digits.starts_with('1') { Some(format!("+{digits}")) } else { None } } fn main() -> Result<(), Box<dyn std::error::Error>> { let mut buf = String::new(); io::stdin().read_to_string(&mut buf)?; let rows: Vec<InRec> = serde_json::from_str(&buf)?; let out: Vec<OutRec> = rows .into_iter() .map(|r| { let email = r .email .map(|e| e.trim().to_lowercase()) .filter(|e| e.contains('@')); let phone_e164 = r.phone.as_deref().and_then(normalize_us_phone); let ok = email.is_some() || phone_e164.is_some(); OutRec { phone_e164, email, ok, error: if ok { None } else { Some("no valid email or phone".into()) }, } }) .collect(); serde_json::to_writer(io::stdout(), &out)?; Ok(()) } Python:
import json, subprocess, sys from pathlib import Path BIN = Path(__file__).resolve().parent / "bin" / "normalize" def normalize_batch(records: list[dict]) -> list[dict]: proc = subprocess.run( [str(BIN)], input=json.dumps(records).encode(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30, check=False, ) if proc.returncode != 0: raise RuntimeError(proc.stderr.decode()[:500]) return json.loads(proc.stdout) if __name__ == "__main__": rows = [{"phone": "(312) 555-0199", "email": "Ops@Example.COM"}] print(json.dumps(normalize_batch(rows), indent=2)) Ship a .env.example, never a secret, and keep the Rust binary path configurable. In production, log the Rust exit code and a hash of the input batch, not the raw personal data, unless your retention policy allows it.
When a library is better than a CLI
A CLI is enough for batch jobs. If Python must call the Rust code thousands of times per second inside one process, a PyO3 extension or a small FFI module avoids process startup. Keep the exported API as small as the CLI contract: one function in, one struct out. Do not leak Rust types into the rest of the Python app.
How to test the seam
- Fixture JSON in, fixture JSON out. Run it from Rust unit tests and from a Python test that shells out to the same binary.
- Fail closed: malformed JSON, empty stdin, or a non-zero exit must stop the job, not skip records silently.
- Time the batch on a realistic file size on your machine if you need to decide whether the split is worth it. Do not publish invented speedups.
FAQ
Should every automation project use Rust and Python together?
No. If the work is mostly waiting on a browser, an HTTP API, or a human, Python alone is simpler and easier to hire for. Add Rust when you have a tight, well-specified loop that you will run often.
Is this the same as rewriting the service in Rust?
No. The service stays a Python application. Rust is a dependency for one job, the way you might already call ffmpeg or a Go verifier.
How do I deploy both parts?
Build the Rust binary in CI for the target OS (for example x86_64-pc-windows-msvc or x86_64-unknown-linux-gnu), attach it to the release, and have Python look it up from a known bin/ path. Pin the binary version next to the Python package version.
What about the GIL?
A separate Rust process does not hold the Python GIL. A PyO3 module can release the GIL around the tight loop; do that if you stay in-process and you actually run threads.
Can I put API keys in the Rust binary?
No. Keep secrets in the environment or a secret store on the host. The Rust tool should only see the data it needs to transform.
What this is not
This article does not claim production benchmarks, client results, or a required rewrite of any named product. It is an architecture pattern for Rust & Python automation services.
Written by Muhammad Afzal, a Rust & Python automation engineer at INDUS Web Agency in Islamabad.