# Running in production

> Operate agdb_server in production: TLS, pepper, admin account, reverse proxy, durability, backups, monitoring and upgrades

This guide collects what an operator of `agdb_server` should set up beyond the defaults. It does not repeat the configuration reference, please see the [server reference](/docs/references/server) for every option and the [How to run the server?](/docs/guides/how-to-run-server) guides for the deployment methods (bare metal, Docker, Kubernetes, single node or cluster).

## TLS

The server serves TLS (via `rustls`) when both `tls_certificate` and `tls_key` are set in `agdb_server.yaml`. If either is empty the server listens on plain HTTP without any warning, so check the startup log for the `TLS enabled` line.

```yaml
# agdb_server.yaml
address: https://db.example.com:3000
tls_certificate: /etc/agdb/cert.pem
tls_key: /etc/agdb/cert.key.pem
tls_root: "" # only for a private CA, see below
```

- The `tls` cargo feature must be compiled in: `cargo install agdb_server --features tls` (requires CMake, see [bare metal](/docs/guides/how-to-run-server/server-bare-metal)). Without it the `tls_*` settings have no effect. The Docker image is built with all features.
- The certificate and key are read once on start. Restart the server to use a renewed certificate.
- `tls_root` is the root CA file the server trusts when it connects to the other nodes of a cluster. It is needed only if the nodes use certificates from a private CA or self-signed ones. The certificate must be valid for the names used in `address` and `cluster`.
- Rust clients need the `tls` feature of `agdb_api` to connect to an `https://` address: `cargo add agdb_api --features tls` (see the [Rust client](/api-docs/rust)).

If a reverse proxy terminates TLS for you (see below) the server itself can stay on plain HTTP on a private network, but `address` must still be the public `https://` address clients use.

## Password pepper

Passwords are stored as PBKDF2 hashes that include a 16 byte secret, the pepper. By default the server uses the pepper built into the binary (`agdb_server/pepper` in the sources), which is public. In production use your own, either baked in when [building the server](/docs/guides/how-to-run-server/server-bare-metal) or loaded at runtime:

```yaml
pepper_path: /run/secrets/agdb_pepper # a file with exactly 16 bytes
```

Surrounding whitespace in the file (such as a trailing newline) is trimmed and the server refuses to start if the file is unreadable or the value is not 16 bytes long.

<warning>

The pepper is part of every stored password hash. A server with a different pepper cannot verify any existing password, so store it as a secret, back it up, and never change it on a server that has users. All nodes of a cluster must use the same pepper. If it is lost, follow the recovery steps in the [bare metal guide](/docs/guides/how-to-run-server/server-bare-metal): start with a new pepper and a new `admin` name, then reset the passwords with `/api/v1/admin/user/{username}/change_password`.

</warning>

## Admin account

On the first start the server creates the user named by `admin` (default `admin`) with a password equal to its name. Change it before exposing the server:

```bash
token=$(curl -s -X POST -H 'Content-Type: application/json' localhost:3000/api/v1/user/login -d '{"username":"admin","password":"admin"}')
curl -X PUT -H "Authorization: Bearer ${token}" -H 'Content-Type: application/json' \
    localhost:3000/api/v1/user/change_password -d '{"password":"admin","new_password":"a-long-random-password"}'
```

