---
question: How do I take a lock only the holder can release?
kind: task
via_web: na
via_cli: na
via_python: available
via_api: na
via_config: na
ref_python: set_if_not_exists
prereq: A module that declares the `kv` service. See [Store a value](/capabilities/build/platform/store-a-value?via=python).
next:
  - /capabilities/build/platform/store-a-value
  - /capabilities/build/modules/module-jobs
---

# Compare and set

The key-value service has two atomic checks: write only when the key is absent, delete only when the value matches. Together they make a lock only its holder can release. It has no single call that replaces a value only when the old bytes match.

## Web UI

Not applicable. System › Data › Key-value writes and deletes keys unconditionally, after you type the key back. Use the Python steps on this page.

## CLI

Not applicable. There is no `abi` command for the key-value store. Use the Python steps on this page.

## Python

### Write only when the key is absent

```python
import secrets

kv = self.engine.services.kv
token = secrets.token_bytes(16)
wrote = await kv.set_if_not_exists("my_module:lock:job", token, ttl=30)
```

It returns `True` when it wrote, `False` when the key was already there. The random token is what proves, later, that you hold the key.

### Delete only when the value matches

```python
removed = await kv.delete_if_value_matches("my_module:lock:job", token)
```

It returns `True` when the stored bytes equalled the value and the key was deleted.

### Hold the lock around the work

```python
if await kv.set_if_not_exists("my_module:lock:job", token, ttl=60):
    try:
        ...  # the work only one holder may do
    finally:
        await kv.delete_if_value_matches("my_module:lock:job", token)
else:
    ...  # someone else holds it
```

Only the holder's token deletes the key. Keep `ttl` longer than the work: if the process dies, the key expires and frees the lock. The SDK has no lock context manager (`kv.lock(...)` raises `NotImplementedError`), so retry and timeout are yours to write.

:::note Across processes
The lock is shared only when the store is: `redis`, or the `python` adapter on one SQLite file. The `python` adapter without `persistence_path` is in memory, in the engine's process.
:::

## REST API

Not applicable. The System routes of the Nexus API write and delete keys unconditionally; none of them compares first. Use the Python steps on this page.

## Config

Not applicable. A conditional write is a call, not a setting.
