ACTIAS

kv

Key-value namespaces.

Declare

local visits = kv "visits"

Top level only. Scoped to the project, so two scripts in one project declaring kv "visits" share it.

Methods

ns:get("hits")                          -- value, or nil
ns:set("hits", 41)
ns:set_batch({ hits = 41, banner = { text = "back at 09:00" } })
ns:delete("hits")
ns:list({ limit = 100 })                -- one page, ascending by key
MethodReturns
get(key)the value, or nil
set(key, value)nothing; a nil value is a delete
set_batch(table)nothing; writes every pair, deletes the nil ones
delete(...keys)nothing; several keys go in one call
list(options?)one page: { entries, cursor }

Listing

One page per call, in ascending key order. entries is an array of { key, value }; cursor names where the next page starts, and a page without one is the last. limit defaults to 100; a value outside 1 to 1000 is refused, not clamped. The options are { limit, cursor }.

local cursor
repeat
    local page = ns:list({ cursor = cursor })
    for _, entry in page.entries do
        print(entry.key, entry.value)
    end
    cursor = page.cursor
until not cursor

A page is a snapshot of a range, not a lock: writes that land between pages appear or not depending on where their keys sort.

Types

kv stores the type you wrote and returns it.

You writeYou get back
stringstring
integerinteger
numbernumber
booleanboolean
tabletable, through JSON

Example

local cache = kv "cache"

on "fetch" (function(request)
    local hits = (cache:get("hits") or 0) + 1
    cache:set("hits", hits)
    return { body = tostring(hits) }
end)

Gotchas

  • Listing pages by key order; there is no query by value. Anything richer than a key range wants a database.
  • Functions and userdata cannot be stored. Tables go through JSON, so what comes back is a copy, not the table you put in.
  • A nil value in set or set_batch is a delete, not a stored nil.
  • A value has no fixed size limit. state.store on an object caps at 64 KB; kv does not.
  • A namespace name starting with __ is reserved for the platform and refused.
  • Where data goes compares kv with databases and objects.
  • state.store is the same surface on a durable object's own storage: kv for state one object owns.