# Give every customer or agent its own database

Each tenant or agent gets its own SQLite file with a stable name, so you can place, restore, and move them one at a time.

- [All docs](https://litebackup.com/docs)

## How to place and hand off databases

- **A database for each tenant**. Keep each customer in a file of its own and back up the whole directory with one rule under a prefix such as tenants/, which also covers tenants you add later. Build file names from IDs your app created and validated, never from raw request input, and note that names keep their case, so ACME.sqlite and acme.sqlite are different databases.
- **Placing tenants on machines**. Because each name has one writer, assign each tenant to one machine and route its requests there, or use shard prefixes such as shards/eu-1/ for namespaces that are truly separate. To move a tenant, stop its writes, wait for its backup, stop the backup, and acquire the same name on the new machine before you send it traffic.
- **Acquire and release**. When any worker may handle any database, acquire it before the job opens it and release it afterwards. acquire takes the write lock and brings the newest version to this machine, release sends the final changes to your server, and the next machine to acquire the name continues from there.
- **New databases**. acquire fails with not_found for a name that has no version yet, so a typo never creates a database by accident. To create one, leave an empty file at the path first, and acquire turns it into a new database.
- **Copying a database under a new name**. To start a tenant or agent from the state of another, restore the version you want to a new file, then acquire the new name at that path, as in litebackup restore agents/42.sqlite /var/lib/app/agents/43.sqlite --version 120 followed by litebackup acquire agents/43.sqlite /var/lib/app/agents/43.sqlite. The copy is a new database that starts at version 1 with that content, and the original keeps its own versions.
- **Databases in use**. acquire fails with lock_unavailable while another machine holds the database. Retry with backoff under the same name, and let your scheduler run one job at a time for each agent or tenant.
- **Closing before release**. release fails with still_open while any process has the file open, so close every connection first. Treat a failed release as a failed job and keep the local file, because it holds the changes that have not been sent yet.
- **Disk space on busy workers**. release with offload removes the local copy once your server holds it, and the next acquire downloads it again. For backup rules that cover many files, maximumLocalDatabases offloads the idle ones above a count you choose.

## Run an agent with a database of its own

The agent acquires its database, works on it with any driver, and releases it so the next run can continue on any machine.

### TypeScript

```ts
import Database from "better-sqlite3";
import { ErrorCode, Litebackup, LitebackupError } from "@litebackup/sdk";
import { adapter } from "@litebackup/sdk/better-sqlite3";

const litebackup = new Litebackup();
const pool = litebackup.databases.pool({ adapter: adapter(Database) });

try {
  // A new agent's first lease creates its database; later ones continue from the latest version.
  await pool.lease(
    "agents/42.sqlite",
    { path: "/var/lib/app/agents/42.sqlite", lockTimeout: "2m" },
    (db) => {
      db.exec("CREATE TABLE IF NOT EXISTS memory (id INTEGER PRIMARY KEY, body TEXT)");
      db.prepare("INSERT INTO memory (body) VALUES (?)").run("Tests passed on main");
    },
  );
} catch (error) {
  if (error instanceof LitebackupError && error.code === ErrorCode.lockUnavailable) {
    console.error("This agent is running on another machine; try again later");
    process.exit(75);
  }
  throw error;
} finally {
  // Closing the pool closes the database and releases it once your server has the run's progress.
  await pool.close();
}
```

### Go

```go
package main

import (
	"context"
	"database/sql"
	"errors"
	"log"
	"time"

	_ "github.com/mattn/go-sqlite3"

	"github.com/litebackup/sdk/litebackup"
)

func main() {
	ctx := context.Background()
	client, err := litebackup.Default(ctx)
	if err != nil {
		log.Fatal(err)
	}
	pool, err := litebackup.NewPool(client, &litebackup.PoolArgs[*sql.DB]{
		Adapter: litebackup.SQLAdapter("sqlite3", nil),
	})
	if err != nil {
		log.Fatal(err)
	}
	// A new agent's first lease creates its database; later ones continue from the latest version.
	err = pool.Lease(ctx, "agents/42.sqlite", &litebackup.LeaseArgs{
		Path:        "/var/lib/app/agents/42.sqlite",
		LockTimeout: 2 * time.Minute,
	}, func(ctx context.Context, db *sql.DB) error {
		_, err := db.ExecContext(
			ctx,
			"CREATE TABLE IF NOT EXISTS memory (id INTEGER PRIMARY KEY, body TEXT)",
		)
		return err
	})
	if litebackup.IsCode(err, litebackup.CodeLockUnavailable) {
		log.Fatal("this agent is running on another machine; try again later")
	}
	// Closing the pool closes the database and releases it once your server has the run's progress.
	if err := errors.Join(err, pool.Close(ctx)); err != nil {
		log.Fatal(err)
	}
}
```

### Command line

```bash
# Create, acquire, and release a SQLite database for one agent.
# Runs on Linux and macOS.
mkdir -p /var/lib/app/agents
touch /var/lib/app/agents/42.sqlite   # an empty file becomes a new database

litebackup acquire agents/42.sqlite /var/lib/app/agents/42.sqlite --timeout 2m
sqlite3 /var/lib/app/agents/42.sqlite <<'SQL'
CREATE TABLE IF NOT EXISTS memory (id INTEGER PRIMARY KEY, body TEXT);
INSERT INTO memory (body) VALUES ('Tests passed on main');
SQL
litebackup release agents/42.sqlite --timeout 30m
```
