10.1 Serialization

IPCSTATUS: STABLELEVEL: INTERMEDIATEREVIEWED: 2026-11-18

10.1.1 Motivation

When two R processes exchange data, a pointer to memory in process A has no meaning in process B. Serialization solves this by converting an object graph into a byte sequence. Deserialization rebuilds the object on the receiving side. This byte stream can travel across a socket, a pipe, or any communication channel.

Process-based parallelism forces this cost. Process boundaries create isolated address spaces. Threads in the same process share memory. Processes do not by default, so data sent between them as messages must become bytes and back. The exceptions are a shared mapping and memory a child inherits through fork.

10.1.2 The problem

Consider a simple function call across a process boundary.

worker_process <- function(x) {
  x + 1
}

# The main process calls it with data
result <- call_remote(worker_process, 42)

The main process must send two things to the worker: the function worker_process and its argument 42. The worker must send back a result. All three are R objects. None can cross the process boundary as pointers.

What must happen at each step:

  1. The main process walks the object graph for both the function and the argument.
  2. It converts everything it finds to bytes.
  3. Those bytes travel to the worker.
  4. The worker converts bytes back to live R objects.
  5. The worker executes the function.
  6. The worker converts the result to bytes.
  7. Those bytes travel back.
  8. The main process rebuilds the result.

Each of these steps has a cost.

10.1.3 Mental model: what lives in bytes and what lives in memory

Serialization turns objects into bytes, and deserialization turns them back. The constraint that shapes everything else is that the byte stream has to stand on its own. It cannot point at memory in the process that wrote it, because the process that reads it has no access to that memory and often is not running yet.

When an R object lives in process memory, the runtime uses pointers to navigate it. A SEXP pointing to a cons cell points to an actual memory address. That SEXP becomes useless the moment the object moves to another process.

A byte stream has no pointers. It contains only values. Deserialization reads those bytes sequentially and reconstructs the graph by allocating new memory and establishing new pointers.

Both directions require traversal: serialization walks the live graph and writes it down. Deserialization reads the bytes and rebuilds the graph. Both allocate memory on their respective sides.

10.1.4 R’s serialization format

serialize() and unserialize() use R’s own serialization format, in one of three encodings: XDR binary (the default), binary in the machine’s native byte order (xdr = FALSE), or ASCII text (ascii = TRUE).

flowchart LR
  objgraph["object graph<br/>(pointers)"] -->|"serialize()<br/>walks the graph"| bytes["byte stream<br/>(no pointers)"]
  bytes -->|"socket or pipe, then<br/>unserialize() rebuilds"| objgraph2["object graph<br/>(new copy)"]

Serialization pipeline: object graphs cross process boundaries as bytes, requiring allocation and full copying on each side.

# Serialize an object to bytes
bytes <- serialize(list(a = 1, b = "hello"), NULL)

# Deserialize it back
obj <- unserialize(bytes)

The stream describes itself. A short header names the encoding, the format version, the R version that wrote it and the oldest R version that can read it, and from version 3 on the native character encoding. Each object follows as a flags word holding its type, then its length, then its data. Version 3 has been the default since R 3.6.0; what it added over version 2 is custom serialization of ALTREP objects and the encoding record. In the XDR encoding (External Data Representation), integers and doubles are written big-endian, so a stream written on one platform reads on any other. The serialize() help page notes that xdr = FALSE avoids the byte swapping between little-endian machines and can be up to 3x faster.

saveRDS() and readRDS() write and read the same stream as a file, compressed with gzip by default, or with bzip2, xz or zstd.

10.1.5 Serialization costs

Five factors accumulate to make R serialization costly in process-based parallelism.

The walk covers everything reachable. Serialization visits every list element, every attribute and every environment it can reach from the object. It keeps a hash table of the reference objects it has already written (environments, symbols, external pointers), so an environment shared by two closures goes out once and its second appearance becomes a back-reference. That table, and the output buffer when the target is a raw vector, are allocations on top of the object itself.

Attributes ride along. Any R object can carry attributes: names, class, dim, dimnames, and custom ones. When you serialize a vector, you serialize its attributes too, which is why the named vector below takes 115 bytes against 55 for the same values without names. Serialization writes every attribute, since it has no way to know which ones the receiver needs.

Environments drag their parent chains. An environment holds a frame of bindings and a pointer to its parent. Serializing an environment writes its parent first and then its frame, and each parent does the same, all the way up the chain. The walk stops at the global environment, the base environment, a package namespace or an attached package, which R writes as a marker or a name in place of their contents. Every ordinary environment in between goes out in full, so a small function defined in a small environment can bring a large amount of data along.

