> ## Documentation Index
> Fetch the complete documentation index at: https://www.orionjs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Rust libraries in Orionjs

> Write the hot paths of your app in Rust and inject them as async services, in the same process

Some work doesn't belong on the JavaScript thread: crunching thousands of Mongo documents, parsing
files, hashing, scoring. Until now the options were a separate service (another deploy, another
network hop) or a hand-written native addon (a lot of plumbing). Orionjs 4.6 adds a third one: put a
small Rust library in `./rust`, and it shows up in your app as a service.

```bash theme={null}
bun add @orion-js/native
bunx orion rust new file-analyzer
```

```rust theme={null}
// rust/file-analyzer/src/lib.rs
use orion_native::prelude::*;

#[model]
pub struct Item {
  pub _id: String,
  pub price: f64,
  pub created_at: DateTime,
}

#[export]
pub fn total(items: Vec<Item>) -> Result<f64> {
  if items.is_empty() {
    return Err(NativeError::user("emptyItems", "There are no items to sum"));
  }
  Ok(items.iter().map(|item| item.price).sum())
}
```

```ts theme={null}
import {FileAnalyzerService} from 'app/rust/file-analyzer'

@Service()
export class ReportService {
  @Inject(() => FileAnalyzerService)
  private fileAnalyzer: FileAnalyzerService

  async getTotal(items: Item[]) {
    return await this.fileAnalyzer.total(items)
  }
}
```

`orion dev` compiles the library, generates `app/rust/file-analyzer.ts` with the service and the
TypeScript types, and restarts the app when the Rust code changes.

## One library per folder

Each folder in `./rust` is its own Cargo crate with its own dependencies, and becomes one service:
`rust/file-analyzer` is `FileAnalyzerService`, `rust/pricing` is `PricingService`. Libraries can
depend on each other directly in Rust, and share models; the generated TypeScript imports them from
the other library's file.

Under the hood, all libraries are linked into a single native addon. That matters: each addon would
otherwise bring its own thread pool, and several pools would compete with the JavaScript thread for
the CPU. With one addon, there is one pool (one thread fewer than the number of cores) and one set of
limits for the whole process.

## Always async, never blocking

Every exported function returns a Promise, even if the Rust code is synchronous. The call runs on the
Rust thread pool, and the pool runs at a lower OS priority than the JavaScript thread, so a heavy
computation on every core doesn't stall your requests.

Getting data across the boundary is the other half. Arguments and results travel as MessagePack, and
large collections are split into small frames: a top-level `Vec<T>` of 100,000 orders is encoded in
pieces of about 512 KB, yielding to the event loop between them.

We measured event-loop delay while sending 100,000 orders to Rust and back, on Node and Bun:

| Scenario | Node p99 / max | Bun p99 / max |
| - | - | - |
| 100k orders, `Vec<Order>` param and return | 1.0 / 3.0 ms | 1.2 / 1.8 ms |
| 100k Mongo documents, `RawBsonList` | 1.1 / 2.8 ms | 3.0 / 6.2 ms |
| 60k small structs | 1.0 / 1.2 ms | 1.2 / 1.3 ms |

## Skip decoding Mongo documents

The fastest JavaScript work is the work you don't do. Ask the Mongo driver for raw BSON and Rust
decodes it, in parallel, off the main thread:

```rust theme={null}
#[export]
pub fn get_stats(examples: RawBsonList<Example>) -> ExampleStats { ... }
```

```ts theme={null}
const docs = await collection.rawCollection.find<Buffer>({}, {raw: true}).toArray()
const stats = await this.exampleStats.getStats(docs)
```

For 20,000 documents this cuts the main-thread work from about 55 ms to about 2 ms.

## Errors you already know

`NativeError::user` becomes a `UserError` and `NativeError::validation` a `ValidationError`, so
resolvers and routes handle them like any other. Input that doesn't match the model is a
`ValidationError` with the field path (`items.0.price`). A `panic!` rejects the promise and the app
keeps running. 64-bit integers don't fit in a JavaScript number, so using one in a model is a compile
error instead of a silent precision loss.

## Deploying

`orion build` compiles the libraries in release mode, fails if `app/rust` is out of date, and writes
`native.node` next to the bundle. The build machine needs a Rust toolchain; the server running the
bundle does not, but it must have the same OS and CPU architecture as the build machine (build in
the same Docker image you deploy). Read the [Rust libraries guide](https://www.orionjs.com/guides/rust.md) for the full reference.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.