# Locks

A **lock** lets one caller at a time run a piece of code, across every instance of the app. Use it where two runs at once do harm: a scheduled task that must not overlap itself when three replicas schedule it, an admin button that starts a rebuild, an import that two users could start together.

`withLock(key, fn, options)` takes the lock, runs `fn`, releases the lock, and tells you whether it ran:

````ts [data/locks-task.ts]
import { defineTask, withLock } from "hamur/server"

declare function reindex(): Promise<number>

export default defineTask({
  description: "Rebuild the search index, never on two instances at once",
  async run(_payload, ctx) {
    const result = await withLock("reindex", async () => ({ indexed: await reindex() }), { ttl: 600 })
    if (!result.ran) ctx.log.info("another run holds the reindex lock; skipping")
    return result.ran ? result.value : null
  },
})
````

It returns `{ ran: true, value }` with what `fn` returned, or `{ ran: false }` when another caller holds the lock. **It never waits**: a caller that does not get the lock is answered at once and decides for itself, to skip as the task does, or to refuse the request:

````ts [data/locks-handler.ts]
import { createError, defineHandler, withLock } from "hamur/server"

declare function rebuildSite(): Promise<{ pages: number }>

export const rebuild = defineHandler({
  route: "/api/admin/rebuild",
  method: "POST",
  async handler() {
    const result = await withLock("rebuild", rebuildSite, { ttl: 300, storage: "locks" })
    if (!result.ran) throw createError({ status: 409, message: "A rebuild is already running" })
    return result.value
  },
})
````

## What it does

`withLock` writes the key `lock:<key>` on a [storage](/storage-and-cache) mount with `increment` and a `ttl`. The caller whose `increment` returns `1` holds the lock; every other caller gets `{ ran: false }`. The lock is released with `removeItem` when `fn` returns, throws or rejects, and an error `fn` throws reaches the caller.

| Option    | Default  | Meaning                                                                             |
| --------- | -------- | ----------------------------------------------------------------------------------- |
| `ttl`     | `60`     | whole seconds the lock lasts at most; a holder that crashed frees the lock after it |
| `storage` | `"data"` | the mount that holds the key                                                        |

Set `ttl` above the longest `fn` takes. A holder that runs past its `ttl` no longer holds the lock: another caller may take it, and the first one does not remove it when it ends, so it cannot release the lock of the caller that followed. The two runs overlap in that case; storage has no compare-and-delete to prevent it, so keep `fn` safe to run twice, as for any [task](/tasks#queues-and-enqueue).

`key` is a non-empty string and `ttl` a positive whole number, else `TypeError: withLock key must be a non-empty string` or `withLock ttl must be a positive integer of seconds`.

## Per preset

The mount must give an `increment` that is atomic across the instances. `withLock` checks it at the first call, before `fn` runs, and throws when it is not:

| Mount                                 | Passes on                            | Across instances                         |
| ------------------------------------- | ------------------------------------ | ---------------------------------------- |
| `redis`, `db` (`dbStorage`), `sqlite` | every preset the driver runs on      | yes                                      |
| `memory`, `fs`                        | `bun`, `node`, `hamur dev` and tests | no: each process holds a lock of its own |

Any other mount, `memory` and `fs` on another preset included, throws `withLock needs an atomic increment; storage "data" uses fs on the cloudflare preset; mount it on redis, db or sqlite`. A mount with `encrypt` throws too, because the `increment` of an encrypted mount is not atomic: `withLock needs an atomic increment; storage "data" has encrypt, whose increment is not atomic; mount it on redis, db or sqlite`.

So the default `data` mount works for one `bun` or `node` process and in development, and fails on `cloudflare`, `vercel` and `netlify`. For several instances, give the lock its own mount on a shared driver, as the handler sample does with `storage: "locks"`:

````ts [data/locks-config.ts]
import { defineConfig, env } from "hamur"
import { redis } from "hamur/storage"

export default defineConfig({
  framework: "react",
  preset: "bun",
  storage: { locks: redis({ url: env("REDIS_URL") }) },
})
````

`redis` runs on `bun`, `node` and `cloudflare`; on `vercel` and `netlify` use `dbStorage` of `@hamur/db/storage` ([Storage and cache](/storage-and-cache)). A name that is not mounted fails with `withLock needs an atomic increment; storage "x" is not mounted; mount it on redis, db or sqlite`.

The signature is in the [server API reference](/api-reference/server#withlock).
