---
title: Rules for lunas
description: Nine rules that keep an app on Luna correct as it grows, each with the way that breaks and the way that holds.
related:
  - /concepts/the-life-of-a-luna
  - /lunas/write-handlers
  - /lunas/call-another-luna
---

These rules come from how a luna runs: one thread, memory that does not survive sleep, and writes that commit with the handler. Each shows the way that breaks first, then the way that holds.

## Give each owner of data its own luna

Each luna runs its handlers on one thread. A single luna that holds every list takes one call at a time for all of them, and keeps every list's rows in one database.

This puts every list in one luna:

```ts luna/lunas/shop.ts
await ctx.call(Lists, { id: "all" }).add({ list: "groceries", text: "milk" });
```

This gives each list its own luna, so lists run side by side:

```ts luna/lunas/shop.ts
await ctx.call(List, { id: "groceries" }).add({ text: "milk" });
```

## Keep state in tables

Memory does not survive sleep, and a luna sleeps after 30 seconds without calls by default. A variable in your module may be empty on the next call.

This keeps the items in a variable, and loses them:

```ts luna/lunas/list.ts
const items: string[] = [];

add: h({ args: { text: t.string() } }, (ctx, { text }) => {
  items.push(text);
}),
```

This keeps them in the luna's table:

```ts luna/lunas/list.ts
add: h({ args: { text: t.string() } }, (ctx, { text }) => {
  ctx.db.items.insert({ text });
}),
```

## Take only the args you need from a handler's input

A handler's input holds the luna's key fields as well as its args. Passing the whole input to `insert` writes the key fields too, and the insert throws on a field the table has no column for.

This fails on a `Card`, with `notes has no column board`:

```ts luna/lunas/card.ts
add: h({ args: { text: t.string() } }, (ctx, input) => {
  ctx.db.notes.insert(input);
}),
```

This names the args it writes:

```ts luna/lunas/card.ts
add: h({ args: { text: t.string() } }, (ctx, { text }) => {
  ctx.db.notes.insert({ text });
}),
```

## Mark every read as a query

An app can watch only a handler with `query: true`, and a query that tries to write fails. A read without it cannot be watched, and nothing stops it from writing later.

This read cannot be watched:

```ts luna/lunas/list.ts
all: h({}, (ctx) => ctx.db.items.find({ orderBy: "id" })),
```

This one can, and stays read only:

```ts luna/lunas/list.ts
all: h({ query: true }, (ctx) => ctx.db.items.find({ orderBy: "id" })),
```

## Send a message when you do not need the answer

A call ties your handler to the luna it calls. When that call fails, your handler fails, and its writes roll back. A message is stored with your writes, and a message that fails is tried again, up to 10 times by default.

This refund fails whenever the wallet does:

```ts luna/lunas/shop.ts
refund: h({ args: { amount: t.int() } }, async (ctx, { amount }) => {
  await ctx.call(Wallet, { id: ctx.key.id }).credit({ amount });
}),
```

This refund commits at once, and the credit reaches the wallet when it answers:

```ts luna/lunas/shop.ts
refund: h({ args: { amount: t.int() } }, (ctx, { amount }) => {
  ctx.send(Wallet, { id: ctx.key.id }).credit({ amount });
}),
```

## Do outside work in durable steps

A message that fails is tried again from the start, and Luna takes back the writes of the failed try. It cannot take back a request your code sent to another service.

This handler takes messages. When shipping fails, the next try sends the receipt again:

```ts luna/lunas/shop.ts
fulfil: h({ args: { amount: t.int() } }, async (ctx, { amount }) => {
  const order = String(amount);
  await fetch("https://mail.example.com/receipts", { method: "POST", body: order });
  await fetch("https://ship.example.com/orders", { method: "POST", body: order });
}),
```

This records each step once it finishes, so a run that starts again skips the receipt:

```ts luna/lunas/shop.ts
fulfil: h({ args: { amount: t.int() }, durable: true }, async (ctx, { amount }) => {
  const order = String(amount);
  for (const url of ["https://mail.example.com/receipts", "https://ship.example.com/orders"]) {
    await ctx.step(url, async () => {
      await fetch(url, { method: "POST", body: order });
    });
  }
}),
```

[Run durable work](/background/run-durable-work) covers steps and their retries.

## Read across lunas with an index

Each call wakes the luna it names. A loop of calls over many lunas wakes every one of them, and takes as long as all of them together.

This wakes every card on the board:

```ts luna/lunas/board.ts
for (const card of cards) {
  found.push(...(await ctx.call(Card, { board: ctx.key.id, card }).tasksFor({ user })));
}
```

This reads one index that Luna keeps filled from every card's rows:

```ts luna/lunas/board.ts
const found = await ctx.index(BoardTasks).find({ partition: ctx.key.id, where: { assignee: user } });
```

[Query across lunas](/data/query-across-lunas) shows how to define the index.

## Give each retried call an idempotency key

A call that times out may still have run. Calling again without a key can charge a wallet twice.

This charges again on every retry:

```ts luna/lunas/shop.ts
await ctx.call(Wallet, { id: ctx.key.id }).charge({ amount });
```

This returns the first call's result to any retry with the same key:

```ts luna/lunas/shop.ts
await ctx.call(Wallet, { id: ctx.key.id }).charge({ amount }, { idempotencyKey: `order-${orderId}` });
```

## Write onMigrate so a second run changes nothing

`onMigrate` runs each time a luna moves to a new version, not only after the deploy that added it. A hook that rewrites every row undoes your app's changes on each deploy.

This resets every quantity on each deploy:

```ts luna/lunas/list.ts
onMigrate: (ctx) => {
  ctx.exec("UPDATE items SET qty = 1");
},
```

This fills in only the rows that have no quantity yet:

```ts luna/lunas/list.ts
onMigrate: (ctx) => {
  ctx.exec("UPDATE items SET qty = 1 WHERE qty IS NULL");
},
```

[Change a schema](/data/change-a-schema) covers the rest of a migration.

## The rule of thumb

Give each thing its own luna, keep what matters in its tables, and let Luna carry what must outlast a failure. You then write no locks, no queues and no retry loops of your own.
