Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 134 ยท Metaprogramming

Ractors

Learn Ruby Ractors, the actor-style way to run Ruby code in parallel. Understand isolation, message passing, ports, shareable objects and the errors you will meet.

Ruby threads share all their data, which is convenient and dangerous: two threads can change the same array at the same moment, and the interpreter's global lock stops them from running Ruby code truly in parallel. A Ractor takes the opposite approach. It is a unit of execution with its own private objects, and it talks to other Ractors only by sending messages. Because nothing is shared by accident, different Ractors can run Ruby code at the same time on different CPU cores without locks.

This lesson is the introduction: how to create a Ractor, what isolation means, how messages are copied or moved, what a shareable object is and which errors tell you that you broke the rules. Parallelism and Ractors later compares Ractors with threads and processes for real workloads. If you have not yet met threads, read Threads first; it will make the differences clear.

Ractors are experimental in Ruby 4.0. The API has already changed between releases (Ruby 4.0 replaced Ractor#take and Ractor.yield with Ractor#value and Ractor::Port), and the first Ractor you create prints a warning. Use them to learn and to experiment, and check the release notes before depending on them in production.

Your first Ractor

Ractor.new starts a Ractor that runs the block you give it. The call returns immediately, and the block runs on its own. value waits until the block finishes and returns the block's result, much like Thread#value.

Ruby Creating a Ractor and reading its value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The stderr panel shows main.rb:1: warning: Ractor API is experimental and may change in future versions of Ruby. once, at the first Ractor.new. You can silence it with Warning[:experimental] = false, which the other examples in this lesson do so that the output stays readable.

Arguments given to Ractor.new(7) are handed to the block as parameters. This is not a cosmetic detail. The block of a Ractor cannot see the local variables around it, so anything it needs must be passed in as an argument. Calling value a second time simply returns the same result again.

Isolation: the block cannot see outside

A normal block is a closure: it reads and writes the variables around it. If a Ractor block could do that, two Ractors could share a variable and the whole safety idea would collapse. So Ruby checks the block when you create the Ractor and refuses if it uses an outer local variable.

Ruby A Ractor block cannot capture a local variable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The program stops with can not isolate a Proc because it accesses outer variables (counter). (ArgumentError) raised from Ractor.new. The fix is to pass what you need as an argument and return the result instead of mutating something outside:

Ruby Pass data in, get results out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Isolation goes further than local variables. Inside a Ractor you cannot reach most state that lives at the top level of the program:

  • Global variables such as $count raise Ractor::IsolationError.
  • Constants that hold non-shareable objects (an unfrozen array, for example) raise Ractor::IsolationError when read.
  • Instance variables of classes and modules (class-level state like @count on a class) cannot be set from a non-main Ractor.

Ruby is protecting you: each of these would have been a hidden shared variable. The next section explains what can be shared.

Shareable objects

An object is shareable if it is safe for several Ractors to hold at once. That means it can never change: numbers, symbols, nil, true, false, frozen strings, and frozen collections whose contents are all shareable. Classes and modules are shareable too, so a Ractor can call Point.new or Math.sqrt.

Ruby Asking whether an object is shareable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

[1, "a"].freeze is not shareable, because freezing an array only freezes the array itself, not the string inside it. Ractor.make_shareable walks the whole structure and freezes everything (a deep freeze), after which any number of Ractors can read the same object safely, with no copying. This ties back to Immutability and freeze: immutable data is the easy way to share state between Ractors.

For constants the rule is practical. Wrap them with Ractor.make_shareable when you define them, and Ractors can read them:

Ruby Constants and global variables from a Ractor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

When a Ractor fails while running, the error does not appear in the main Ractor right away. It is stored, and value raises Ractor::RemoteError whose cause is the original exception. That is why attempt rescues RemoteError and then looks at e.cause. The Thread.report_on_exception = false line only stops Ruby from also printing the failure to the error output as it happens.

Sending messages

Every Ractor has an incoming mailbox. Any Ractor can put a message into it with send (or the << alias), and the receiving Ractor reads the next message with Ractor.receive, which blocks until one arrives.

Ruby send and receive

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The worker collects what it receives and returns the list when it sees the :stop message. Sending a sentinel value such as :stop is the usual way to tell a worker that the work is finished.

Copy or move

A message that is not shareable cannot simply be handed over, because both Ractors would then hold it. By default Ruby makes a deep copy and gives the copy to the receiver. The sender keeps its original, and nothing the receiver does to its copy is visible to the sender.

If copying is too expensive (a huge string or array), you can move the object with send(obj, move: true). The receiver gets the real object, and the sender's variable turns into a husk that raises Ractor::MovedError when you use it.

Ruby Copy by default, move on request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The receiver changed its copy to "hello world" while note stays "hello", so the two Ractors never touched the same string. After the move, the variable big still exists, but any method call on it, even size, raises Ractor::MovedError. Move is an optimization for large data, and it makes the "ownership" rule visible: once you give an object away, you may not use it.

Messages that cannot be copied at all raise TypeError. Examples are Proc and Method objects (allocator undefined for Proc). Send data, not code, and send a shareable proc made with Ractor.shareable_proc if you really need to pass a block of code.

Ports: collecting results from many Ractors

Ractor.receive reads from a Ractor's own mailbox. When one Ractor wants to gather answers from several others, Ruby 4.0 offers a Port: a small mailbox you create, send to workers, and read from. Only the Ractor that created a port can receive from it, but any Ractor can send to it.

Ruby Workers reply through a port

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The main Ractor hands numbers out round-robin, reads six answers from the port in whatever order they arrive and then sorts them, because the arrival order is not guaranteed. This fan-out/fan-in shape is the standard worker-pool pattern. A Ractor::Port is also what lets you wait for whichever of several Ractors answers first.

On this website each program runs on a single CPU core, so you will not see a speed-up here. On a multi-core machine the three workers could compute at the same time, which threads cannot do for Ruby code.

Ractors versus threads

Thread Ractor
Memory Shares everything Shares only shareable objects
Parallel Ruby code No, one thread at a time (GVL) Yes, one GVL per Ractor
Communication Shared variables + Mutex / Queue Messages (copy or move)
Data races Possible Prevented by isolation
Startup cost Small Larger, and each Ractor has its own heap
Ecosystem support Everything works Many gems are not Ractor-safe

Remember that the last row is the real-world limit today. A gem that keeps state in a class variable or a global will fail inside a Ractor. See Mutex, Queue and ConditionVariable for the thread-based tools, and Parallelism and Ractors for guidance on choosing between them.

Common mistakes

  • Reading an outer variable. The block cannot see it. Pass it as an argument.
  • Sending huge objects by copy. Use move: true, or share a frozen object with Ractor.make_shareable.
  • Using an object after moving it. It raises Ractor::MovedError.
  • Treating value as optional. An error inside a Ractor is stored until you call value; if you never call it you will never see it.
  • Expecting printed output order. Output from several Ractors is not synchronized. Return values and send results to the main Ractor instead of printing from workers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does Ractor.new { counter += 1 } raise an ArgumentError when counter is a local variable outside the block?

    Ractors share nothing by accident. Ruby checks the block when the Ractor is created and refuses if it reads or writes an outer local variable. Pass data in as an argument.
  2. 2. What does Ractor.shareable?([1, "a"].freeze) return?

    A shareable object must be deeply immutable. Freezing the array does not freeze its string element. Ractor.make_shareable freezes the whole structure.
  3. 3. What happens by default when you send a non-shareable object to another Ractor?

    Messages are deep-copied unless you pass move: true. A move transfers ownership and turns the sender's reference into a Ractor::MovedObject.
  4. 4. An exception is raised inside a Ractor. Where do you see it in the main Ractor?

    The failure is stored and re-raised by value (or join) wrapped in Ractor::RemoteError. Use e.cause to inspect the real error.
  5. 5. Which statement about Ractors in Ruby 4.0 is correct?

    Each Ractor has its own interpreter lock, so Ruby code can run in parallel. The API is still experimental, take was replaced by value and ports, and many gems are not Ractor-safe.

Summary

  • Ractor.new(args) { |params| ... } starts an isolated unit of execution; value waits for and returns its result.
  • A Ractor block cannot use outer local variables, global variables or non-shareable constants; pass data in as arguments.
  • Shareable objects (numbers, symbols, deeply frozen structures, classes) can be used by many Ractors; Ractor.make_shareable deep-freezes data for that purpose.
  • Messages are sent with send or << and read with Ractor.receive; they are deep-copied by default and moved with move: true.
  • Ractor::Port lets one Ractor collect answers from many workers.
  • Errors inside a Ractor surface as Ractor::RemoteError from value; the original exception is cause.
  • The feature is experimental in Ruby 4.0: expect API changes and gems that are not Ractor-safe.

Next: Regular Expressions