{"id":13579139,"url":"https://github.com/slawlor/ractor","last_synced_at":"2026-03-06T21:09:45.091Z","repository":{"id":65185185,"uuid":"584833604","full_name":"slawlor/ractor","owner":"slawlor","description":"Rust actor framework","archived":false,"fork":false,"pushed_at":"2025-05-07T14:24:54.000Z","size":3218,"stargazers_count":1715,"open_issues_count":10,"forks_count":94,"subscribers_count":32,"default_branch":"main","last_synced_at":"2025-05-10T08:08:12.857Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/slawlor.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-01-03T16:24:32.000Z","updated_at":"2025-05-09T17:50:48.000Z","dependencies_parsed_at":"2023-01-07T10:11:20.352Z","dependency_job_id":"6908a7fd-16c9-4474-94ab-20a932f86c12","html_url":"https://github.com/slawlor/ractor","commit_stats":{"total_commits":57,"total_committers":6,"mean_commits":9.5,"dds":0.5263157894736843,"last_synced_commit":"6e36b8b50a4e80d9b4b61cbd674f66100fc32b07"},"previous_names":[],"tags_count":65,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/slawlor%2Fractor","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/slawlor%2Fractor/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/slawlor%2Fractor/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/slawlor%2Fractor/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/slawlor","download_url":"https://codeload.github.com/slawlor/ractor/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253384868,"owners_count":21899937,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T15:01:36.884Z","updated_at":"2026-03-06T21:09:45.081Z","avatar_url":"https://github.com/slawlor.png","language":"Rust","readme":"# ractor\n\n\u003cp align=\"center\"\u003e\n    \u003cimg src=\"https://raw.githubusercontent.com/slawlor/ractor/main/docs/ractor_logo.svg\" width=\"50%\" /\u003e\n\u003c/p\u003e\n\n*Pronounced rak-ter*\n\nA pure-Rust actor framework. Inspired from [Erlang's `gen_server`](https://www.erlang.org/doc/man/gen_server.html), with the speed + performance of Rust!\n\n* [\u003cimg alt=\"github\" src=\"https://img.shields.io/badge/github-slawlor/ractor-8da0cb?style=for-the-badge\u0026labelColor=555555\u0026logo=github\" height=\"20\"\u003e](https://github.com/slawlor/ractor)\n* [\u003cimg alt=\"crates.io\" src=\"https://img.shields.io/crates/v/ractor.svg?style=for-the-badge\u0026color=fc8d62\u0026logo=rust\" height=\"20\"\u003e](https://crates.io/crates/ractor)\n* [\u003cimg alt=\"docs.rs\" src=\"https://img.shields.io/badge/docs.rs-ractor-66c2a5?style=for-the-badge\u0026labelColor=555555\u0026logo=docs.rs\" height=\"20\"\u003e](https://docs.rs/ractor)\n* [\u003cimg alt=\"docs.rs\" src=\"https://img.shields.io/badge/docs.rs-ractor_cluster-66c2a5?style=for-the-badge\u0026labelColor=555555\u0026logo=docs.rs\" height=\"20\"\u003e](https://docs.rs/ractor_cluster)\n* [![CI/main](https://github.com/slawlor/ractor/actions/workflows/ci.yaml/badge.svg?branch=main)](https://github.com/slawlor/ractor/actions/workflows/ci.yaml)\n* [![codecov](https://codecov.io/gh/slawlor/ractor/branch/main/graph/badge.svg?token=61AGYYPWBA)](https://codecov.io/gh/slawlor/ractor)\n* `ractor`: ![ractor Downloads](https://img.shields.io/crates/d/ractor.svg)\n* `ractor_cluster`: ![ractor_cluster Downloads](https://img.shields.io/crates/d/ractor_cluster.svg)\n\n## Runtime semantics\n\nSee the detailed runtime semantics and guarantees in docs/runtime-semantics.md for priority channels, supervision semantics, RPC/cluster behaviors, and recommended best practices: [Semantics](docs/runtime-semantics.md)\n\n## Updates\n\n* **Website**: Ractor has a companion website for more detailed getting-started guides along with some best practices and is updated regularly. Api docs will still be available at [docs.rs](https://docs.rs/ractor) however this will be a supplimentary site for `ractor`. Try it out! \u003chttps://slawlor.github.io/ractor/\u003e\n* **RustConf'24** Ractor was a key part of a presentation at [RustConf'24](https://rustconf.com/schedule/#wednesday). It's used as the basis for Meta's Rust [thrift](https://github.com/facebook/fbthrift) overload protection scheme. The presentation's slides are [available here](https://slawlor.github.io/ractor/assets/rustconf2024_presentation.pdf).\n\n## About\n\n`ractor` tries to solve the problem of building and maintaining an Erlang-like actor framework in Rust. It gives\na set of generic primitives and helps automate the supervision tree and management of our actors along with the traditional actor message processing logic. It was originally designed to use the `tokio` runtime, however does now support the `async-std` runtime.\n\n`ractor` is a modern actor framework written in 100% Rust.\n\nAdditionally `ractor` has a companion library, `ractor_cluster` which is needed for `ractor` to be deployed in a distributed (cluster-like) scenario. `ractor_cluster` shouldn't be considered production ready, but it is relatively stable and we'd love your feedback!\n\n### Why ractor?\n\nThere are other actor frameworks written in Rust ([Actix](https://github.com/actix/actix), [riker](https://github.com/riker-rs/riker), or [just actors in Tokio](https://ryhl.io/blog/actors-with-tokio/)) plus a bunch of others like this list compiled on [this Reddit post](https://www.reddit.com/r/rust/comments/n2cmvd/there_are_a_lot_of_actor_framework_projects_on/).\n\nRactor tries to be different by modelling more on a pure Erlang `gen_server`. This means that each actor can also simply be a supervisor to other actors with no additional cost (simply link them together!). Additionally we're aiming to maintain close logic with Erlang's patterns, as they work quite well and are well utilized in the industry.\n\nAdditionally we wrote `ractor` without building on some kind of \"Runtime\" or \"System\" which needs to be spawned. Actors can be run independently, in conjunction with other basic `tokio` runtimes with little additional overhead.\n\nWe currently have full support for:\n\n1. Single-threaded message processing\n2. Actor supervision tree\n3. Remote procedure calls to actors in the `rpc` module\n4. Timers in the `time` module\n5. Named actor registry (`registry` module) from [Erlang's `Registered processes`](https://www.erlang.org/doc/reference_manual/processes.html)\n6. Process groups (`ractor::pg` module) from [Erlang's `pg` module](https://www.erlang.org/doc/man/pg.html)\n\nOn our roadmap is to add more of the Erlang functionality including potentially a distributed actor cluster.\n\n### Performance\n\nActors in `ractor` are generally quite lightweight and there are benchmarks which you are welcome to run on your own host system with:\n\n```bash\ncargo bench -p ractor\n```\n\nFurther performance improvements are being tracked in [#262](https://github.com/slawlor/ractor/issues/262)\n\n## Installation\n\nInstall `ractor` by adding the following to your Cargo.toml dependencies.\n\n```toml\n[dependencies]\nractor = \"0.15\"\n```\n\nThe minimum supported Rust version (MSRV) of `ractor` is `1.64`. However to utilize the native `async fn` support in traits and not rely on the `async-trait` crate's desugaring functionliaty, you need to be on Rust version `\u003e= 1.75`. The stabilization of `async fn` in traits [was recently added](https://blog.rust-lang.org/2023/12/21/async-fn-rpit-in-traits.html).\n\n## Features\n\n`ractor` exposes the following features:\n\n1. `cluster`, which exposes various functionality required for `ractor_cluster` to set up and manage a cluster of actors over a network link. This is work-in-progress and is being tracked in [#16](https://github.com/slawlor/ractor/issues/16).\n2. `async-std`, which enables usage of `async-std`'s asynchronous runtime instead of the `tokio` runtime. **However** `tokio` with the `sync` feature remains a dependency because we utilize the messaging synchronization primatives from `tokio` regardless of runtime as they are not specific to the `tokio` runtime. This work is tracked in [#173](https://github.com/slawlor/ractor/pull/173). You can remove default features to \"minimize\" the tokio dependencies to just the synchronization primatives.\n3. `monitors`, Adds support for an erlang-style monitoring api which is an alternative to direct linkage. Akin to [Process Monitors](https://www.erlang.org/doc/system/ref_man_processes.html#monitors)\n4. `message_span_propogation`, Propagates the span through the message between actors to keep tracing context.\n\n## Working with Actors\n\nActors in `ractor` are very lightweight and can be treated as thread-safe. Each actor will only call one of its handler functions at a time, and they will\nnever be executed in parallel. Following the actor model leads to microservices with well-defined state and processing logic.\n\nAn example `ping-pong` actor might be the following\n\n```rust\nuse ractor::{async_trait, cast, Actor, ActorProcessingErr, ActorRef};\n\n/// [PingPong] is a basic actor that will print\n/// ping..pong.. repeatedly until some exit\n/// condition is met (a counter hits 10). Then\n/// it will exit\npub struct PingPong;\n\n/// This is the types of message [PingPong] supports\n#[derive(Debug, Clone)]\npub enum Message {\n    Ping,\n    Pong,\n}\n\nimpl Message {\n    // retrieve the next message in the sequence\n    fn next(\u0026self) -\u003e Self {\n        match self {\n            Self::Ping =\u003e Self::Pong,\n            Self::Pong =\u003e Self::Ping,\n        }\n    }\n    // print out this message\n    fn print(\u0026self) {\n        match self {\n            Self::Ping =\u003e print!(\"ping..\"),\n            Self::Pong =\u003e print!(\"pong..\"),\n        }\n    }\n}\n\n#[async_trait]\n// the implementation of our actor's \"logic\"\nimpl Actor for PingPong {\n    // An actor has a message type\n    type Msg = Message;\n    // and (optionally) internal state\n    type State = u8;\n    // Startup initialization args\n    type Arguments = ();\n\n    // Initially we need to create our state, and potentially\n    // start some internal processing (by posting a message for\n    // example)\n    async fn pre_start(\n        \u0026self,\n        myself: ActorRef\u003cSelf::Msg\u003e,\n        _: (),\n    ) -\u003e Result\u003cSelf::State, ActorProcessingErr\u003e {\n        // startup the event processing\n        cast!(myself, Message::Ping)?;\n        // create the initial state\n        Ok(0u8)\n    }\n\n    // This is our main message handler\n    async fn handle(\n        \u0026self,\n        myself: ActorRef\u003cSelf::Msg\u003e,\n        message: Self::Msg,\n        state: \u0026mut Self::State,\n    ) -\u003e Result\u003c(), ActorProcessingErr\u003e {\n        if *state \u003c 10u8 {\n            message.print();\n            cast!(myself, message.next())?;\n            *state += 1;\n        } else {\n            println!();\n            myself.stop(None);\n            // don't send another message, rather stop the agent after 10 iterations\n        }\n        Ok(())\n    }\n}\n\n#[tokio::main]\nasync fn main() {\n    let (_actor, handle) = Actor::spawn(None, PingPong, ())\n        .await\n        .expect(\"Failed to start ping-pong actor\");\n    handle\n        .await\n        .expect(\"Ping-pong actor failed to exit properly\");\n}\n```\n\nwhich will output\n\n```bash\n$ cargo run\nping..pong..ping..pong..ping..pong..ping..pong..ping..pong..\n$\n```\n\n## Messaging actors\n\nThe means of communication between actors is that they pass messages to each other. A developer can define any message type which is `Send + 'static` and it\nwill be supported by `ractor`. There are 4 concurrent message types, which are listened to in priority. They are\n\n1. Signals: Signals are the highest-priority of all and will interrupt the actor wherever processing currently is (this includes terminating async work). There\nis only 1 signal today, which is `Signal::Kill`, and it immediately terminates all work. This includes message processing or supervision event processing.\n2. Stop: There is also the pre-defined stop signal. You can give a \"stop reason\" if you want, but it's optional. Stop is a graceful exit, meaning currently executing async work will complete, and on the next message processing iteration Stop will take priority over future supervision events or regular messages. It will **not** terminate currently executing work, regardless of the provided reason.\n3. SupervisionEvent: Supervision events are messages from child actors to their supervisors in the event of their startup, death, and/or unhandled panic. Supervision events are how an actor's supervisor(parent) or peer monitors are notified of events of their children/peers and can handle lifetime events for them. If you set `panic = 'abort'` in your `Cargo.toml`, panics **will** start cause program termination and not be caught in the supervision flow.\n4. Messages: Regular, user-defined, messages are the last channel of communication to actors. They are the lowest priority of the 4 message types and denote general actor work. The first\n3 messages types (signals, stop, supervision) are generally quiet unless it's a lifecycle event for the actor, but this channel is the \"work\" channel doing what your actor wants to do!\n\n## Ractor in distributed clusters\n\nRactor actors can also be used to build a distributed pool of actors, similar to [Erlang's EPMD](https://www.erlang.org/doc/man/epmd.html) which manages inter-node connections + node naming. In our implementation, we have [`ractor_cluster`](https://crates.io/crates/ractor_cluster) in order to facilitate distributed `ractor` actors.\n\n`ractor_cluster` has a single main type in it, namely the `NodeServer` which represents a host of a `node()` process. It additionally has some macros and a procedural macros to facilitate developer efficiency when building distributed actors. The `NodeServer` is responsible for\n\n1. Managing all incoming and outgoing `NodeSession` actors which represent a remote node connected to this host.\n2. Managing the `TcpListener` which hosts the server socket to accept incoming session requests.\n\nThe bulk of the logic for node interconnections however is held in the `NodeSession` which manages\n\n1. The underlying TCP connection managing reading and writing to the stream.\n2. The authentication between this node and the connection to the peer\n3. Managing actor lifecycle for actors spawned on the remote system.\n4. Transmitting all inter-actor messages between nodes.\n5. Managing PG group synchronization\n\netc..\n\nThe `NodeSession` makes local actors available on a remote system by spawning `RemoteActor`s which are essentially untyped actors that only handle serialized messages, leaving message deserialization up to the originating system. It also keeps track of pending RPC requests, to match request to response upon reply. There are special extension points in `ractor` which are added to specifically support `RemoteActor`s that aren't generally meant to be used outside of the standard\n\n```rust\nActor::spawn(Some(\"name\".to_string()), MyActor).await\n```\n\npattern.\n\n### Designing remote-supported actors\n\n**Note** not all actors are created equal. Actors need to support having their message types sent over the network link. This is done by overriding specific methods of the `ractor::Message` trait all messages need to support. Due to the lack of specialization support in Rust, if you choose to use `ractor_cluster` you'll need to derive the `ractor::Message` trait for **all** message types in your crate. However to support this, we have a few procedural macros to make this a more painless process\n\n#### Deriving the basic Message trait for in-process only actors\n\nMany actors are going to be local-only and have no need sending messages over the network link. This is the most basic scenario and in this case the default `ractor::Message` trait implementation is fine. You can derive it quickly with:\n\n```rust\nuse ractor_cluster::RactorMessage;\nuse ractor::RpcReplyPort;\n\n#[derive(RactorMessage)]\nenum MyBasicMessageType {\n    Cast1(String, u64),\n    Call1(u8, i64, RpcReplyPort\u003cVec\u003cString\u003e\u003e),\n}\n```\n\nThis will implement the default ```ractor::Message``` trait for you without you having to write it out by hand.\n\n#### Deriving the network serializable message trait for remote actors\n\nIf you want your actor to *support* remoting, then you should use a different derive statement, namely:\n\n```rust\nuse ractor_cluster::RactorClusterMessage;\nuse ractor::RpcReplyPort;\n\n#[derive(RactorClusterMessage)]\nenum MyBasicMessageType {\n    Cast1(String, u64),\n    #[rpc]\n    Call1(u8, i64, RpcReplyPort\u003cVec\u003cString\u003e\u003e),\n}\n```\n\nwhich adds a significant amount of underlying boilerplate (take a look yourself with `cargo expand`) for the implementation. But the short answer is, each enum variant needs to serialize to a byte array of arguments, a variant name, and if it's an RPC give a port that receives a byte array and de-serialize the reply back. Each of the types inside of either the arguments or reply type need to implement the ```ractor_cluster::BytesConvertable``` trait which just says this value can be written to a byte array and decoded from a byte array. If you're using `prost` for your message type definitions (protobuf), we have a macro to auto-implement this for your types.\n\n```rust\nractor_cluster::derive_serialization_for_prost_type! {MyProtobufType}\n```\n\nBesides that, just write your actor as you would. The actor itself will live where you define it and will be capable of receiving messages sent over the network link from other clusters!\n\n## Differences between an actor's \"state\" and `self`\n\nActors can (but don't need to!) have internal state. In order to facilitate this `ractor` gives implementors of the `Actor` trait the ability to define the state type for an actor. The actor's `pre_start` routine is what initializes and sets up this state. You can imagine doing things like\n\n1. Opening a network socket + storing the `TcpListener` in the state\n2. Setting up a database connection + authenticating to the DB\n3. Initializing basic state variables (counters, stats, whatever)\n\nBecause of this and the possibility that some of these operations are fallible, `pre_start` captures panic's in the method during the initialization and returns them to the caller of `Actor::spawn`.\n\nWhen designing `ractor`, we made the explicit decision to make a separate state type for an actor, rather than passing around a mutable `self` reference. The reason for this is that if we were to use a `\u0026mut self` reference, creation + instantiation of the `Self` struct would be outside of the actor's specification (i.e. not in `pre_start`) and the safety it gives would be potentially lost, causing potential crashes in the caller when it maybe shouldn't.\n\nLastly is that we would need to change some of the ownership properties that `ractor` is currently based on to pass an owned `self` in each call, returning a `Self` reference which seems clunky in this context.\n\n**In the current realization** an actor's `self` is passed as a read-only reference which shouldn't ideally contain state information, but could contain configuration / startup information if you want. However there is also `Arguments` to each `Actor` which allows passing owned values to the state of an actor. In an ideal world, all actor structs would be empty with no stored values.\n\n## Contributors\n\nThe original author of `ractor` is Sean Lawlor (@slawlor). To learn more about contributing to `ractor` please see [CONTRIBUTING.md](https://github.com/slawlor/ractor/blob/main/CONTRIBUTING.md).\n\n## License\n\nThis project is licensed under [MIT](https://github.com/slawlor/ractor/blob/main/LICENSE).\n","funding_links":[],"categories":["Rust","Libraries","\u003ca name=\"Rust\"\u003e\u003c/a\u003eRust"],"sub_categories":["Network programming"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fslawlor%2Fractor","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fslawlor%2Fractor","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fslawlor%2Fractor/lists"}