# Run work one at a time with locks and leases

When an app runs on more than one server, or a client sends the same request twice, the same work can start twice at the same time. Two syncs write the same rows. Two reports send the same email. A lock or a lease lets one runner do the work while the others skip it or wait.

- A **lock** is a key that one runner holds for a fixed time. [`kv.lock()`](https://vitehub.dev/docs/kv/server-api#locks) keeps it in KV.
- A **lease** is a lock that its holder can extend and that you can inspect. [`useLeases()`](https://vitehub.dev/docs/guides/run-one-at-a-time#hold-a-lease-for-long-work) from `vite-hub/database` keeps it in the app's Database.

Both end at a release or when their time passes, so a server that crashes blocks the key only until then.

## Choose one

| You need | Use |
| --- | --- |
| A Schedule that runs once per time on several servers | Nothing. The [Schedule](https://vitehub.dev/docs/schedule/configure#run-on-more-than-one-server) Process Runtime takes a lease for each occurrence. |
| A retried webhook or request that does its work once, and repeats that get the first result | [`withIdempotency()`](https://vitehub.dev/docs/database/server-api#run-work-once-for-a-key) from `vite-hub/database` |
| A job that must not run twice at once and ends in a known time | [`kv.lock()`](https://vitehub.dev/docs/guides/run-one-at-a-time#lock-a-short-job) |
| Work that runs longer than you can predict, one leader among servers, or a holder that you can see | [A lease](https://vitehub.dev/docs/guides/run-one-at-a-time#hold-a-lease-for-long-work) |
| A limit on how often a user or an IP calls a route | [Rate Limit](https://vitehub.dev/docs/rate-limit) |
| Background jobs that one consumer handles at a time | [Queue](https://vitehub.dev/docs/queue) with `concurrency: 1` |

A lock or a lease stops two runs at the same time. It does not stop a second run after the first one ended. When a repeat must not run at all, use `withIdempotency()`.

## Lock a short job

`kv.lock(key, { ttl })` gives the key to one runner. `run()` takes the lock, calls your function, and releases the lock, also when the function throws:

```ts [server/api/sync/github.post.ts]
import { defineEventHandler, HTTPError } from 'h3'
import { kv } from 'vite-hub/kv'

async function syncGitHubIssues() {
  const response = await fetch('https://api.github.com/repos/vite-hub/vitehub/issues?per_page=100')
  const issues: { number: number, title: string }[] = await response.json()
  return issues.length
}

export default defineEventHandler(async () => {
  const [error, result] = await kv.lock('sync:github-issues', { ttl: 60 }).run(syncGitHubIssues)
  if (error) throw new HTTPError({ status: 503, message: error.why })
  if (!result.acquired) return { skipped: true }
  return { synced: result.value }
})
```

- `ttl` is required, in seconds. Pick a value longer than the work. A lock does not renew, so when the work runs longer than `ttl`, another runner can take the key while the first one still runs.
- `wait` is optional, in seconds. Without it, a held lock returns `{ acquired: false }` at once. With it, `run()` tries again until the lock is free or `wait` ends.
- The `redis`, `upstash`, and `database` KV drivers support locks. Cloudflare KV, Deno KV, and `fs-lite` return `KV_UNSUPPORTED_OPERATION` and do not call your function. On Cloudflare, give the KV store the `upstash` driver (see [KV configuration](https://vitehub.dev/docs/kv/configure)), or use a lease.

## Hold a lease for long work

`useLeases()` returns the leases of the app. They live in the `vitehub_leases` table of the default Database, which every server of the app shares. The first call creates the table. Acquire the lease, renew it while the work runs, and release it at the end:

```ts [server/api/reindex.post.ts]
import { defineEventHandler, HTTPError } from 'h3'
import { useLeases } from 'vite-hub/database'

async function reindexSearch(signal: AbortSignal) {
  for (const page of ['getting-started', 'guides', 'reference']) {
    signal.throwIfAborted()
    await fetch(`https://search.example.com/index/${page}`, { method: 'POST', signal })
  }
}

export default defineEventHandler(async () => {
  const [error, lease] = await useLeases().acquire('search:reindex', { ttl: 30, owner: process.env.HOSTNAME ?? 'local' })
  if (error) throw new HTTPError({ status: 503, message: error.why })
  if (!lease) return { skipped: true }

  // Stop the work when the lease is lost, so that two runners never write at once.
  const lost = new AbortController()
  const renewal = setInterval(async () => {
    const [renewError, renewed] = await lease.renew()
    if (renewError || !renewed) lost.abort(renewError ?? new Error('Another runner took the lease.'))
  }, 10_000)
  try {
    await reindexSearch(lost.signal)
    return { reindexed: true }
  }
  catch (cause) {
    if (lost.signal.aborted) throw new HTTPError({ status: 409, message: 'The reindex lost its lease and stopped.', cause })
    throw cause
  }
  finally {
    clearInterval(renewal)
    await lease.release()
  }
})
```

- `acquire()` returns `[error, lease]`. `lease` is `null` when another runner holds the key. Leases are not reentrant: the same `owner` also gets `null`.
- `renew({ ttl? })` moves the end of the lease and returns `[error, renewed]`. `renewed` is `false` when the lease expired and another runner took it. Then stop the work, as the `AbortController` above does. Work that already ran stays done.
- `get(key)` returns `[error, lease]` with the live lease, its `owner` and `expiresAt`, or `null`. Use it to show who runs a job.
- `owner` is a label for inspection, such as the server name. `acquire()` does not compare it.
- Expiry uses the clock of the Database, not the clocks of the servers.
- `useLeases({ database: 'jobs' })` keeps the leases in another Database of the app.

Leases work on every Database driver: Postgres, PGlite, libSQL, local SQLite, and D1. Each operation is one SQL statement, so D1 needs no transaction. Do not run several server processes on one local SQLite file: `@libsql/client` can lose writes after `SQLITE_BUSY`, and ViteHub prints a warning. Read the leases with `vitehub database sql "SELECT * FROM vitehub_leases"`.

Without a ViteHub Database, pass your own SQL client to `createSqlLeaseStore()` from `vite-hub/runtime`. For one process and for tests, use `createMemoryLeaseStore()`.

The [runtime README](https://github.com/vite-hub/vitehub/tree/main/packages/runtime#leases) shows the SQL that creates the table, for a Database where the app role cannot run `CREATE TABLE`.

## Lock or lease

| | `kv.lock()` | Lease |
| --- | --- | --- |
| Store | KV on `redis`, `upstash`, or `database` | The app's Database, on every driver |
| Extend while the work runs | No | `renew()` |
| See who holds the key | No | `get()` |
| Release after a crash | After `ttl` | After `ttl` |
| Errors | `KV_UNSUPPORTED_OPERATION`, `KV_OPERATION_FAILED` | `RUNTIME_LEASE_FAILED`, `RUNTIME_LEASE_INVALID_TTL` |

Neither one can stop a runner that paused longer than its `ttl`, such as a server that froze, from writing after another runner took the key. When a late write does damage, make the write itself safe: check a version column in the `UPDATE`, or use `withIdempotency()`.

<!-- vitehub-docs:section-links -->
## In this section

- [Overview](https://vitehub.dev/raw/docs/guides.md)
- [Agents](https://vitehub.dev/raw/docs/guides/deploy-agent-cloudflare-vercel.md)
- [Chat bots](https://vitehub.dev/raw/docs/guides/slack-ai-bot.md)
- [Storage](https://vitehub.dev/raw/docs/guides/upstash-redis.md)
- [Databases](https://vitehub.dev/raw/docs/guides/turso.md)
- Server work
  - [Resend](https://vitehub.dev/raw/docs/guides/resend.md)
  - [Cloudflare Browser Run](https://vitehub.dev/raw/docs/guides/cloudflare-browser.md)
  - [Sandbox providers](https://vitehub.dev/raw/docs/guides/sandbox-providers.md)
  - [Background jobs](https://vitehub.dev/raw/docs/guides/background-jobs.md)
  - [Vercel Queues](https://vitehub.dev/raw/docs/guides/vercel-queues.md)
  - [Cloudflare Queues](https://vitehub.dev/raw/docs/guides/cloudflare-queues.md)
  - [Vercel Cron Jobs](https://vitehub.dev/raw/docs/guides/vercel-cron-jobs.md)
  - [Locks and leases](https://vitehub.dev/raw/docs/guides/run-one-at-a-time.md) (this page)
- [Better Auth on Cloudflare](https://vitehub.dev/raw/docs/guides/better-auth-cloudflare.md)
- [Concepts](https://vitehub.dev/raw/docs/guides/rate-limiting-algorithms.md)

Next: [Better Auth on Cloudflare](https://vitehub.dev/raw/docs/guides/better-auth-cloudflare.md)

All pages: [llms.txt](https://vitehub.dev/llms.txt)
