The Futureverse: one tweak to parallelize your R code

Futureverse · Session 1

1 Before the slides: what does “parallel” mean to you?

1.1 Class brainstorm

No slides, no spoilers: just you. In pairs, spend 4 minutes writing down everything you associate with parallelising R code. Don’t filter:

  • Have you ever made R use more than one core? How, and how did it go?
  • What stopped you — setup, exports, platform quirks, fear of breaking something?
  • Have you waited for a long loop thinking “why isn’t this using all my CPU?”

We’ll collect your answers on the board, group them, and the session builds from there.

1.2 Why are you here?

Henrik’s useR! 2026 tutorial opens with polls. Let’s steal them:

  • Which tools have you tried? mclapply(), parLapply(), foreach %dopar%, {mirai}, Futureverse… or none?
  • Where does your code run today? laptop, shared workstation, cloud, HPC cluster?
  • Why are you attending? make it faster, use more memory, keep an app responsive?

Keep your answer: every wall you just named has a name in this course.

1.3 This course at a glance

  • Session 1 · The Futureverse — futures and plan(), apply/map idioms, then the one-pipe trick: futurize() + progressify(); errors, RNG, and when parallelising does not help.
  • Session 2 · mirai, mori & mizu — the async engine {mirai}, the memory wall of parallel processes, and shared-memory {mori} / {mizu}.
  • Session 3 · Parallel data science — {purrr} & {tidymodels}: parallelism built into your pipelines (in_parallel(), parallel_over).

One thread runs through all three: your code keeps its shape — only where and how fast it runs changes.

1.4 The promise

Everything this course is about, in one line (Henrik, COMPUTE! 2026, Paris):

res <- lapply(patients, fit_model) |> futurize() |> progressify()

“From sequential to parallel in ~10 years… That’s it.” The code you already write gets parallel with one pipe and a live progress bar with another — and runs unchanged on your laptop, your lab’s workstation, or a Slurm cluster.

2 Why parallelize?

2.1 The seed idea: split the work

Say an analysis takes 2 minutes:

x <- 1:1e7
h <- function(x) sum(x, na.rm = TRUE)

## 1 process         2 min
y <- h(x)

## 2 processes       1 min
y <- h(x[1:5e6]) + h(x[5e6 + 1:5e6])

## 4 processes       30 s
y <- h(x[1:2.5e6]) + h(x[2.5e6 + 1:2.5e6]) +
     h(x[5e6 + 1:2.5e6]) + h(x[7.5e6 + 1:2.5e6])

The pieces of a sum can be computed in any order — that’s all parallelisation needs: independent parts. Nothing about the answer changes, only how many processes compute it.

2.2 The speed-up, drawn

1 worker · 2 min
sum(x)
split→
2 workers · 1 min
sum(x[1:5e6])
sum(x[5e6+1:5e6])
split→
4 workers · 30 s
1
2
3
4

Real tasks aren’t perfectly uniform (we’ll meet chunking for that). The principle stands: more independent workers, less wall-clock time.

2.3 Four good reasons

  1. Speed — finish in minutes instead of hours by using the cores you already have.
  2. Memory footprint — split a big computation across workers so each process holds less.
  3. Avoid transfers — move the computation to the data, not gigabytes to the computation.
  4. Async UI — keep an app (or your console) responsive while work is running.

2.4 When NOT to parallelize

Parallelising is not free — each task must be shipped to a worker. The common no-gos:

  • Tasks too small — if one iteration is microseconds, shipping overhead dominates. Rule of thumb: iterations worth at least ≈ 1 ms (we refine this in Session 3 with {purrr}’s rule).
  • Large data — if every worker needs a full copy of a huge object, copying beats computing. (This exact wall is Session 2’s problem: {mori} / {mizu}.)
  • Bottleneck isn’t CPU — I/O, network or memory latency won’t speed up with more cores.
  • Already vectorized — BLAS and many C-level functions already use all your cores.

Measure first. system.time() (or tictoc::tic/toc) before and after. Small tasks can be grouped — that’s chunking, later today.

3 Where can you parallelize?

3.1 The ladder: laptop → HPC

  1. Your laptop — 4–16 cores, already under your fingers.
  2. Shared workstation — your lab’s big machine; be nice to your colleagues.
  3. Cloud — rent machines on demand.
  4. HPC cluster — Slurm / SGE / TORQUE-PBS; thousands of cores.

The Futureverse’s promise: the same code runs on every rung. What changes is only where work goes — one function call: plan() (in a few minutes).

4 The built-in attempts

4.1 mclapply(): fork, and its limits

