{"slug": "bundling-a-python-backend-inside-a-single-rust-binary-and-the-windows-tz-gotcha", "title": "Bundling a Python backend inside a single Rust binary (and the Windows tz database gotcha)", "summary": "A developer behind JoeBro Desktop, a GPL-3.0 local-first workspace for AI agents, packaged a roughly 24,000-line stdlib-only Python backend into a single Rust executable by zipping it into a ~700 KB zipapp, embedding it with include_bytes!, and extracting it to disk under an FNV-1a content hash so updates replace stale copies. The approach does not embed a Python interpreter, so the app requires Python 3.10+ and falls back to a winget install prompt or a server-connect mode on Windows, where Microsoft Store execution-alias stubs and timezone database handling caused the main problems. The writeup also covers bearer-token passing via environment variables, port fallback to OS-assigned ports, parent-PID watchdog threads to prevent orphaned backends, and graceful shutdown via an API call before killing the process.", "body_md": "I have a Mac app whose backend is about 24,000 lines of plain-stdlib Python. When I wrote the Windows and Linux version in Rust, I didn't want to rewrite that backend or maintain two copies, and I didn't want users to install anything besides the app. This is how I ended up shipping the Python backend inside a single Rust executable, and what went wrong on Windows.\n\nThe app is [JoeBro Desktop](https://github.com/joexk1/JoeBro-Desktop), a local-first workspace for AI agents (GPL-3.0, I made it). The relevant part here is only the packaging.\n\nThe Rust app is the UI. The backend is a Python process listening on `127.0.0.1`. The UI starts it on launch and stops it on quit. There is nothing to `pip install`, because the backend only uses the standard library.\n\nThe trick that keeps this to one file is a **zipapp**. Python can run a zip file that has a `__main__.py` in it (`python thing.pyz`). So:\n\n`.py` files plus a small shim `__main__.py` into `joebro_backend.pyz` (about 700 KB).`include_bytes!`.` python joebro_backend.pyz`.\n\n```\nstatic PYZ: &[u8] = include_bytes!(\"../backend/joebro_backend.pyz\");\n```\n\nYou can't run Python from memory, so the file has to land on disk. I name it by a hash of the contents so an app update writes a new file and deletes the old ones:\n\n``` js\nlet mut h: u64 = 0xcbf29ce484222325; // FNV-1a over the archive\nfor b in PYZ {\n    h = (h ^ *b as u64).wrapping_mul(0x100000001b3);\n}\nlet p = dir.join(format!(\"joebro_backend-{h:016x}.pyz\"));\n```\n\nFNV-1a is not a security measure here, just a cheap \"is this the same archive\" check. The build script uses fixed timestamps for every zip entry, so the archive is byte-identical for the same sources and the hash only changes when the code does.\n\nThis does not embed Python. The machine needs Python 3.10 or newer. On Linux that is nearly always already there. On Windows it usually isn't, so the app shows a message with `winget install Python.Python.3.12` and a Check again button, and it offers a \"connect to a server\" mode that needs no Python at all.\n\nI chose that over bundling an interpreter because it keeps the download small and keeps the backend identical to the Mac one. If you're building something similar for non-technical users, think hard about whether that trade is right for you.\n\nFinding Python turned out to be fiddly enough to deserve its own function:\n\n`python3`, then `python`, then on Windows `py -3`.`-c \"import sys; print(...)\"` and parse the version, instead of trusting the name.`WindowsApps`. Those are the Microsoft Store \"app execution alias\" stubs: running one opens the Store instead of Python.\nNone of these are clever, but each one cost me an evening.\n\n**The token goes in the environment, not on the command line.** The backend demands a random bearer token on every request. The app generates 32 random bytes on first start, saves them in a file with mode 0600, and passes them to the child as `JOEBRO_TOKEN`. Command lines are visible to other users in a process list on many systems; environment variables are much harder to read.\n\n**Port selection.** Prefer 8765, and if something is already there, bind port 0 and let the OS choose. The app then polls `/api/health` for up to 25 seconds before calling the backend started, and it keeps the tail of the log to show in the error if it doesn't.\n\n**Orphans.** If the Rust app crashes, you don't want a Python server left behind. The shim takes `--parent-pid` and a daemon thread checks every two seconds that the parent still exists, then calls `os._exit(0)`. Checking whether a PID is alive is different on each platform. On Unix, `os.kill(pid, 0)` works. On Windows you open the process and compare the exit code to 259 (`STILL_ACTIVE`):\n\n```\nh = k.OpenProcess(0x1000, False, pid)  # PROCESS_QUERY_LIMITED_INFORMATION\n...\nreturn code.value == 259  # STILL_ACTIVE\n```\n\n**Clean shutdown.** On quit the app calls `POST /api/shutdown` so SQLite closes properly, waits up to three seconds, and only then kills the process. The shim adds that endpoint by wrapping the backend's request handler, so the shared backend code doesn't need to know about desktop hosting.\n\n**No console window flash.** On Windows a GUI app that spawns Python gets a console window unless you pass `CREATE_NO_WINDOW` (`0x08000000`) in the creation flags.\n\nThe backend was written on macOS and uses `fcntl.flock` and `os.fchmod`. Neither exists on Windows Python. Rather than edit the shared backend, the shim installs stand-ins before importing it:\n\n```\nm = types.ModuleType(\"fcntl\")\nm.LOCK_EX, m.LOCK_SH, m.LOCK_UN, m.LOCK_NB = 2, 1, 8, 4\nm.flock = lambda *a, **k: None\nsys.modules[\"fcntl\"] = m\n```\n\nThis is a no-op lock. It's fine here because only one process (this app's own backend) writes to that data directory, but it's worth saying out loud: it's a shim, not a port.\n\nThis is the one that actually got through to CI.\n\nI have an end-to-end test that starts the real bundled backend, points it at fake servers, and calls its API. On Linux it passed. On the Windows runner it failed with:\n\n```\nevents failed: HTTP 502: CalDAV sync failed: 'No time zone found with key UTC'\n```\n\nPython's `zoneinfo` reads the IANA time zone database from the operating system. Linux and macOS have one in `/usr/share/zoneinfo`. Windows does not, and the Windows builds of Python don't bundle one either. The PyPI package `tzdata` exists for exactly this case: `zoneinfo` falls back to it when it is importable. A backend that calls `ZoneInfo(\"UTC\")` works everywhere except a stock Windows install.\n\nSince the whole point was \"nothing to install\", I vendored the `tzdata` wheel (about 350 KB) into the repo and had the build script copy its `tzdata/` package into the zipapp:\n\n```\nfor whl in sorted((here / \"vendor\").glob(\"tzdata-*.whl\")):\n    with zipfile.ZipFile(whl) as w:\n        for n in sorted(w.namelist()):\n            if n.startswith(\"tzdata/\") and not n.endswith(\"/\"):\n                z.writestr(...)\n```\n\nA wheel is a zip file, so this is just copying entries from one zip into another. Python's import system reads from the `.pyz`, so `import tzdata` works and `zoneinfo` finds the data. The lesson I took from it: the tests I ran on my own Linux machine said nothing about what a clean Windows machine has. Running the real end-to-end test on a Windows runner caught it before a user did.\n\nI'd do again: one shared backend, a shim for host-specific behaviour, a hash-named file in the data directory, and testing the actual packaged thing on every OS in CI.\n\nWhat I'd reconsider: needing a system Python at all. If your users are developers, as mine mostly are, it's reasonable. If they aren't, an embedded interpreter or a rewrite of the hot path in Rust might be worth the size.\n\nThe code is open if you want to read it: the process management is `src/backend.rs`, the packaging is `backend/build_pyz.py`, and the shim is `backend/shim/__main__.py` in [JoeBro-Desktop](https://github.com/joexk1/JoeBro-Desktop). If you've solved \"ship a Python backend with a native app\" differently, I'd like to hear how.", "url": "https://wpnews.pro/news/bundling-a-python-backend-inside-a-single-rust-binary-and-the-windows-tz-gotcha", "canonical_source": "https://dev.to/joexk1/bundling-a-python-backend-inside-a-single-rust-binary-and-the-windows-tz-database-gotcha-2p5", "published_at": "2026-11-24 19:31:41+00:00", "updated_at": "2026-11-24 19:45:58.093340+00:00", "lang": "en", "topics": ["ai-agents", "developer-tools"], "entities": ["JoeBro Desktop", "Rust", "Python", "Windows", "Microsoft Store", "SQLite", "winget"], "also_reported_by": [], "takeaway": "Embedding a stdlib-only Python backend as a ~700 KB zipapp via include_bytes! and extracting it under an FNV-1a content hash keeps a Rust app to one file, but you still need Python 3.10+ on the machine and must skip WindowsApps execution-alias stubs when locating it.", "recommendation": {"advice": "When shipping a sidecar backend in a desktop app, pass secrets via environment variables, fall back to port 0 if the preferred port is taken, and have the child poll a parent PID so it exits instead of orphaning.", "playbook": "production-ops", "playbook_url": "https://wpnews.pro/playbooks/production-ops"}, "alternates": {"html": "https://wpnews.pro/news/bundling-a-python-backend-inside-a-single-rust-binary-and-the-windows-tz-gotcha", "markdown": "https://wpnews.pro/news/bundling-a-python-backend-inside-a-single-rust-binary-and-the-windows-tz-gotcha.md", "text": "https://wpnews.pro/news/bundling-a-python-backend-inside-a-single-rust-binary-and-the-windows-tz-gotcha.txt", "jsonld": "https://wpnews.pro/news/bundling-a-python-backend-inside-a-single-rust-binary-and-the-windows-tz-gotcha.jsonld"}}