served

Articles ·

One database per customer

Giving every customer their own SQLite file removes a whole class of bugs. What the pattern buys you, what it costs, and how to run it.

The usual way to keep customers' data apart is a customer_id column on every table and a WHERE customer_id = ? on every query. It works until the day someone forgets the WHERE.

There is an older, blunter way: give each customer their own database. With most databases that is impractical, because each one is a server process or at least a heavy object. With SQLite, a database is a file. A thousand customers is a thousand files.

What it buys

What it costs

Running it on Served

One API key covers any number of databases, and a database that is not being used costs only the disk it occupies, so the pattern maps directly.

When a customer signs up, create their database and apply the schema in one transaction. Creating is safe to repeat, so the signup code can be retried.

curl https://api.served.dev/v1/databases \
  -H "Authorization: Bearer $SERVED_KEY" -d '{"name": "cust-4182"}'

curl https://api.served.dev/v1/databases/cust-4182/query \
  -H "Authorization: Bearer $SERVED_KEY" \
  -d '[{"sql": "CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY, total INTEGER, placed_at TEXT)"},
       {"sql": "PRAGMA user_version = 1"}]'

Name the database from your own customer id, not from anything the customer types. Names are lowercase letters, digits, - and _.

For migrations, use PRAGMA user_version, which SQLite stores in the file for exactly this purpose. List the databases, and for each one read the version and apply what is missing, with the new version number set in the same transaction as the change:

[{"sql": "ALTER TABLE orders ADD COLUMN currency TEXT DEFAULT 'USD'"},
 {"sql": "PRAGMA user_version = 2"}]

If the loop stops halfway, run it again. Databases already at version 2 are skipped.

When a customer asks for their data, the download endpoint gives you the file to pass on. When they leave, DELETE /v1/databases/cust-4182 removes it.

When not to

If your product is mostly about what customers have in common, such as a marketplace or a social feed, their data is not really separate and separate files will fight you. The pattern suits products where each customer's data is their own world: a workspace, a project, a shop, a device, an agent.

It also suits agents unusually well, for the same reasons. A task that gets its own database cannot trample another task's tables, and when the task is done, so is the database.

Served is hosted SQLite. Real SQLite behind an HTTP API, $3 a month, and the file is yours to download whenever you like.

Read the docs