---
title: Optimistic locking
description: "Stop two saves of one record from overwriting each other."
seo:
  description: "Optimistic locking in Active Record: a lock_version column checked by every save, destroy, and touch, StaleRecord for a stale copy, version fields in forms, and retrying with reload."
---

## At a glance

| To                                     | Write                                                   |
| -------------------------------------- | ------------------------------------------------------- |
| turn locking on                        | a `lock_version INTEGER NOT NULL DEFAULT 0` column      |
| catch a save from a stale copy         | `catch (error) { if (error instanceof StaleRecord) … }` |
| catch an edit made since a form loaded | `article.assign({ lockVersion: Number(form.get(…)) })`  |
| try again with the row’s values        | `await article.reload()`, then make the change again    |
| write without checking the version     | `article.updateColumns({ … })`                          |

## The Model

The examples use this Model, whose attributes come from its table through the schema `active-record schema` generates:

```ts article.ts
import { ApplicationRecord } from "./application-record";

export class Article extends ApplicationRecord {} // its lockVersion turns locking on
```

```ts schema.ts
// Generated by `active-record schema` from migrations/ — don't edit.
// schema: 8e9f2af487ba

import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";

/** articles — last changed by 0001_create_articles.sql */
export const articles = {
  id: { type: "string", null: false, generateId: true },
  title: { type: "string", null: false },
  body: "string",
  lockVersion: { type: "integer", null: false, default: () => 0 },
  updatedAt: "datetime",
} as const;

/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
export const schema = defineSchema({
  adapter: d1({ binding: "DB" }),
  tables: {
    articles: { attributes: articles, primaryKey: "id" },
  },
  models: { Article: "articles" },
});

declare module "../models/article" {
  interface Article extends TableAttributes<typeof articles, (typeof Article)["attributes"]> {}
}
```

```sql D1
CREATE TABLE articles (
  id TEXT PRIMARY KEY NOT NULL,
  title TEXT NOT NULL,
  body TEXT,
  lock_version INTEGER NOT NULL DEFAULT 0,
  updated_at DATETIME
);
```

```sql Postgres
CREATE TABLE articles (
  id UUID PRIMARY KEY,
  title TEXT NOT NULL,
  body TEXT,
  lock_version INTEGER NOT NULL DEFAULT 0,
  updated_at TIMESTAMPTZ
);
```

## Turning it on

Add a `lock_version` integer column to a table, and its Model’s records lock. Every save that writes the row checks that the row still has the record’s `lockVersion`, then adds 1 to it.

- A record with no changes sends nothing, so its version stays the same.
- A new record is saved with version 0 when it has none.
- A row whose `lock_version` is NULL reads as version 0.

## Saving a stale record

When another save changes the row after you load a record, saving your copy throws `StaleRecord`:

```ts
import { Article } from "./models/article";

const mine = await Article.findByOrThrow({ title: "Hello" });
const theirs = await Article.findByOrThrow({ title: "Hello" });

await theirs.update({ body: "Their edit" }); // the row's lockVersion goes from 0 to 1
console.log(theirs.lockVersion); // 1

mine.body = "My edit";
await mine.save(); // throws StaleRecord: mine still has version 0
```

- `save()` throws, as `saveOrThrow()` does. Nothing in its write is kept, so the record’s autosaved records, counter caches, and touches roll back with it, as do the other records of a [batch](/batches).
- The error’s `record` is the stale record, and its `action` is `"update"`, `"destroy"`, or `"touch"`.
- The record keeps its changes, and the version it had.

## Destroying a stale record

`destroy()` checks the version too:

```ts
import { Article } from "./models/article";

const mine = await Article.findByOrThrow({ title: "Hello" });
const theirs = await Article.findByOrThrow({ title: "Hello" });

await theirs.update({ title: "Hello again" });
await mine.destroy(); // throws StaleRecord, and the article stays
```

The article stays, and so do the records its `dependent` associations would have destroyed on its database. Those on [another database](/several-databases) are destroyed first, in a write of their own, so they’re gone.

:::note
`touch()` checks the version as well, and adds 1 to it.
:::

## Catching edits made in another request

Put the record’s `lockVersion` in its form, and assign it back when the form is sent. The save then checks the version the form was shown with:

```ts
import { StaleRecord } from "@forestfuture/active-record";
import { Article } from "./models/article";

export async function updateArticle(request: Request): Promise<Response> {
  const article = await Article.find(new URL(request.url).searchParams.get("id") ?? "");
  // lockVersion is the version the form was shown with, from a hidden field
  article.assign(Article.permit(await request.formData(), "body", "lockVersion"));
  try {
    await article.saveOrThrow();
  } catch (error) {
    if (!(error instanceof StaleRecord)) throw error;
    return new Response("Someone else changed this article. Reload it and try again.", {
      status: 409,
    });
  }
  return new Response("Saved");
}
```

## Recovering from a stale record

Reload the record to read the row’s values and its version, then make your change again:

```ts
import { StaleRecord } from "@forestfuture/active-record";
import { Article } from "./models/article";

const article = await Article.findByOrThrow({ title: "Hello" });
await (await Article.find(article.id)).update({ title: "Hello, world" }); // another request's edit

article.body = "A new paragraph.";
try {
  await article.saveOrThrow();
} catch (error) {
  if (!(error instanceof StaleRecord)) throw error;
  await article.reload(); // the row's values, and its version
  article.body = "A new paragraph.";
  await article.saveOrThrow();
}
```

## Writing without the check

`updateColumns`, `updateColumn`, `incrementColumn`, `decrementColumn`, and `toggleColumn` write straight to the row. They don’t check `lockVersion` or change it, and neither do counters, [counter caches](/counter-caches), `updateAll`, `deleteAll`, `touchAll`, and `Article.delete(ids)`.

:::warning[Touches change the version]
When a comment [touches](/touching) its article, the article’s `lockVersion` goes up by 1 without being checked. Someone editing the article when a comment arrives then gets `StaleRecord`. If a locked record’s children touch it often, drop their `touch`, or write them inside `noTouching`.
:::

> **Compared with Rails**
>
> Rails names the error `ActiveRecord::StaleObjectError`, and its `attempted_action` is `action` here.
>
> Rails’ `locking_column` and `lock_optimistically = false` aren’t here: a table locks when it has `lock_version`.
>
> When a comment touches a locked article, Rails checks the article’s version and can refuse the comment’s save. Here the touch adds 1 to the article’s version without checking it.
