# Add Optimistic Locking to TypeORM Entities

Yes. An agent adds a version column to your TypeORM entities, makes a stale update fail instead of overwriting, proves it with a concurrent test and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-optimistic-locking/typeorm/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the write paths first, because a lock is only useful on the ones that lose data. In an API laid out like lujakob/nestjs-realworld-example-app, NestJS 7 uses TypeORM 0.2.24 against MySQL through `ormconfig.json` (`synchronize: true`, entities by glob). `ArticleEntity` in `src/article/article.entity.ts` has `slug`, `title`, `description`, `body`, a `simple-array` `tagList`, `created` and `updated` timestamps with a `@BeforeUpdate` hook, a `favoriteCount` with default `0`, an author and eager comments. `ArticleService.update` loads the article by slug with `findOne`, applies the request body with `Object.assign` and calls `save`: a read-modify-write with nothing in between, so two editors who open the same article and save overwrite each other and the second one never learns it. `favorite` and `unFavorite` do `article.favoriteCount++` or `--` in memory and `save`, which loses counts under concurrent requests. Tests run with Jest 25 through `jest.json` and ts-jest, and the only spec is `tag.controller.spec.ts`.

TypeORM has the pieces: a `@VersionColumn()` that increments on every `save`, and a `lock: { mode: 'optimistic', version }` option on `findOne` that makes `save` throw `OptimisticLockVersionMismatchError` when the row's version has moved on. The agent adds `@VersionColumn() version: number` to `ArticleEntity`, returns it in the article response, adds an optional `version` to the update DTO, and changes `update` to load with the optimistic lock when a version is sent and to map the mismatch to a `409 Conflict` `HttpException` whose body names the current version. A client that sends no version gets the old behaviour, so the existing frontend keeps working and the conflict check arrives as clients adopt it.

Favourites are a different problem and get a different fix. Two readers favouriting the same article is not a conflict, so rejecting one with a 409 would be wrong; the count only needs to be changed atomically. The agent replaces the in-memory `++` and `--` with the repository's `increment` and `decrement` on `favoriteCount`, which run as a single SQL statement, and reloads the article afterwards for the response. The join table behind `UserEntity.favorites` is left as it is.

With `synchronize: true` the new column appears in development the moment the entity changes; the pull request says that production needs a migration and that the repository has none yet. In its sandbox the agent installs MySQL from apt, copies `ormconfig.json.example` to `ormconfig.json` with local credentials, and writes `src/article/article.service.spec.ts` against the real database through Nest's testing module: load an article twice, update through the first copy, update through the second with its stale version and expect the 409; then favourite one article from two users in a `Promise.all` and expect `favoriteCount` to be exactly two. It runs `npm test` to show the existing spec still passes beside the new one.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add optimistic locking to the article entity in this TypeORM API. Read ormconfig.json.example, every file under src/article/ and src/user/, src/app.module.ts, jest.json and package.json first. Add a version column to the article entity and return it in the article response. Make the update path load the article with TypeORM's optimistic lock when the request carries a version and answer 409 Conflict with the current version on a mismatch; a request without a version keeps the current behaviour. Replace the in-memory favorite count increment and decrement with the repository's atomic increment and decrement. Do not change the user entity or the favorites join table. Note in the pull request that synchronize is on and production needs a migration. In the sandbox, install MySQL, configure ormconfig.json locally, write a service spec against the real database that proves a stale update is rejected and that two concurrent favorites count as two, and run the whole test suite. Open a pull request whose description quotes the test output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that changes `article.entity.ts`, `article.service.ts`, the article DTO and interface, and adds `article.service.spec.ts`. The description quotes the Jest output with the new spec's cases named, shows the 409 body a stale client receives, and states that the column exists in development through `synchronize` and needs a migration elsewhere.

The run's record keeps the MySQL setup, the test session and the SQL TypeORM logged for the increment, so a reviewer can see the single `UPDATE` statement that replaced the read-modify-write.

Before merging, a reviewer decides whether the frontend should start sending `version` now, checks that the 409 body gives a client enough to reload and retry, and writes or requests the migration before the change reaches a database that is not synchronised.

## Run it on every Linear issue labelled conflict

In the console, add an automation to the Project with a `linear` trigger on `linear.issue.labeled` and the label `conflict`, with this prompt. When a support engineer files an issue about an edit that vanished and labels it, the run starts with the issue as its context, makes the change in the Project's repository and opens a pull request on its own branch linked to the issue. A label added by an app integration never fires the trigger, and the automation starts at most `max_runs_per_hour` runs in an hour.

To start it from a support tool instead, send this body to `POST /o/{org}/sessions` with the issue text appended to the prompt and a `request_id` that is a UUID v5 of the issue id, so a retried delivery returns the run already started.

## Why run it on Rush?

Lost updates are invisible in development because one person is editing. Proving a lock works takes a real database, two concurrent requests and a test that reads the row back, which is the part that gets skipped when the change is made on a laptop between other work. In a Rush sandbox the agent installs the database, runs the concurrent spec against it and reads TypeORM's SQL log before it opens anything.

The test session and the SQL stay with the run, so the reviewer sees the rejected stale write and the single-statement increment rather than reading the service and reasoning about it. Several services with the same pattern run in parallel, each with its own database and its own pull request.

## Frequently asked questions

### Will clients that do not send a version break?

No. The version is optional on the update request; without it the service behaves as before. The response now includes `version`, so a client adopts the check by sending back what it last read.

### Why not lock favorites the same way?

Because two users favouriting the same article at once is not a conflict, and a 409 would make one of them retry for no reason. An atomic `increment` makes the count correct under concurrency without rejecting anyone; the version column still increments on those saves, which is why `update` compares versions rather than counts.

### What about the migration?

The repository runs with `synchronize: true`, so development databases gain the column automatically. Any database that is not synchronised needs a migration that adds an integer `version` column with a default, and the pull request says so rather than adding migration tooling as a side effect.

### Does this work on the TypeORM version in the lockfile?

Yes. `@VersionColumn`, the optimistic lock option on `findOne` and `OptimisticLockVersionMismatchError` exist in the 0.2 line the project pins, and the spec in the sandbox runs against exactly that version.

### Why test against MySQL and not an in-memory database?

The behaviour under test is what the database does with concurrent statements, and SQLite in memory serialises writes differently from MySQL. The spec runs against the engine `ormconfig.json` names so the result means what it says.

## More TypeORM jobs

- [Add Query Timeouts to a TypeORM + NestJS App](https://getrush.ai/run/add-query-timeouts/typeorm/)
- [Add Read Replicas to a TypeORM App](https://getrush.ai/run/add-read-replicas/typeorm/)
- [Add Seed Data to a NestJS TypeORM App](https://getrush.ai/run/add-seed-data/typeorm/)

## The same job on other stacks

- [Add Optimistic Locking to a GORM Model in a Gin API](https://getrush.ai/run/add-optimistic-locking/gorm/)
- [Add Optimistic Locking to a Mongoose API](https://getrush.ai/run/add-optimistic-locking/mongoose/)
- [Add Optimistic Locking to Prisma Models](https://getrush.ai/run/add-optimistic-locking/prisma/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