New passwords must be at least 8 characters. Pick the `admin` name before the first start. On every start the server makes the user named by `admin` the admin, creating it with the password equal to its name if it does not exist, so changing the field later hands the admin role to that user (with a weak password if it is new) rather than renaming the existing admin (see [Configuration](/docs/references/server#configuration)). Use a regular user for day to day work and keep the admin for operations (see [Admin](/docs/references/server#admin)).

## Reverse proxy

To serve the server under a path of a proxy set `basepath` and `address`. The `address` holds only the scheme and host (a path in it is ignored with a warning) and the server serves all its routes, including `/studio/` when built with the `studio` feature, under `basepath`. The proxy must therefore forward the full path without stripping the prefix.

```yaml
bind: 127.0.0.1:3000
address: https://db.example.com
basepath: /agdb
request_body_limit: 10485760 # bytes, default 10 MiB
```

The `request_body_limit` caps the size of any request. Raise it if you send large query batches and set the proxy limit to at least the same value. In a cluster `request_body_limit` must be at least `cluster_max_append_size` plus 64 KiB (otherwise the node refuses to start) and any proxy between the nodes must accept the same size.

The snapshot a lagging node fetches from the leader is one long streamed response of `GET {basepath}/api/v1/cluster/snapshot/{id}`. The server sends it with `X-Accel-Buffering: no`, which nginx honours by default and passes the stream through unbuffered. Do not override that with `proxy_ignore_headers` or turn buffering on for this route.

A minimal nginx example (adapt it, it is not a complete hardened configuration):

```nginx
location /agdb/ {
    # no URI part in proxy_pass: the path is forwarded unchanged
    proxy_pass http://127.0.0.1:3000;
    proxy_set_header Host $host;
    client_max_body_size 10m; # at least request_body_limit
}
```

## Durability and memory

Three settings control how the databases are written and how much memory they take. Their meaning and trade-offs are explained in [Sync Mode](/docs/references/server#sync-mode), [Overlay Limit](/docs/references/server#overlay-limit) and the [storage concepts](/docs/guides/concepts#storage):

```yaml
sync_mode: none # none (default), commit or strict
overlay_limit: 67108864 # bytes of a transaction kept in memory before commit
memory_limit: 0 # bytes per user database, 0 = unlimited
```

`sync_mode` and `overlay_limit` apply to the server database, the cluster log and the user databases. `memory_limit` applies only to user databases. The values in use are logged on start (`sync_mode`, `overlay_limit`).

## Backups and restore

Back up on two levels.

**Per database** with the backup API. The database admin (or the server admin via `/api/v1/admin/db/...`) creates, restores or rolls back a backup:

```bash
curl -X POST -H "Authorization: Bearer ${token}" localhost:3000/api/v1/db/alice/my_db/backup
curl -X POST -H "Authorization: Bearer ${token}" localhost:3000/api/v1/db/alice/my_db/restore
```

- `backup` keeps one backup per database and overwrites the previous one.
- `restore` replaces the database with the backup and keeps the backup, so it can be repeated.
- `rollback` swaps the database and the backup, so calling it twice toggles between the two states (for `mapped` and `file` databases; for `memory` databases it behaves like `restore`).
- The audit log is backed up and restored together with the database.

For several generations of backups use `copy` and `rename` as described in [Backups](/docs/references/server#backups).

**Per server** by copying `data_dir` (default `agdb_server_data`):

<table>
<thead>
  <tr>
    <th>
      Path
    </th>
    
    <th>
      Content
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        agdb_server.agdb
      </code>
      
      , <code>
        .agdb_server.agdb
      </code>
    </td>
    
    <td>
      server database (users, sessions) and its WAL
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        agdb_server.log
      </code>
    </td>
    
    <td>
      cluster log (a database file)
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        .agcluster/staging
      </code>
    </td>
    
    <td>
      snapshots prepared for other nodes (cluster)
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        {owner}/{db}
      </code>
    </td>
    
    <td>
      user databases (and their dot-prefixed WAL files)
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        {owner}/backups/{db}.bak
      </code>
    </td>
    
    <td>
      the backups made by the backup API
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        {owner}/backups/{db}.audit
      </code>
    </td>
    
    <td>
      the audit log of the backup
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        {owner}/audit/{db}/YYYY-MM-DD.log
      </code>
    </td>
    
    <td>
      audit log, one file per UTC day
    </td>
  </tr>
</tbody>
</table>

Shut the server down (`/api/v1/admin/shutdown` or `CTRL+C`) before taking a file level copy and keep the [pepper](#password-pepper) and the configuration with it. Test the restore on a spare machine.

### Audit log retention

Every mutable query is recorded in the audit log, which grows with each write. Trim it regularly, e.g. from a scheduled job. The call keeps today and the given number of UTC days before it, in both the live log and the backup:

```bash
curl -X POST -H "Authorization: Bearer ${token}" "localhost:3000/api/v1/db/alice/my_db/audit/trim?keep_days=90"
```

The server admin can use `/api/v1/admin/db/{owner}/{db}/audit/trim` for any database. See [Audit](/docs/references/server#audit) for the details.

## Monitoring

<table>
<thead>
  <tr>
    <th>
      Endpoint
    </th>
    
    <th>
      Use
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        GET /api/v1/status
      </code>
    </td>
    
    <td>
      liveness / readiness probe, no token, <code>
        200 OK
      </code>
      
       when the node is up, always answered locally
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        GET /api/v1/admin/status
      </code>
    </td>
    
    <td>
      admin only: <code>
        uptime
      </code>
      
      , <code>
        dbs
      </code>
      
      , <code>
        users
      </code>
      
      , <code>
        logged_in_users
      </code>
      
      , <code>
        size
      </code>
      
       (data directory), <code>
        memory
      </code>
      
      , <code>
        log_level
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        GET /api/v1/cluster/status
      </code>
    </td>
    
    <td>
      no token: per node <code>
        address
      </code>
      
      , <code>
        status
      </code>
      
      , <code>
        leader
      </code>
      
      , <code>
        executed_index
      </code>
      
      , <code>
        resync
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        POST /api/v1/admin/set_log_level
      </code>
    </td>
    
    <td>
      admin only: <code>
        ?new_level=
      </code>
      
       one of <code>
        off
      </code>
      
      , <code>
        error
      </code>
      
      , <code>
        warn
      </code>
      
      , <code>
        info
      </code>
      
      , <code>
        debug
      </code>
      
      , <code>
        trace
      </code>
    </td>
  </tr>
</tbody>
</table>

- `memory` is the memory of the server process (reported as 0 on platforms other than Linux and Windows).
- Without a cluster `cluster/status` returns just the node itself as the leader. In a cluster it shows the nodes as the leader last reported them, so a node that has not heard from a leader recently reports only itself. A node with `resync: true` is catching up with the leader. Alert on a missing leader and on `executed_index` falling behind.
- The server logs to the standard output. Set the level with `log_level` in the configuration, or change it at runtime with `set_log_level`. The runtime change applies to the one node that received it and is not written to the configuration, so it is lost on restart.
- At the `debug` and `trace` levels the request and response bodies are logged, and at every level except `off` the body of a `5xx` response, truncated to `log_body_limit` bytes (default 10240, `0` disables the body logging). Bodies can contain sensitive data, so use these levels only temporarily. Below `debug` the polled status endpoints are not logged.

## Sessions and token expiry

A login creates a session token valid for `token_expiry_seconds` from the login (60 to 86400, default 3600). The expiry is not extended by using the token, clients log in again on `401`. Expired tokens are removed on start and periodically. Users can log out the current, all or other sessions, the admin can force a logout of a user or of all non-admin users, see [Users](/docs/references/server#users) and [Admin](/docs/references/server#admin). Use `/api/v1/cluster/user/login` to get one token valid on every node of a cluster.

## Upgrading

- Configuration changes require a restart. The server refuses to start with an invalid value or an unknown key, so check the log after a restart.
- Take a backup first (see above), especially for a cluster topology change, whose steps are in the [Cluster](/docs/references/server#cluster) section.
- The nodes of a cluster refuse messages of a cluster with a different agdb database version, `cluster` list or `cluster_max_log_entries`, so keep every node on the same release and these settings identical on all nodes.
- When upgrading from a version with the previous cluster implementation, the new version does not replay the old cluster log and removes it on start. Let all nodes catch up with the leader and stop them all before the upgrade so that they start with the same data.
- Audit logs in the older single-file format are converted automatically. Call `audit/trim` only after all nodes run a version that supports it.
- For a node that is down for long (e.g. during an upgrade) and fell behind the leader, see [Failures and repair](/docs/references/server#failures-and-repair): it receives a full snapshot from the leader.

## Production checklist

- [ ] TLS enabled on the server or a TLS terminating proxy in front, `address` set to the public URL
- [ ] Server built with the `tls` feature if the server terminates TLS
- [ ] Own pepper (`pepper_path` or built in), backed up and identical on all nodes
- [ ] `admin` password changed, regular users for applications
- [ ] `cluster_token` changed from the default `cluster` in a cluster, and treated as a secret
- [ ] `request_body_limit` and the proxy body limits consistent (cluster: at least `cluster_max_append_size` + 64 KiB)
- [ ] `sync_mode` chosen for your storage (see [Sync Mode](/docs/references/server#sync-mode))
- [ ] Regular database backups and audit trimming scheduled, a restore tested
- [ ] `/api/v1/status` wired to the health checks, `cluster/status` and `admin/status` monitored
- [ ] `log_level` at `info` in normal operation (not `debug` or `trace`)
- [ ] `token_expiry_seconds` set to what your clients need and no more

For common problems see [Troubleshooting](/docs/guides/troubleshooting).
