One database per account
Keep each account's data in a file of its own with tenant.Pool, a writer per account and one hub for every account's views, and erase an account for good.
An app whose accounts never share data can keep each account in a SQLite file of its own. A query then only ever sees one account's rows, so data cannot leak between accounts through a forgotten WHERE, and backing up, restoring or erasing one account is a matter of one file. The price is an open database, with its connections and its writer, for every account in use. lith/tenant keeps that bounded: a pool opens an account's database on first use, and closes idle ones, least recently released first, when more than its cap are open.
The board app's accounts are in site/internal/docs/example/tenants.
An account
An account is its open database and the writer that owns it. One database has one writer, so each account gets its own. The pool closes an account through its Close, which lets the writer apply what is queued before the database closes:
// Account is one account's open database and the writer that owns it.
type Account struct {
DB *sqlite.DB
W *writer.Writer
}
// Close stops the writer, which applies what is queued, then closes the
// database. The pool calls it when it evicts the account.
func (a *Account) Close() error { return errors.Join(a.W.Close(), a.DB.Close()) }
The pool
tenant.New(maxOpen, open) returns a pool of values keyed by string. The opener runs outside the pool's lock, once per key: everyone else who needs that key waits for it, so a slow open, such as a restore from a replica, holds up only its own account, and an account never opens twice.
func Open(dir string, maxOpen int, hub *live.Hub, log *slog.Logger) *Accounts {
a := &Accounts{dir: dir}
a.pool = tenant.New(maxOpen, func(ctx context.Context, key string) (*Account, error) {
return open(ctx, a.path(key), key, hub)
}, tenant.WithLogger(log))
return a
}
The opener opens the file with small settings, since many are open at once, and starts the account's writer. Its commits mark the hub's views under topics that carry the account, so a commit of one account marks no view of another:
db, err := sqlite.Open(ctx, path, sqlite.Options{
Migrations: migrations.FS,
Readers: 2, // few readers: an account's renders and GETs are few at a time
CacheKiB: 2000, // many files are open at once: a small page cache for each
Checkpoint: sqlite.CheckpointWriter,
})
if err != nil {
return nil, err
}
w, err := writer.New(db, writer.Options{OnCommit: func(topics []string) {
scoped := make([]string, len(topics))
for i, t := range topics {
scoped[i] = Topic(key, t)
}
hub.Changed(scoped)
}})
if err != nil {
return nil, errors.Join(err, db.Close())
}
go w.Run(context.Background()) // until Close: the pool evicts the account
The opener's context carries the values of the request that needed the account, but not its cancellation: a request that gives up does not abort an open halfway. The commands stay the board's, unaware of accounts. The account's key names a file, so the pool accepts only keys made of lowercase letters, digits and dashes.
The migrations run when an account opens, so an account unused for months gets every migration since at its next open. A deploy that changes the schema migrates the accounts one by one, as they come back.
Commands and reads
A command or a read pins its account for as long as it runs, with pool.Do:
func (a *Accounts) Do(ctx context.Context, key string, cmd writer.Command) error {
if !validKey(key) {
return fmt.Errorf("tenants: %q is not an account", key)
}
return a.pool.Do(ctx, key, func(acct *Account) error { return acct.W.Do(ctx, cmd) })
}
pool.Get(ctx, key) returns the value and a release function, for a pin that spans more than one call. Hold a pin for one unit of work, a request or a render: the pool evicts only accounts nobody holds.
pool.Peek(key) pins the value only if the account is open, and never opens it or waits: an account being opened or closed counts as not open. A public page that only reads can use the open account when there is one, and read a dormant account's file through a read-only sqlite.Open of its own, once it has checked that the file's migrations are current, instead of opening the account and evicting another for a visitor. A denied key returns its reason rather than false, so such a read never touches a file that is being restored or erased.
Views of an account
One hub serves every account. It needs no read pool of its own, live.Options.Read stays nil, and each view reads from its account's file. A view pins its account for each render only:
func (a *Accounts) CountView(key string, id int64) live.View {
topic := Topic(key, board.Topic(id))
return live.View{
Key: topic,
Topics: []string{topic},
Render: func(ctx context.Context, _ *sql.Tx) (any, error) {
var n int
err := a.View(ctx, key, func(tx *sql.Tx) error {
b, err := board.Load(ctx, tx, id)
for _, l := range b.Lanes {
n += len(l.Cards)
}
return err
})
if err != nil {
return nil, err
}
return sse.PatchElements(fmt.Appendf(nil, `<p id="cards">Cards on the board: %d</p>`, n)), nil
},
}
}
A stream that pinned its account for its whole life would keep the account open as long as the tab stays open, and push the pool past its cap. Pinned per render, an account whose tabs sit idle closes, and its next change opens it again.
An app that keeps shared data in a database of its own, a control plane of users and accounts say, gives that database to the hub's Read. A render's db.View(ctx, fn) on an account's database then sees that the render's transaction reads another file, and opens a transaction of its own on the account's pool.
Erasing an account
Deny(key, reason) makes every later Get of the key fail with reason, and Evict(ctx, key) closes the account now, pinned or not. Together they close an account for good, before its files go:
func (a *Accounts) Erase(ctx context.Context, key string) error {
if !validKey(key) {
return fmt.Errorf("tenants: %q is not an account", key)
}
a.pool.Deny(key, ErrErased)
if err := a.pool.Evict(ctx, key); err != nil {
return err
}
var errs []error
for _, suffix := range []string{"", "-wal", "-shm"} {
if err := os.Remove(a.path(key) + suffix); err != nil && !errors.Is(err, fs.ErrNotExist) {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
A restore runs the same way: Deny, Evict, put the restored file in place, then Allow(key) lifts the denial. Pins held on an evicted value go stale: releasing them does nothing. An account replicated with Litestream also has its replica purged and its Litestream directory removed (Backups).
Sizing the pool
maxOpen is a soft cap: Get never waits for a free slot, so pinned accounts can exceed it. Each open account holds a write connection, its readers with their page caches, and a writer goroutine. At the settings above each of the three connections may cache up to 2,000 KiB of pages, though with the file inside MmapBytes they hold far less (below). pool.Stats() reports the accounts open, pinned and opening, the cap, and the opens and evictions since start. Pinned close to MaxOpen is the state to alert on: nothing is left to evict, and every account that opens grows the pool past its cap.
Many databases in one process
The memory of an open database is mostly its connections, and a process with hundreds of them adds up fast. Past Readers and CacheKiB, the options below are off by default; a process with one database doesn't need them.
sqlite.Options.Readersis the most read connections a database opens, for a burst. An open reader holds its page cache, schema and cached statements: about 0.2 to 1 MiB once warmed, most of it statements when its cache is full.ReaderIdleTimecloses a reader that has sat idle that long, down to none, and leaves a burst its connections until then; database/sql runs one goroutine per pool for it while the pool has a connection open.IdleReadersbounds how many readers stay open idle. A connection that comes back while that many sit idle closes at once, during a burst too. SetReaderIdleTimefirst and keepIdleReadersat its default or at 1 or more:IdleReaders: -1opens a connection for every read onRoutside a transaction. A reopen parses the schema, about 0.15 to 0.6 ms with 40 tables and 0.3 to 1.6 ms with 120 by their columns and indexes, and the reads after it prepare their statements again.- What closing readers gives back depends on how many were open at once: modernc keeps part of that memory for the next connections. With 300 accounts whose two readers had all been open together,
ReaderIdleTimeleft about 600 KiB more per account thanIdleReaders: -1. CacheKiBis per connection, the write connection included, and a full cache takes about 1.9 times the setting in memory, since each 4 KiB page sits in an 8 KiB slot of modernc's allocator. Every connection maps the file (MmapBytes), the write connection too, and reads a page inside the map from it, in a write transaction as well, unless the WAL holds a copy not yet checkpointed. So a cache holds page 1, the pages in the WAL and, on the write connection, the pages it writes: in a probe of Libretto, up to 103 KiB on a reader and about 134 KiB on a writer. 2,000 KiB across 3 connections, up to about 11 MiB per account, is the ceiling only for connections that read past the map: a file larger thanMmapBytes, a negativeMmapBytes, or a WAL that holds as much. For the same reason a small page cache costs little read speed.- The write connection maps the file like the readers, so the pages that migrations and commands read through it do not stay in its cache while the account is open; it keeps the pages it writes.
- A page cache empties when its connection closes, and at the connection's next transaction after another connection committed, since its pages may be out of date. Other connections take its pages too: modernc builds SQLite with
SQLITE_ENABLE_MEMORY_MANAGEMENT, which puts the caches of all the process's connections in one group, so a connection whose cache is full takes the least recently used page of any connection, and frees what it holds when it closes. A restore verification'sintegrity_checkreads a whole database that way and takes the pages of the connections that sit idle, which is why memory drops during a verification pass: Libretto's first, ten minutes after a start, gave back about 420 MiB that the write connections of 128 accounts held.PRAGMA shrink_memoryon any connection frees every page of every connection in the process that no statement holds, in about 50 ms with 128 full caches.PRAGMA soft_heap_limitdoes nothing under modernc: the limit works from SQLite's memory statistics, which modernc's build turns off (SQLITE_DEFAULT_MEMSTATUS=0). - With a hub per database, each worker holds a read connection for the hub's life by default.
live.Options.ReleaseAftergives them back once the hub has rendered nothing for that long, and its next tick with work takes only the ones it renders with:Readers: 2then is plenty for a hub with one worker, since at rest it holds none. The pool closes a connection it gets back only withReaderIdleTimeset orIdleReadersnegative; otherwise it stays open idle. When the pool has none to give, the hub logs one warning for the whole wait, and the frames, the notices that wait for them and a new stream's first frames come with the first connection that frees. live.Options.Hibernategives an idle stream's encoder back. A stream asleep holds 32 KiB, and with a budget'sRefusethe smallest window its frame needs.HibernateFirst, such as 200 ms, makes a stream's first rest shorter, so that the streams of a deploy, which all reconnect at once, hand their encoders on to each other instead of each holding one (The first rest).- Hubs are not linked: one that gets no
SSE.Budgetmakes its own, half the memory limit each, and its ownSSE.Compresssemaphore. Share onesse.Budgetand one semaphore between them, withOptions.SSE, so the process's streams stay within one limit and one cap on compression. - An account attached to
lith/backupholds Litestream's state while it is attached. Litestream v0.5.18, which the module requires sincebackup/v0.3.3, keeps the encoder of the last file it wrote for each attached database, about 155 KiB of Go heap, until a fix upstream: about 10 MiB at 64 attached accounts, 78 MiB at 512. - An attached account closes in the order of a stop (Backups): its writer, then its reads, so that no read transaction is open, then detach, then the database, without a checkpoint of its own. Detach starts the WAL over, so the next open reads nothing from it. An account closed with its WAL's frames, by
backup/v0.3.3or with a read still open, reads those pages from the WAL into its connections' page caches at the next open instead of through the mapping, up toCacheKiBeach: 128 accounts of 11 MB, each closed with 717 frames, held 970 MiB more off the Go heap in their two readers. APRAGMA wal_checkpoint(TRUNCATE)before the close saves next to no memory now that the write connection maps the file, and the next attach uploads the whole database again.
Libretto, an app with a database per account, measured these at 256 accounts with Readers: 2 and ReaderIdleTime and ReleaseAfter at a minute. The process held 154 MiB less at rest, about 0.6 MiB per account and all of it off the Go heap. The saving is gone while the accounts are active. The first update after idle came about 60 to 120 ms later, at p50 and p95 on 2 CPUs, for the reopen and its statements. Hubs that wake together pay their reopens together: 60 hubs woken at once got their last first frame out after about 0.2 s on 20 cores, against 0.06 s with their connections kept.
GOMEMLIMIT covers the memory the Go runtime manages. modernc's SQLite allocates its page caches, statements and schema from a C heap of its own, mapped directly, outside what the Go runtime counts. Size GOMEMLIMIT as the unit's MemoryHigh minus that off-heap part, so the Go heap and SQLite together stay under the limit. Take the off-heap part from what your accounts measure: the worst case, every connection's cache full at 1.9 times CacheKiB, which only reads past the map reach, can exceed the limit at a few hundred accounts. sse.MemoryLimit reports the limit to start from and where it came from; lith never sets it. An app that derives the limit leaves GOMEMLIMIT out of its unit, since MemoryLimit reports a limit already set instead of the cgroup's:
limit, from := sse.MemoryLimit()
if from == "cgroup" && limit > 2*offHeap { // offHeap: what your accounts measure
debug.SetMemoryLimit(limit - offHeap)
}
budget := sse.NewBudget(sse.BudgetOptions{}) // half of the limit the runtime has now
Outside Linux MemoryLimit returns 0 and "", and the budget only counts. With GOMEMLIMIT already set it returns that and "GOMEMLIMIT", and the budget takes half of it. In both cases the example leaves the limit alone.