# Key-value state

Code on this page comes in TypeScript, Rust, Python, and Go. The same page with one language only: [Python](https://docs.laserdata.com/md/python/laser-sdk/state.md), [TypeScript](https://docs.laserdata.com/md/typescript/laser-sdk/state.md), [Rust](https://docs.laserdata.com/md/rust/laser-sdk/state.md), [Go](https://docs.laserdata.com/md/go/laser-sdk/state.md).

Key-value state holds small values your agents read and change by key, such as a service config, a feature flag, or the owner of an incident. Every write goes through the log first, so each value points back to the record that wrote it. Use it when several agents or services need the same current value.

## Quick example

This program writes a config value with a one-day expiry, reads it with its version, and updates it with compare-and-swap. It needs [Laser Stack](/laser-sdk/laser-stack) or LaserData Cloud.

**TypeScript**

```ts
import { Laser } from "@laserdata/laser-sdk"

await using laser = await Laser.connectWithStream("iggy:iggy@127.0.0.1:8090", "ops")
const kv = laser.kv("config")
const key = new TextEncoder().encode("service:auth")

await kv.set(key).json({ log_level: "info" }).ttl(86_400_000).send()

const entry = await kv.getEntry(key)
if (entry === undefined) throw new Error("service:auth is missing")

const version = await kv.set(key).json({ log_level: "debug" }).expectVersion(entry.version).commit()
console.log(`service:auth is at version ${String(version)}`)
```

**Rust**

```rust
use laser_sdk::prelude::*;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), LaserError> {
    let laser = Laser::connect_with_stream("iggy:iggy@127.0.0.1:8090", "ops").await?;
    let kv = laser.kv("config");

    kv.set("service:auth")
        .json(&serde_json::json!({ "log_level": "info" }))?
        .ttl(Duration::from_secs(86_400))
        .send()
        .await?;

    let entry = kv
        .get_entry("service:auth")
        .await?
        .ok_or_else(|| LaserError::Invalid("service:auth is missing".to_owned()))?;

    let version = kv
        .set("service:auth")
        .json(&serde_json::json!({ "log_level": "debug" }))?
        .expect_version(entry.version)
        .commit()
        .await?;
    println!("service:auth is at version {version}");
    Ok(())
}
```

**Python**

```python
import asyncio

import laser_sdk as ls


async def main():
    async with await ls.Laser.connect("iggy:iggy@127.0.0.1:8090", stream="ops") as laser:
        store = laser.kv("config")

        await store.set("service:auth").json({"log_level": "info"}).ttl(86_400_000).send()

        entry = await store.get_entry("service:auth")
        if entry is None:
            raise RuntimeError("service:auth is missing")

        version = await (
            store.set("service:auth")
            .json({"log_level": "debug"})
            .expect_version(entry.version)
            .commit()
        )
        print(f"service:auth is at version {version}")

asyncio.run(main())
```

**Go**

```go
package main

import (
    "context"
    "fmt"
    "os"
    "time"

    "github.com/laserdata/laser-sdk/foreign/go/laser"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
    defer cancel()
    if err := run(ctx); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}

func run(ctx context.Context) error {
    client, err := laser.ConnectWith(ctx, "iggy:iggy@127.0.0.1:8090", laser.Options{DefaultStream: "ops"})
    if err != nil {
        return err
    }
    defer client.Close()
    if err := client.Stream("ops").Ensure(ctx); err != nil {
        return err
    }
    store := client.Kv("config")
    key := []byte("service:auth")

    if err := store.Set(key).JSON(map[string]string{"log_level": "info"}).TTL(24 * time.Hour).Send(ctx); err != nil {
        return err
    }

    entry, err := store.GetEntry(ctx, key)
    if err != nil {
        return err
    }
    if entry == nil {
        return fmt.Errorf("service:auth is missing")
    }

    version, err := store.Set(key).JSON(map[string]string{"log_level": "debug"}).ExpectVersion(entry.Version).Commit(ctx)
    if err != nil {
        return err
    }
    fmt.Println("service:auth is at version", version)
    return nil
}
```

If another writer changed the key after your read, `commit()` fails with a version conflict that carries the current version. Read again and retry.

## Read a value

`get(key)` returns the raw bytes, `get_typed(key)` decodes JSON, and `get_entry(key)` adds the version and expiry. A missing or expired key reads as empty. TypeScript's `getTyped(key, decode)` takes a function that checks the decoded value.

**TypeScript**

```ts
const config = await kv.getTyped(key, (value) => value as { log_level: string })
```

**Rust**

```rust
let config = kv.get_typed::<serde_json::Value>("service:auth").await?;
```

**Python**

```python
config = await store.get_typed("service:auth")
```

**Go**

```go
value, found, err := store.Get(ctx, []byte("service:auth"))
if err != nil {
    return err
}
var config map[string]string
if found {
    if err := json.Unmarshal(value, &config); err != nil {
        return err
    }
}
```

## Create a key only once

`expect_absent()` (TypeScript: `expectAbsent`) writes only when the key does not exist yet. Two agents that race to claim an incident both call it, and the second one gets a version conflict.

**TypeScript**

```ts
const owner = new TextEncoder().encode("incident:4711:owner")
await kv.set(owner).json({ agent: "triage" }).expectAbsent().commit()
```

**Rust**

```rust
kv.set("incident:4711:owner")
    .json(&serde_json::json!({ "agent": "triage" }))?
    .expect_absent()
    .commit()
    .await?;
```

**Python**

```python
await store.set("incident:4711:owner").json({"agent": "triage"}).expect_absent().commit()
```

**Go**

```go
version, err := store.Set([]byte("incident:4711:owner")).
    JSON(map[string]string{"agent": "triage"}).ExpectAbsent().Commit(ctx)
if err != nil {
    return err
}
fmt.Println(version)
```

## Expire values

`.ttl(..)` on a write sets how long the value lives, counted from now. Rust takes a `Duration`, and TypeScript and Python take milliseconds. `expire(key, ttl)` changes the expiry of an existing value without rewriting it. Leave out the TTL (Rust: pass `None`) to clear the expiry.

## Share state between agents

Agents share state by opening the same namespace on the same stream, in any of the four languages. Use compare-and-swap when several agents update one key. When one worker must own a task for a while, use a lease and fenced writes, covered in [Locks and fenced writes](/laser-sdk/advanced/state#locks-and-fenced-writes). Inside a [session](/laser-sdk/session), `session.kv(namespace)` links every write to that session.

To try a change on a copy of your view data before you apply it, use a [fork](/laser-sdk/advanced/state#forks).

## Good to know

* Key-value state needs Laser Stack or LaserData Cloud. Check `capabilities.kv.available`, and `capabilities.kv.cas` before you call `commit()`. Without the capability, the call fails with an unsupported error.
* Finish a guarded write with `.commit()` and a plain write with `.send()`. Mixing them fails with an invalid error, so a precondition is never dropped.
* Keys are at most 512 bytes, values at most 8 MiB, and namespaces at most 128 bytes. TypeScript keys are `Uint8Array` values.
* Namespaces are scoped to the default stream, so `laser.kv("config")` addresses `stream:<stream>/config`.
* Each entry from `get_entry` carries `source`, the log record that wrote it.
* After the managed backend on a node restarts, reads in a namespace that its memory replay can change wait while the replay moves, and stop waiting once it made no progress for 30 seconds. The SDK sends a held read to another node, or waits for it on a single node. See [Reads after a restart](/laser-sdk/advanced/memory#reads-after-a-restart).

- [Key-value state in depth](/laser-sdk/advanced/state): Every operation, leases and fenced writes, local state stores, forks, and session links
- [Memory](/laser-sdk/memory): Facts your agents remember and recall
- [Sessions](/laser-sdk/session): Units of work that link the keys they write
- [KV example](https://github.com/laserdata/laser-sdk/tree/main/examples/rust/src/kv): Runnable set, compare-and-swap, leases, and a fork in Rust, Python, and TypeScript

Source: https://docs.laserdata.com/laser-sdk/state
