Skip to main content

Module runtime

Module runtime 

Source
Expand description

The centralized Tokio runtime for a running Nautilus system.

§Design Rationale

NautilusTrader uses a single global Tokio runtime because:

  • A single long-lived runtime avoids repeated startup/shutdown overhead.
  • The runtime is lazily initialized on first call to get_runtime() via OnceLock.
  • Worker thread count is configurable via the NAUTILUS_WORKER_THREADS environment variable.
  • Rust-native hosts can install a pre-built runtime via set_runtime before first use.

§Custom Runtime Injection

Callers who use set_runtime must supply a multi-threaded runtime built with tokio::runtime::Builder::new_multi_thread() and enable_all(). Adapters assume I/O, timers, spawning, and tokio::task::block_in_place() are available.

§Python Support

When the python feature is enabled, the runtime initializes the Python interpreter before starting worker threads. The PyO3 module registers an atexit handler via shutdown_runtime() to cleanly shut down when Python exits.

A runtime passed to set_runtime is already built, so this module cannot run the default Python initialization hook before its worker threads start. Hosts using custom runtimes with Python support must prepare Python before building the runtime.

§Testing Considerations

The global runtime pattern makes it harder to inject test doubles. For testing:

  • Unit tests can use #[tokio::test] which creates its own runtime.
  • Integration tests should be aware they share the global runtime state.

Functions§

get_runtime
Returns a reference to the global Nautilus Tokio runtime.
set_runtime
Sets a custom pre-built Tokio runtime as the global Nautilus runtime.
shutdown_runtime
Provides a best-effort flush for runtime tasks during shutdown.