Closures drag their environments. A closure is a function with captured variables. The captured variables live in the closure’s environment. When you serialize a closure, you serialize its environment. That environment has a parent chain. Serialization follows the chain. A closure defined deep inside another function can capture the entire outer scope. Send that closure to a worker, and you send everything it can see.

Each transfer ends in a full copy. The worker allocates new memory for every object it rebuilds, so the data now exists on both heaps, and the result makes the same trip in reverse. Where the bytes wait in between depends on the target. serialize(x, NULL) builds the whole stream in memory before returning it. Serializing to a connection, as the parallel package’s socket clusters do, writes the bytes out in pieces as they are produced, so the sender never holds the complete stream.

Here is a concrete example.

# A simple vector
v <- c(1, 2, 3)
object.size(v)            # 80 bytes in memory, for 24 bytes of doubles

bytes <- serialize(v, NULL)
length(bytes)             # 55 bytes on the wire, with headers and type info

# A named vector
v_named <- c(a = 1, b = 2, c = 3)
object.size(v_named)      # 440 bytes: the names are a character vector of their own

bytes_named <- serialize(v_named, NULL)
length(bytes_named)       # 115 bytes

10.1.6 A closure that drags its context

Consider this function that generates a closure.

make_adder <- function(threshold) {
  # This vector will be captured by the closure
  lookup_table <- rnorm(10000)

  function(x) {
    if (x > threshold) x + mean(lookup_table) else x
  }
}

adder <- make_adder(5)

When you serialize adder to send it to a worker, serialization must include:

flowchart TD
  ser["serialize(adder)"] -->|writes| clo["closure: adder"]
  clo -->|environment| e1["frame of make_adder:<br/>threshold, lookup_table"]
  e1 -->|binding| big["lookup_table:<br/>10,000 doubles, ~80 KB"]
  e1 -.->|parent, written<br/>as a reference| ge["global environment"]

Serializing the closure writes its whole enclosing frame, every binding in it whether used or not. The chain stops at the global environment, which goes out as a reference.

  1. The closure itself: its formals and its body.
  2. The closure’s environment (containing threshold and lookup_table).
  3. That environment’s parent. make_adder was defined at top level, so the parent is the global environment, which goes out as a marker and not as its contents.

length(serialize(adder, NULL)) comes to about 80 KB, nearly all of it lookup_table. The 10,000 doubles travel with the function, although the closure only ever uses their mean. The worker receives it. If the closure runs a million times on the worker, the vector stays in worker memory the entire time. You paid the serialization cost once but the memory cost continuously.

10.1.7 Special cases

Namespaces and the global environment. R does not serialize the contents of a namespace, an attached package or the global environment. A function from a package still goes out with its formals and body; only its environment, the package namespace, is replaced by the namespace’s name and version. That is why serialize(stats::sd, NULL) is about 1.5 KB and not the size of the stats namespace. On the receiving side, unserialize() looks the namespace up and loads it if it is not loaded yet, so the package must be installed on the worker. If it cannot be loaded, R puts the global environment in its place, and it does not always warn, so a function sent to a worker can end up with the global environment without a message.

A PSOCK cluster from the parallel package sends every call and every result through serialize() on its socket connection, and the other side reads it with unserialize(). A closure goes with its environment chain, and any namespace in that chain goes by name.

ALTREP objects. Some R objects use an alternate representation (ALTREP) in memory. A sequence made with : is one: 1:1000000 stores its length, start and step, not a million integers. Format version 3 lets an ALTREP class write that compact state in place of the elements, so serialize(1:1e6, NULL) is 133 bytes, against 4,000,022 bytes with version = 2. The receiver rebuilds the compact form. Each ALTREP class decides this through its own serialization method, and a class that does not supply one is written out as an ordinary vector, every element included.

10.1.8 Where this cost bites

Every round trip in a parallel session pays three costs: serialization, transport, and deserialization.

parLapply() splits its input into one chunk per worker by default and sends each chunk, with the function, as one serialized call; each worker sends back one serialized result. With 32 workers and 1,000 elements that is 32 round trips, and the function, with everything its environment chain reaches, is serialized 32 times. clusterApply(), and parLapplyLB() with chunk.size = 1, make one round trip per element instead. When the function captures a large environment, serialization can take longer than the computation.

The future package’s multisession and cluster backends and mirai’s daemons work the same way: the expression and the values it needs are serialized and sent to the worker, and the result comes back as serialized bytes.