parallel::mclapply() is the tempting drop-in: “just” fork the process N ways.

  • Unix-only — Windows has no fork(), so mclapply() simply does not work there.
  • fork() copies the entire process — memory, connections, RNG — once per worker.
  • Forking from inside GUIs or apps is fragile; Simon Urbanek (author of parallel) has long warned that forked children inherit live state and can corrupt the parent.
  • One crashing child can take your whole R session with it.
options(mc.cores = 8)

res <- parallel::mclapply(xs, f)   # Unix only

mclapply() looks like a drop-in. But “works on my Mac, not my colleague’s Windows” is exactly the platform friction that made parallel code rare.

4.2 parLapply(): sockets, and chores

makeCluster() + parLapply() works everywhere — including Windows — at the price of choreography:

  • clusterEvalQ(cl, ...) to load packages on workers;
  • clusterExport(cl, "x") to ship data and functions;
  • stopCluster(cl) at the end.
  • Forget one export → “object not found” on workers that “works locally”.

This is the setup tax — and it kills readability for real analyses.

cl <- makeCluster(8)
clusterEvalQ(cl, library(future.apply))
clusterExport(cl, "fit_model")

res <- parLapply(cl, xs, fit_model)

stopCluster(cl)

4.3 The refactoring tax

COMPUTE! 2026 pictures pre-Futureverse parallelism:

res <- if (parallel) {
  if (.Platform$OS.type == "windows") {
    cl <- makeCluster(8)
    on.exit(stopCluster(cl))
    parLapply(cl, xs, fit)
  } else {
    options(mc.cores = 8L)
    mclapply(xs, fit)
  }
} else {
  lapply(xs, fit)
}

Every analysis that wanted both platforms paid this branching tax; code coverage only ever exercised one branch; every change to fit meant re-exporting and re-testing. The barrier was never the hardware — it was friction.

4.4 The community verdict

The Futureverse approach (“keep the code parallel and readable”) caught on:

  • +40% reverse dependencies every year — ~575 packages depend directly, ~1,300 recursively (boot, glmnet, lme4, mlr3, DESeq2…).
  • Top 0.6% of the most-downloaded R packages.
  • Niceties other parallelism does not give you: auto-exported globals, auto-relayed messages/warnings/errors, proper parallel RNG.

Then someone went further: “we can simplify it even more.” The rest of this session: futures — and then the one-pipe trick.

5 A Future is…

5.1 The oldest idea in this talk

Futures are from the 1970s (Friedman & Wise 1976/1977; also Hibbard 1976; Baker & Hewitt 1977): a future is a placeholder for a value that is being computed — possibly elsewhere.

The mental shift.

An ordinary expression is its value:

v <- sum(x)      # v IS the number

A future expression describes a value that arrives later:

f <- future(sum(x))   # f is a handle
v <- value(f)         # blocks until ready

A Future is: an object representing a value that will be available later — queryable (resolved(f)), awaitable (value(f)), and one per expression.

Today, “futures” in R means the {future} package. You write what to compute once; plan() decides how/where it runs.

5.2 Value vs future: side by side

  1. Sequential — v <- expr — evaluate now, block, get result.
  2. Future — f <- future(expr); v <- value(f) — start now, block later.
  3. Future-assignment — v %<-% expr — same, sugar-coated: “v will be expr”.
library(future)
plan(multisession)

a %<-% h(x[1:5])    # starts immediately
b %<-% h(x[6:10])   # runs in parallel
y  <- a + b         # waits for both

%<-% is called the future-assignment operator. Two lines of code, and parts of a sum run on different cores — the splitting we drew earlier, with zero manual choreography.

5.3 A Future is… (Henrik’s unpacking)

Questions the seminar’s futures answer:

  • Started? — yes, immediately upon creation (unlike some other languages’ lazy futures).
  • Finished? — resolved(f) is non-blocking; poll it any time.
  • Result? — value(f) blocks until ready, then returns it (and re-raises errors).
  • Same everywhere? — futures are backend-agnostic: plan() swaps the how/where, code stays identical.

In Session 2 you’ll meet {mirai}, which makes the same promise with a different engine — the concepts carry over, and that’s the point of building both futures and mirai into one course.

6 plan(): write once, run anywhere

6.1 The one function that changes everything

Separate WHAT (the developer’s future_lapply / %<-% code) from HOW/WHERE (the user’s plan()).

plan(sequential)                          # single process, default
plan(multisession, workers = 4)           # 4 local R processes
plan(multicore, workers = 4)              # fork — Unix only
plan(future.callr::callr, workers = 4)    # isolated, memory returned early
plan(cluster, workers = c("n1", "vm.cloud.org", "hpc.uni.edu"))
plan(batchtools_slurm, workers = 100)     # HPC scheduler

