Write

Persist versioned key/value data with full history.

Writing data in Litebase means storing a value under a key — durably, immutably, and with version control. Every write creates a new version, tied to a unique transaction and timestamp, so you can always trace changes over time.

This guide walks through how to structure keys, store values, and leverage versioned writes as part of your application logic.


1. Choose a key

Keys are strings used to organize and retrieve data. They follow a flat but hierarchical structure — typically dot-separated to group related records:

  • user.abc123.profile
  • project.42.status
  • order.20250405.receipt

Keys must be unique. Writing to the same key creates a new version — previous values are preserved.


2. Prepare your value

Values can be any valid JSON-serializable object:

  • Flat key-value maps
  • Nested objects
  • Arrays
  • Numbers, strings, or booleans

Avoid excessively large values (e.g. >1MB) unless necessary — all writes are versioned and retained.

Example:

{
  "name": "Jane Doe",
  "email": "[email protected]",
  "status": "active"
}

3. Write to the key

Send an HTTP PUT request to the key’s endpoint:

curl -X PUT https://api.litebase.io/v1/kv/user.abc123.profile \
  -H "Authorization: Bearer $LITEBASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
        "name": "Jane Doe",
        "email": "[email protected]",
        "status": "active"
      }'

The response will include:

  • key: the key name
  • time: the commit timestamp
  • tx: the transaction ID
  • version: the version number of this write

Example:

{
  "key": "user.abc123.profile",
  "time": "2025-04-06T09:00:00Z",
  "tx": "tx_9c012abc",
  "version": 4
}

4. Write multiple keys (batch)

You can write multiple keys in a single transaction to ensure consistency:

curl -X POST https://api.litebase.io/v1/kv/batch \
  -H "Authorization: Bearer $LITEBASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
        "writes": [
          {
            "key": "user.abc123.profile",
            "value": { "name": "Jane", "status": "active" }
          },
          {
            "key": "user.abc123.meta",
            "value": { "login_count": 42 }
          }
        ]
      }'

All writes in a batch are applied under the same transaction.


5. (Optional) Publish events

You can optionally emit an event alongside your write to keep state and stream timelines in sync:

{
  "writes": [
    {
      "key": "order.ord_123.status",
      "value": { "status": "paid" }
    }
  ],
  "events": [
    {
      "stream": "order.paid",
      "data": {
        "order_id": "ord_123",
        "amount": 49.00
      }
    }
  ]
}

This ensures strong consistency between your stored data and your event log — perfect for reactive systems.