sunlight changes what each worker has to load, not what each task has to send.

sunlight loads the declared packages once in a template process and forks workers from it, so a worker starts with every package namespace already in memory. Tasks still travel as serialized bytes: pmap() serializes the function and its arguments into each chunk it dispatches, with xdr = FALSE. A package function in that payload costs little, since its namespace goes by name and the worker already has it loaded. Objects that hatch(setup = ) creates in the template reach every worker through the fork, with no transfer.

10.1.9 Alternatives and tradeoffs

Several alternatives exist. Each trades off generality for speed.

qs2. The qs2 package by Travers Ching, the successor to qs (which CRAN archived in January 2026), saves and loads R objects faster and smaller than saveRDS(). Its qs2 format runs R’s own serializer through the C API and wraps it in zstd compression, multithreaded if you ask for it, and faster I/O. Its qdata format has a serializer of its own, but only for data: vectors, lists, data frames and matrices, with functions and environments replaced by NULL. The qs2 format therefore still walks the graph, includes attributes and carries environments. It is faster, not free. Use it when serialization is the bottleneck and you cannot change the architecture.

Apache Arrow. Arrow is a columnar binary format for typed tables and arrays, nested structs and lists included. A data frame with 1,000,000 rows and 50 columns can be sent as Arrow IPC bytes, and the reader can use each column’s buffer where it lies in the received bytes or in a memory-mapped file, without decoding it. Turning those columns into R vectors is a separate step, which the arrow package delays with ALTREP vectors where it can. Arrow cannot represent closures, environments or arbitrary R objects. Use it when you are moving data, not code or complex objects.

Shared memory without serialization. The other way to avoid serialization is to not move bytes at all. Shared memory lets several processes map the same region. One process writes data there and another reads it without copying or deserializing. Two problems limit this approach. The first is addresses: each process can map the region at a different address, so a pointer stored inside it is valid only in the process that wrote it. The second is lifetime: if one process frees an object in the region while another is still reading it, the reader crashes. Shared memory needs explicit lifetime coordination.

Buffer ownership transfer. Some systems move data by transferring ownership of a buffer from one process to another. This is possible with memory-mapped files or in microkernel architectures. R cannot do this portably. It requires OS-specific mechanisms.

10.1.10 Comparison: when to use each approach

Workload Method Pros Cons
General R code, any objects serialize() Handles nearly any R object, portable Slow, copies data twice
Saving or sending R objects qs2 Faster and smaller than saveRDS() Still walks the whole graph, copies data
Numeric data tables, large Apache Arrow Zero-copy reads, very fast Not suitable for functions, custom objects, or code
Same packages on every worker sunlight (fork template) Packages already loaded in every worker Tasks still serialized; POSIX only (fork)
Workers in one process threaded-r (THREAD cluster) No worker processes; bytes move in memory, not over sockets Still serializes each value; needs the threaded-r build of R

10.1.11 Serialization as an architecture signal

A high serialization cost often points to a boundary in the wrong place.

When serialization dominates your runtime, ask: what am I serializing repeatedly? If you serialize the same function a million times, move it closer. If you serialize large data repeatedly, consider whether the consumer must live on the same process where data is generated. If you serialize environments and closures, ask whether you can partition your computation differently.

In a multi-interpreter runtime, work that fits in one interpreter should stay there. If a function and its data serialize to hundreds of kilobytes and run a thousand times, sending them once and keeping them on one interpreter would avoid most of that cost. Threads that shared one heap could skip serialization entirely, but that moves the problem from IPC bandwidth to synchronization: concurrent access to the shared heap must not race.

threaded-r runs several interpreters in one process, each with its own heap, garbage collector and symbol table. Its channels still move values with serialize() and unserialize(), through memory instead of a socket, so a value crosses between interpreters as bytes even though it never leaves the address space. Whether a direct copy from one heap to another could replace that step, and how much it would save, is open.

Can a direct deep copy between interpreter heaps in one address space replace serialized bytes as the transfer mechanism in a multi-interpreter R? The copy still has to walk the object graph and rebuild every pointer, so the saving is the encoding and decoding, not the walk. Which one wins depends on object size and on the workload: which object types it moves, how often it sends closures, and how deep their environment chains go.

Further reading

Where this appears

  • sunlight sunlight’s template process loads the packages once and then forks the workers, so no worker loads them again. Tasks still reach workers as serialized bytes.
  • threaded-r threaded-r’s interpreters share one process but not a heap, so its channels still move values with serialize() and unserialize().

Where to go next

Back to top