Cache

Version 0.1.0 · Owners: @benallfree

Extensions and apps often compute the same thing many times: a rendered page, an answer from another API, a compiled module. Cache gives them named buckets to keep those results in, as bytes or as the Go values themselves, from one store in your app's process, with an optional folder on disk for more than fits in memory. Each bucket has its own budget, and you can change it without touching the code that uses it.

On a multisite host the store is shared by every instance: one memory ceiling and one disk tier for all of them. Each instance still sees only its own buckets. On disk, identical bytes (the same compiled template, the same .wasm file) are one file however many instances or keys hold them.

Cache provides cache/v1 and cache.clear/v1. Code that caches talks only to those contracts, so a cache shared between servers (Redis, Memcached) can replace this one later without any of it changing.

Install · Configure · Use · Integrations · Example

Install

Cache is built into pocketone and on by default; there's nothing to install. Turn it off with cache: {enabled: false} in pocketone.yaml. In your own Go build it comes with the standard set, or on its own:

extkit.Setup(app, []extkit.Extension{cache.New(cache.Config{})}, nil, nil)

Configure

Nothing to configure: each bucket gets 32MiB of memory (and 256MiB of disk, when there's a disk tier), the store 128MiB for every bucket together. To change them, add a cache section to pocketone.yaml. The top keys are the store's; defaults fill in what a bucket's code leaves unset; buckets set a named bucket's limits over what its code asks for:

cache:
  max_memory: 512MiB       # the store: every bucket together
  disk: true               # a disk tier in pb_cache/cache; leave out for memory only
  max_disk: 10GiB
  defaults:
    max_memory: 16MiB
    ttl: 10m
  buckets:
    pages.compiled:
      max_memory: 64MiB    # one app's bucket
      max_disk: 1GiB

The store, ceilings over every bucket together:

Key What it does
max_memory Memory for every bucket together (default 128MiB)
eviction Which values leave memory (or disk) first when the store reaches a ceiling: lru (default), mru, fifo, lifo
disk Turns on the disk tier in pb_cache/cache, next to pb_data; on a multisite host, in the host's own pb_cache (the store serves every instance)
disk_path Puts the disk tier in a cache folder there instead, and turns it on. Relative paths are to the app's folder (the one holding pb_data) when the app has the process to itself, and to the working directory when several apps share it (Pocker)
max_disk Size of the disk tier (default 1GiB)

Each bucket (defaults and buckets.<name>), its own budget:

Key What it does
max_items Most entries the bucket holds, in memory or on disk
max_memory Most bytes of keys and values the bucket holds in memory (default 32MiB)
max_disk Most bytes of disk files the bucket's keys point at, each counted in full even when shared (default 256MiB)
eviction Which of its entries go first when the bucket is full
ttl How long an entry lives unless its code says otherwise

Sizes take KiB, MiB, GiB (or KB, MB, GB); durations take s, m, h.

The disk tier is pb_cache: never backed up or deployed, and emptied when the process starts. pocketone cache clear cache empties it by hand.

pocketone.yaml reference

cache:

The cache (cache/v1): one store for every app in the process (memory, disk tier), and caps per bucket.

Key Type Default Description
enabled bool Turns the cache off when false; extensions then run uncached.
eviction string Which values leave memory (or disk) first when the store reaches its ceiling: lru, mru, fifo or lifo.
max_memory int Memory for every bucket together, such as 512MiB. Default 128MiB.
disk bool Turns on a disk tier in pb_cache/cache, next to pb_data (on a multisite host, the host's own pb_cache).
disk_path string Puts the disk tier in a cache folder there instead of pb_cache, and turns it on. Relative: to the app's folder (the one holding pb_data) when the app has the process to itself, the working directory when several apps share it (Pocker).
max_disk int Size of the disk tier for every bucket together, such as 10GiB. Default 1GiB.
defaults.eviction string Which of the bucket's entries go first when it's full: lru, mru, fifo or lifo.
defaults.max_items int Most entries the bucket holds.
defaults.max_memory int Most bytes of keys and values the bucket holds in memory, such as 32MiB (the default).
defaults.max_disk int Most bytes of disk files the bucket's keys point at, each counted in full, such as 256MiB (the default).
defaults.ttl int How long an entry lives unless the code says otherwise, such as 10m.
buckets map of object Caps per bucket name, over what its code asks for.

Use

Nothing to click. A bucket that's full moves its values to the disk tier when there is one, and a read brings them back. The cache, disk tier included, starts empty with the process. On a multisite host, an instance that restarts or sleeps keeps its entries: the store belongs to the host.

To empty an app's cache, as a superuser: pocketone remote cache clear (every bucket) or pocketone remote cache clear --bucket pages.compiled (one), through cache.clear/v1.

Commands and APIs

Generated from the pocketone binary and the contracts this extension provides.

cache.clear/v1

Operation CLI REST MCP
clear pocketone remote cache clear --bucket <value> POST /api/_c/cache.clear/v1 cache_clear_clear

Integrations

Extension How they fit
Multisite Every instance that runs PocketOne has Cache (a standard member). With Pocker, every instance shares the host's one store (its memory, its disk tier), and sees only its own buckets: keys live under the instance's id. An instance that sleeps keeps its entries, so it wakes to a warm cache. An instance's extensions.cache may set enabled, defaults and buckets for itself; the store's keys are the host's only.
Docker Each container runs its own pocketone, so it has its own store.

Building on Cache

Open a bucket through cache/v1 at serve time, keep it, and get and set keys:

b, err := cachev1.Open(app, "myext.answers", cachev1.Options{MaxItems: 1000, TTL: 10 * time.Minute})

Declare cache/v1 in WorksWith: when nothing provides it, Open returns a bucket that keeps nothing, so your code runs uncached. Name buckets after your extension so they never collide.

To cache Go values rather than bytes, make them cachev1.Items and open the bucket with cachev1.OpenItems (Go values). Each key keeps its own value in memory, never shared with another key. A value that is also a cachev1.Marshaler is marshaled only when it goes to disk, and comes back decoded as long as its CacheVersion matches the reader's; one that isn't stays in memory only.

Cache provides cache/v1 and cache.clear/v1 as defaults: another extension that provides them (a Redis cache, say) replaces it without any providers: line. On a multisite host, the host empties the whole store (every instance's buckets) with the extension's Clear.

Example

A PocketBase app with one bucket, example.slow. GET /slow takes a second the first time and answers from the cache for the next minute.

// Command example is a PocketBase app with cache/v1 and one bucket, "example.slow". GET /slow takes a second the first
// time and answers from the cache for the next minute:
//
//	go run ./example serve --http=127.0.0.1:8090
//	curl http://127.0.0.1:8090/slow   # slow
//	curl http://127.0.0.1:8090/slow   # cached
//
// Logins (ext/devusers, local testing only): dashboard [email protected] / password, app user [email protected] / password.
package main

import (
	"log"
	"net/http"
	"time"

	"ganigeorgiev.com/pocketbase/pocketbase"
	"ganigeorgiev.com/pocketbase/pocketbase/core"

	"pocketone.dev/ext/cache"
	cachev1 "pocketone.dev/ext/contracts/cache/v1"
	"pocketone.dev/ext/devusers"
	"pocketone.dev/ext/extkit"
)

func main() {
	app := pocketbase.New()
	devusers.Register(app) // local testing: superuser [email protected] and user [email protected], password "password"
	if _, err := extkit.Setup(app, []extkit.Extension{cache.New(cache.Config{})}, nil, nil); err != nil {
		log.Fatal(err)
	}
	app.OnServe().BindFunc(func(se *core.ServeEvent) error {
		b, err := cachev1.Open(app, "example.slow", cachev1.Options{MaxItems: 100, TTL: time.Minute})
		if err != nil {
			return err
		}
		se.Router.GET("/slow", func(e *core.RequestEvent) error {
			ctx := e.Request.Context()
			if v, ok, _ := b.Get(ctx, "answer"); ok {
				return e.String(http.StatusOK, "cached: "+string(v)+"\n")
			}
			time.Sleep(time.Second) // the expensive part
			v := time.Now().Format(time.RFC3339)
			_ = b.Set(ctx, "answer", []byte(v), 0)
			return e.String(http.StatusOK, "computed: "+v+"\n")
		})
		return se.Next()
	})
	if err := app.Start(); err != nil {
		log.Fatal(err)
	}
}

How it works

One store per process. Each app's buckets are namespaces in it, <instance id>/<bucket> (just /<bucket> when the app has the process to itself), so no app can read another's keys.

Memory and disk follow different rules. In memory every key holds its own value, bytes or a Go value, and nothing is shared between keys. On disk values are files named by the SHA-256 of their bytes (an item's MarshalCache bytes): the same bytes under any number of keys, from any number of instances, are one file with a reference count, removed when the last key pointing at it goes. A key points at its file with the value's version beside it: (bucket, key, version) -> SHA.

Each bucket has its own budget: entries, memory (its keys and the values it holds there) and disk (the files its keys point at, each in full). When a bucket is over its memory, its values move to disk (by its own strategy); over its entries or its disk, its keys go. A busy bucket never evicts another bucket's values. The store's ceilings (memory, disk) hold over every bucket together, so the total stays bounded however many instances there are; reaching one evicts across buckets by the store's strategy.

Memory is the hot tier and the disk tier the cold one: a value reaches disk only when memory evicts it (an item is marshaled then, never before), goes back to memory and leaves disk when it's read, and the folder is emptied when the process starts. Nothing on disk outlives the process, so nothing on disk can be stale after a restart or a crash.

One lock guards the in-memory index, and it's never held across disk IO, marshaling or decoding. One IO goroutine, running only while it has work, marshals, writes and removes files in the order the lock decided them. A write waits in a slot of its key's, at most one per key, and writes whatever the key holds when its turn comes, so a key evicted again and again before the disk catches up is marshaled and written once, with its latest value. A value waiting to be written stays readable from memory (at most a quarter of max_memory waits; past that, evicted values are dropped). A file is read once however many readers want it, and a key's bytes are decoded once however many readers want its item; both are checked against the index again before they're used, so a key changed meanwhile never gets its old value back.

The store is tested against a model under fuzzing (bytes and items: no value deleted, replaced, expired or belonging to another key ever comes back; no value is shared between keys in memory; every count and list stays consistent; the disk tier holds exactly the files it should) and under concurrent load with the race detector.

License

MIT