From the user’s menu to the laptop→HPC ladder from earlier: each rung is one plan(). The code above it never changes.

6.2 plan() as a menu

The user-facing table (from Henrik’s COMPUTE! 2026):

Backend Where Notes
sequential one machine default, debugging
multisession one machine parallel cores
mirai_multisession one machine powered by {mirai} (S2)
mizu_multisession one machine shared memory via {mizu} (S2)
cluster many machines SSH / explicit hosts
batchtools_slurm HPC Slurm / SGE / LSF / TORQUE schedulers

New array since 2026: mirai_multisession (low latency) and mizu_multisession (shared memory) — both covered hands-on in Session 2.

6.3 Sum of a vector, 4 ways

The same code, proving “write once”:

## sequential
res <- lapply(xs, slow_sqrt)

## parallel, same shape
res <- future_lapply(xs, slow_sqrt)          # future.apply

## future-assignment
a %<-% h(x[1:5]); b %<-% h(x[6:10])
y  <- a + b

## future-lapply is a drop-in
res <- furrr::future_map(xs, slow_sqrt)      # furrr

And then came the transpiler that removes even the future_ / future_map rename — the next two slides’ futurize().

6.4 Globals: exported for you

How do workers see fit_model and x? The Futureverse inspects your code’s AST (the abstract syntax tree) and finds free variables:

future_lapply(xs, fit_model)
# -> detects `fit_model` and `xs` as globals,
#    serialises and exports them automatically

