Ray: tasks, actors, the object store and Ray Train

Reading: 34 min, plus 9 in closed details. Every run on a real Ray 2.59.0 cluster in containers (a head and 2 workers, 4 fake GPUs) with the topic's running example. Data as of October 2026.

The idea

Ray turns Python functions and classes into tasks and actors scheduled across a cluster; their results are immutable objects kept in each node's shared-memory store, and every object has an owner, the worker that created it, which counts its references, knows where its copies are and decides whether it can be rebuilt after a failure.

Fig. 1, step by step: one call, y = f.remote(x), on the cluster every number on this page came from measured

  1. The cluster. Ray 2.59.0 in three containers on one laptop (setup in the root's src/data/README.md). The head offers 0 CPUs, so no task runs there; it holds the GCS (cluster metadata and node health checks) and your driver. Each worker, w1 and w2, offers 2 CPUs, an 80 MB object store and 2 fake_gpu (a custom resource Ray counts and hands out, not a device); every node runs a raylet. Idle memory from docker stats: head 692 MB of a 2,000 MB cap, workers 244 and 243 MB of 1,100 MB.
  2. The call returns a ref and makes an owner. Nothing runs yet: the driver (your script) creates the ObjectRef y, becomes its owner and writes its table: 1 reference, no location yet, and the lineage, the task f(x), to re-run if every copy is lost.
  3. A lease, with spillback. The owner asks its local raylet (the head's) for a worker lease that fits 1 CPU. The head offers 0 CPUs, so its raylet answers with spillback: ask w1, which has free CPUs (it knows other nodes' free resources from the cluster view the GCS keeps in sync). w1's raylet grants a lease on one of its pooled worker processes, or starts one.
  4. Push straight to the worker. The owner sends the task directly to the leased worker. The GCS is not on this path, which is why ordinary tasks keep running while it is briefly slow. If w1 has no copy of the argument x, its object manager pulls one first.
  5. The result lands in w1's store. 8 MB is over the 100 KB inline limit, so it is written to w1's object store and the worker tells the owner "y is at w1"; the lease can be reused for the next task of the same shape. A result under 100 KB would travel inside the reply and live in the owner's memory instead.
  6. A reader on w2 pulls a copy. The owner tells w2 where y is; w2's raylet pulls a copy into its own store, and that copy serves every reader on w2. Measured with a 16 MB object: the first read on w2 took 0.42 s, the second 5 ms.
  7. Freed when the count reaches 0. The driver deletes y: the owner tells both stores to free their copies and forgets the lineage.

The owner's table in the driver is the only record of y's references, copies and lineage. Message order from the Ownership paper and Ray's architecture whitepaper; no timings are drawn per message because none were measured. Ray Train, Data, Serve and Tune are libraries built from these pieces; the machines underneath come from Kubernetes or Slurm. Positions are schematic.

Where it sits. Slurm and Kubernetes hand out machines to jobs (the root page's Scheduling lab compares them). Ray runs inside machines you already have, usually Kubernetes pods (KubeRay) or a Slurm allocation, and schedules the tasks of one program across them. It is not a rival to Slurm for "who gets the cluster"; it is the layer that makes one program distributed.

You need: DDP and torch.distributed for the Ray Train section (Distributed PyTorch); the root page's Slurm, Kubernetes and Ray comparison for the cluster layer below.

New terms

  • Task: one call of a remote function; stateless, retryable.
  • Actor: an instance of a remote class; one process with state.
  • ObjectRef: a future, a handle to a result that will exist.
  • Object store: per-node shared memory holding large objects.
  • Owner: the worker that created a ref; holds its count, locations, lineage.
  • Lineage: the task that made an object, kept to re-run it.
  • Raylet: per-node daemon: scheduler, object manager, worker pool.
  • GCS: Global Control Service on the head: cluster metadata.
  • Placement group: bundles of resources reserved all or nothing.
  • Block: Ray Data's unit, a chunk of rows in the object store.
How the evidence was made

All runs: Ray 2.59.0 (PyPI 2026-10-02), torch 2.14.1 CPU, 2026-10-16, scripts in src/scripts/ (ry_core.py tasks, actors, objects, spilling, failures and a node loss; ry_data.py Ray Data; ry_train.py Ray Train with its checkpoint API), raw output scrubbed in src/runs/. Timings are measured on Apple M1 Pro, Docker Desktop VM, shared machine: rough, useful for ratios and orders of magnitude, not as cluster numbers. Placements, counts, error types, messages and event orders are deterministic and transfer to a real cluster. Ray source is quoted at tag ray-2.59.0 (commit dd83c3a), file and line, located by pattern in src/scripts/ry_quotes.py; Ray Serve defaults were read from the same tag on 2026-10-24. The head was given a 2,000 MB cap, 500 MB more than the shared setup's 1,500 MB (see Processes). Process sizes are resident memory (RSS) read from /proc, which double-counts shared pages. The containers share a Docker bridge network and a volume mounted at /shared on all three. Ray runs in Linux containers because it refuses a multi-node cluster on macOS ("Multi-node Ray clusters are not supported on Windows and OSX").

Where ray.get sits decides whether tasks overlap measured

Tasks: remote functions and futures

@ray.remote registers a function with the cluster. f.remote(x) does not run f: it sends a task description (function, arguments, resource request, by default 1 CPU) to Ray and returns an ObjectRef at once. ray.get(ref) blocks until the result exists; ray.wait(refs) returns the ones that are ready. Because .remote() returns immediately, you submit many tasks before waiting for any: that is where the parallelism comes from.

From src/scripts/ry_core.py (section tasks), run as the driver on the head:

@ray.remote
def noop():
    return socket.gethostname()

# one at a time: submit, wait, repeat (100 times)
for _ in range(100):
    ray.get(noop.remote())
# 1,000 at once: submit all, then wait for all
hosts = ray.get([noop.remote() for _ in range(1000)])

measured One tiny task round trip (submit, schedule, run, return) took about 3 ms on this laptop; 1,000 tasks submitted together cost well under 1 ms each, because Ray pipelines them across the 4 worker processes and reuses a leased worker for many tasks. The 1,000 results came from both workers (the split is in the card). The Ownership paper (NSDI 2021, the design Ray implements) reports about 1 ms per task on a real cluster published: the same order.

Predict: eight tasks that each sleep 0.5 s, on 4 free CPUs. How long does ray.get([nap.remote(i, 0.5) for i in range(8)]) take, and how long does [ray.get(nap.remote(i, 0.5)) for i in range(8)] take? Answer, then watch the replay.
About 1 s (two waves of 4 on 4 CPUs) against about 4 s: 4.0 s instead of 1.1 s here. In the second form each ray.get waits for its task before the next is even submitted, so the eight run one after another: the classic "ray.get in a loop" mistake.

The replay, in stretches of the recorded run

  1. Submit all eight. Every .remote() returns at once; four tasks start within 12 ms, one on each worker process (two per worker node).
  2. The first wave. Four run side by side for 0.5 s; the other four wait for a free CPU.
  3. The second wave. Each freed process takes the next task (two on w2 started 0.1 s late, at 0.61 s); ray.get returns all eight at 1.12 s: two waves of 4 on 4 CPUs.

Each lane is one worker process (node and pid from the run); each bar is one task, placed where and when it really ran. Same eight tasks, same cluster.

Cost. A task is a scheduling decision, a message and a serialisation: milliseconds, not microseconds. Batch tiny work into fewer, larger tasks. The Ray docs' own example (anti-pattern: too fine-grained tasks published) runs 10,000 calls of a 10-microsecond function: about 0.17 s as plain calls, 1.6 s as one task each, 0.03 s as batches of 1,000 per task.

Check. ray status shows CPUs in use; ray timeline writes a Chrome trace with each task as a bar per worker, as drawn here. Serial bars that should overlap mean a ray.get between submissions.

Actors: a process with state

Tasks forget everything between calls; a model on a GPU, a replay buffer or a simulator must live in one process. @ray.remote on a class makes an actor class: Counter.remote() starts a dedicated worker process, runs __init__ there and returns an actor handle. Calls from one caller run one at a time in submission order (unless you ask for max_concurrency or async methods), so two calls never touch the state at once.

@ray.remote
class Counter:
    def __init__(self):
        self.n = 0
    def incr(self):
        self.n += 1
        return self.n

c = Counter.remote()                                  # a new process on some node
vals = ray.get([c.incr.remote() for _ in range(1000)])  # 1,000 calls queued, run in order

Fig. 2, step by step: three Counters from ry_core.py measured

  1. Counter.remote() starts a process. Ray placed a dedicated worker process for the actor on w1 in 0.16 s, ran __init__ there (n = 0) and returned a handle.
  2. Calls go straight to that process. 100 calls one at a time: a median round trip of 0.95 ms, against 2.96 ms for a task. After creation, an actor call round trip is faster than a task's: no scheduling decision, the caller talks straight to the actor's process.
  3. Queued calls run in order. 1,000 incr calls submitted at once took 0.23 s and returned 101 to 1100: the 1,000 queued calls came back in order (the counter starts above 1 because the 100 single calls ran first).
  4. The process dies, max_restarts=1. A second Counter, on w2 with n at 3, is killed. The call in flight fails with ActorUnavailableError; Ray starts a new process on w1 with a new pid, __init__ runs again, and the next call returns 1: the state is gone.
  5. The default, max_restarts=0. A third Counter, on w1, is killed and stays dead: every later call raises ActorDiedError.
TaskActor
State between callsnonekept in the actor's process
Where it runsany node with free resources, chosen per callone process, placed once at creation
Order of callsnone: tasks run as resources free upone caller's calls run in submission order
Resources heldwhile running (1 CPU by default)for its lifetime if it asks for any; by default 1 CPU to place it and 0 while it runs (Ray docs: resources)
On a crashretried 3 times by default (system failures)not restarted by default; with max_restarts, restarted with fresh state
Typical usepreprocessing, scoring, parallel mapmodel replicas, simulators, rollout workers, Ray Train workers (RayTrainWorker), vLLM engines in RL stacks

Copies appear where objects are read measured

Objects and the object store

Tasks pass data to each other. Sending every result back through the submitting program would make it the bottleneck, so every node runs an object store (historically Plasma): shared memory, managed by the node's raylet, that every worker on the node can map. A result is stored where its task ran, and:

  • Small objects travel inline. A result under max_direct_call_object_size = 100 KB (src/ray/common/ray_config_def.h line 274) goes back to the owner inside the reply and never enters a store.
  • Big objects stay put until read. A reader on another node pulls a copy into its own store in 5 MB chunks (object_manager_default_chunk_size, line 432); that copy serves every reader on the node.
  • Reads are zero-copy, objects immutable. A NumPy array from the store is a read-only view of shared memory; a new value is a new object.
  • The store has a size. By default 30% of the node's memory (DEFAULT_OBJECT_STORE_MEMORY_PROPORTION, python/ray/_private/ray_constants.py line 110), capped at 200 GB (line 106); this cluster sets 80 MB per node with --object-store-memory.

The stepper: copies per node, read from ray.experimental.get_object_locations after each action measured

  1. Two tasks on w1 return a 1 KB and a 1 MB array. The 1 MB array is in w1's store, where its task ran. The 1 KB result has no store location: inline, 1,269 bytes serialised, held by the driver. Both tasks were pinned to w1 with NodeAffinitySchedulingStrategy.
  2. The driver calls ray.get on the 1 MB one. Now it has two copies, on w1 and on the head (the driver's node). The array the driver got is read-only (writeable False, owndata False), a view of shared memory: writing to it raised ValueError: assignment destination is read-only.
  3. The driver calls ray.put on a 4 MB array. ray.put stores the value in the store of the caller's node, the head, and the driver owns it.
  4. A task on w2 reads a 16 MB object made on w1. w2 had no copy, so its raylet pulled one from w1 in 5 MB chunks: 0.419 s end to end. Copies afterwards: w1 and w2.
  5. A second task on w2 reads it again. A local copy already existed: no transfer, 0.005 s.
  6. A task on w1 reads it. Local as well: 0.008 s. Copies stay on w1 and w2 until the owner frees them.

Cost. A cross-node read pays the network once per node, then is free on that node: here the first 16 MB read on the other worker took about 0.4 s and the second about 5 ms (a Docker bridge on a laptop, far below a real 100 to 400 Gb/s fabric; the ratio is the lesson). Passing a big array by value to many tasks stores a fresh copy per call; ray.put it once and pass the ref. (Both were timed; at 4 calls of 8 MB the difference was within this laptop's noise, so no number is quoted.) Check: ray memory lists every reference with its size, owner and why it is alive; --stats-only prints store usage and spill counters.

When the store fills: spilling

Past object_spilling_threshold = 0.8 of capacity (ray_config_def.h line 827), the raylet writes objects that are referenced but not in use to local disk through IO worker processes (max_io_workers = 4 per node) and restores them when read. Unreferenced objects are deleted; objects in use cannot be spilled. Only if spilling cannot keep up does a put fail with ObjectStoreFullError (spilling is on by default, automatic_object_spilling_enabled, line 804).

When it matters. Spilling turns an out-of-memory crash into slower progress: right for data pipelines, wrong for a latency-sensitive actor. Its hidden cost showed up later here: the spill and restore IO workers stayed alive (two of each, about 400 MB of resident memory on a 1.1 GB node, src/runs/debug/ps_w1_after_spill.txt), and the next Ray Train run on that node was killed by Ray's memory monitor (Mistakes). ray memory --stats-only printed "Spilled 64 MiB, 8 objects, avg write throughput 212 MiB/s" and "Restored 64 MiB, 8 objects, avg read throughput 1591 MiB/s"; spill throughput that low on a real node means a slow disk: point object_spilling_config (in ray start --system-config) at local NVMe (Ray docs: object spilling).

Spilling makes reads slower, not failures: 14 objects of 8 MB into an 80 MB store measured

Ownership: who is responsible for an object

Once refs are passed between tasks on many nodes, someone must know when an object can be freed, where its copies are and what to do if its node dies; a central table for every object would be a bottleneck at millions of tasks per second. Ray's answer, from the Ownership paper (Wang et al., NSDI 2021): the worker that creates an ObjectRef, by .remote() or ray.put, is its owner, and keeps in its own memory the reference count (borrowers report back to it), the locations of the copies and the lineage, the task that produced it, kept while the object is referenced (lineage_pinning_enabled, line 208) up to max_lineage_bytes = 1 GB per owner (line 224). Fig. 1, at the top of the page, follows one task while the owner's table changes (steps 2, 5 and 7).

Consequences. The driver owns everything it submits. A task that calls ray.put or submits tasks inside its body owns those objects, and they die with that worker even if the data sat on a healthy node. ray.put objects have no lineage (no task made them), so they cannot be rebuilt. Small inline objects live in the owner's memory, so they survive the loss of the node that computed them. Failures, below, shows all four on a real node loss.

Processes: the GCS, raylets, workers and the driver

Four kinds of process make the cluster in Fig. 1; knowing which holds what is how you read logs and failures.

GCS (head only)

The Global Control Service (older papers: Global Control Store), gcs_server: the node table, the actor table (where each actor lives, its restarts), placement groups, jobs, a key-value store. It health-checks every raylet and declares nodes dead. It does not hold objects or schedule ordinary tasks.

Raylet (every node)

A scheduler that grants worker leases for this node's resources or points the request elsewhere (spillback), the object store and object manager, and the worker pool that starts and reuses Python workers.

Workers

Python processes running tasks and actors. Each embeds a core worker library, which is where ownership lives.

Driver

Your script after ray.init(): a worker that owns everything it submits. Here and for Ray Jobs it runs on the head, so the head needs memory for it.

When it matters. The head is a single point of failure and a memory hot spot. The root's Failure lab saw the head at 95% of its 1.5 GB cap during Ray Train runs, and Ray's memory monitor killed 13 non-training worker processes there. On a real cluster: no training on the head (--num-cpus 0, as here), memory for the driver, dashboard and Ray Train's controller, and GCS fault tolerance (Failures, below).

Found here: raising a container's memory cap does not raise Ray's kill threshold

Ray's memory monitor kills workers when a node's memory use passes memory_usage_threshold = 0.95 (ray_config_def.h line 79), checked every 250 ms (line 83). The threshold in bytes is computed once, when the raylet starts (src/ray/common/monitors/threshold_memory_monitor.cc line 33 stores it; line 126 compares against it). After docker update --memory 2000m on the running head, a Ray Train run still died with "Memory usage 1539858432B exceeded threshold of 1494220800B (71.2% of 2097152000B limit)": 1,494,220,800 is 95% of the old 1,500 MiB limit. Raise memory before ray start, or restart Ray after resizing. (This page then ran its head with 2,000 MB from the start, on 2026-10-16.)

On the head, the dashboard outweighs the GCS measured

Scheduling: resources, policies and placement groups

Resources are counters. A node advertises numbers (CPU, GPU, memory, any custom name such as fake_gpu); a task or actor asks for amounts (num_cpus=1, num_gpus=0.5, resources={"fake_gpu": 1}) and runs only where they are free. The numbers are for placement, not enforcement: Ray does not stop a task from using more (unlike Slurm with cgroups). On a real GPU node Ray sets CUDA_VISIBLE_DEVICES for the GPUs it assigned; for a custom resource it sets nothing.

Policies. The default hybrid policy prefers the local node until its critical resource passes scheduler_spread_threshold = 0.5 utilisation (ray_config_def.h line 252), then picks randomly among the least-loaded few (src/ray/raylet/scheduling/policy/hybrid_scheduling_policy.h lines 29 to 48: "Scheduling a task on a new node incurs a cold start penalty ... Past a certain utilization threshold, a big noisy neighbor problem occurs"). "SPREAD" spreads; NodeAffinitySchedulingStrategy(node_id, soft) pins to one node (soft: fall back if it is gone).

Placement groups reserve several bundles at once, all or nothing, so a multi-worker job never starts with half its GPUs: Ray's gang scheduling. The GCS reserves them with a two-phase commit across raylets ("The first phase of 2PC ... prepare resources", "The second phase of 2PC", src/ray/gcs/gcs_placement_group_scheduler.h lines 114 and 116). Ray Train puts its worker group in one (ScalingConfig(placement_strategy="PACK") by default).

Four bundles, two nodes of two: only the strict strategies refuse measured

Each bundle is 1 CPU + 1 fake_gpu, what one Ray Train worker asks for. Placements as recorded by the root's Scheduling lab (src/sched/runs/ray/ray_pg.jsonl in the root's folder, Ray 2.59.0, 2026-10-16). PACK prefers one node but settles for two; SPREAD spreads bundles over nodes, best effort; the STRICT_ variants wait rather than settle: STRICT_PACK needs one node with 4 and STRICT_SPREAD four nodes, so both stayed PENDING (with 2 bundles each, both were created) and the autoscaler printed "Error: No available node types can fulfill resource request ... {'CPU': 4.0, 'fake_gpu': 4.0}". A second group that needed 3 of 4 GPUs waited holding nothing, then got all 3 at once 0.68 s after the first was removed.

Failures: what survives a crash

Ray handles tasks, actors, objects and nodes differently. Every row below was run on this cluster (ry_core.py fault and lineage); error names and messages are Ray's own.

What failedDefault behaviour (source)What happened here
  • Tasks are retried up to max_retries = 3 times when the worker process or node dies (DEFAULT_TASK_MAX_RETRIES = 3, ray_constants.py line 633; ray_option_utils.py line 182). An exception from your code is not retried unless retry_exceptions=True (line 207): a crash is the machine's fault, an exception yours. Retries re-run the function, so tasks should be idempotent.
  • Actors are not restarted by default (max_restarts = 0, line 254). With max_restarts=N a new process runs __init__ again: the state is gone (the counter went from 3 back to 1 here). Calls in flight fail unless max_task_retries is set (default 0, line 255).
  • Objects lost with a node are rebuilt by their owner re-running the task (the GCS log said "Attempting to recover 2 lost objects by resubmitting their tasks"), if that task is retryable. Objects whose owner died are lost for good (OwnerDiedError), and so are ray.put objects whose only copy was on the lost node.
  • Nodes are declared dead by the GCS after health_check_failure_threshold = 5 failed checks, sent every health_check_period_ms = 3,000 ms with a health_check_timeout_ms = 10,000 ms timeout (ray_config_def.h lines 1060 to 1064). Here the first check failed 11.7 s after the node was killed and the node was dead at 29.9 s; the root's Failure lab measured 30.0 s on its own run.

Fig. 3 · one node lost, six fates

One node lost, six fates, decided by owner and lineage

The node-loss run puts the ownership rule to work: on ray-w2, A an 8 MB task output (driver owns it, retryable), B the same with max_retries=0, C an 8 MB array a task on w2 ray.put itself and returned, D a 1 KB task output (inline), and two actors (max_restarts=1 and the default 0). Then docker kill mi-ray-w2, and the driver asked for each. Predict each fate, then follow Fig. 3.

Fig. 3, step by step: seconds after the kill measured

  1. Before the kill. A, B and C sit in w2's object store, and both Counter actors run on w2. D came back inline when its task finished, so it lives in the driver's memory on the head.
  2. w2 is killed at 0 s. The driver asks for D first: it returns at once (0.42 s after the kill, when the driver started asking), because it was never on w2. Then it asks for A and waits.
  3. The GCS health checks fail. The first failed check came 11.7 s after the kill, then one every 3 s: 20.9, 23.9, 26.9 and 29.9 s. Nobody else knows the node is gone; ray.get(A) is still waiting.
  4. Node declared dead at 29.9 s. After 5 failed checks the GCS marks w2 dead, reschedules its placement groups and hands its actors to the actor manager.
  5. A is rebuilt from lineage. Its owner, the driver, is alive and holds the lineage, and the task is retryable (max_retries 3): it re-ran the task on w1 at 31.4 s, and ray.get(A) returned after 31.0 s of waiting.
  6. B and C are lost. B: ObjectReconstructionFailedError, the owner is alive but may not re-run a max_retries=0 task. C: OwnerDiedError at 41.7 s; its owner was the worker on w2 that called ray.put, and ray.put objects have no lineage anyway.
  7. The actors. With max_restarts=1 the GCS restarted the Counter on w1; __init__ ran again, so the next call returned 1. With the default 0 it is dead: ActorDiedError.

Times from the host's clock (kill), the GCS log (health checks, node death), the shared run log (re-executed task) and the driver (each ray.get). The driver asked in order D, A, B, C, then the actors, so B's and C's answers came after A's 31 s wait. The GCS timings are set by its health-check settings and transfer to real clusters. Positions are schematic.

Each item: owner, outcome, why, and Ray's message
Thing on the dead nodeOwnerOutcomeWhy
Predict: a task on node B calls ray.put(big_array) and returns the ref to the driver. Node B dies. The array's only copy was on node C, which is healthy. Can the driver still ray.get it?
No. The owner is the worker on B that called ray.put; its count and location table died with it. Ray's docs: "Currently, Ray does not support recovery from owner failure", and "Ray will clean up any remaining copies of the object's value to prevent a memory leak" (object fault tolerance). The error reads "The object's owner has exited. This is the Python worker that first created the ObjectRef via .remote() or ray.put()"; measured here with the copy on the killed node itself (object C). Rule: let the driver or a long-lived actor own what you cannot lose; return values from tasks instead of ray.put inside them.

The head is the exception: without GCS fault tolerance, losing it loses the cluster. With GCS fault tolerance the GCS writes its tables to an external Redis; when it restarts, raylets and workers reconnect (they wait up to gcs_rpc_server_reconnect_timeout_s = 60 s, line 549) and running tasks and actors continue (Ray docs: GCS fault tolerance; on KubeRay 1.3.0 and later, a gcsFaultToleranceOptions field in the RayCluster spec: KubeRay GCS fault tolerance). not run here: it needs a Redis and a head restart, which teaches little on a toy cluster beyond what the docs state.

Ray Data: streaming blocks through the cluster

Training reads and transforms data while GPUs wait. Inside each training process, preprocessing is tied to the trainer's CPUs; all up front, it needs storage for the whole result and a long wait. A Ray Data Dataset is a lazy plan (read_* or from_items, then map_batches(fn), then a consumer such as iter_batches or a Ray Train worker). Data moves as blocks in the object store, which Ray Data "attempts to bound ... between 1 MiB and 128 MiB" (Ray Data internals; DEFAULT_TARGET_MAX_BLOCK_SIZE, python/ray/data/context.py line 76). The streaming executor runs every operator at once: each "takes in and outputs a stream of blocks", each block is one Ray task (or an actor pool for stateful work such as a model), and the first batch arrives once the first block has passed every stage.

  • Operator fusion. Consecutive map operators with compatible remote arguments become one task per block, with no store hop between them (are_remote_args_compatible, python/ray/data/_internal/logical/rules/operator_fusion.py lines 886 to 899: different num_cpus means no fusion).
  • Backpressure. "To limit object store use, Ray Data applies backpressure and stops launching tasks once enough data is buffered" (same page), so a slow consumer does not make producers fill memory.

From src/scripts/ry_data.py: the running example's text (TinyShakespeare) in 24 blocks, two pretend stages (0.3 s and 0.2 s per block), a pretend training loop (0.1 s per batch of 512):

ds = ray.data.from_items(items, override_num_blocks=24)
ds = ds.map_batches(encode, batch_size=1)                 # characters to ids
# staged: ds = ds.materialize()   (finish stage 1 everywhere first)
ds = ds.map_batches(window, batch_size=1)                 # pipelined: num_cpus=0.5 stops fusion
for b in ds.iter_batches(batch_size=512, batch_format="numpy"):
    time.sleep(0.1)                                       # a training step

Predict which plan feeds the training loop first and which finishes last, then watch the three runs.

The three runs, in stretches

  1. Start-up. The plan is built and FromItems cuts the text into 24 blocks; the first tasks start at 1.02 s.
  2. Fused tasks, then the first batch. Each block is one task that runs encode and then window, four at a time; the first batch reaches the training loop at 2.38 s.
  3. Everything overlaps. The workers keep producing blocks while the training loop consumes batches; the last block is done at 6.26 s.
  4. Training drains. All 35 batches are done at 6.76 s.

measured Same 24 blocks, same 17,424 samples in 35 batches, three plans; lanes are worker processes, the bottom lane the training loop in the driver. Fused: each block is one task running both functions, and training starts as soon as the first blocks are done. Two operators: separate tasks interleave on the same 4 CPUs (window asks for 0.5 CPU) with a store hop between, which cost time here; on a real pipeline you unfuse on purpose when stages need different resources (CPU decode, GPU model). Staged: every encode finishes before any window starts, so training waits for the whole first stage: the bulk-synchronous plan streaming replaced. The shapes are the lesson, not the seconds.

Operators, tasks and wall time per plan, from ds.stats()
ModeOperators reported by ds.stats()TasksWall time

Published claim. The Ray Data paper (Luan et al., The Streaming Batch Model for Efficient and Fault-Tolerant Heterogeneous Execution, 2025-01-16; UC Berkeley and Anyscale, Ray's company) reports "2.5-12x" throughput on heterogeneous batch inference over batch and stream processing systems, and 31% higher training throughput for Stable Diffusion than single-node data loaders published, authors' own measurements. Not reproduced here.

When it matters. Heavy preprocessing, or preprocessing on a different machine type than training (CPU nodes decoding video for GPU trainers), and offline batch inference. For a text run already tokenized into shards, a plain loader is simpler (Storage and loading covers formats and loaders).

Ray Train: the worker group, checkpoints and failures

Distributed PyTorch needs N processes on the right machines, each told its rank, the world size and rank 0's address, a process group, and someone to restart from a checkpoint when one dies. torchrun does this per node and Slurm or Kubernetes supply machines; Ray Train does all of it inside a Ray cluster, from one call: TorchTrainer(train_loop, scaling_config=ScalingConfig(num_workers=4, ...), run_config=RunConfig(...)).fit().

Fig. 4, step by step: run 1 of the crash test measured

  1. fit() starts a controller. A controller actor (Ray Train v2, the default: RAY_TRAIN_V2_ENABLED defaults to true, python/ray/train/v2/_internal/constants.py line 149) runs on the head and requests a placement group of N bundles ("Requesting resources: {'CPU': 1, 'fake_gpu': 1} * 4"), PACK by default.
  2. The bundles are reserved together. The GCS reserves all four at once with its two-phase commit, two on w1 and two on w2: one bundle per fake GPU, and no rank starts until every rank can.
  3. One worker per GPU. It starts N RayTrainWorker actors, one in each bundle (ranks 0 and 1 on w1, 2 and 3 on w2), and sets MASTER_ADDR, MASTER_PORT, RANK, WORLD_SIZE, LOCAL_RANK. In run 1 the group was running 9.0 s after fit().
  4. The process group. The workers initialise the process group with TorchConfig(backend=...) ("Setting up process group for: env:// [rank=0, world_size=4]"), gloo here, before your loop runs. Then every worker runs your train_loop, and DDP all-reduces the gradients every step. The root's Launch lab has the env dump.
  5. Reports and checkpoints. ray.train.report(metrics, checkpoint=Checkpoint.from_directory(d)) uploads the checkpoint to storage_path and queues a report. The controller polls the workers every DEFAULT_HEALTH_CHECK_INTERVAL_S = 2.0 s (line 35; controller.py line 436) and registered step 50 at 11.67 s, once it held the report of every worker.
  6. Rank 3 dies after reporting step 100. All four ranks reported step 100, and rank 0 uploaded its checkpoint, at 11.67 s. Rank 3 exited with code 13 at step 120 (12.14 s), before the next poll, and its report died with it: step 100 is never registered.
  7. A new group from step 50. The poll found the failure at 13.69 s and applied FailureConfig: a new worker group from the latest checkpoint, up to max_failures times (default 0: python/ray/air/config.py line 368), or raise. ray.train.get_checkpoint() returns the latest registered one after a restart, step 50: the new group started at 19.02 s and redid 70 steps.

Positions are schematic; the times are seconds after fit() in run 1 (runs 2 and 3 below behaved the same).

The loop of src/scripts/ry_train.py (the running example on Ray Train's checkpoint API)
ck = ray.train.get_checkpoint()                 # None on the first attempt
if ck:
    with ck.as_directory() as d:
        st = torch.load(os.path.join(d, "state.pt"))
    model.load_state_dict(st["model"]); opt.load_state_dict(st["opt"]); start = st["step"]
ddp = DistributedDataParallel(model)
for step in range(start, steps):
    ...                                          # forward, backward, AdamW, all-reduce of the loss
    if done % 50 == 0:
        with tempfile.TemporaryDirectory() as d:
            c = None
            if rank == 0:
                torch.save({...}, os.path.join(d, "state.pt")); c = Checkpoint.from_directory(d)
            ray.train.report({"step": done, "gloss": g.item()}, checkpoint=c)

TorchTrainer(loop, torch_config=TorchConfig(backend="gloo"),
    scaling_config=ScalingConfig(num_workers=4, resources_per_worker={"CPU": 1, "fake_gpu": 1}, placement_strategy="PACK"),
    run_config=RunConfig(storage_path="/shared/results", failure_config=FailureConfig(max_failures=1),
                         checkpoint_config=CheckpointConfig(num_to_keep=2))).fit()

training stepsreport called (worker)checkpoint registered (controller)crash or failure seen

Every rank calls report at step 100 (the second tick on each lane), but no green dot for 100 follows on the controller lane, so the restart begins at 50. 4 workers on 2 nodes; rank 3 exits with code 13 at step 120. Three runs; pick one above. The scrubber walks the run event by event.

The crash, replayed: why the restart began at step 50

Predict: checkpoints every 50 steps; rank 3 crashes at step 120 on the first attempt; max_failures=1. From which step does the second attempt start?
From step 50, in all three runs made here, although every worker had called report for step 100 and rank 0 had written the step-100 checkpoint half a second before the crash. A report reaches the controller only when it polls, and it registers a checkpoint only once it holds that report from every worker (report_handler.py lines 40 and 63: "Wait for all workers to report training results", if not all(self._training_report_queues): return). Rank 3's step-100 report died inside its process, so step 100 was never registered: 70 steps redone instead of 20, and the step-100 files stayed in storage as an orphan directory that num_to_keep=2 did not delete.

measured The restarted group recomputed steps 50 to 120 and finished; its loss matched the uninterrupted running example at most logged steps and differed by one float32 rounding step (2.4e-7) at steps 70, 180 and 200, the DDP bucket-rebuild effect the root's Failure lab explains (a restarted process steps once with the initial bucket layout).

Storage after the run, and the loss after the restart against the uninterrupted run
Directory under /shared/results/ry-t1BytesWhat it is
StepThis run (rank 0's global loss)Uninterrupted running exampleDifference

The uninterrupted reference is the root's recorded Ray run (src/data/runs/ray, same image, seed and world size).

Cost. Launch: the root's Launch lab measured a median 10.0 s from submit to first step on Ray Train, against 7.5 s on Slurm and 5.8 s on Kubernetes (5 runs each, image preloaded, laptop), mostly starting workers and importing torch. Recovery: about 6 to 7 s from crash to the new group's first step here, plus the steps redone. Memory: the controller (about 0.21 GB) and the driver (about 0.23 GB) live on the head.

Measured in the root's Failure and Launch labs (not repeated here)

With train.py writing its own checkpoints, the Failure lab ran: max_failures=0 and a rank crash: fit() raised WorkerGroupError after 1.27 s; max_failures=2: a new worker group resumed from step 100 10.15 s after the crash; a killed worker node: Ray waited for 4 fake_gpu with only 2 alive and resumed only when the node came back (93.6 s), because Ray Train does not shrink the group unless you configure elastic scaling. The Launch lab found that the worker-group start timeout (60 s, RAY_TRAIN_WORKER_GROUP_START_TIMEOUT_S) is retried forever when capacity never comes.

Check. The driver log shows the controller's decisions ("[FailurePolicy] RETRY ... Error count: 1 (max allowed: 1)", "Started training worker group of size 4" with every rank's node and pid); result.checkpoint and result.best_checkpoints are what the controller registered. A newest checkpoint on disk that get_checkpoint() did not return is this race.

Ray Serve: replicas are actors behind a proxy

Ray Serve runs online inference on a Ray cluster. A deployment is a class decorated with @serve.deployment; each copy of it is a replica, an actor. A controller actor ("a global actor unique to each Serve instance that manages the control plane") creates and replaces replicas; an HTTP proxy actor (by default "one HTTP proxy actor on the head node", port 8000) receives requests and routes them to replicas through a DeploymentHandle. Deployments call each other through handles, so a pipeline of models is one Python program (Ray Serve architecture).

Batching and LLMs. @serve.batch gathers concurrent calls into one list (defaults max_batch_size = 10, batch_wait_timeout_s = 0.01, python/ray/serve/batching.py lines 803 and 804). For LLMs, Ray Serve LLM wraps an engine ("Engine-agnostic backends such as vLLM and SGLang") behind LLMConfig and build_openai_app, an OpenAI-compatible app, with prefill-decode disaggregation, multi-LoRA and prefix-aware routing (Ray Serve LLM). What those mechanisms are is the serving topic's: vLLM and LLM serving in production own batching, routing and autoscaling as ideas. not run here: a Serve app on this cluster would show actor placement already measured above; on Kubernetes it runs as a RayService.

A request queues at the proxy only when every replica is at max_ongoing_requests

from the source Defaults at tag ray-2.59.0 (python/ray/serve/_private/constants.py lines 283 and 284, python/ray/serve/config.py lines 695 and 704, read 2026-10-24): each replica takes up to max_ongoing_requests = 5 at once; with autoscaling on, the controller aims for target_ongoing_requests = 2 per replica between min_replicas and max_replicas (both 1 by default), adding replicas after upscale_delay_s = 30 s of load and removing them after downscale_delay_s = 600 s. "When replica Actors fail, the Controller Actor replaces them with new ones."

Ray Tune, briefly

Tuner(trainable, param_space={...}, tune_config=TuneConfig(num_samples=N, scheduler=ASHAScheduler())) runs many trials, each an actor or a whole Ray Train run; a search algorithm proposes configurations (random, grid, Bayesian through Optuna and others) and a trial scheduler stops bad trials early (ASHA, successive halving) or mutates good ones (Population Based Training). Right for many small or medium trials on a shared cluster; one large pretraining run has nothing to tune in parallel (Ray Tune docs). not run here: a sweep would only repeat the task and actor mechanics above.

KubeRay: Ray on Kubernetes

In production a Ray cluster usually lives on Kubernetes through the KubeRay operator (v1.7.1, released 2026-09-21), which adds three custom resources:

  • RayCluster: a head pod and worker groups (pod template and replica range); with autoscaling, a Ray autoscaler sidecar asks for worker pods when tasks wait for resources and removes idle ones.
  • RayJob: a RayCluster plus an entrypoint (your driver), created for the job and deleted after. Kueue admits it as one workload, so team quotas and gang admission come from Kueue while Ray schedules inside.
  • RayService: a RayCluster running Ray Serve, with zero-downtime upgrades.

GPUs come from the Kubernetes device plugin as nvidia.com/gpu in the pod spec; Ray reads them as its GPU resource. Operators, device plugins and Kueue are taught on Kubernetes for ML; KubeRay docs. not run here: KubeRay plus a Ray cluster on the topic's kind cluster would add about 3 GB of containers to a laptop already near its budget; the root's Tool map lists KubeRay's status.

When Ray is the right layer

For training work (the root's Reading tab has the cluster-level comparison):

Your job looks likeGood fitWhy
One big SPMD training run (every rank runs the same program): pretraining, large SFTSlurm + torchrun, or Kubernetes + JobSet (launchers: Launching distributed training)No dynamic tasks to schedule; Ray Train adds a controller and a head to run and size, for a launcher you already have. It still works (it ran the running example here), and is convenient if the rest of your stack is Ray.
Many cooperating programs of different shapes: RL post-training (policy trainer, rollout engines, reward and reference models), agents with environmentsRay, usually on Kubernetes via KubeRayEach piece is an actor with its own resources; placement groups colocate or separate them; one Python driver orchestrates the loop. This is why the open RL stacks are built on it.
Heterogeneous data processing feeding training or batch inferenceRay DataStreaming between CPU and GPU stages with backpressure, on one cluster.
Online inference made of several models or stepsRay Serve (RayService on Kubernetes)Replicas are actors with their own resources; handles compose deployments in Python.
Hyperparameter sweeps of small and medium runsRay Tune, or a scheduler's job arraysTune adds early stopping and search; Slurm arrays are simpler if every trial is independent.

Who uses it. verl, the open version of ByteDance's HybridFlow (Sheng et al., arXiv 2409.19256, EuroSys 2025), uses Ray for its driver ("The centralized single controller is built on top of Ray", section 7) and argues for a "single controller" (one driver directing everything, Ray's model) over "multi-controller" SPMD inside each model's workers. OpenRLHF's README: "OpenRLHF leverages Ray for efficient distributed scheduling. It separates the Actor, Reward, Reference, and Critic models across different GPUs" (OpenRLHF on GitHub, read 2026-10-16). Ray joined the PyTorch Foundation on 2025-10-22. The RL algorithms are on RL for LLMs; DDP, FSDP2 and c10d on Distributed PyTorch.

Common mistakes, with the real messages

Every message below was printed on this cluster on 2026-10-16 (addresses scrubbed); the run that produced it is named.

ray.get inside the submission loop. The tasks run one at a time.
No error at all, just a slow program: eight 0.5 s tasks took 4.0 s instead of 1.1 s (ry_core.py tasks, the animation in Tasks). Submit everything, then ray.get the list, or use ray.wait to process results as they finish.
Writing into an array you got from ray.get.
ValueError: assignment destination is read-only
The array is a zero-copy view of the object store (ry_core.py objects). Copy it (a = a.copy()) if you need to modify it.
ray.put inside a task, then the task's node dies. The object is gone even if a copy exists elsewhere.
OwnerDiedError: Failed to retrieve object 00d7b3a94be6e983ffffffffffffffffffffffff0500000002e1f505. ...
The object's owner has exited. This is the Python worker that first created the ObjectRef via `.remote()` or `ray.put()`.
(ry_core.py lineage, object C.) Return values from tasks (the caller then owns them and lineage can rebuild them), or let a long-lived actor or the driver own data you cannot lose.
max_retries=0 on a task whose output you keep. A node loss makes the output unrecoverable.
ObjectReconstructionFailedError: ... [OBJECT_UNRECONSTRUCTABLE_RETRIES_DISABLED] The object cannot be reconstructed because the task was created with max_retries=0. Consider enabling retries using `@ray.remote(max_retries=N)`.
(ry_core.py lineage, object B.) Turning retries off is right for tasks with side effects; then do not depend on their outputs surviving.
Expecting retries to cover your exceptions. They do not, by default.
RayTaskError(ValueError): ray::raise_first() (pid=606, ip=<ip-1>)
  File "/shared/ry/ry_core.py", line 204, in raise_first
    raise ValueError("bad batch in shard 7")
ValueError: bad batch in shard 7
One attempt only; with retry_exceptions=True the same task ran twice and succeeded. A crashed worker process, by contrast, is retried ("Task crash_first failed. There are 3 retries remaining, so the task will be retried.").
Retrying a task that is not idempotent.
A retried task runs from the start. The test task here counted its attempts in a file: 2 after one crash. A task that appends to a database or uploads a file will do it twice; make the side effect idempotent (write to a unique name, then rename) or set max_retries=0.
Assuming an actor's state survives a restart.
With max_restarts=1, the counter at 3 came back as 1 after its process died, on another node, with a new pid. The in-flight call failed:
ActorUnavailableError: The actor ... is unavailable: The actor is temporarily unavailable: RpcError: RPC error: Socket closed rpc_code: 14. The task may or may not have been executed on the actor.
Without max_restarts:
ActorDiedError: The actor died unexpectedly before finishing this task.
Checkpoint actor state yourself if it matters.
A node near its memory limit. Ray's memory monitor kills workers before the kernel does.
Training failed due to controller error:
1 worker(s) were killed due to the node running low on memory. Memory on the node (IP: <ip-1>, ...) was 1.03GB used / 1.07GB limit (0.961193)
OOM kill reason: Memory usage 1104416768B exceeded threshold of 1095761920B (95.0% of 1153433600B limit)
(A Ray Train run on a worker where the spill test's IO workers were still resident, src/runs/core/train_oom.out.) Size nodes for the workers plus Ray's own processes; restart Ray after resizing a container (the threshold is fixed at raylet start, see Architecture).
A resource request no node can satisfy. It waits forever.
(autoscaler +3s) Error: No available node types can fulfill resource request defaultdict(<class 'float'>, {'CPU': 4.0, 'fake_gpu': 4.0}). Add suitable node types to this cluster to resolve this issue.
(The root's Scheduling lab, a STRICT_PACK group of 4 on nodes of 2.) The group stays PENDING; nothing fails. Put a timeout on pg.wait() and check ray status for "Pending Demands".
Trusting the newest checkpoint on disk.
After a crash Ray Train restored step 50 while a step-100 checkpoint directory sat in storage (Ray Train). Restore from what ray.train.get_checkpoint() returns, and treat other directories under the run's storage path as possibly incomplete or unregistered.
A multi-node Ray cluster on macOS or Windows.
Multi-node Ray clusters are not supported on Windows and OSX
(The topic's setup.) Use Linux nodes or containers; a single-node Ray on a Mac is fine for development.

Interview questions

Task or actor: how do you choose?
Task for stateless, retryable work that can run anywhere (map over data). Actor when state must persist between calls (a loaded model, a simulator, a buffer) or calls must be ordered. Actors hold their placement for their lifetime and lose state on restart.
What is an object's owner, and what happens when it dies?
The worker that created the ref (.remote() or ray.put). It holds the reference count, the copies' locations and the lineage. When it dies the object is lost (OwnerDiedError) even if copies exist; Ray cleans up the copies.
A node dies. Which objects come back?
Task outputs whose owner is alive and whose task is retryable: the owner re-runs the task (lineage reconstruction; measured here 31 s after the kill, most of it the 30 s needed to declare the node dead). Not: ray.put objects with no other copy, outputs of max_retries=0 tasks, objects owned by workers on the dead node. Small inline objects were never on that node.
How long until Ray notices a dead node, and what sets it?
The GCS health checks: period 3 s, timeout 10 s, 5 failures (ray_config_def.h lines 1060 to 1064). About 30 s here. A crashed worker process is noticed in under a second by its raylet.
Why is a placement group needed for distributed training?
All N workers must start together, or none: a partial group holds GPUs and waits forever (the gang problem). A placement group reserves all bundles atomically (two-phase commit in the GCS). PACK minimises nodes; STRICT_PACK insists on one node; SPREAD and STRICT_SPREAD spread for fault isolation.
How does Ray Train set up torch.distributed?
The controller creates a placement group, starts one worker actor per rank, picks rank 0's address and a free port, sets MASTER_ADDR, MASTER_PORT, RANK, WORLD_SIZE, LOCAL_RANK, and calls init_process_group with the TorchConfig backend (env://) before your loop runs. No torchrun.
A Ray Train job restarted from an older checkpoint than the newest one on disk. Why?
The controller registers a checkpoint only after collecting that report from every worker, by polling (every 2 s). A worker that dies after report but before the poll takes its report with it, so the latest checkpoint is never registered (measured: restart from 50 with 100 on disk, 3 of 3 runs). Shorter gap between checkpoints, or accept up to one interval more of lost work.
The head node keeps running out of memory. What lives there?
The GCS, the dashboard and its modules (most of the head's memory here), the autoscaler monitor, the driver, Ray Train's controller and anything scheduled on it. Give the head --num-cpus 0 so no tasks land there, enough memory for the driver and controller, and GCS fault tolerance so its loss is survivable.
Design: an RL post-training system for a 70B policy on 256 GPUs with vLLM rollouts.
Kubernetes with KubeRay (a RayJob per experiment) and Kueue for team quotas and gang admission of the whole RayCluster. Inside: one driver (single controller) running the loop; actor groups for the trainer (FSDP or Megatron workers, one placement group, STRICT_PACK per node for NVLink), vLLM engines (actors with their own placement groups), reward and reference models. Decide colocation: shared GPUs (hybrid engine, swap weights) saves GPUs, separate pools allow asynchronous rollouts. Move weights trainer to engines over NCCL, not the object store (too big); move prompts, rollouts and rewards through the object store (small). Checkpoint the trainer to object storage with DCP at an interval set by the failure rate; restart engines freely (stateless); GCS fault tolerance with Redis; watch the head's memory. Failure plan: a lost trainer node restarts the trainer group from checkpoint (Ray Train or your own), a lost engine is replaced and its prompts re-queued.
Design: a pipeline that decodes video on CPUs and embeds it on GPUs, feeding training.
Ray Data: read on CPU nodes, map_batches(decode) as CPU tasks, map_batches(Embedder, num_gpus=1, concurrency=N) as an actor pool on GPU nodes (different resources, so not fused), consumed by Ray Train workers with iter_torch_batches. Streaming keeps GPUs busy from the first blocks; backpressure bounds memory; size blocks (1 to 128 MiB) and pools so neither stage starves; spill to local NVMe.
Sources: Ray 2.59.0 source at tag ray-2.59.0 (commit dd83c3a703a5422d0b47f142cb380c6330817608), every quoted line listed with file and line in src/inputs/source_quotes.json; Ray documentation pages linked in place (read 2026-10-16); the Ownership (NSDI 2021), HybridFlow (EuroSys 2025) and Ray Data (arXiv 2501.12407) papers. Measurements: this page's runs on 2026-10-16 (src/runs/) and the root page's Scheduling, Launch and Failure labs, all on Apple M1 Pro, Docker Desktop VM, shared machine. The fake GPUs are a custom resource; nothing ran on a real GPU.