Backend Engineer Guide: Designing Modular Hardware Plugin Daemons with Subprocess Isolation
When a POS terminal, medical telemetry station, or industrial gateway daemon loads vendor-supplied USB/Serial C-extensions (such as NFC smartcard readers, thermal printers, or biometric scanners) directly into the main Python process, a single segfault or blocking USB I/O hang in one vendor SDK crashes the entire appliance. As a backend engineer building resilient Linux client daemons, I isolate hardware drivers behind strict Python Protocol interfaces and supervised worker subprocesses.
1. Typed Driver Contracts with typing.Protocol
Every hardware capability is defined as a structural Protocol with deterministic timeout and health-status semantics, allowing local hardware simulators in CI and real USB/Serial drivers in production to share identical supervisor code:
# daemon/contracts.py
from dataclasses import dataclass
from typing import Protocol
@dataclass(frozen=True)
class DeviceHealth:
driver_name: str
connected: bool
firmware_version: str
last_error: str | None = None
class SmartCardReaderPlugin(Protocol):
def initialize(self, port_path: str) -> None: ...
def read_card_uid(self, timeout_ms: int = 2000) -> str | None: ...
def health_check(self) -> DeviceHealth: ...
def shutdown(self) -> None: ...
2. Subprocess Sandboxing for Vendor C-Extensions
Instead of calling `ctypes` or vendor `.so` libraries inside the primary event loop, the supervisor spawns a dedicated worker process per physical port and communicates over length-prefixed JSON-RPC pipes. If a vendor driver hangs on a half-unplugged USB cable or triggers a `SIGSEGV`, the supervisor kills and restarts only that plugin subprocess:
# daemon/plugin_supervisor.py
import asyncio
import json
import logging
logger = logging.getLogger(__name__)
class IsolatedHardwareWorker:
def __init__(self, plugin_module: str, port_path: str):
self.plugin_module = plugin_module
self.port_path = port_path
self.proc: asyncio.subprocess.Process | None = None
async def start(self) -> None:
self.proc = await asyncio.create_subprocess_exec(
"/usr/bin/python3", "-m", "daemon.worker_entry",
"--plugin", self.plugin_module,
"--port", self.port_path,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
)
async def call(self, method: str, params: dict, timeout_sec: float = 3.0) -> dict:
if not self.proc or self.proc.returncode is not None:
await self.start()
assert self.proc and self.proc.stdin and self.proc.stdout
req = json.dumps({"method": method, "params": params}).encode() + b"
"
self.proc.stdin.write(req)
await self.proc.stdin.drain()
try:
line = await asyncio.wait_for(self.proc.stdout.readline(), timeout=timeout_sec)
return json.loads(line.decode())
except asyncio.TimeoutError:
logger.error("Hardware plugin %s timed out on %s; restarting worker", self.plugin_module, self.port_path)
self.proc.kill()
await self.proc.wait()
raise