{future} walks lobstr::ast() — here { → slow_sum → x — captures exactly the referenced objects, and ships them. Manual globals = c("fit_model","x") is still possible when the magic misses (loops, indexing).

7 Apply the same function over and over

7.1 They’re all the same

Henrik asks you to see these four as one idea:

## base R
ys <- lapply(xs, slow_sum)

## purrr
ys <- map(xs, slow_sum)

## plyr
ys <- llply(xs, slow_sum)

## foreach (NOT a for loop!)
ys <- foreach(x = xs) %do% slow_sum(x)

“Take-home: they’re all the same.” A loop that returns values — same shape, same result. That single insight is why one parallelisation can cover all four.

7.2 “Your turn”: draw an owl

Start sequential, end parallel — without changing the function:

xs <- 1:10

ys <- xs |> map(slow_sqrt)           # sequential today

ys <- xs |> parallel_map(slow_sqrt)  # parallel tomorrow

parallel_map() is buildable in two loops: fire all future()s, then collect all value()s. (Prefer value(fs) over lapply(fs, value) — it stops early on failure and cancels outstanding tasks.)

7.3 parallel_map(), by hand

The two loops that make up every parallel map:

parallel_map <- function(xs, f, ...) {
  fs <- lapply(xs, function(x) future(f(x), ...))  # fire all
  value(fs)                                        # collect all
}

## benchmark vs sequential
t_seq <- system.time(ys <- lapply(xs, slow_sqrt))
t_par <- system.time(ys <- parallel_map(xs, slow_sqrt))

This is the entire conceptual core of the Futureverse: futures + a map. Everything else in the ecosystem (future_lapply, future_map, %dofuture%, mirai_map, purrr::in_parallel()) is this function wearing different clothes.

7.4 foreach() is NOT a for loop

The classic trap:

## WRONG: %dopar% with a side effect
res <- foreach(i = seq_len(n)) %dopar% {
  res[i] <- f(xs[i])       # nobody sees this!
}
## RIGHT: collect the value
res <- foreach(i = seq_len(n),
               .combine = c) %dopar% f(xs[i])

Like lapply/map, foreach returns values — assignment inside the body vanishes. Same rule, parallel or not.

8 futuristic one-pipe: futurize()

8.1 The 2026 headline

Futureverse’s newest idea (since January 2026) — a transpiler that rewrites your pipe:

ys <- lapply(xs, slow_sqrt) |> futurize()

ys <- map(xs, slow_sqrt)      |> futurize()
ys <- foreach(x = xs) %do% slow_sum(x) |> futurize()
ys <- llply(xs, slow_sum)     |> futurize()
ys <- bplapply(xs, slow_sum)  |> futurize()

future.apply, furrr and doFuture “are now only used in the background” — you don’t call them anymore. Your existing code plus one pipe.

8.2 Under the hood: a transpiler

How can a pipe rewrite the call it receives? Lazy evaluation:

evil_eval <- function(expr) {
  expr <- substitute(expr)     # receive the CODE, not the result
  expr[[1]] <- as.name("-")    # swap + for -
  eval(expr, parent.frame())
}

evil_eval(1 + 2)   # 1 - 2 = -1

futurize() does the same swap: it receives lapply(xs, f), rewrites the root symbol to future_lapply, and executes the parallel version. futurize(eval = FALSE) shows you the generated call instead.

8.3 What the transpiler generates

futurize(eval = FALSE) is inspectable:

lapply(xs, slow_sqrt) |> futurize(eval = FALSE)
# future.apply::future_lapply(
#   xs, slow_sqrt,
#   future.seed = FALSE,
#   future.globals = TRUE,
#   future.stdout = TRUE,
#   future.conditions = "condition",
#   future.scheduling = 1,
#   future.label = "fz:base::lapply-%d"
# )

Same for map → future_map, boot → makeClusterFuture + boot(parallel = "snow"). Teaching aid, debugging aid — and your insurance that you stay in control.

8.4 Futures can be resolved anywhere

The same |> futurize() line, five backends:

plan(sequential)                                  # debug
plan(multisession, workers = 4)                   # local cores
plan(future.mirai::mirai_multisession, workers = 4) # low latency (S2)
plan(future.callr::callr, workers = 4)            # memory returns early
plan(cluster, workers = c("m1","m2","server.uni.edu"))
plan(batchtools_slurm, workers = 100)             # HPC

Write once, run anywhere — the pitch slide of the Futureverse. Sessions 2–3 will put mirai_multisession, mizu_multisession, in_parallel() and parallel_over in that same slot.

9 progressify(): watch it work

9.1 The other new pipe

Since January 2026, progress bars join the same pipeline:

library(progressify)

## must be enabled once, per session
handlers(global = TRUE)

ys <- lapply(xs, slow_sqrt) |> progressify()

## ...and together with parallelisation
ys <- lapply(xs, slow_sqrt) |> progressify() |> futurize()

progressify() = progressr + sensible defaults. On the cluster it shows near-live progress — because futures relay condition messages as they go.

9.2 The handlers menu

  • default — utils::txtProgressBar (=>>), erased on completion.
  • cli — ■■■ 80% | ETA: 1s, live-updating.
  • cli + beepr — same bar, plus a sound when done.
  • tutorial — keeps output for copy-pasting notes.
  • tutorial + newline — keeps every update: [0s] 0% … [5s] 100%.

Per-session: handlers(global = TRUE) once. Demo live (30s): 10 slow sqrts, cli handler, then tutorial+newline, then + beepr if you like audio.

9.3 Same call, plus one pipe — on the cluster

COMPUTE! 2026’s demo went from ETA 12m → 23s once parallelised:

handlers("cli", global = TRUE)
plan(cluster, workers = c("m1","m2","m3","server.uni.edu"))

ys <- lapply(xs, slow_sqrt) |> progressify() |> futurize()

Progress across workers: one bar for the whole job, updated as futures resolve. That’s messages-relaying (next section) doing real work in the UI.

10 Messages, warnings, errors

10.1 Business as usual — in parallel

Henrik’s g() throws all three at once:

g <- function(x) {
  message("x = ", x)
  if (x < 0) stop("x must be non-negative: ", x)
  if (x > 10) warning("large x: ", x)
  x
}

ys <- map_dbl(c(1, 2, -3, 4), g)   # sequential: error on -3
ys <- map_dbl(c(1, 2, -3, 4), g) |> futurize()   # SAME: error on -3

Parallel map_dbl terminates identically on the first bad input; messages (x = 1, x = 2…) and warnings (NaNs produced) are relayed to your console in order. With mclapply/parLapply/doParallel, output is muffled or lost.

10.2 Relayed, not swallowed

  1. Futureverse — messages/warnings/errors relayed as they happen, in order.
  2. mclapply / parLapply / doParallel — output muffled or lost; errors opaque.
  3. That’s the difference — parallel code that still talks to you; debugging doesn’t stop at plan().

Under the hood this is future.conditions marshalling — the topic of the course FAQ.

10.3 Errors that matter, RNG that’s reproducible

## proper parallel RNG
ys <- lapply(xs, slow_sqrt) |> futurize(seed = TRUE)
#  L'Ecuyer-CMRG: reproducible STREAMS per worker

## without it, you get a warning
#  UNRELIABLE VALUE: Future(...) unexpectedly generated random numbers
#  without specifying argument 'seed'

future.seed = TRUE gives each task its own reproducible stream — the parallel analogue of set.seed(). Parallel simulation (bootstrap, CV, MCMC…) needs it to be trustworthy.

11 When parallelization does NOT help (recap)

11.1 The three walls

  • Small tasks — overhead dominates (ship + start + collect). Fix: chunking (Session 2 lab meets mirai_map, Session 3 in_parallel()).
  • Big shared data — every worker copies it (Session 2: {mori}, {mizu}).
  • Non-CPU bottleneck — I/O, network, memory bandwidth: more cores ≠ faster.

And one more, from the tutorial: already-vectorized code — BLAS-backed C loops already use all cores.

11.2 The fix when tasks are tiny: chunking

Group elements so each worker does more per trip (diagram = 4 workers, 8 tasks):

chunk.size = 1 (8 trips)
1
2
3
4
5
6
7
8
fewer trips→
chunk.size = 2 (4 trips)
1,2
3,4
5,6
7,8

future.scheduling / future.chunk.size tune this. Uniform tasks → larger chunks; variable tasks → smaller chunks keeps the pipe full.

12 Non-exportable references

12.1 Objects that can’t travel

Some R objects cannot be serialised to another process:

  • DBI connections — a live database handle lives in this process.
  • External pointers — xgboost, torch, keras, Rcpp objects.
  • reticulate Python sessions.
## catch it early
options(future.globals.onReference = "error")

## fix: create the resource ON the worker
future_lapply(files, function(path) {
  con <- DBI::dbConnect(RSQLite::SQLite(), path)   # per worker
  on.exit(DBI::dbDisconnect(con))
  DBI::dbGetQuery(con, "SELECT * FROM t")
})

future.globals.onReference = "error" turns the silent failure (weird behaviour in workers) into an immediate, named error. The recipe: build the connection inside the task.

13 Domain packages: your code, one pipe

13.1 Bootstraps, fits, cross-validation

The whole point: your existing call, unchanged, plus one pipe:

## boot
b <- boot::boot(data, statistic = fit_glm, R = 1000) |>
     progressify() |> futurize()

## glmnet / caret / mgcv / lme4…
cv <- glmnet::cv.glmnet(x, y) |> futurize()
tr <- caret::train(...)        |> futurize()
b  <- mgcv::bam(...)           |> futurize()
mb <- lme4::bootMer(...)       |> futurize()

~30 packages on CRAN — boot, caret, glmnet, lme4, mgcv, mlr3, DESeq2… — plus Bioconductor’s BiocParallel family. “Your existing call, plus one pipe.”

13.2 Bootstrap, 100,000 resamples

COMPUTE! 2026’s demo: R = 100e3, then:

b <- boot::boot(data, statistic = fit_glm, R = 100e3) |>
     futurize()

## sequential: hours   32 workers: minutes
## results: IDENTICAL

Identical because futures with seed = TRUE use reproducible per-worker RNG and relay results faithfully — parallel changes time, not answers.

14 Under the hood & the road ahead

14.1 Nested parallelization — with care

Futures inside futures work, but multiply processes multiplicatively:

## sequential    4 workers        nested 5×3
##    10s            2.8s          (over-parallelized)

Use one level of parallelism in production; reserve nesting for when inner tasks are heavy. (Session 3: tune’s two strategies are exactly about where to put the parallelism.)

14.2 Roadmap: the Futureverse is still moving

From Henrik’s 2026 decks:

  • Shared memory by default (via {mori}) — “same machine only” today, but aiming for fully automatic; existing code improves for free.
  • Declarative Resource API ys <- lapply(xs, fit) |> resources(memory = 2*GiB, gpu = TRUE, time = 5*hours) |> futurize().
  • Fail fast — “Cannot meet resources(memory = 8 GiB): this R session has only 4 GiB”; auto-select workers (“6 of 32 cores = 48 GiB fits in 50 GiB”).
  • Intent-based computing — |> resources(by = "08:00", budget = 25*USD).

Resources lets the maintainer declare resources(fit_model) <- resources(memory = 1.5 * size_of(patient)) once — and every user inherits it. Sessions 2–3 are the rest of this roadmap: {mirai}, {mori}, {mizu}, and pipeline-native parallelism.

14.3 What you can do now

Take-home cheat sheet (also in the lab and the FAQ):

  1. Choose the backend: plan(multisession) (or sequential to debug).
  2. Parallelise: just add a pipe — |> futurize().
  3. Watch it: |> progressify(); make it reproducible: futurize(seed = TRUE).
  4. Remember the building blocks: future() / value() / %<-%.

Next, the lab: you’ll build parallel_map(), watch futurize() transpile, and race 2/4/6/8 workers with progressify running. Then in Session 2, we ask “how does this actually move data?” — and meet mirai, mori and mizu.