Keel by ChimpLabs
Jump to page or section Esc
Primitives

Lock

Distributed leases with fencing tokens, automatic TTL renewal, and guaranteed release on exit or interruption.

Lock provides mutually exclusive distributed leases across processes, workers, and containers. It renews leases in the background when autoRenew: true and releases the lease when your critical section finishes, throws, or is interrupted.

Use Lock to serialize concurrent mutations on a shared resource, such as checkout carts, seat reservations, leader election, or ledger reconciliations. For client request deduplication with cached responses, see Idempotency.


Declaring a Lock

Plain TypeScript SDK (@chimp-labs/keel/sdk)

import { k } from "@chimp-labs/keel/sdk"

export const CheckoutLock = k.lock("checkout", {
  ttl: "15 seconds",
  autoRenew: true,
})

Configuration options

Option Type Default Description
ttl Duration.Input "30 seconds" Lease expiration window if the holder crashes.
autoRenew boolean true Extends the lease in the background while the critical section runs.

Effect v4 (@chimp-labs/keel/lock)

import { Lock } from "@chimp-labs/keel/lock"

export class CartLock extends Lock<"cart", `cart:${string}`>("cart", {
  ttl: "15 seconds",
  autoRenew: true,
}) {}

Attaching to a Service

export const CheckoutService = k.service("checkout", {
  resources: [OrdersTable, CheckoutLock],
  operations: { /* ... */ },
})

Operations reference

Running a critical section (withLock)

const receipt = await keel.checkoutLock.withLock(
  `cart:${cartId}`,
  async () => {
    // Only one worker across the fleet runs this block for cartId at a time
    const cart = await keel.carts.getById(cartId)
    return finalizeCheckout(cart)
  },
  { ttl: "20 seconds" }
)

If another caller already holds the lease for cart:${cartId}, withLock returns LockBusyError (409, retryable). You can reject the request or retry with backoff.

Scoped lease acquisition (Effect v4)

In Effect v4, acquireLock ties the lease lifecycle to an Effect Scope. It renews the lease while the scope is open and releases the lease on completion, error, or fiber interruption:

import { Effect } from "effect"
import { acquireLock } from "@chimp-labs/keel/lock"

const program = Effect.scoped(
  Effect.gen(function* () {
    const lease = yield* acquireLock(CartLock, `cart:${cartId}`)
    yield* Effect.logInfo(`Acquired lease token=${lease.token}`)
    return yield* processCart(cartId)
  })
)

SDK and Effect API mapping

SDK method (keel.<lock>.*) Effect function (@chimp-labs/keel/lock) Description
withLock(key, fn, { ttl? }) withLock(lock, key, effect, opts?) Acquire a lease, run the critical section, and release the lease on exit.
Available via runEffect acquireLock(lock, key, opts?) Acquire a scoped LockLease with background renewal and cleanup.

Errors and failure modes

Error tag Category HTTP status Retryable When it occurs
LockBusyError conflict 409 Yes Another holder owns the lease for key.
LockStoreError internal 500 Yes Backend lock storage failure.

Backends and infrastructure

  • Memory uses an in-process lease map with Effect Clock expiration and background renewal fibers.
  • PostgreSQL 17 (KeelPostgresLive or backend: "postgres"), SQLite, and SurrealDB 4 use DistributedLockMemory by default in createKeel for single-node setups. For multi-replica locking, provide a custom DistributedLock layer backed by PostgreSQL AtomicKV (setIfNotExists and compareAndSwap in keel_kv) or PostgresClient advisory locks. Verify the owner token on release so an expired holder cannot release another holder’s lease.

Testing in memory

await using keel = await createKeel({
  backend: "memory",
  resources: { checkoutLock: CheckoutLock },
})

const result = await keel.checkoutLock.withLock("cart:42", async () => {
  // Re-acquiring the same key while held fails with LockBusyError
  const contention = await tryKeel(() =>
    keel.checkoutLock.withLock("cart:42", async () => "blocked")
  )
  // contention.ok === false && contention.error.tag === "LockBusyError"
  return "completed"
})
// result === "completed", lease is now released