# KV

URL: https://docs.folkways.io/docs/primitives/kv

The latest value per key, for read receipts, scores, locations and status, with snapshots, deletes and time-to-live.

A **KV** event sets a value under a key in its topic. Folkways keeps only the latest value for each event name and
key. A new subscriber gets a **snapshot** of the current values, then each change; it never sees the history of
intermediate updates.

**Use it for:** read receipts, live scores, where each driver is, a document's title, a user's status, a poll's
counts.

## How it behaves [#how-it-behaves]

- **Latest wins.** Writing `read` for key `alice` replaces alice's previous `read`. Values with other keys are kept.
- **The key defaults to the publisher.** With no key, the value is stored under the publisher's identity, so `read`
  means "my read receipt". Set your own key for a shared value, such as `score` with key `match`.
- **Deletes.** Deleting a key removes it and tells subscribers with a deletion event (a tombstone) that carries the
  name, key and publisher but no payload.
- **Time-to-live.** A value can expire. When it does, subscribers get the same deletion event, within about 5
  seconds of the deadline. So a driver who goes offline drops off the map without anyone publishing for them.
- **Snapshots.** A subscriber receives every current value of the topic first, possibly in several chunks, then live
  changes. Deleted keys are never in a snapshot.
- **Positions.** KV values have a uid. They don't replay: a reconnecting subscriber gets a fresh snapshot.

## Protect each user's key [#protect-each-users-key]

Turn on **Only the publisher can write its key** (`key_is_publisher`) for an event like `read`. Then nobody but
your backend can write or delete another user's value, so a user can't move someone else's read receipt.

## Limits and settings [#limits-and-settings]

| Setting | Default | Meaning |
| --- | --- | --- |
| Time-to-live | none (kept until replaced) | Default lifetime of a value; a publish can set its own |
| Max keys | 10,000 per topic | KV values and signals held per topic, together |
| Payload limit | Segment's limit, at most 60 KiB | Largest value |

Writing needs `set` (or `publish`) in both the token and the rule.

## In code [#in-code]

<Tabs items={['JavaScript', 'Realtime API']}>
  <Tab value="JavaScript">
    ```ts
    await room.publish('read', { upTo: receipt.uid }, { delivery: 'kv' });
    await scores.publish('score', { home: 2, away: 1 }, { delivery: 'kv', key: 'match', ttlMs: 3_600_000 });
    ```

    See [KV in the SDK](/docs/js-sdk/kv).
  </Tab>
  <Tab value="Realtime API">
    Send [`Publish`](/docs/realtime-api/publish) with `delivery: LastValue`, an optional `key` and `ttl_ms`, or
    `tombstone: true` to delete.
  </Tab>
</Tabs>
