---
title: Use more threads
description: Hand a luna's data to worker threads with ctx.thread and attach, for work that needs more than one core.
---

A luna runs its handlers on one thread. Work that needs more cores, such as heavy computing over a luna's rows, can run on worker threads that read and write the same luna.

## Hand the luna to a thread

`ctx.thread()` returns a handle, a plain string you pass to a worker thread. In the thread, `attach` turns the handle back into the luna's data.

```ts luna/lunas/report.ts
import { Worker, isMainThread, workerData, parentPort } from "node:worker_threads";
import { attach, defineLuna, t, table } from "luna";

export const Report = defineLuna({
  name: "Report",
  key: { id: t.string() },
  schema: { totals: table({ id: t.id(), part: t.int(), sum: t.float() }) },
  handlers: (h) => ({
    build: h({ args: { parts: t.int() } }, async (ctx, { parts }) => {
      const handle = ctx.thread();
      await Promise.all(
        Array.from({ length: parts }, (_, part) => new Promise((done, fail) => {
          const w = new Worker(new URL(import.meta.url), { workerData: { handle, part } });
          w.once("message", done);
          w.once("error", fail);
        })),
      );
      return ctx.db.totals.count();
    }),
  }),
});

if (!isMainThread) {
  const report = attach(Report, workerData.handle);
  report.db.totals.insert({ part: workerData.part, sum: Math.random() });
  parentPort?.postMessage("done");
}
```

## What a thread can do

An attached luna has the luna's tables and nothing else.

| Member | Does |
| --- | --- |
| `db` | The luna's tables, with the same methods as `ctx.db` |
| `exec(sql, params)` | Runs one SQL statement |
| `sql` | Runs SQL written as a template string |
| `transaction(fn)` | Runs several reads and writes as one |

A thread cannot call other lunas, send messages or fail the call. Do that in the handler, once the threads finish.

## Reads and writes from threads

Threads read in parallel, each from the luna's latest stored data. A write from a thread is stored before it returns, and the same thread sees it on its next read.

## Write several rows as one

`transaction` runs a function whose reads and writes are kept together. If another write changed what the function read, it runs the function again.

```ts luna/lunas/report.ts
report.transaction(() => {
  const row = report.db.totals.first({ where: { part: 0 } });
  report.db.totals.update({ where: { part: 0 }, set: { sum: (row?.sum ?? 0) + 1 } });
});
```

The function must be synchronous and do nothing but read and write the luna, because it may run more than once. If it throws, none of its writes are kept.

:::note
`attach` works only on another thread. On the luna's own thread, it throws.
:::

## Next steps

- [The life of a luna](/concepts/the-life-of-a-luna) explains the luna's own thread.
- [Write handlers](/lunas/write-handlers) for work that fits on one thread.
