# SurrealDB documentation - CLI and Studio

> surreal db, surreal cloud, environment variables, Studio. This is one of the bundles the SurrealDB documentation is split into. The page index at https://surrealdb.com/docs/llms.txt lists every bundle, and https://surrealdb.com/docs/llms-full.txt holds every page. Each page starts with a "Source:" line naming its canonical URL, and every page is also available individually by appending `.md` to its URL. In code examples, a fenced block whose title contains "output" holds the result of the block above it rather than runnable code, and a qualifier such as "Example output" or "Possible output" means the value shown is one of several possible ones. Inside a block, a "//-" comment marks a value the statement above it returned, while "--" is an ordinary comment.

---

Source: https://surrealdb.com/docs/reference/cli

# CLI tools

Overview of every command in the surreal launcher, surreal db, surreal cloud and surreal ext, with links to each reference page, plus the separate surqlfmt formatter.

SurrealDB has one command line, `surreal`. The `surreal` launcher installs once, then installs, versions and runs **components**, each with its own commands: the database (`surreal db`), SurrealDB Cloud (`surreal cloud`) and SurrealDB extensions (`surreal ext`). This section is the reference for all of them. For how they fit together, start with the [SurrealDB CLI guide](/docs/reference/cli/guides.md).

```bash
surreal install cloud
surreal db start --user root --pass secret
surreal cloud instance list
```

| Reference | Covers |
| --- | --- |
| [Launcher commands](/docs/reference/cli/launcher.md) | Installing, upgrading, pinning and removing components, version names, `+VERSION`, and the launcher's environment variables |
| [`surreal db`](/docs/reference/cli/db.md) | The database: run a server, query it, and move data in and out |
| [`surreal cloud`](/docs/reference/cli/cloud.md) | SurrealDB Cloud: organisations, instances, backups, members and tokens |
| [`surreal ext`](/docs/reference/cli/ext.md) | SurrealDB extensions |
| [`surqlfmt`](/docs/reference/cli/formatter/overview.md) | Formatting `.surql` files, distributed separately as an npm package |

## Launcher commands

These commands belong to the launcher, and nothing else installs or changes component versions. See [Launcher commands](/docs/reference/cli/launcher.md) for options and examples.

| Command | Purpose |
| --- | --- |
| `surreal install <COMPONENT[@VERSION]>...` | Install components, or another version of one beside those installed |
| `surreal upgrade [<COMPONENT[@VERSION]> \| cli]...` | Upgrade the launcher and every installed component, or those named |
| `surreal use <COMPONENT@VERSION>` | Make an installed version the default |
| `surreal uninstall <COMPONENT[@VERSION]>...` | Remove a version, or a component entirely |
| `surreal list` | Show each component, the version that runs, and where it runs from |
| `surreal --version` | Print the launcher's own version |
| `surreal +VERSION <COMPONENT> ...` | Run another version for one command |
| `surreal help` | Print the launcher's help |

## surreal db

The database component. Everything after `db` goes to the database, so the same flags and `SURREAL_*` variables apply. Each command has its own page under [database commands](/docs/reference/cli/db/commands.md).

| Command | Purpose |
| --- | --- |
| [`surreal db start`](/docs/reference/cli/db/commands/start.md) | Run a SurrealDB server |
| [`surreal db sql`](/docs/reference/cli/db/commands/sql.md) | Open an interactive SurrealQL shell |
| [`surreal db import`](/docs/reference/cli/db/commands/import.md) | Load a SurrealQL file into a database |
| [`surreal db export`](/docs/reference/cli/db/commands/export.md) | Dump a database to SurrealQL |
| [`surreal db is-ready`](/docs/reference/cli/db/commands/isready.md) | Check that a server accepts connections |
| [`surreal db validate`](/docs/reference/cli/db/commands/validate.md) | Validate SurrealQL files |
| [`surreal db fix`](/docs/reference/cli/db/commands/fix.md) | Repair storage issues |
| [`surreal db mcp`](/docs/reference/cli/db/commands/mcp.md) | Run the Model Context Protocol server over stdio |
| [`surreal ext`](/docs/reference/cli/ext.md) | Build, sign, install and run SurrealDB extensions |
| [`surreal db version`](/docs/reference/cli/db/commands/version.md) | Print the database or server version |

The old top-level forms, such as `surreal start`, still run and print a deprecation warning. Upgrading the database is `surreal upgrade db`, a launcher command.

## surreal cloud

The SurrealDB Cloud component. Every command takes `--json`, and sends its data to stdout and everything else to stderr. See [global flags](/docs/reference/cli/cloud/global-flags.md) and [output and exit codes](/docs/reference/cli/cloud/output-and-exit-codes.md).

| Command | Purpose |
| --- | --- |
| [`surreal cloud auth`](/docs/reference/cli/cloud/commands/auth.md) | Sign in, sign out, and inspect credentials |
| [`surreal cloud org`](/docs/reference/cli/cloud/commands/org.md) | Manage organisations, usage, spend and plans |
| [`surreal cloud instance`](/docs/reference/cli/cloud/commands/instance.md) | Create, scale, pause, back up, connect to and delete instances |
| [`surreal cloud team`](/docs/reference/cli/cloud/commands/team.md) | Manage organisation members |
| [`surreal cloud invite`](/docs/reference/cli/cloud/commands/invite.md) | Manage organisation invitations |
| [`surreal cloud token`](/docs/reference/cli/cloud/commands/token.md) | Manage personal access tokens |
| [`surreal cloud catalog`](/docs/reference/cli/cloud/commands/catalog.md) | Browse regions, instance types and versions |
| [`surreal cloud config`](/docs/reference/cli/cloud/commands/config.md) | Read and write configuration |
| [`surreal cloud context`](/docs/reference/cli/cloud/commands/context.md) | Inspect and switch profiles |
| [`surreal cloud whoami`, `api`, `open`, `status`, `version`, `completion`](/docs/reference/cli/cloud/commands/misc.md) | Identity, raw API calls, dashboard links, diagnostics and shell completions |

## surreal ext

The SurrealDB extension component, which builds, signs and installs extensions. Its first release is not published yet. Before SurrealDB 4.0, the same commands were `surreal db module`. See [`surreal ext`](/docs/reference/cli/ext.md).

## SurrealQL formatter

`surqlfmt` reformats `.surql` files to a consistent style. It is distributed as an npm package rather than as a component of `surreal`, which makes it easy to pin in a project and run in CI.

```bash
npm install -g @surrealdb/surql-fmt
surqlfmt --check ./src/**/*.surql
```

See the [SurrealQL formatter reference](/docs/reference/cli/formatter/overview.md) for its options and usage patterns.

---

Source: https://surrealdb.com/docs/reference/cli/cloud

# surreal cloud reference

What surreal cloud is, where the control plane ends and the database commands begin, how it relates to the former surrealctl, the command grammar, and how this reference is organised.

`surreal cloud` is the component of the [`surreal` launcher](/docs/reference/cli/launcher.md) that manages SurrealDB Cloud from the command line. It is the control plane: it creates and scales instances, reads logs and metrics, manages organisation members and invitations, and mints credentials, all through the SurrealDB API at `https://api.surrealdb.com`.

This reference is for operators, CI pipelines and agents. Every command emits machine-readable JSON on request, keeps its data payload on stdout, and returns an exit code precise enough to branch on.

For installing the launcher, see [Install](/docs/reference/cli/guides/install.md). The launcher offers to fetch `surreal cloud` the first time you run it, or you can install it ahead of time with `surreal install cloud`. For a first walkthrough, see the [guide](/docs/reference/cli/guides/cloud.md).

## Coming from surrealctl

`surreal cloud` was previously the standalone `surrealctl` tool. The commands and flags are the same, so a script written for `surrealctl` works after replacing the program name with `surreal cloud`. Two things migrate automatically:

- **Configuration and login.** On its first run, `surreal cloud` copies your configuration and stored login from `~/.config/surrealctl` (`%APPDATA%\surrealctl` on Windows) to `~/.surrealdb/cloud`. The original is left in place, and from then on the two are independent.
- **Environment variables.** `SURREALCTL_*` variables still work as deprecated aliases for their `SURREAL_CLOUD_*` replacements. When one is set, a single warning on stderr lists each old name with its replacement. The new name wins when both are set.

The `--json` contract and the exit codes are unchanged.

## The control plane and the data plane

`surreal cloud` owns the **control plane**: the resources around a database - instances, organisations, members, tokens, capabilities, backups. The database commands, `surreal db ...`, own the **data plane**: queries, imports, exports, and running a server. Both are reached through the same `surreal` launcher, and `surreal cloud` follows the same conventions so you can move between them without relearning anything.

| Task | Command |
| --- | --- |
| Create, scale, pause or delete a Cloud instance | `surreal cloud instance` |
| Read an instance's logs, metrics or usage | `surreal cloud instance` |
| Invite a colleague, change their role | `surreal cloud team`, `surreal cloud invite` |
| Mint a database token or fetch a key set | `surreal cloud instance token`, `surreal cloud instance jwks` |
| Run a SurrealQL query | [`surreal db sql`](/docs/reference/cli/db/commands/sql.md) |
| Run a local server | [`surreal db start`](/docs/reference/cli/db/commands/start.md) |

Three commands cross the boundary. [`instance sql`](/docs/reference/cli/cloud/commands/instance.md#instance-sql), [`instance import`](/docs/reference/cli/cloud/commands/instance.md#instance-import) and [`instance export`](/docs/reference/cli/cloud/commands/instance.md#instance-export) resolve the instance, mint a database token, and hand off to `surreal db sql`, `surreal db import` or `surreal db export` through the launcher rather than reimplementing SurrealQL. Everything after a `--` separator is forwarded to the database command verbatim.

`surreal cloud` never installs or locates the database itself. The launcher does, and it offers to install the database if it is missing. Run on its own, outside the launcher, the three handoff commands refuse and say how to run them. See [Components](/docs/reference/cli/guides/components.md) for how the launcher runs them.

## Command grammar

The grammar is regular, so it only has to be learned once:

- **Groups are singular nouns.** `instance`, not `instances` - the plural is a visible alias.
- **Verbs are `list`, `get`, `create`, `update`, `delete`.** The only aliases are `ls` for `list` and `rm` for `delete`.
- **Destructive commands take `--force`**, never `--skip-confirmations`. The global `--yes` pre-answers every confirmation in one invocation.
- **`--json` is the only encoding switch.** There is no `--format`.
- **Two deliberate exceptions**, both in `team`: `team remove` ends a membership rather than deleting a person, and `team invite` sends an invitation, which no house verb covers.

Any noun group invoked on its own prints its own help, and `help` works at every level:

```bash
surreal cloud instance
surreal cloud help instance create
```

## How this reference is organised

The cross-cutting pages describe behaviour shared by every command. Read them once.

| Page | Covers |
| --- | --- |
| [Authentication](/docs/reference/cli/cloud/authentication.md) | Login sessions, personal access tokens, and where credentials are stored |
| [Global flags](/docs/reference/cli/cloud/global-flags.md) | The 16 flags every command accepts, their environment variables, and the precedence chain |
| [Output and exit codes](/docs/reference/cli/cloud/output-and-exit-codes.md) | The `--json` contract, the stream split, list presentation flags, and every exit code |
| [Long-running operations](/docs/reference/cli/cloud/long-running-operations.md) | `--wait`, `--no-wait`, polling behaviour, and exit code `10` |

The command pages document every flag, argument and refusal, one page per group. The [commands index](/docs/reference/cli/cloud/commands.md) lists every command:

| Group | Purpose |
| --- | --- |
| [`auth`](/docs/reference/cli/cloud/commands/auth.md) | Sign in, sign out, and inspect credentials |
| [`org`](/docs/reference/cli/cloud/commands/org.md) | Manage organisations, roles, usage and spend |
| [`instance`](/docs/reference/cli/cloud/commands/instance.md) | Manage instances, capabilities and backups |
| [`team`](/docs/reference/cli/cloud/commands/team.md) | Manage organisation members |
| [`invite`](/docs/reference/cli/cloud/commands/invite.md) | Manage organisation invitations |
| [`token`](/docs/reference/cli/cloud/commands/token.md) | Manage personal access tokens |
| [`catalog`](/docs/reference/cli/cloud/commands/catalog.md) | Browse the platform catalogues |
| [`config`](/docs/reference/cli/cloud/commands/config.md) | Read and write configuration |
| [`context`](/docs/reference/cli/cloud/commands/context.md) | Inspect and switch profiles |
| [`whoami`, `api`, `open`, `status`, `version`, `completion`](/docs/reference/cli/cloud/commands/misc.md) | Identity, the raw API escape hatch, and diagnostics |

## Reference syntax

Usage blocks in this reference use one notation throughout:

| Notation | Meaning |
| --- | --- |
| `<NAME>` | A required value you supply |
| `[NAME]` | An optional value you supply |
| `[OPTIONS]` | Zero or more flags |
| `...` | The preceding item may be repeated |
| `--` | Everything after this separator is passed to another program |

Usage blocks are notation, not commands - they carry brackets a shell will not accept. Copy from the examples instead.

## Resource references

Most commands accept a resource by more than one spelling. An organisation is named by id or name. An instance is named by id, slug, name, or `org/name`. A bare id is used without a lookup; anything else is resolved against the organisation in force, and an unrecognised name is answered with a did-you-mean list.

Omit the reference entirely and, on a terminal, the command offers an interactive picker. In a non-interactive session it exits `2` and lists what was available, so a CI failure names the fix.

```bash
surreal cloud instance get production
surreal cloud instance get acme/production
surreal cloud instance get 67upif0m8sh1cn1p2c8t
```

---

Source: https://surrealdb.com/docs/reference/cli/cloud/authentication

# surreal cloud authentication

How surreal cloud signs in, the difference between a login session and a personal access token, what a token cannot do, and where credentials are stored on disk.

`surreal cloud` holds one credential per profile. There are two kinds, and they differ in what they can *write* rather than in what they can reach.

| Credential | Created by | Suited to |
| --- | --- | --- |
| **Login session** | `surreal cloud auth login` | Interactive use. Can do everything your role allows. |
| **Personal access token** | `surreal cloud token create`, or the dashboard | CI and automation. Read-only on the Cloud surface. |

A login session is an OAuth 2.0 authorisation-code flow with PKCE against `https://auth.surrealdb.com/`. It stores a refresh token and one access token per audience, and renews them as they expire. A personal access token is a long-lived `sdbp_…` string that carries a fixed set of scopes and never expires on a schedule.

## Signing in

```bash
surreal cloud auth login
```

The command tries three flows in order, and stops at the first one that can run.

| Flow | Used when |
| --- | --- |
| Browser loopback | A browser is available and a `127.0.0.1` port can be bound |
| Device code | `--flow device`, or no browser is available |
| Paste | `--flow paste`, or nothing else could run |

Only *mechanical* failures fall through to the next flow - specifically, the loopback listener failing to bind or serve. If you decline the consent screen, or your email address is unverified, the command says so rather than asking again in a different form. An incomplete interactive flow exits `30`.

Naming a flow explicitly means it is used or it fails; there is no silent substitution.

```bash title="Sign in on a machine with no browser"
surreal cloud auth login --flow device
```

The browser flow is skipped automatically when `SSH_CONNECTION` or `SSH_TTY` is set, because a browser at the far end of an SSH connection opens on the wrong machine.

Signing in when the profile already holds a credential is a no-op that exits `0`. Pass `--force` to replace it.

```bash title="Sign in to a second profile"
surreal cloud --profile staging auth login
```

### How the browser flow is hardened

These details matter when a corporate network is in the way:

- The listener binds the literal `127.0.0.1`, never `localhost`, which resolves through `/etc/hosts` and DNS and can answer on `::1`.
- One of four ports is used - `9375`, `9376`, `9377`, `9378` - because the identity provider matches callback URLs exactly.
- Only `/callback` is answered; anything else gets a 404.
- The `state` parameter is compared in constant time, and the flow has a 180-second deadline.
- The device flow gets 600 seconds, because a device code is typed on a phone.

## Personal access tokens

A token is supplied per invocation and is never persisted:

**Bash**

```bash title="From the environment - the usual choice in CI"
export SURREAL_CLOUD_TOKEN=sdbp_...
surreal cloud instance list
```

**PowerShell**

```powershell title="From the environment - the usual choice in CI"
$env:SURREAL_CLOUD_TOKEN = "sdbp_..."
surreal cloud instance list
```

```bash title="From a file, or from stdin"
surreal cloud --token-file /run/secrets/surreal-cloud instance list
cat /run/secrets/surreal-cloud | surreal cloud --token-file - instance list
```

`--token` and `--token-file` are mutually exclusive: a credential comes from a flag or from a file, never both. `--token` deliberately has no short form, because `-t` reads as `--type` on the instance commands, and because a credential belongs in the environment or a file rather than in `argv`, where `ps` and shell history can both see it.

The only way to *store* a token is `auth login --with-token`, which reads it from stdin:

```bash
echo "$SURREAL_CLOUD_TOKEN" | surreal cloud auth login --with-token --label "ci runner"
```

### What a personal access token cannot do

**It cannot manage personal access tokens.** All four verbs - `token list`, `token create`, `token delete` and `token scopes` - are refused locally, before any request is sent, and exit `4`. A leaked token must not be able to mint its own replacements, nor revoke the one an operator would use to clean up after it.

```text
Managing personal access tokens needs an interactive login session, so nothing was sent.

Sign in with:  surreal cloud auth login
```

**It cannot make Cloud writes.** The gateway refuses a token on every non-`GET` Cloud route, so the mutating verbs - `instance create`, `org update` and the rest - answer 403, exit `4`, even when the token carries the matching write scope. Use a login session for those.

**It cannot exceed its scopes.** A missing scope is a 403 naming the scope, relayed rather than predicted.

Everything else works, including `org list`, `instance list`, `instance endpoint`, `instance token`, `auth status`, `auth scopes` and `auth logout`.

### Scopes

The scope vocabulary is shared with the Cloud MCP tools, and the set offered depends on the account. The common ones are:

| Scope | Grants |
| --- | --- |
| `read:cloud` | Read access across the Cloud surface |
| `write:cloud-instances` | Create, update and delete instances |
| `write:cloud-organization` | Change organisation settings and membership |
| `write:cloud-billing` | Change billing details |

Two commands answer two different questions. [`token scopes`](/docs/reference/cli/cloud/commands/token.md#token-scopes) is the catalogue of what *can* be granted; [`auth scopes`](/docs/reference/cli/cloud/commands/auth.md#auth-scopes) is what the credential in hand *carries*.

`auth scopes` on a login session returns an empty list and points you at [`org permissions`](/docs/reference/cli/cloud/commands/org.md#org-permissions), because OAuth identity scopes are not an authorisation model - your role in the organisation is.

## What each `auth` verb does when nothing is signed in

| Verb | Behaviour |
| --- | --- |
| `auth status` | Succeeds, exit `0` |
| `auth logout` | Succeeds, exit `0`, and still emits a document |
| `auth scopes` | Exits `3` |
| `auth refresh` | Exits `3` |

A diagnostic that errors because there is no credential cannot help you fix it, and logging out of nothing is a no-op rather than a failure - a teardown script must not fail on its second run. `scopes` and `refresh` each answer a question *about* a credential, and with none there is no answer to give.

`auth status` and `auth scopes` touch no network at all, so they work on a plane, in a container with no egress, and in a CI job that is about to fail for a different reason. [`whoami`](/docs/reference/cli/cloud/commands/misc.md#whoami) is the command that asks the API who you are.

## Where credentials are stored

One directory holds everything:

| Path | Holds |
| --- | --- |
| `config.toml` | Non-secret configuration: profiles, the persisted organisation |
| `credentials.json` | Tokens, the Cloud user id, and the observed clock skew |
| `credentials.lock` | A zero-byte advisory lock file |

The directory is created mode `0700`, and `credentials.json` mode `0600`. The split between the two files is about **atomicity, not sensitivity**: the few non-secret values that must be replaced in the same transaction as a token live beside it in `credentials.json`.

`config.toml` is safe to commit or to sync into a dotfiles repository. `credentials.json` is not.

### Paths

The directory is resolved in this order:

1. The path given to `--config` (or `SURREAL_CLOUD_CONFIG`): the directory itself, or the directory containing a file
2. `SURREAL_CLOUD_CONFIG_DIR`
3. `cloud` inside the SurrealDB home: `~/.surrealdb/cloud`, or `$SURREAL_CLI_HOME/cloud` when `SURREAL_CLI_HOME` is set to an absolute path

On Windows the default is `%USERPROFILE%\.surrealdb\cloud`.

On its first run, when the default directory does not exist and the one used by the former `surrealctl` does, `surreal cloud` copies `~/.config/surrealctl` (`%APPDATA%\surrealctl` on Windows) into it, stored login included, and prints one note saying so. The original is never moved or removed, so a `surrealctl` still installed keeps working, and from then on the two are independent: signing in or out of one does not change the other. An explicit `--config` or `SURREAL_CLOUD_CONFIG_DIR` is left alone, and an existing new directory is never touched.

```bash title="Print the resolved path"
surreal cloud config path
```

### Permissions are enforced, not warned about

Reading `credentials.json` with any group or other bit set is a hard error:

```text
/Users/ana/.surrealdb/cloud/credentials.json is mode 644 and holds a refresh token.
Fix it with:  chmod 600 /Users/ana/.surrealdb/cloud/credentials.json
```

The file is created with its final mode, so there is no window in which it is readable by anyone else. Windows has no file mode, and the check does not apply there.

### Why a file, and not the OS keyring

This reverses the obvious default deliberately. macOS keychain ACLs are bound to the requesting binary's code signature, so a CLI installed by `cargo install` or Homebrew re-prompts *"surreal-cloud wants to use your confidential information"* after every upgrade - unanswerable inside a CI job. Headless Linux and containers have no Secret Service at all. `gh`, `aws`, `gcloud` and `flyctl` are all file-based for the same reasons.

There is **no keyring backend**. If one is ever added, the rule it has to follow is that selecting it and finding it unavailable fails loudly rather than silently downgrading to the file.

### Concurrent invocations

Refresh-token rotation makes a race genuinely dangerous: a losing racer presents an already-consumed refresh token, and the identity provider's breach detection may then invalidate the whole token family, signing you out everywhere.

So every mutation takes an exclusive advisory lock on `credentials.lock`, re-reads under the lock in case a sibling has already refreshed, performs the network call inside the lock, and writes through a temporary file in the same directory followed by an atomic rename. Readers take no lock at all, because a rename is atomic - a reader sees either the old file or the new one, never a mix.

The diagram below shows two processes refreshing at the same moment, without and with the lock.

<img src="~/assets/img/diagrams/light/ops-cli-refresh-lock-light.webp" darkSrc="~/assets/img/diagrams/ops-cli-refresh-lock.webp" alt="Two surreal cloud processes refreshing at the same moment. Without a lock, both read refresh token R1. Process A refreshes with R1, gets R2 and writes it. Process B then refreshes with R1, which is already used, and the identity provider may revoke the whole token family, which signs out both processes and every other session using it. With the lock on credentials.lock, process A takes the lock, re-reads R1, refreshes to get R2, writes a temporary file and renames it, and releases the lock. Process B waits for the lock, for up to 30 seconds, takes it, re-reads the file, finds R2 already fresh, and sends nothing." />

The lock budget is 30 seconds. Past that:

```text
another surreal-cloud is updating credentials (waited 30s for /Users/ana/.surrealdb/cloud/credentials.lock).
Retry in a moment.
```

### Clock skew

Skew is learned from the `Date` header on every response, successful or not - a 401 caused by a bad clock is exactly the case this fixes - and folded into the next write rather than triggering one. `auth status` warns when the observed skew exceeds five minutes.

Only an `invalid_grant` from the identity provider ever deletes a stored session. Local time is an input to scheduling, never to invalidation, which is what stops a broken clock from becoming a lockout.

## Renewing and signing out

```bash title="Renew now, rather than waiting for expiry"
surreal cloud auth refresh
```

`auth refresh` forces both the access token and the Cloud session. `--all` additionally renews the token used for the account-management routes. On a personal access token it reports that a token does not expire on a schedule and cannot be refreshed, then exits `0` without sending anything.

```bash title="Remove the stored credential for this profile"
surreal cloud auth logout
```

`auth logout` revokes the refresh token at the identity provider on a best-effort basis and removes only this profile's entry. A failed revocation never blocks the local wipe, but does produce a warning:

```text
warning: The refresh token could not be revoked at the identity provider. It was removed from this
machine, but may still be usable elsewhere.
```

## What is sent on the wire

Two headers carry the credential, and they are attached in one place in the client rather than by individual commands:

| Header | Value |
| --- | --- |
| `Authorization` | `Bearer <access token or sdbp_… token>` |
| `X-Cloud-Token` | The bare Cloud session JWT, with no `Bearer ` prefix - added only for routes that need it |

Every request also carries `X-Request-Id` (a client-minted identifier, echoed back and reported in error output), `X-Client-Name`, `X-Client-Version` and a `User-Agent` naming the version and build target.

`--debug` logs every request and response to stderr with the credential reduced to a digest - `Authorization: Bearer <sha256:8f3a91c4>` - so a debug transcript can be pasted into an issue.

## Advanced environment variables

Three variables exist for support and for non-production tenants. They are absent from `--help` on purpose.

| Variable | Purpose |
| --- | --- |
| `SURREAL_CLOUD_SESSION_TOKEN` | Supply an already-minted Cloud session token, bypassing sign-in. For debugging and support reproduction only: the session lives about an hour, so it is no use as a CI credential. `auth status` reports when it is set. |
| `SURREAL_CLOUD_AUTH_CLIENT_ID` | Override the OAuth client id, for a non-production tenant |
| `SURREAL_CLOUD_AUTH_ISSUER` | Override the OAuth issuer, for a non-production tenant |

Use a [personal access token](#personal-access-tokens) for automation. It is the only credential designed to be handed to a machine.

## Related pages

- [`auth` commands](/docs/reference/cli/cloud/commands/auth.md) - every flag on every verb
- [`token` commands](/docs/reference/cli/cloud/commands/token.md) - creating and revoking tokens
- [Global flags](/docs/reference/cli/cloud/global-flags.md) - `--token`, `--token-file`, `--profile`
- [surreal cloud reference](/docs/reference/cli/cloud.md) - the rest of the reference
- [Database CLI](/docs/reference/cli/db.md) - database credentials, which are a separate concern from these

---

Source: https://surrealdb.com/docs/reference/cli/cloud/commands

# surreal cloud commands

A map of every surreal cloud command group and leaf command, with links to the page documenting each one.

`surreal cloud` groups its commands by noun. A group on its own prints its own help; the leaf commands below do the work. Every command accepts the [global flags](/docs/reference/cli/cloud/global-flags.md), and every command except [`token create`](/docs/reference/cli/cloud/commands/token.md#token-create) accepts `--json`.

| Group | Leaf commands |
| --- | --- |
| [`auth`](/docs/reference/cli/cloud/commands/auth.md) | `login`, `logout`, `status`, `refresh`, `scopes` |
| [`org`](/docs/reference/cli/cloud/commands/org.md) | `list`, `get`, `create`, `update`, `archive`, `use`, `roles`, `permissions`, `usage`, `spend`, `plans` |
| [`instance`](/docs/reference/cli/cloud/commands/instance.md) | `list`, `get`, `create`, `update`, `delete`, `pause`, `resume`, `watch`, `status`, `endpoint`, `token`, `jwks`, `sql`, `import`, `export`, `metrics`, `logs`, `usage`, `estimate`, `capabilities get`, `capabilities set`, `backup list`, `backup create`, `backup policy get`, `backup policy set` |
| [`team`](/docs/reference/cli/cloud/commands/team.md) | `list`, `get`, `invite`, `update`, `remove` |
| [`invite`](/docs/reference/cli/cloud/commands/invite.md) | `list`, `create`, `delete` |
| [`token`](/docs/reference/cli/cloud/commands/token.md) | `list`, `create`, `delete`, `scopes` |
| [`catalog`](/docs/reference/cli/cloud/commands/catalog.md) | `regions`, `instance-types`, `storage-types`, `instance-versions`, `billing-countries` |
| [`config`](/docs/reference/cli/cloud/commands/config.md) | `list`, `get`, `set`, `unset`, `path`, `edit` |
| [`context`](/docs/reference/cli/cloud/commands/context.md) | `show`, `use`, `list` |
| [Other commands](/docs/reference/cli/cloud/commands/misc.md) | `whoami`, `api`, `open`, `status`, `version`, `completion` |

## Aliases

Plural spellings of the group nouns work, and so do two verb aliases. Nothing else is aliased.

| Alias | Means |
| --- | --- |
| `orgs`, `instances`, `teams`, `invites`, `tokens`, `contexts` | The singular group |
| `ls` | `list` |
| `rm` | `delete` - and `team remove` |
| `doctor` | `status` |

## Reading these pages

Each leaf command gets a usage block, a table of its arguments, a table of its own options, at least one runnable example, and a note on how it refuses.

Usage blocks are notation, not commands: `<NAME>` is a value you must supply, `[NAME]` one you may, `[OPTIONS]` any number of flags, and `...` marks something repeatable. Copy from the examples instead.

Flags shared across many commands are documented once:

- The [global flags](/docs/reference/cli/cloud/global-flags.md), accepted everywhere.
- The [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags) - `--columns`, `--wide`, `--no-header`, `--sort`, `--reverse` and `--limit` - carried by every list-shaped command.
- The [wait flags](/docs/reference/cli/cloud/long-running-operations.md#the-wait-flags) - `--wait`, `--no-wait` and `--wait-timeout` - carried by five `instance` commands.

For queries, imports, exports and running a server, use the [database commands](/docs/reference/cli/db.md) (`surreal db ...`) instead. See the [overview](/docs/reference/cli/cloud.md) for where that boundary sits.

---

Source: https://surrealdb.com/docs/reference/cli/cloud/commands/auth

# surreal cloud auth

Reference for surreal cloud auth - signing in, signing out, inspecting the stored credential, renewing it, and listing what it is permitted to do.

`surreal cloud auth` signs in, signs out, and inspects credentials. Four of its five verbs work entirely from the local credential store; only `login`, `refresh` and `auth status --verify` touch the network.

<Synopsis>
surreal cloud auth <COMMAND> [OPTIONS]
</Synopsis>

| Verb | Purpose |
| --- | --- |
| [`login`](#auth-login) | Sign in to SurrealDB Cloud |
| [`logout`](#auth-logout) | Remove the stored credentials for a profile |
| [`status`](#auth-status) | Show which credentials are in use |
| [`refresh`](#auth-refresh) | Renew the stored credentials now |
| [`scopes`](#auth-scopes) | Show what the current credential is permitted to do |

Behaviour when nothing is signed in is deliberate and differs by verb: `status` and `logout` succeed with exit `0`, while `scopes` and `refresh` exit `3`. See [Authentication](/docs/reference/cli/cloud/authentication.md#what-each-auth-verb-does-when-nothing-is-signed-in) for why.

## surreal cloud auth login {#auth-login}

Sign in to SurrealDB Cloud, storing a credential for the active profile.

<Synopsis>
surreal cloud auth login [OPTIONS]
</Synopsis>

This command takes no positional arguments.

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--with-token",
            "description": "Read a personal access token from standard input instead of signing in. This is the only way to store a token."
        },
        {
            "name": "--label",
            "value": "<NAME>",
            "description": "A label to remember this personal access token by. Requires `--with-token`."
        },
        {
            "name": "--flow",
            "value": "<FLOW>",
            "description": "Which sign-in flow to use: `browser`, `device` or `paste`. Conflicts with `--with-token`."
        },
        {
            "name": "--no-browser",
            "description": "Do not open a browser; show a code or a URL instead. Conflicts with `--with-token` and `--flow`."
        },
        {
            "name": "--force",
            "description": "Sign in again even if this profile already has a credential."
        }
    ]}
/>

| `--flow` value | Behaviour |
| --- | --- |
| `browser` | Open a browser and listen on `127.0.0.1` for the redirect |
| `device` | Show a code to type on another device, following RFC 8628 |
| `paste` | Print a URL and take back the address the browser was redirected to |

Left to itself the command tries browser, then device, then paste, and stops at the first one that can run. A flow named explicitly is used or it fails; there is no silent substitution.

```bash title="Sign in interactively"
surreal cloud auth login
```

```bash title="Sign in over SSH, where a local browser is no use"
surreal cloud auth login --flow device
```

```bash title="Store a personal access token for a profile"
echo "$CI_TOKEN" | surreal cloud --profile ci auth login --with-token --label "build runner"
```

**Refusals and short-circuits.** A profile that already holds a credential is a no-op that exits `0` and names the remedy:

```text
Profile `default` is already signed in as ana@acme.example.
Replace it with:
  surreal cloud auth login --force
```

An interactive flow that does not complete exits `30`. A session with nobody present and no way to prompt cannot start a flow at all, and says so rather than printing a device code nobody will read.

Only `--with-token` stores a credential. `--token`, `--token-file` and `SURREAL_CLOUD_TOKEN` are request-scoped and never written to disk.

## surreal cloud auth logout {#auth-logout}

Remove the stored credentials for a profile.

<Synopsis>
surreal cloud auth logout [OPTIONS]
</Synopsis>

This command takes no positional arguments.

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--force",
            "description": "Do not ask for confirmation."
        }
    ]}
/>

```bash title="Sign out of the active profile"
surreal cloud auth logout
```

```bash title="Tear down a profile in a script"
surreal cloud --profile ci auth logout --force --json
```

Logging out revokes the refresh token at the identity provider on a best-effort basis and removes only this profile's entry. A failed revocation warns but never blocks the local wipe.

Signing out when nothing is signed in still succeeds and still emits a document, so `auth logout --json` in a teardown script has the same shape on its second run as on its first:

```json title="Output"
{
  "profile": "ci",
  "removed": false,
  "revoked": false
}
```

Declining the confirmation prints `Nothing was changed.` and exits `0`.

## surreal cloud auth status {#auth-status}

Show which credentials are in use, without touching the network.

<Synopsis>
surreal cloud auth status [OPTIONS]
</Synopsis>

This command takes no positional arguments.

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--verify",
            "description": "Also check the credential against the API. Adds one request."
        }
    ]}
/>

```bash title="What am I signed in as?"
surreal cloud auth status
```

```bash title="Confirm the credential still works"
surreal cloud auth status --verify
```

The document has the same shape signed in and signed out, so a script can read one field without branching first. `status` warns when the machine's clock is more than five minutes out, and when `SURREAL_CLOUD_SESSION_TOKEN` is supplying a session token.

For the API's own view of your identity, use [`whoami`](/docs/reference/cli/cloud/commands/misc.md#whoami), which spends a request.

## surreal cloud auth refresh {#auth-refresh}

Renew the stored credentials now, rather than waiting for them to expire.

<Synopsis>
surreal cloud auth refresh [OPTIONS]
</Synopsis>

This command takes no positional arguments.

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--all",
            "description": "Also renew the token for the account-management routes."
        }
    ]}
/>

```bash
surreal cloud auth refresh
```

The command forces both the access token and the Cloud session. `--all` additionally renews the token used for the account-management routes, which is the one the [`token` commands](/docs/reference/cli/cloud/commands/token.md) need.

**Refusals.** With nothing signed in, this exits `3`. On a personal access token it reports that a token does not expire on a schedule and cannot be refreshed, then exits `0` without sending anything.

## surreal cloud auth scopes {#auth-scopes}

Show what the current credential is permitted to do.

<Synopsis>
surreal cloud auth scopes [OPTIONS]
</Synopsis>

This command takes no positional arguments.

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--no-header",
            "description": "Omit the header row."
        }
    ]}
/>

> [!NOTE]
> This is the one list-shaped command that carries only `--no-header`. It has no `--columns`, `--wide`, `--sort`, `--reverse` or `--limit`.

```bash title="What may this token do?"
surreal cloud auth scopes
```

```text title="Output"
SCOPE
read:cloud
write:cloud-instances
```

The single column is `scope`.

**Refusals.** With nothing signed in, this exits `3` - a script asking "what may this credential do" and getting an empty list would read it as "nothing is permitted" rather than "nothing is signed in".

On a login session the list is empty, and a sentence on stderr points at [`org permissions`](/docs/reference/cli/cloud/commands/org.md#org-permissions): identity scopes are not an authorisation model, and your role in the organisation is what decides what you may do.

For the catalogue of scopes a token *can* be granted, use [`token scopes`](/docs/reference/cli/cloud/commands/token.md#token-scopes).

## Related pages

- [Authentication](/docs/reference/cli/cloud/authentication.md) - the credential model, login flows and credential storage
- [`token` commands](/docs/reference/cli/cloud/commands/token.md) - creating and revoking personal access tokens
- [`context` commands](/docs/reference/cli/cloud/commands/context.md) - switching between profiles
- [surreal cloud reference](/docs/reference/cli/cloud.md) - the rest of the reference
- [Database authentication](/docs/reference/cli/db.md) - database-level authentication, which these credentials do not cover

---

Source: https://surrealdb.com/docs/reference/cli/cloud/commands/catalog

# surreal cloud catalog

Reference for surreal cloud catalog - the platform-wide lists of regions, SurrealDB Earth residencies, instance types, storage types, SurrealDB versions and billing countries.

`surreal cloud catalog` browses the platform catalogues: the regions, Earth residencies, instance types, versions and billing countries SurrealDB Cloud offers. These are the slugs [`instance create`](/docs/reference/cli/cloud/commands/instance.md#instance-deploy) and [`instance update`](/docs/reference/cli/cloud/commands/instance.md#instance-update) expect.

<Synopsis>
surreal cloud catalog <COMMAND> [OPTIONS]
</Synopsis>

| Command | Purpose |
| --- | --- |
| [`regions`](#catalog-regions) | List the regions instances can be deployed in |
| [`residencies`](#catalog-residencies) | List the areas where SurrealDB Earth places the data of its instances |
| [`instance-types`](#catalog-instance-types) | List the instance types available on the platform |
| [`storage-types`](#catalog-storage-types) | List the storage instance types available on the platform |
| [`instance-versions`](#catalog-instance-versions) | List the SurrealDB versions instances can run |
| [`billing-countries`](#catalog-billing-countries) | List the countries billing details can be registered in |

These are nouns rather than `list` verbs, because a catalogue has exactly one thing you can do with it. None takes a positional argument, none takes `--org`, and none carries any flag beyond the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags).

> [!IMPORTANT]
> These lists are **global**. What an organisation may actually deploy is narrower, and [`org plans`](/docs/reference/cli/cloud/commands/org.md#org-plans) is the organisation-scoped answer - the one to trust before a create.

## surreal cloud catalog regions {#catalog-regions}

List the regions instances can be deployed in.

<Synopsis>
surreal cloud catalog regions [OPTIONS]
</Synopsis>

This command takes no positional arguments and no options of its own. Column ids are `slug` and `description`, with `flag` under `--wide`.

```bash
surreal cloud catalog regions
```

```text title="Output"
SLUG        DESCRIPTION
aws-euw1    Europe (Ireland)
aws-use1    US East (N. Virginia)
aws-usw2    US West (Oregon)
```

```bash title="Just the slugs"
surreal cloud catalog regions --columns slug --no-header
```

The `slug` is what `--region` accepts. The list holds the cloud regions for dedicated instances. SurrealDB Earth is not one of them: `--region earth` deploys an Earth instance, and is the default.

## surreal cloud catalog residencies {#catalog-residencies}

List the areas where [SurrealDB Earth](/docs/operate/instances/earth.md) places the data of its instances. A residency is a placement, not a guarantee of where the data is stored or processed.

<Synopsis>
surreal cloud catalog residencies [OPTIONS]
</Synopsis>

This command takes no positional arguments and no options of its own. Column ids are `name`, `label`, `default` and `locations`, with `slug` and `description` under `--wide`.

```bash
surreal cloud catalog residencies
```

```text title="Output"
NAME   RESIDENCY       DEFAULT  LOCATIONS
eu     European Union  false    weur, eeur
us     United States   false    wnam, enam
world  Worldwide       true     wnam, enam, weur, eeur, apac, oc
```

The `name` is what [`instance deploy --residency`](/docs/reference/cli/cloud/commands/instance.md#instance-deploy) accepts, and `locations` lists the values its `--location-hint` accepts with that residency. A residency cannot be changed after the instance is deployed.

## surreal cloud catalog instance-types {#catalog-instance-types}

List the instance types available on the platform.

<Synopsis>
surreal cloud catalog instance-types [OPTIONS]
</Synopsis>

This command takes no positional arguments and no options of its own. Column ids are `slug`, `category`, `cpu`, `memory`, `units`, `price_hour`, `storage` and `enabled`, with `display_name`, `restricted` and `description` under `--wide`.

```bash
surreal cloud catalog instance-types
```

```bash title="Cheapest first"
surreal cloud catalog instance-types --sort price_hour
```

The `slug` is what `--type` accepts. Prices stay in integer minor units under `--json`.

The `enabled` column is left unset here, because whether a type is available to you is a property of your organisation's plan rather than of the platform - check [`org plans`](/docs/reference/cli/cloud/commands/org.md#org-plans), or price a specific combination with [`instance estimate`](/docs/reference/cli/cloud/commands/instance.md#instance-estimate).

## surreal cloud catalog storage-types {#catalog-storage-types}

List the storage instance types available on the platform.

<Synopsis>
surreal cloud catalog storage-types [OPTIONS]
</Synopsis>

This command takes no positional arguments and no options of its own. The columns are the same as [`instance-types`](#catalog-instance-types).

```bash
surreal cloud catalog storage-types
```

An empty list is a success, and says why on stderr:

```text
No storage instance types are offered. Distributed storage may not be available here.
```

## surreal cloud catalog instance-versions {#catalog-instance-versions}

List the SurrealDB versions instances can run.

<Synopsis>
surreal cloud catalog instance-versions [OPTIONS]
</Synopsis>

This command takes no positional arguments and no options of its own. The single column id is `version`.

```bash
surreal cloud catalog instance-versions
```

```bash title="The version an update would move to"
surreal cloud catalog instance-versions --limit 1 --no-header
```

The API's own order is newest-first and is left alone. `--sort version` sorts as strings, so `3.10.0` would come before `3.9.0` - prefer the default order when you want the newest release.

An empty list should not happen, and says so:

```text
The API returned no versions, which should not happen. Try again, or report it.
```

## surreal cloud catalog billing-countries {#catalog-billing-countries}

List the countries billing details can be registered in.

<Synopsis>
surreal cloud catalog billing-countries [OPTIONS]
</Synopsis>

This command takes no positional arguments and no options of its own. Column ids are `code` and `name`.

```bash
surreal cloud catalog billing-countries
```

```bash title="Check one country is supported"
surreal cloud catalog billing-countries --json | jq -e '.[] | select(.code == "IE")' > /dev/null
```

## Related pages

- [`instance create`](/docs/reference/cli/cloud/commands/instance.md#instance-deploy) - where these slugs are used
- [`org plans`](/docs/reference/cli/cloud/commands/org.md#org-plans) - the organisation-scoped subset
- [`instance estimate`](/docs/reference/cli/cloud/commands/instance.md#instance-estimate) - pricing a type and region before committing to it
- [surreal cloud reference](/docs/reference/cli/cloud.md) - the rest of the reference
- [`surreal db sql`](/docs/reference/cli/db/commands/sql.md) - for working with the data inside an instance

---

Source: https://surrealdb.com/docs/reference/cli/cloud/commands/config

# surreal cloud config

Reference for surreal cloud config - listing, reading, setting and clearing configuration values, printing the file path, and opening it in an editor.

`surreal cloud config` reads and writes the CLI's own configuration file. Nothing here sends a request: the file never leaves the machine.

<Synopsis>
surreal cloud config <COMMAND> [OPTIONS]
</Synopsis>

| Verb | Purpose | Alias |
| --- | --- | --- |
| [`list`](#config-list) | List every configuration key and its value | `ls` |
| [`get`](#config-get) | Show one configuration value | |
| [`set`](#config-set) | Set a configuration value | |
| [`unset`](#config-unset) | Clear a configuration value | |
| [`path`](#config-path) | Print the path to the configuration file | |
| [`edit`](#config-edit) | Open the configuration file in your editor | |

Every verb works on **one profile** - whichever `--profile`, `SURREAL_CLOUD_PROFILE` and the file's own `active_profile` settle on - and each one says which profile it touched.

## The keys

Four keys are recognised. Each is outranked by an environment variable, and by a command-line flag above that; see the [precedence chain](/docs/reference/cli/cloud/global-flags.md#the-precedence-chain).

| Key | Type | Description | Outranked by |
| --- | --- | --- | --- |
| `org` | Text | Default organisation for this profile | `SURREAL_CLOUD_ORG` |
| `api` | URL | Base URL of the SurrealDB API | `SURREAL_CLOUD_API` |
| `json` | Boolean | Always emit machine-readable JSON | `SURREAL_CLOUD_JSON` |
| `plain` | Boolean | Always disable tables, spinners and relative times | `SURREAL_CLOUD_PLAIN` |

The persisted context - what [`org use`](/docs/reference/cli/cloud/commands/org.md#org-use) records - is **not** reachable from here. There is no `config set context.org`. The two live in separate tables of the same file so that `org use` never overwrites an `org` value you set by hand, and the hand-written one wins.

```toml title="config.toml"
active_profile = "work"

[profile.work]
org = "acme"          # written by a person

[profile.work.context]
org = "67upif0m8sh1cn1p2c8t"   # written by `org use`
```

Keys this build has never heard of are preserved on write, so an older binary editing a newer file does not discard anything.

## surreal cloud config list {#config-list}

List every configuration key and its value.

<Synopsis>
surreal cloud config list [OPTIONS]
</Synopsis>

This command takes no positional arguments and no options of its own.

Accepts the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags). Column ids are `key`, `value`, `set` and `description`, with `kind` under `--wide`.

```bash
surreal cloud config list
```

```text title="Output"
KEY              VALUE   SET  DESCRIPTION
org              acme    yes  Default organization for this profile
api                      no   Base URL of the SurrealDB API
json                     no   Always emit machine-readable JSON
plain                    no   Always disable tables, spinners and relative times
```

Every key is listed whether or not it is set, and the `set` column is what distinguishes a configured value from a default. Only a key this profile has actually set carries a value, so an unset key - `api` above, which falls back to the built-in default - has an empty `value` cell. A note on stderr reports the profile and the file path.

## surreal cloud config get {#config-get}

Show one configuration value.

<Synopsis>
surreal cloud config get [OPTIONS] <KEY>
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "<KEY>",
            "required": true,
            "description": "The configuration key."
        }
    ]}
/>

This command has no options of its own.

The output is the value alone plus a newline, with no label and no styling, so `$(…)` captures exactly the value. An unset key writes **zero bytes**, so `[ -z "$(surreal cloud config get org)" ]` and `wc -l` agree with each other.

```bash
ORG=$(surreal cloud config get org)
```

```bash title="Branch on whether a key is set"
if [ -z "$(surreal cloud config get org)" ]; then
    echo "no default organisation for this profile"
fi
```

**Refusals.** An unrecognised key is a usage error, exit `2`, and lists the keys that exist.

## surreal cloud config set {#config-set}

Set a configuration value.

<Synopsis>
surreal cloud config set [OPTIONS] <KEY> <VALUE>
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "<KEY>",
            "required": true,
            "description": "The configuration key."
        },
        {
            "name": "<VALUE>",
            "required": true,
            "description": "The value to store."
        }
    ]}
/>

This command has no options of its own.

```bash title="Always emit JSON from this profile"
surreal cloud config set json true
```

```bash title="Point at a different API"
surreal cloud config set api https://api.example.com
```

```bash title="Configure a second profile"
surreal cloud --profile staging config set org contoso
```

**Warnings.** When the corresponding environment variable is exported, the command says so, because the variable silently outranks what you just wrote:

```text
warning: SURREAL_CLOUD_JSON is set and takes precedence over this. Unset it for the configured value to apply.
```

**Refusals**, exit `2`: an unrecognised key, or a value the key's type rejects - a non-boolean for `json`, or a URL with a path for `api`.

## surreal cloud config unset {#config-unset}

Clear a configuration value.

<Synopsis>
surreal cloud config unset [OPTIONS] <KEY>
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "<KEY>",
            "required": true,
            "description": "The configuration key."
        }
    ]}
/>

This command has no options of its own.

```bash
surreal cloud config unset json
```

Clearing a key restores the CLI's default rather than falling back to another profile. Clearing an already-unset key is a no-op that succeeds.

## surreal cloud config path {#config-path}

Print the path to the configuration file.

<Synopsis>
surreal cloud config path [OPTIONS]
</Synopsis>

This command takes no positional arguments and no options of its own.

The output is the path alone plus a newline.

```bash
surreal cloud config path
```

```text title="Output"
/Users/ana/.surrealdb/cloud/config.toml
```

```bash title="Back the file up before editing it"
cp "$(surreal cloud config path)" "$(surreal cloud config path).bak"
```

`credentials.json` lives beside it in the same directory. See [credential storage](/docs/reference/cli/cloud/authentication.md#where-credentials-are-stored) for how that directory is chosen.

## surreal cloud config edit {#config-edit}

Open the configuration file in your editor.

<Synopsis>
surreal cloud config edit [OPTIONS]
</Synopsis>

This command takes no positional arguments and no options of its own.

```bash
surreal cloud config edit
```

The file is opened with `$VISUAL`, or `$EDITOR` when that is unset. A value such as `code --wait` works, because it is split on whitespace. The file is created first if it does not exist yet, and re-read when the editor exits, so a mistake is reported while the editor is still fresh in mind: `<path> is valid, with N profiles.` on success, and the parse error on failure. A broken file is left in place for you to fix.

With no terminal there is nothing to attach an editor to, so in a non-interactive session the command exits `2` rather than hanging; use [`config set`](#config-set) instead. It also exits `2` when neither variable is set.

Editing the file by hand is supported - [`config list`](#config-list) will show whatever you wrote, and unknown keys survive - but a file written by a newer `surreal cloud` is refused rather than migrated:

```text
<path> was written by a newer surreal-cloud (file version 2, this build understands 1).
Refusing to touch it - upgrade surreal-cloud, or point --config elsewhere.
```

## Related pages

- [Global flags](/docs/reference/cli/cloud/global-flags.md) - the flags and environment variables these keys sit beneath
- [`context` commands](/docs/reference/cli/cloud/commands/context.md) - switching between profiles
- [`org use`](/docs/reference/cli/cloud/commands/org.md#org-use) - remembering an organisation within a profile
- [Authentication](/docs/reference/cli/cloud/authentication.md#where-credentials-are-stored) - the credential file beside this one
- [surreal cloud reference](/docs/reference/cli/cloud.md) - the rest of the reference

---

Source: https://surrealdb.com/docs/reference/cli/cloud/commands/context

# surreal cloud context

Reference for surreal cloud context - showing what an invocation resolved, switching between profiles, and listing the profiles that are configured.

`surreal cloud context` inspects and switches profiles. A profile bundles a credential, an API base URL and a set of configuration values, so switching profile changes all three in one move.

<Synopsis>
surreal cloud context <COMMAND> [OPTIONS]
surreal cloud contexts <COMMAND> [OPTIONS]
</Synopsis>

| Verb | Purpose | Alias |
| --- | --- | --- |
| [`show`](#context-show) | Show the context this invocation resolved | |
| [`use`](#context-use) | Switch to a different profile | |
| [`list`](#context-list) | List the configured profiles | `ls` |

`context use` switches *profile*. [`org use`](/docs/reference/cli/cloud/commands/org.md#org-use) remembers an organisation *within* a profile. Neither is expressible as the other, and you will usually want both: one profile per account or tenant, one remembered organisation inside each.

## surreal cloud context show {#context-show}

Show the context this invocation resolved.

<Synopsis>
surreal cloud context show [OPTIONS]
</Synopsis>

This command takes no positional arguments and no options of its own.

```bash
surreal cloud context show
```

```text title="Output"
Profile         work
Organization    acme
Id              67upif0m8sh1cn1p2c8t
Source          persisted context (`org use`)
API             https://api.surrealdb.com
Config          /Users/ana/.surrealdb/cloud/config.toml
Store           /Users/ana/.surrealdb/cloud/credentials.json
```

The command resolves through the **same chain every other command uses**, including the interactive picker when several organisations are available and nothing has chosen - so what it reports is exactly what the next command will do.

A failure to resolve an organisation is reported as *part of the answer* rather than as an error: the profile, the API base and both file paths are still printed, followed by a note and the hint `surreal cloud org use <name>`.

```bash title="Which organisation would this command hit?"
surreal cloud context show --json | jq -r '.organization.name + " via " + .source'
```

## surreal cloud context use {#context-use}

Switch to a different profile.

<Synopsis>
surreal cloud context use [OPTIONS] <PROFILE>
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "<PROFILE>",
            "required": true,
            "description": "The profile to make active."
        }
    ]}
/>

This command has no options of its own.

```bash title="Switch"
surreal cloud context use staging
```

```bash title="Create a profile and sign into it"
surreal cloud context use staging
surreal cloud auth login
```

The profile is created if it does not exist. A **new** profile gets a note that it has no stored credentials, plus the hint naming the login command for it.

**Refusals.** An empty or whitespace-only name is a usage error, exit `2`:

```text
Ensure the profile name is not empty.
```

**Warnings.** The command warns when `SURREAL_CLOUD_PROFILE` is set, because the variable outranks the file it just wrote.

For a single command against a different profile, pass `--profile` rather than switching:

```bash
surreal cloud --profile staging instance list
```

## surreal cloud context list {#context-list}

List the configured profiles.

<Synopsis>
surreal cloud context list [OPTIONS]
</Synopsis>

This command takes no positional arguments and no options of its own.

Accepts the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags). Column ids are `profile`, `active`, `org` and `api`, with `source` under `--wide`.

```bash
surreal cloud context list
```

```text title="Output"
PROFILE   ACTIVE  ORGANIZATION  API
default   no      contoso       https://api.surrealdb.com
work      yes     acme          https://api.surrealdb.com
```

```bash title="See where each organisation came from"
surreal cloud context list --wide
```

The profile in force is always listed, even when the file has no entry for it - so `--profile scratch context list` shows `scratch`. The order is stable between runs.

## Related pages

- [Global flags](/docs/reference/cli/cloud/global-flags.md#the-precedence-chain) - the chain `context show` reports on
- [`config` commands](/docs/reference/cli/cloud/commands/config.md) - the values a profile holds
- [`org use`](/docs/reference/cli/cloud/commands/org.md#org-use) - remembering an organisation within a profile
- [`auth` commands](/docs/reference/cli/cloud/commands/auth.md) - signing a profile in
- [surreal cloud reference](/docs/reference/cli/cloud.md) - the rest of the reference

---

Source: https://surrealdb.com/docs/reference/cli/cloud/commands/instance

# surreal cloud instance

Reference for surreal cloud instance - deploy SurrealDB Earth and dedicated instances, update, pause, resume, delete and watch instances, read status, endpoint, logs, metrics and usage, mint database tokens, open sql, import and export through surreal db, and manage capabilities, network policies and backups.

`surreal cloud instance` manages instances: the databases themselves. It is the largest group in the CLI, and covers provisioning, scaling, observability, credentials, capabilities and backups. Three of its commands, `sql`, `import` and `export`, run the database through the `surreal` launcher as [`surreal db sql`](/docs/reference/cli/db/commands/sql.md), [`surreal db import`](/docs/reference/cli/db/commands/import.md) and [`surreal db export`](/docs/reference/cli/db/commands/export.md).

An instance is one of two kinds. A [SurrealDB Earth](/docs/operate/instances/earth.md) instance is serverless and runs on the Cloudflare network, and it is what [`deploy`](#instance-deploy) creates by default. A dedicated instance runs in one cloud region on the Start or Scale plan. Most commands work on both kinds; [Earth instances](#earth-instances) lists the ones that differ.

This group declares the scopes `read:cloud` and `write:cloud-instances`. A personal access token is read-only here: the gateway refuses every non-GET Cloud route for one, so the commands that change an instance answer 403 and exit `4` regardless of the token's scopes. See [Authentication](/docs/reference/cli/cloud/authentication.md#what-a-personal-access-token-cannot-do).

<Synopsis>
surreal cloud instance <COMMAND> [OPTIONS]
surreal cloud instances <COMMAND> [OPTIONS]
</Synopsis>

| Verb | Purpose | Alias |
| --- | --- | --- |
| [`list`](#instance-list) | List the instances in an organisation | `ls` |
| [`get`](#instance-get) | Show one instance | |
| [`deploy`](#instance-deploy) | Deploy an instance, asking for anything not given | `create` |
| [`update`](#instance-update) | Change an instance's name, type, size, or version | |
| [`delete`](#instance-delete) | Delete an instance and everything in it | `rm` |
| [`pause`](#instance-pause) | Pause a running instance | |
| [`resume`](#instance-resume) | Resume a paused instance | |
| [`watch`](#instance-watch) | Watch an operation that was started elsewhere | |
| [`status`](#instance-status) | Show an instance's deployment phase and restorable snapshots | |
| [`endpoint`](#instance-endpoint) | Print the endpoint a client connects to | |
| [`token`](#instance-token) | Mint a database token for an instance | |
| [`jwks`](#instance-jwks) | Fetch the key set that verifies an instance's tokens | |
| [`sql`](#instance-sql) | Open a SurrealQL session against an instance | |
| [`import`](#instance-import) | Import a file into an instance | |
| [`export`](#instance-export) | Export an instance to a file | |
| [`metrics`](#instance-metrics) | Show an instance's resource metrics | |
| [`logs`](#instance-logs) | Show an instance's logs | |
| [`usage`](#instance-usage) | Show what an instance has consumed | |
| [`estimate`](#instance-estimate) | Estimate what an instance would cost | |
| [`capabilities get`](#instance-capabilities-get) | Show an instance's capability configuration | |
| [`capabilities set`](#instance-capabilities-set) | Change an instance's capability configuration | |
| [`network get`](#instance-network-get) | Show which addresses may connect to an Earth instance | |
| [`network set`](#instance-network-set) | Change which addresses may connect to an Earth instance | |
| [`backup list`](#instance-backup-list) | List the snapshots an instance can be restored from | `ls` |
| [`backup create`](#instance-backup-create) | Take a backup of an instance now | |
| [`backup policy get`](#instance-backup-policy-get) | Show the backup retention policy | |
| [`backup policy set`](#instance-backup-policy-set) | Change the backup retention policy | |

## Earth instances {#earth-instances}

An Earth instance has no instance type, compute units, storage size, SurrealDB version choice, backups, metrics or logs, so the commands for those refuse one before sending a request:

| Command | On an Earth instance |
| --- | --- |
| [`update`](#instance-update) | Only `--name` applies. `--type`, `--compute-units`, `--storage` and `--version` are refused |
| [`backup`](#instance-backup-list) commands | Refused: Earth does not offer backups or snapshots |
| [`metrics`](#instance-metrics) and [`logs`](#instance-logs) | Refused: Earth does not offer metrics or logs |
| [`jwks`](#instance-jwks) | Refused: an Earth instance has no key set of its own |
| [`estimate`](#instance-estimate) | Prices dedicated instance types only |

The refusal names the instance and what it lacks, and exits `9`:

```text
`edge-api` is a SurrealDB Earth instance, which does not offer metrics or logs.
```

[`usage`](#instance-usage) reports what an Earth instance has consumed, in the meters that [Earth plans](/docs/operate/instances/earth.md#plans-and-usage) are measured in, and [`network get`](#instance-network-get) and [`network set`](#instance-network-set) manage its network policy.

No `update` flag changes the number of cells. To change it, send the request to the Cloud API with [`surreal cloud api`](/docs/reference/cli/cloud/commands/misc.md#api), as [Choose a cell count](/docs/operate/instances/earth.md#choose-a-cell-count) shows.

## Naming an instance

Four spellings are accepted: the id, the slug, the name, or `org/name`. Only a bare id avoids a lookup against the organisation. A slug always contains a hyphen, so it can never be mistaken for an id.

```bash
surreal cloud instance get production
surreal cloud instance get production-6xk2
surreal cloud instance get acme/production
surreal cloud instance get 67upif0m8sh1cn1p2c8t
```

Omit the reference entirely and, on a terminal, you get a picker. Elsewhere it is a usage error, exit `2`, listing what was available:

```text
No instance was given and this session cannot prompt.
Name one, or pass --org to change which organization is searched.

Available:
  production
  staging
```

There is deliberately no `instance use`, and no default instance: a sticky implicit target is fine for a noun whose verbs are mostly reads, and wrong for one whose verbs include `delete`. The organisation searched comes from `--org` and the [precedence chain](/docs/reference/cli/cloud/global-flags.md#the-precedence-chain), and [`org use`](/docs/reference/cli/cloud/commands/org.md#org-use) can remember one.

Every `[INSTANCE]` argument below behaves this way: only the organisation is resolved from context, so without an instance argument a command prompts on a terminal and refuses elsewhere.

A command that waits for the instance (`create`, `update`, `delete`, `pause`, `resume` and `watch`) follows the rules in [Long-running operations](/docs/reference/cli/cloud/long-running-operations.md). The waiting default is on, the timeout is 15 minutes, a timeout exits `10`, and an instance that enters a failed state exits `6`. `--wait-timeout` takes a duration such as `30s`, `10m` or `2h`, and a bare number is seconds.

## surreal cloud instance list {#instance-list}

List the instances in an organisation.

<Synopsis>
surreal cloud instance list [OPTIONS]
</Synopsis>

This command takes no positional argument, deliberately: a positional here would read as an *instance*. The organisation comes from `--org` and the [precedence chain](/docs/reference/cli/cloud/global-flags.md#the-precedence-chain).

Accepts the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags) and nothing else. Column ids are `name`, `state`, `type`, `version`, `region`, `compute_units` and `storage`, with `id`, `slug`, `host`, `access_type` and `organization_id` under `--wide`. An organisation with no instances is a success: exit `0`, a note, and an empty array under `--json`.

```bash
surreal cloud instance list
```

```text title="Output"
NAME        STATE   TYPE          VERSION  REGION     UNITS  STORAGE
production  ready   production-2  3.2.4    aws-euw1       4   100 GB
staging     paused  shared-1      3.2.4    aws-euw1       1    10 GB
```

```bash title="Ready instances only, as names"
surreal cloud instance list --json | jq -r '.[] | select(.state == "ready") | .name'
```

## surreal cloud instance get {#instance-get}

Show one instance.

<Synopsis>
surreal cloud instance get [OPTIONS] [INSTANCE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug, name, or org/name. Omit to choose interactively."
        }
    ]}
/>

This command has no options of its own.

```bash
surreal cloud instance get production
```

```bash title="One field, for a script"
surreal cloud instance get production --json | jq -r .state
```

The detail view reports the id, slug, state, type, version, region, compute units, storage, access type, endpoint, private host when there is one, and the owning organisation. It adds the storage cool-off when storage cannot be changed yet, the storage backend and backup retention when the platform reports them, and the versions the instance can upgrade to.

For an Earth instance the view reports the id, state, region `earth`, data residency, preferred location, cells, network policy, version, endpoint and owning organisation instead, followed by the commands that go with it.

## surreal cloud instance deploy {#instance-deploy}

Deploy an instance, asking for anything not given. `create` is an alias.

<Synopsis>
surreal cloud instance deploy [OPTIONS] [NAME]
surreal cloud instance create [OPTIONS] [NAME]
</Synopsis>

`--region` decides the kind of instance. With no `--region`, or `--region earth`, the command deploys a [SurrealDB Earth](/docs/operate/instances/earth.md) instance, which runs the platform's latest SurrealDB. With any other region it deploys a dedicated instance in that cloud region. Each kind has its own flags, and a flag that belongs to the other kind is refused.

At a terminal the command asks for anything not given as a flag, starting from the same defaults as the deploy page in SurrealDB Studio. `--yes`, or a session that cannot prompt, takes every default without asking.

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[NAME]",
            "description": "A name for the instance. Between 1 and 30 characters, counted after trimming. Defaults to a generated name, such as `brave-falcon`."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--region",
            "value": "<REGION>",
            "default": "earth",
            "description": "`earth` for a SurrealDB Earth instance, or a cloud region for a dedicated instance. See `surreal cloud catalog regions`."
        },
        {
            "name": "--wait",
            "description": "Wait for the instance to become ready. On by default."
        },
        {
            "name": "--no-wait",
            "description": "Return as soon as the API accepts the request."
        },
        {
            "name": "--wait-timeout",
            "value": "<DURATION>",
            "default": "15m",
            "description": "How long to wait before giving up. A duration such as `30s`, `10m` or `2h`."
        }
    ]}
/>

<OptionsTable
    title="SurrealDB Earth options"
    options={[
        {
            "name": "--residency",
            "value": "<RESIDENCY>",
            "default": "world",
            "description": "Where Earth places the data: `world`, `eu` or `us`. This is a placement, not a guarantee of where the data is stored or processed. See `surreal cloud catalog residencies`. Cannot be changed later."
        },
        {
            "name": "--location-hint",
            "value": "<LOCATION>",
            "description": "Where in its residency the instance prefers to run: `wnam`, `enam`, `weur`, `eeur`, `apac` or `oc`, as the residency allows. Defaults to automatic placement. Cannot be changed later."
        },
        {
            "name": "--cells",
            "value": "<N>",
            "description": "The most [cells](/docs/operate/instances/earth.md#cells) the instance may run across, from the counts the deploy page offers. More cells take on more work at once."
        },
        {
            "name": "--allow-ip",
            "value": "<CIDRS>",
            "description": "Admit only these IP addresses or CIDR blocks, comma-separated."
        },
        {
            "name": "--deny-ip",
            "value": "<CIDRS>",
            "description": "Refuse these IP addresses or CIDR blocks, comma-separated."
        },
        {
            "name": "--allow-guests, --deny-guests",
            "description": "Allow or refuse unauthenticated guest access."
        },
        {
            "name": "--allow-<LIST>, --deny-<LIST>",
            "value": "<VALUES>",
            "description": "Capability lists, comma-separated, for `experimental`, `arbitrary-query`, `eval-query`, `rpc`, `http` and `funcs`. They take the same values as [`capabilities set`](#instance-capabilities-set)."
        }
    ]}
/>

<OptionsTable
    title="Dedicated options"
    options={[
        {
            "name": "--nodes",
            "value": "<N>",
            "description": "How many nodes the instance runs on: 1 for a single-node instance, 3 or more for a multi-node one."
        },
        {
            "name": "--type",
            "value": "<SLUG>",
            "description": "The instance type, by slug, among those for the node count. See `surreal cloud catalog instance-types`. Must be one the organisation's plan offers."
        },
        {
            "name": "--version",
            "value": "<VERSION>",
            "description": "The SurrealDB version to run. Defaults to the latest."
        },
        {
            "name": "--storage",
            "value": "<GB>",
            "description": "Storage to allocate, in gigabytes, within the type's range."
        },
        {
            "name": "--access-type",
            "value": "<ACCESS>",
            "description": "How the instance may be reached: `public`, `private` or `dual`."
        },
        {
            "name": "--restore-from",
            "value": "<INSTANCE/SNAPSHOT>",
            "description": "Restore from a snapshot, as `<instance>/<snapshot>`."
        }
    ]}
/>

| `--access-type` value | Meaning |
| --- | --- |
| `public` | Reachable over the public internet. The API's own default |
| `private` | Reachable over PrivateLink only. Needs PrivateLink on the organisation |
| `dual` | Reachable both ways |

```bash title="An Earth instance with the defaults"
surreal cloud instance deploy edge-api --yes
```

```bash title="An Earth instance that keeps its data in the EU"
surreal cloud instance deploy edge-api \
    --residency eu \
    --location-hint weur \
    --cells 10 \
    --allow-ip 203.0.113.0/24
```

```bash title="A dedicated single-node instance"
surreal cloud instance deploy api --region aws-euw1 --nodes 1 --type shared-1
```

```bash title="A dedicated multi-node instance"
surreal cloud instance deploy production \
    --region aws-euw1 \
    --nodes 3 \
    --type production-2 \
    --storage 100
```

```bash title="Clone a dedicated instance from a snapshot"
surreal cloud instance deploy staging \
    --region aws-euw1 \
    --type shared-1 \
    --restore-from production/rsnapshot-20260811-150405
```

The command prints ``Deploying `<name>` (<place>).`` on stderr as soon as the API accepts the request, where the place is the slug of a dedicated instance or the region and residency of an Earth instance. With the wait, it then reports progress and emits a fresh detail view of the ready instance. With `--no-wait` it emits the accepted request and hints at `surreal cloud instance watch <name>`.

The organisation comes from `--org` and the [precedence chain](/docs/reference/cli/cloud/global-flags.md#the-precedence-chain).

**Refusals**, all exit `2` and all before any request:

- A name outside 1 to 30 characters, with the length it counted.
- A flag for the other kind of instance, such as `--nodes` with `--region earth` or `--cells` with a cloud region.
- A `--cells` count that is not on offer. The message lists the counts that are, and the count above which more cells are available on request.
- `--storage` below 1 (`Storage starts at 1 GB.`).
- A `--type` or `--region` that the organisation's plan does not offer. The message suggests the closest match and lists what is available. This check is skipped when the plan lists none.
- A malformed `--restore-from`, which is split on the last `/`:

```text
`prod-snap-1` is not a snapshot reference. Use <instance>/<snapshot>, for example
production/rsnapshot-20250128-150405.
Run `surreal cloud instance status <instance>` to list the snapshots an instance can be restored from.
```

> [!WARNING]
> The create route accepts no idempotency key, so a retried create is a second instance and a second bill. `surreal cloud` does not retry it after a timeout or a `502`, because the request may already have been processed. It replays only a `429` or `401`, which the gateway answers before any handler runs. If a deploy times out, run [`instance list`](#instance-list) before running it again.

## surreal cloud instance update {#instance-update}

Change an instance's name, type, size, or version.

<Synopsis>
surreal cloud instance update [OPTIONS] [INSTANCE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug, name, or org/name. Omit to choose interactively."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--name",
            "value": "<NAME>",
            "description": "Rename the instance. SurrealDB Earth instances only."
        },
        {
            "name": "--type",
            "value": "<SLUG>",
            "description": "Move to this instance type, by slug."
        },
        {
            "name": "--compute-units",
            "value": "<N>",
            "description": "Scale to this many compute units. Minimum 1."
        },
        {
            "name": "--storage",
            "value": "<GB>",
            "description": "Grow storage to this many gigabytes. Minimum 1."
        },
        {
            "name": "--version",
            "value": "<VERSION>",
            "description": "Upgrade to this SurrealDB version."
        },
        {
            "name": "--access-type",
            "value": "<ACCESS>",
            "description": "Change how the instance may be reached: `public`, `private` or `dual`."
        },
        {
            "name": "--wait",
            "description": "Wait for the instance to become ready again. On by default."
        },
        {
            "name": "--no-wait",
            "description": "Return as soon as the API accepts the last change."
        },
        {
            "name": "--wait-timeout",
            "value": "<DURATION>",
            "default": "15m",
            "description": "How long to wait before giving up. A duration such as `30s`, `10m` or `2h`."
        }
    ]}
/>

A rename comes first. It restarts nothing, prints ``Renamed `<old>` to `<new>`.``, and with no other flag the command returns at once. The other flags apply to dedicated instances, and on an Earth instance the command refuses them before sending any request, so a rename is never half of a refused change.

There is no single update route on the API - each field has its own - so one invocation is several requests. They are applied in a fixed order and stop at the first failure:

1. `--type`
2. `--compute-units`
3. `--storage`
4. `--version`
5. `--access-type`

> [!IMPORTANT]
> Every one of these restarts the instance. A single `instance update` that changes three fields restarts it once per field, in the order above.

```bash title="Rename an Earth instance"
surreal cloud instance update edge-api --name edge-api-eu
```

```bash title="Scale up"
surreal cloud instance update production --compute-units 8
```

```bash title="Upgrade the SurrealDB version"
surreal cloud instance update production --version 3.2.4
```

```bash title="Move to a larger instance type"
surreal cloud instance update production --type production-4
```

Each change prints `Set the <field> to <value>.` on stderr as it is accepted. The command stops at the first request the API refuses, so earlier changes stay applied. On the platform a change of instance type counts as a storage change, so passing `--type` and `--storage` together can be refused at the storage step after the type has already changed. The [Storage limits on Start](/docs/operate/instances/scaling.md#storage-limits-on-start) page lists the storage each type starts with.

With the wait, the command then waits for the instance to be ready again and emits a fresh detail view. With `--no-wait` it hints at `surreal cloud instance watch <name>` and emits the instance as it stands.

**Refusals**, all exit `2`:

- No flags at all:

```text
Nothing to update. Pass at least one of --name, --type, --compute-units, --storage, --version, or --access-type.
```

- `--compute-units` below 1 (`Compute units start at 1.`), or `--storage` below 1 (`Storage starts at 1 GB.`).
- `--storage` while the storage cool-off is in force, naming the interval and, when known, when storage was last changed:

```text
`production` cannot be resized yet: storage may be changed only once every 6 hours.
It was last changed at 2026-08-11T10:00:00Z.
```

- `--compute-units` outside the current type's range, when `--type` is not also being changed:

```text
`shared-1` accepts 1-2 compute units; 8 is outside that.
```

## surreal cloud instance delete {#instance-delete}

Delete an instance and everything in it.

<Synopsis>
surreal cloud instance delete [OPTIONS] [INSTANCE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug, name, or org/name. Omit to choose interactively."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--force",
            "description": "Delete without confirming."
        },
        {
            "name": "--wait",
            "description": "Wait for the instance to disappear. On by default."
        },
        {
            "name": "--no-wait",
            "description": "Return as soon as the API accepts the request."
        },
        {
            "name": "--wait-timeout",
            "value": "<DURATION>",
            "default": "15m",
            "description": "How long to wait before giving up."
        }
    ]}
/>

```bash title="Delete, with a confirmation"
surreal cloud instance delete staging
```

```bash title="Delete from a teardown script"
surreal cloud instance delete staging --force --json
```

The confirmation names the instance, its slug and its region, so the wrong terminal tab is caught before the request. Declining prints `Nothing was deleted.` and exits `0` with no document. In a non-interactive session without `--force` or `--yes`, it exits `2` having sent nothing.

The delete route answers with no body, so the emitted document is synthesised. Its `state` is `deleted` once the wait has seen the instance disappear, and `deleting` under `--no-wait`, which also hints at `surreal cloud instance watch <name> --until deleted`:

```json title="Output"
{
  "id": "67upif0m8sh1cn1p2c8t",
  "name": "staging",
  "slug": "staging-4jd1",
  "state": "deleted"
}
```

While waiting, a `404` is the success condition - there is nothing left to fetch.

## surreal cloud instance pause {#instance-pause}

Pause a running instance.

<Synopsis>
surreal cloud instance pause [OPTIONS] [INSTANCE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug, name, or org/name. Omit to choose interactively."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--wait",
            "description": "Wait for the instance to pause. On by default."
        },
        {
            "name": "--no-wait",
            "description": "Return as soon as the API accepts the request."
        },
        {
            "name": "--wait-timeout",
            "value": "<DURATION>",
            "default": "15m",
            "description": "How long to wait before giving up."
        }
    ]}
/>

```bash
surreal cloud instance pause staging
```

With the wait, the command emits a fresh detail view once the instance has paused. With `--no-wait` it emits the accepted response and hints at `surreal cloud instance watch <name> --until paused`.

Pausing something already paused prints a note and still emits a document, exit `0`. The shape of the answer does not change with remote state, so a script does not need to know which case it hit.

## surreal cloud instance resume {#instance-resume}

Resume a paused instance.

<Synopsis>
surreal cloud instance resume [OPTIONS] [INSTANCE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug, name, or org/name. Omit to choose interactively."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--wait",
            "description": "Wait for the instance to become ready. On by default."
        },
        {
            "name": "--no-wait",
            "description": "Return as soon as the API accepts the request."
        },
        {
            "name": "--wait-timeout",
            "value": "<DURATION>",
            "default": "15m",
            "description": "How long to wait before giving up."
        }
    ]}
/>

```bash
surreal cloud instance resume staging
```

Resuming something already ready behaves like pausing something already paused: a note, a document, exit `0`. Resuming is usually slower than pausing, so the wait matters more here. With `--no-wait` the command hints at `surreal cloud instance watch <name>`.

## surreal cloud instance watch {#instance-watch}

Watch an operation that was started elsewhere.

<Synopsis>
surreal cloud instance watch [OPTIONS] [INSTANCE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug, name, or org/name. Omit to choose interactively."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--until",
            "value": "<STATE>",
            "default": "ready",
            "description": "The state to wait for: `ready`, `paused` or `deleted`."
        },
        {
            "name": "--wait-timeout",
            "value": "<DURATION>",
            "default": "15m",
            "description": "How long to watch before giving up."
        }
    ]}
/>

There is no `--wait` or `--no-wait` here, because a watch is nothing but a wait. The exit codes are those of any wait: `10` on timeout, `6` when the instance settles in a different state, and `5` when it disappears while you wait for another state.

| `--until` value | Finishes when |
| --- | --- |
| `ready` | The instance is running and healthy |
| `paused` | The instance is deliberately stopped |
| `deleted` | The instance is gone - a `404` while polling is what finishes this one |

```bash title="Pick up a create started in an earlier CI job"
surreal cloud instance watch api
```

```bash title="Wait for a pause to complete"
surreal cloud instance watch staging --until paused
```

> [!NOTE]
> This is the one command where `--json` writes to stdout continuously. The transitions *are* the answer, so the newline-delimited stream goes to stdout and nothing else is emitted. In text mode the run ends with a fresh detail view, except under `--until deleted`, where there is nothing left to fetch. Elsewhere, `--json` puts the progress stream on stderr and one final document on stdout.

```bash title="Follow the transitions as they happen"
surreal cloud instance watch api --json | jq -r '.event + " " + (.state // "")'
```

## surreal cloud instance status {#instance-status}

Show an instance's deployment phase and restorable snapshots.

<Synopsis>
surreal cloud instance status [OPTIONS] [INSTANCE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug, name, or org/name. Omit to choose interactively."
        }
    ]}
/>

Also accepts the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags), which arrange the snapshot table. Column ids are `snapshot_id`, `started_at`, `tiers` and `on_demand`, with `valid_versions` under `--wide`.

```bash
surreal cloud instance status production
```

The answer is one composite document: a phase, then the snapshots the instance can be restored from. In plain mode the phase is written as `phase<tab><Phase>` before the table, so `grep ^phase` works the same way it does on [`instance get`](#instance-get). An instance with no restorable snapshots gets a note on stderr rather than an empty table with no explanation.

Snapshot ids from here are what [`instance deploy --restore-from`](#instance-deploy) expects.

## surreal cloud instance endpoint {#instance-endpoint}

Print the endpoint a client connects to.

<Synopsis>
surreal cloud instance endpoint [OPTIONS] [INSTANCE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug, name, or org/name. Omit to choose interactively."
        }
    ]}
/>

This command has no options of its own.

The output is the bare endpoint plus a newline, byte-identical in rich and plain output, so `$(…)` captures exactly the value with no label and no styling.

```bash
ENDPOINT=$(surreal cloud instance endpoint production)
surreal db sql --endpoint "$ENDPOINT" --namespace app --database main
```

```bash title="Under --json, the hosts come too"
surreal cloud instance endpoint production --json
```

```json title="Output"
{
  "endpoint": "wss://production-6xk2.aws-euw1.surreal.cloud",
  "host": "production-6xk2.aws-euw1.surreal.cloud",
  "private_host": null,
  "access_type": "public"
}
```

The endpoint has the `wss://` scheme. A private-only instance produces a warning on stderr rather than a refusal - the endpoint is still correct, it is simply not reachable from where you are. The endpoint carries no credential: to connect, add a token from [`instance token`](#instance-token).

## surreal cloud instance token {#instance-token}

Mint a database token for an instance.

<Synopsis>
surreal cloud instance token [OPTIONS] [INSTANCE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug, name, or org/name. Omit to choose interactively."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--reveal",
            "description": "Print the token even when stdout is a terminal."
        }
    ]}
/>

This is a *database* token - the credential a SurrealDB client authenticates with. It is not a [personal access token](/docs/reference/cli/cloud/commands/token.md), which authenticates against the control plane.

```bash title="Copy it to the clipboard"
surreal cloud instance token production | pbcopy
```

```bash title="Use it with the database CLI"
SURREAL_TOKEN=$(surreal cloud instance token production) \
    surreal db sql --endpoint "$(surreal cloud instance endpoint production)" --namespace app --database main
```

To open a session without handling the token yourself, use [`instance sql`](#instance-sql), which does the same thing.

**Refusals.** Printing a credential into a terminal's scrollback is refused, exit `2`, and the check happens *before* the token is minted - so a forgotten `--reveal` never costs a credential nobody can recover:

```text
Refusing to print a database token to a terminal, where it would stay in your scrollback.
Pipe it:  surreal cloud instance token production | pbcopy
Or pass --reveal if you meant to see it.
```

Under `--json` the answer is a document with three fields, `kind` (`instance_token`), `instance_id` and `token`, so `surreal cloud instance token production --json | jq -r .token` works. Without `--json`, the bare token is the whole of stdout.

## surreal cloud instance jwks {#instance-jwks}

Fetch the key set that verifies an instance's tokens.

<Synopsis>
surreal cloud instance jwks [OPTIONS] [INSTANCE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug, name, or org/name. Omit to choose interactively."
        }
    ]}
/>

Also accepts the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags). Column ids are the JWK member names - `kid`, `kty`, `alg` and `use`, with `crv` under `--wide` - so a member the key type does not carry renders as missing rather than empty.

```bash title="Inspect the keys"
surreal cloud instance jwks production
```

```bash title="Pipe the whole key set into a verifier"
surreal cloud instance jwks production --json > jwks.json
```

Under `--json` the whole key set is emitted, `keys` wrapper included, so it can be handed straight to a JWT library.

A key set is public, so this is the one instance route that does not need a Cloud session. Addressing the instance by id avoids any lookup; a name or slug still needs to list the organisation's instances first, which needs a credential.

## Handing off to the database

`sql`, `import` and `export` do not speak SurrealQL themselves. Each one resolves the instance, mints a short-lived database token, and then becomes the matching database command, run through the `surreal` launcher:

| Command | Runs | Endpoint scheme |
| --- | --- | --- |
| `surreal cloud instance sql` | `surreal db sql` | `wss://` |
| `surreal cloud instance import` | `surreal db import` | `https://` |
| `surreal cloud instance export` | `surreal db export` | `https://` |

What the handoff passes to the database:

- `--endpoint` is added as `<scheme>://<instance host>`, unless the arguments after `--` already contain `--endpoint` or `-e`, in which case yours is used and nothing is added.
- The token is passed in the environment as `SURREAL_TOKEN`, never on the command line, so it does not appear in `ps` output or shell history.
- `--namespace` and `--database` become `SURREAL_NAMESPACE` and `SURREAL_DATABASE` in the child's environment.
- Everything after `--` is forwarded unchanged, because the database's own flags are documented on its own pages and change independently. Pass them as you would to `surreal db sql`, `surreal db import` or `surreal db export`.

The database is reached only through the launcher, at the path the launcher records in `SURREAL_CLI_LAUNCHER`. The component does not search `PATH` for a `surreal` binary, install anything, or fetch the database itself. If the database is not installed, the launcher offers to install it when it runs the command. Unattended, in CI or with `--no-input`, the launcher exits `12` and names the install command instead. See [`surreal`](/docs/reference/cli/launcher.md).

Run `surreal-cloud` directly rather than as `surreal cloud` and these three commands refuse with exit `2`, because there is no launcher to hand off to. They check this first, before anything else, so no token is minted for nothing.

On Unix the handoff replaces the process, so the database command owns the terminal, signals and exit code. On Windows the command stays alive and forwards the database's exit code.

Two warnings, neither of which stops the handoff: the instance is private-only, so its host resolves only inside its own network, and the instance is paused, failed or deleted, so the connection will probably be refused. `Connecting to <name> at <host>.` goes to stderr as the last thing printed, so `export -- -` can be piped without the note getting into the data.

## surreal cloud instance sql {#instance-sql}

Open a SurrealQL session against an instance.

<Synopsis>
surreal cloud instance sql [OPTIONS] [INSTANCE] [-- <ARGS>...]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug or name. Omit to choose interactively."
        },
        {
            "name": "[ARGS]...",
            "description": "Arguments for `surreal db sql`, after a `--` separator."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--deploy",
            "description": "Deploy a new instance first, as [`instance deploy`](#instance-deploy) does, and open the session once it is ready. With `--yes`, every setting takes its default."
        },
        {
            "name": "--namespace",
            "value": "<NS>",
            "description": "The namespace to open."
        },
        {
            "name": "--database",
            "value": "<DB>",
            "description": "The database to open."
        }
    ]}
/>

This runs [`surreal db sql`](/docs/reference/cli/db/commands/sql.md) against the instance, as described in [Handing off to the database](#handing-off-to-the-database).

```bash title="Open a shell"
surreal cloud instance sql production --namespace app --database main
```

`--deploy` creates the instance and opens a session on it in one command. With no other flag it deploys an Earth instance with a generated name, which is the default of `instance deploy`:

```bash title="Deploy an Earth instance and open a shell"
surreal cloud instance sql --deploy --yes --namespace app --database main
```

```bash title="Pass flags through to surreal db sql"
surreal cloud instance sql production -- --ns app --db main --pretty
```

```bash title="Run a query from a pipeline"
echo "SELECT count() FROM person GROUP ALL;" \
    | surreal cloud instance sql production --namespace app --database main
```

`--namespace` and `--database` are optional here, because `surreal db sql` accepts a session without them.

## surreal cloud instance import {#instance-import}

Import a file into an instance.

<Synopsis>
surreal cloud instance import [OPTIONS] [INSTANCE] [-- <ARGS>...]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug or name. Omit to choose interactively."
        },
        {
            "name": "[ARGS]...",
            "description": "Arguments for `surreal db import`, after a `--` separator. The file to load goes here."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--namespace",
            "value": "<NS>",
            "required": true,
            "description": "The namespace to import into. Required by this command, though `--help` does not mark it so."
        },
        {
            "name": "--database",
            "value": "<DB>",
            "required": true,
            "description": "The database to import into. Required by this command, though `--help` does not mark it so."
        }
    ]}
/>

This runs [`surreal db import`](/docs/reference/cli/db/commands/import.md) against the instance, as described in [Handing off to the database](#handing-off-to-the-database). The file is the positional argument of the database command, so it goes after the `--`.

```bash
surreal cloud instance import production --namespace app --database main -- ./seed.surql
```

**Refusals.** `surreal db import` requires both a namespace and a database, so this command does too. The check fires before a token is minted, exit `2`:

```text
`surreal cloud instance import` needs both --namespace and --database; `surreal import` requires them.
```

See [`surreal db import`](/docs/reference/cli/db/commands/import.md) for the flags available after the `--`.

## surreal cloud instance export {#instance-export}

Export an instance to a file.

<Synopsis>
surreal cloud instance export [OPTIONS] [INSTANCE] [-- <ARGS>...]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug or name. Omit to choose interactively."
        },
        {
            "name": "[ARGS]...",
            "description": "Arguments for `surreal db export`, after a `--` separator. The destination goes here, or `-` for stdout."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--namespace",
            "value": "<NS>",
            "required": true,
            "description": "The namespace to export from. Required by this command, though `--help` does not mark it so."
        },
        {
            "name": "--database",
            "value": "<DB>",
            "required": true,
            "description": "The database to export from. Required by this command, though `--help` does not mark it so."
        }
    ]}
/>

This runs [`surreal db export`](/docs/reference/cli/db/commands/export.md) against the instance, as described in [Handing off to the database](#handing-off-to-the-database).

```bash title="Export to a file"
surreal cloud instance export production --namespace app --database main -- ./backup.surql
```

```bash title="Export to stdout and compress"
surreal cloud instance export production --namespace app --database main -- - | gzip > backup.surql.gz
```

Like `import`, this refuses a missing namespace or database before minting anything. The destination and the export selection flags, such as `--tables` or `--only`, belong to [`surreal db export`](/docs/reference/cli/db/commands/export.md). With no destination the database writes to stdout. Everything this command itself prints goes to stderr, so the dump on stdout stays clean.

For a managed snapshot rather than a SurrealQL dump, use [`instance backup create`](#instance-backup-create).

## surreal cloud instance metrics {#instance-metrics}

Show an instance's resource metrics.

<Synopsis>
surreal cloud instance metrics [OPTIONS] --metric <METRIC> [INSTANCE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug or name. Omit to choose interactively."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--metric",
            "value": "<METRIC>",
            "required": true,
            "description": "Which metric to read, such as `cpu`, `memory` or `disk`."
        },
        {
            "name": "--from",
            "value": "<TIME>",
            "description": "Start of the window, as an RFC 3339 timestamp."
        },
        {
            "name": "--to",
            "value": "<TIME>",
            "description": "End of the window, as an RFC 3339 timestamp."
        },
        {
            "name": "--samples",
            "description": "Show every sample instead of one summary per series."
        }
    ]}
/>

Also accepts the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags). Summary rows carry `series`, `last`, `min`, `mean`, `max` and `unit`, with `samples` and `gaps` under `--wide`; sample rows carry `timestamp`, `series` and `value`, with `unit` under `--wide`.

`--metric` is a free-form string rather than a fixed set, because the platform's metric vocabulary is not published anywhere the CLI can read it.

```bash title="A summary per series"
surreal cloud instance metrics production --metric cpu
```

```bash title="Every sample over a window"
surreal cloud instance metrics production \
    --metric memory \
    --from 2026-08-11T10:00:00Z \
    --to 2026-08-11T12:00:00Z \
    --samples
```

Timestamps are validated locally and forwarded byte-for-byte, never reformatted:

```text
Ensure `11-08-2026` is an RFC3339 timestamp, such as 2026-08-11T10:00:00Z
```

`--samples` chooses a table, not a payload: `--json` carries the whole document either way. A note on stderr states the metric, its unit and the window, which matters when neither bound is given because the API then chooses the window. An empty window prints a note suggesting a wider `--from` or a check of the metric name.

## surreal cloud instance logs {#instance-logs}

Show an instance's logs.

<Synopsis>
surreal cloud instance logs [OPTIONS] [INSTANCE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug or name. Omit to choose interactively."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--from",
            "value": "<TIME>",
            "description": "Start of the window, as an RFC 3339 timestamp."
        },
        {
            "name": "--to",
            "value": "<TIME>",
            "description": "End of the window, as an RFC 3339 timestamp. Conflicts with `--follow`."
        },
        {
            "name": "--level",
            "value": "<LEVELS>",
            "description": "Show only these levels, comma-separated. Filtered locally; the API has no level parameter."
        },
        {
            "name": "--follow",
            "short": "-f",
            "description": "Keep printing new lines. There is no streaming endpoint, so this polls."
        }
    ]}
/>

Also accepts the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags). Column ids are `timestamp`, `level` and `message`, with `pod` under `--wide`.

```bash title="Recent lines"
surreal cloud instance logs production
```

```bash title="Errors and warnings only"
surreal cloud instance logs production --level error,warn
```

```bash title="Follow, and hand each line to jq"
surreal cloud instance logs production --follow --json | jq -r '.timestamp + " " + .message'
```

`--level` is a display filter applied on this side, and a note reports how many lines were hidden by it. `--json` still carries every line the API sent. `--limit` takes from the start of the window, matching its meaning elsewhere, so to read the most recent lines, narrow the window with `--from`.

`--follow` polls with a moving start time at a fixed five-second interval - there is no streaming endpoint and no interval flag. It runs until interrupted, and lines on the boundary between two polls are not printed twice. Under `--follow --json`, each new line is written as newline-delimited JSON on stdout; in text mode a table is printed per batch, with the header only on the first.

## surreal cloud instance usage {#instance-usage}

Show what an instance has consumed.

<Synopsis>
surreal cloud instance usage [OPTIONS] [INSTANCE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug or name. Omit to choose interactively."
        }
    ]}
/>

Accepts the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags) and nothing else - this route takes no query parameters at all. Column ids are `instance_id`, `metric_type`, `compute_hours`, `disk_used_bytes`, `period_start` and `period_end`, with `instance_type` and `source` under `--wide`.

```bash
surreal cloud instance usage production
```

For an Earth instance the table lists one meter per row instead, as `meter`, `quantity` and `unit`, for the billing period so far:

```bash
surreal cloud instance usage edge-api
```

```text title="Example output"
METER               QUANTITY  UNIT
units               10,703    count
active_seconds      2,589     seconds
requests            3,683     count
rows_read           27,564    count
rows_written        3,588     count
live_notifications  0         count
connection_seconds  715       seconds
storage_mb_minutes  140       mb_minutes
```

`units` is request units and `active_seconds` is active time, the two meters [Earth plans](/docs/operate/instances/earth.md#what-is-measured) are measured in. Under `--json` the meters are in the `earth` array of the usage document, beside `period_start` and `period_end`.

For every instance in the organisation at once, use [`org usage`](/docs/reference/cli/cloud/commands/org.md#org-usage).

## surreal cloud instance estimate {#instance-estimate}

Estimate what an instance would cost.

<Synopsis>
surreal cloud instance estimate [OPTIONS] --type <SLUG> --region <REGION>
</Synopsis>

This command takes no positional argument: it prices a hypothetical instance, so there is nothing to name.

It prices dedicated instance types only. Earth is priced by its plan and its usage; see [Plans and usage](/docs/operate/instances/earth.md#plans-and-usage).

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--type",
            "value": "<SLUG>",
            "required": true,
            "description": "The instance type to price, by slug."
        },
        {
            "name": "--region",
            "value": "<REGION>",
            "required": true,
            "description": "The region to price it in."
        },
        {
            "name": "--units",
            "value": "<N>",
            "description": "How many compute units. Defaults to the type's own. Minimum 1."
        },
        {
            "name": "--storage",
            "value": "<GB>",
            "description": "How much storage, in gigabytes. Defaults to the type's own. Minimum 1."
        }
    ]}
/>

```bash title="Price a change before making it"
surreal cloud instance estimate --type production-4 --region aws-euw1 --units 8 --storage 250
```

Flags you omit are left out of the request rather than sent as null, so the platform's own defaults for that type apply. The estimate is for the organisation resolved from `--org` and the [precedence chain](/docs/reference/cli/cloud/global-flags.md#the-precedence-chain). Nothing is created or billed. The result shows the type, the region, any units or storage you gave, the cost with its currency symbol, and the currency.

**Refusals**, exit `2`:

```text
An instance has at least 1 compute unit; 0 was given.
An instance has at least 1GB of storage; 0 was given.
```

This is the one place the API does not use integer minor units - the cost is a number in a named currency - and `--json` keeps the raw value.

## surreal cloud instance capabilities get {#instance-capabilities-get}

Show an instance's capability configuration.

<Synopsis>
surreal cloud instance capabilities get [OPTIONS] [INSTANCE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug or name. Omit to choose interactively."
        }
    ]}
/>

This command has no options of its own.

```bash
surreal cloud instance capabilities get production
```

The view lists `allow_scripting`, `allow_guests` and `allow_insecure_storable_closures`, then the allowed and denied list for each of `experimental`, `arbitrary_query`, `eval_query`, `rpc_methods`, `http_endpoints`, `networks` and `functions`, named as the API names them (`allowed_functions`, `denied_networks` and so on). A setting the API did not send is left out, which is different from an empty list: an explicitly empty list is shown as `(none)` and permits nothing in that category, while an absent one leaves SurrealDB's default in force. Capabilities this build does not know about are shown as they arrive.

Under `--json` the nested capabilities object is emitted, not the whole instance - so it can be diffed against another instance directly.

```bash title="Compare two instances"
diff <(surreal cloud instance capabilities get staging --json) \
     <(surreal cloud instance capabilities get production --json)
```

## surreal cloud instance capabilities set {#instance-capabilities-set}

Change an instance's capability configuration.

<Synopsis>
surreal cloud instance capabilities set [OPTIONS] [INSTANCE]
</Synopsis>

The capabilities route is a full replacement, so this command reads the current configuration, applies the flags given here, shows what would change, and asks before writing. A list flag **replaces** that list rather than adding to it, and anything not named is left exactly as it is - including capabilities this build does not know about.

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug or name. Omit to choose interactively."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--allow-scripting",
            "description": "Allow embedded scripting functions. Conflicts with `--deny-scripting`."
        },
        {
            "name": "--deny-scripting",
            "description": "Refuse embedded scripting functions."
        },
        {
            "name": "--allow-guests",
            "description": "Allow unauthenticated guest access. Conflicts with `--deny-guests`."
        },
        {
            "name": "--deny-guests",
            "description": "Refuse unauthenticated guest access."
        },
        {
            "name": "--allow-experimental",
            "value": "<NAMES>",
            "description": "Experimental features to allow, comma-separated."
        },
        {
            "name": "--deny-experimental",
            "value": "<NAMES>",
            "description": "Experimental features to deny, comma-separated."
        },
        {
            "name": "--allow-arbitrary-query",
            "value": "<TARGETS>",
            "description": "Arbitrary-query targets to allow, comma-separated."
        },
        {
            "name": "--deny-arbitrary-query",
            "value": "<TARGETS>",
            "description": "Arbitrary-query targets to deny, comma-separated."
        },
        {
            "name": "--allow-eval-query",
            "value": "<TARGETS>",
            "description": "Eval-query targets to allow, comma-separated."
        },
        {
            "name": "--deny-eval-query",
            "value": "<TARGETS>",
            "description": "Eval-query targets to deny, comma-separated."
        },
        {
            "name": "--allow-rpc",
            "value": "<METHODS>",
            "description": "RPC methods to allow, comma-separated."
        },
        {
            "name": "--deny-rpc",
            "value": "<METHODS>",
            "description": "RPC methods to deny, comma-separated."
        },
        {
            "name": "--allow-http",
            "value": "<ENDPOINTS>",
            "description": "HTTP endpoints to allow, comma-separated."
        },
        {
            "name": "--deny-http",
            "value": "<ENDPOINTS>",
            "description": "HTTP endpoints to deny, comma-separated."
        },
        {
            "name": "--allow-net",
            "value": "<TARGETS>",
            "description": "Networks to allow, comma-separated."
        },
        {
            "name": "--deny-net",
            "value": "<TARGETS>",
            "description": "Networks to deny, comma-separated."
        },
        {
            "name": "--allow-funcs",
            "value": "<FUNCTIONS>",
            "description": "Functions to allow, comma-separated."
        },
        {
            "name": "--deny-funcs",
            "value": "<FUNCTIONS>",
            "description": "Functions to deny, comma-separated."
        },
        {
            "name": "--force",
            "description": "Replace the capabilities without confirming."
        }
    ]}
/>

```bash title="Turn scripting off"
surreal cloud instance capabilities set production --deny-scripting
```

```bash title="Replace the allowed function list"
surreal cloud instance capabilities set production --allow-funcs "array,string,time"
```

```bash title="Deny outbound HTTP from a script"
surreal cloud instance capabilities set production --deny-funcs "http::*" --force
```

The diff is printed on stderr in every output mode, `--json` included, then confirmed unless `--force` or the global `--yes` is given. `--quiet` suppresses the diff, so combine it with `--force` rather than with a prompt. Declining prints `Nothing was changed.` and exits `0`. In a non-interactive session without `--force` or `--yes`, the command exits `2` having written nothing.

Flags for the same capability in opposite directions, such as `--allow-scripting` with `--deny-scripting`, are a usage error. A list flag may be given together with its opposite, for example `--allow-funcs` and `--deny-funcs`, and each replaces its own list. Setting a list to the value it already has is not a change. There is no flag for `allow_insecure_storable_closures`: `set` leaves it as it is.

On success the command prints the configuration now in force.

**Refusals and short-circuits.** No flags at all is a usage error, exit `2`, before any request:

```text
Nothing to set. Pass at least one capability flag, such as --allow-scripting or --deny-funcs http::*.
Run `surreal cloud instance capabilities get` to see the current configuration.
```

Flags that would change nothing produce a note and exit `0` without a write:

```text
`production` already has those capabilities. Nothing was changed.
```

## surreal cloud instance network get {#instance-network-get}

Show which addresses may connect to a SurrealDB Earth instance.

<Synopsis>
surreal cloud instance network get [OPTIONS] [INSTANCE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id or name. Defaults to the resolved one."
        }
    ]}
/>

This command has no options of its own.

```bash
surreal cloud instance network get edge-api
```

```text title="Output"
allow	any address
deny	none
```

Under `--json` the policy is emitted as `{"allow": [...], "deny": [...]}`, each a list or `null` when there is none. A dedicated instance has no network policy, so the command refuses one and exits `9`. Its access is set with [`update --access-type`](#instance-update) instead.

## surreal cloud instance network set {#instance-network-set}

Change which addresses may connect to a SurrealDB Earth instance.

<Synopsis>
surreal cloud instance network set [OPTIONS] [INSTANCE]
</Synopsis>

A client is served when `--allow-ip` matches its address, or there is no allow list, and `--deny-ip` does not match it. A denied address stays denied even when the allow list also matches it. See [Limit the addresses that can connect](/docs/operate/instances/earth.md#limit-the-addresses-that-can-connect).

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id or name. Defaults to the resolved one."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--allow-ip",
            "value": "<CIDRS>",
            "description": "Admit only these IP addresses or CIDR blocks, comma-separated."
        },
        {
            "name": "--deny-ip",
            "value": "<CIDRS>",
            "description": "Refuse these IP addresses or CIDR blocks, comma-separated."
        },
        {
            "name": "--open",
            "description": "Admit every address, clearing both lists."
        },
        {
            "name": "--force",
            "description": "Replace the policy without confirming."
        }
    ]}
/>

The policy is replaced whole, so the command works like [`capabilities set`](#instance-capabilities-set): it reads the current policy, replaces only the lists given, shows what would change, and asks before writing. A list flag replaces that list rather than adding to it, and a list that is not named is kept.

```bash title="Admit one office network"
surreal cloud instance network set edge-api --allow-ip 203.0.113.0/24
```

```bash title="Admit every address again"
surreal cloud instance network set edge-api --open
```

On success the command prints ``Replaced the network policy on `<name>`.`` and the policy now in force. A policy that would not change prints a note and exits `0` without a write. No flags at all is a usage error, exit `2`:

```text
Nothing to set. Pass --allow-ip, --deny-ip, or --open.
Run `surreal cloud instance network get` to see the current policy.
```

## surreal cloud instance backup list {#instance-backup-list}

List the snapshots an instance can be restored from.

<Synopsis>
surreal cloud instance backup list [OPTIONS] [INSTANCE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug or name. Omit to choose interactively."
        }
    ]}
/>

Accepts the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags) and nothing else. Column ids are `snapshot_id`, `started_at`, `tiers` and `on_demand`, with `valid_versions` under `--wide`.

```bash
surreal cloud instance backup list production
```

```bash title="The newest snapshot id"
surreal cloud instance backup list production --sort started_at --reverse --limit 1 \
    --columns snapshot_id --no-header
```

There is no backup collection route on the API, so this reads the snapshots off the instance's status route. `--json` carries the snapshot array rather than the whole status document, and an instance too new to have been backed up gives an empty array and a note. [`instance status`](#instance-status) shows the same snapshots alongside the deployment phase.

## surreal cloud instance backup create {#instance-backup-create}

Take a backup of an instance now.

<Synopsis>
surreal cloud instance backup create [OPTIONS] [INSTANCE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug or name. Omit to choose interactively."
        }
    ]}
/>

This command has no options of its own, and carries no `--wait` or `--no-wait`.

```bash
surreal cloud instance backup create production
```

The route answers with no body, so the document is synthesised:

```json title="Output"
{
  "instance_id": "67upif0m8sh1cn1p2c8t",
  "status": "accepted"
}
```

A replayed request is a second snapshot, so this call is not retried after a timeout or a `502`. Requesting a backup while one is already queued answers with a `429` that is reported as a conflict, exit `6`, rather than as a rate limit - the condition is "one is already running", not "you are asking too often". Only one on-demand backup runs at a time.

Poll [`instance backup list`](#instance-backup-list) to see the snapshot appear.

## surreal cloud instance backup policy get {#instance-backup-policy-get}

Show the backup retention policy.

<Synopsis>
surreal cloud instance backup policy get [OPTIONS] [INSTANCE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug or name. Omit to choose interactively."
        }
    ]}
/>

This command has no options of its own.

```bash
surreal cloud instance backup policy get production
```

The answer reports each retention tier, how often snapshots are taken, and which tiers this organisation's plan allows you to change - which is what [`backup policy set`](#instance-backup-policy-set) will accept.

## surreal cloud instance backup policy set {#instance-backup-policy-set}

Change the backup retention policy.

<Synopsis>
surreal cloud instance backup policy set [OPTIONS] [INSTANCE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[INSTANCE]",
            "description": "The instance, by id, slug or name. Omit to choose interactively."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--daily",
            "value": "<DAYS>",
            "description": "How many days of daily snapshots to keep, or the literal `default`."
        },
        {
            "name": "--weekly",
            "value": "<WEEKS>",
            "description": "How many weeks of weekly snapshots to keep, or the literal `default`."
        },
        {
            "name": "--monthly",
            "value": "<MONTHS>",
            "description": "How many months of monthly snapshots to keep, or the literal `default`."
        },
        {
            "name": "--frequency-hours",
            "value": "<HOURS>",
            "description": "How often to take a snapshot, in hours. Checked against the allow-list this organisation's plan publishes, not against a range."
        },
        {
            "name": "--force",
            "description": "Change the policy without confirming."
        }
    ]}
/>

The three retention flags also accept the literal `default`, which restores this organisation's own value for that tier. `--frequency-hours` has no `default` form, because the platform gives it no resettable value.

`--frequency-hours` is an **allow-list**, not a range: the plan publishes the intervals it offers, and a value sitting between two of them is refused rather than rounded. Run [`backup policy get`](#instance-backup-policy-get) to see which intervals this plan offers.

```bash title="Keep a fortnight of dailies"
surreal cloud instance backup policy set production --daily 14
```

```bash title="Snapshot every six hours"
surreal cloud instance backup policy set production --frequency-hours 6
```

```bash title="Reset the monthly tier to the organisation's own value"
surreal cloud instance backup policy set production --monthly default
```

**Confirmation.** Only a *reduction* asks. Lengthening a retention cannot lose a snapshot, so it is applied without a prompt. A reset to `default` counts as a reduction, because the organisation's own value is not known in advance. Changing only `--frequency-hours` never asks, because taking snapshots less often deletes none. The shortened tiers are listed on stderr and the question names the instance. Declining prints `The policy was not changed.` and exits `0`. In a non-interactive session without `--force` or `--yes`, a reduction exits `2` having changed nothing.

**Refusals**, exit `2`:

- No flags at all:

```text
Nothing to set. Pass --daily, --weekly, --monthly or --frequency-hours.
Each retention flag also takes the literal `default`, which restores this organization's own value for that tier.
```

- A tier the plan does not allow changing:

```text
This organization's plan does not allow changing the monthly retention on `production`.
Run `surreal cloud instance backup policy get` to see which tiers are editable.
```

- A value outside the plan's bounds, naming the bound it broke:

```text
Daily retention must be between 1 and 30 days on this plan; 90 was given.
```

- A `--frequency-hours` the plan does not offer, listing the intervals it does:

```text
A backup every 5 hours is not offered on this plan. Choose one of: 6, 12, 24.
```

## Related pages

- [Long-running operations](/docs/reference/cli/cloud/long-running-operations.md) - `--wait`, `--no-wait`, polling and exit code `10`
- [`org` commands](/docs/reference/cli/cloud/commands/org.md) - the organisation that owns these instances
- [SurrealDB Earth](/docs/operate/instances/earth.md) - cells, residency, network policy and usage on Earth
- [`catalog` commands](/docs/reference/cli/cloud/commands/catalog.md) - the region, residency, type and version slugs `deploy` and `update` expect
- [The `surreal` launcher](/docs/reference/cli/launcher.md) - how `sql`, `import` and `export` reach the database component
- [Overview](/docs/reference/cli/cloud.md) - the rest of the reference
- [SurrealDB CLI](/docs/reference/cli/db.md) - the data plane: `surreal db sql`, `surreal db import`, `surreal db export`

---

Source: https://surrealdb.com/docs/reference/cli/cloud/commands/invite

# surreal cloud invite

Reference for surreal cloud invite - list pending organisation invitations, send one with a role, and withdraw one by email address or code. Same command as team invite; email is checked locally and roles come from org roles.

`surreal cloud invite` manages organisation invitations: the ones that have been sent and not yet accepted. Once someone accepts, they become a member and move into [`team`](/docs/reference/cli/cloud/commands/team.md).

<Synopsis>
surreal cloud invite <COMMAND> [OPTIONS]
surreal cloud invites <COMMAND> [OPTIONS]
</Synopsis>

| Verb | Purpose | Alias |
| --- | --- | --- |
| [`list`](#invite-list) | List an organisation's pending invitations | `ls` |
| [`create`](#invite-create) | Invite someone to an organisation | |
| [`delete`](#invite-delete) | Withdraw an invitation | `rm` |

[`team invite`](/docs/reference/cli/cloud/commands/team.md#team-invite) and [`invite create`](#invite-create) are the same command reached two ways - the same arguments, the same validators and the same messages - because sending an invitation is both how a team gains a member and how an invitation comes to exist. Use whichever reads better in the script you are writing.

This group declares the scopes `read:cloud` and `write:cloud-organization`, the same pair as [`org`](/docs/reference/cli/cloud/commands/org.md) and [`team`](/docs/reference/cli/cloud/commands/team.md). A personal access token cannot use the mutating verbs: see [Authentication](/docs/reference/cli/cloud/authentication.md#what-a-personal-access-token-cannot-do). There is no `update`: to change an invitation, withdraw it and send another.

## surreal cloud invite list {#invite-list}

List an organisation's pending invitations.

<Synopsis>
surreal cloud invite list [OPTIONS]
</Synopsis>

This command takes no positional argument. The organisation comes from `--org` and the [precedence chain](/docs/reference/cli/cloud/global-flags.md#the-precedence-chain).

Accepts the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags) and nothing else. Column ids are `email`, `role` and `status`, with `code` and `organization_id` under `--wide`.

```bash
surreal cloud invite list
```

```text title="Output"
EMAIL                ROLE    STATUS
dee@acme.example     member  pending
eli@acme.example     admin   pending
```

```bash title="Include the codes, which withdrawals also accept"
surreal cloud invite list --wide
```

The list is not filtered by status, so it shows every status the API reports. An organisation with no invitations is a success: exit `0`, and an empty array under `--json`.

## surreal cloud invite create {#invite-create}

Invite someone to an organisation.

<Synopsis>
surreal cloud invite create [OPTIONS] --role <ROLE> <EMAIL>
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "<EMAIL>",
            "required": true,
            "description": "The email address to invite."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--role",
            "value": "<ROLE>",
            "required": true,
            "description": "The role to grant. Run `surreal cloud org roles` for the ones this organisation defines."
        }
    ]}
/>

```bash
surreal cloud invite create dee@acme.example --role member
```

```bash title="Invite a whole list, reading roles from a file"
while IFS=, read -r email role; do
    surreal cloud invite create "$email" --role "$role"
done < new-joiners.csv
```

**Refusals**, exit `2`, before any request. The address validator asks only for an `@` with something either side and no internal whitespace; the API is the authority on deliverability:

```text
`dee.acme.example` is not an email address: it has no `@`.
```

Only an empty `--role` is refused locally, because the role vocabulary is per organisation:

```text
A role cannot be empty. Run `surreal cloud org roles` to see the ones this organization defines.
```

A role the API rejects as invalid is annotated with a pointer to [`org roles`](/docs/reference/cli/cloud/commands/org.md#org-roles).

The command is never retried after the request has been written, because a repeat would send a second email carrying a second working code. On success it prints the invitation, including its code.

## surreal cloud invite delete {#invite-delete}

Withdraw an invitation.

<Synopsis>
surreal cloud invite delete [OPTIONS] <INVITE>
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "<INVITE>",
            "required": true,
            "description": "The invitation, by email address or code."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--force",
            "description": "Withdraw without confirming."
        }
    ]}
/>

```bash title="By address"
surreal cloud invite delete dee@acme.example
```

```bash title="By code, without a prompt"
surreal cloud invite delete 7f3a91c4 --force
```

The invitation has no id of its own. The API identifies it by its code, which the recipient also redeems, so `<INVITE>` accepts either. An email address is resolved to its code by listing the invitations first, and the listing also happens when you pass a code, so the confirmation can name the address.

**Refusals.** The confirmation names the address the invitation was sent to. Declining prints `Nothing was withdrawn.` and exits `0`. In a non-interactive session without `--force` or `--yes`, it exits `2` having sent nothing.

Withdrawing an invitation someone has already accepted is not how you remove them - use [`team remove`](/docs/reference/cli/cloud/commands/team.md#team-remove) for that.

## Related pages

- [`team` commands](/docs/reference/cli/cloud/commands/team.md) - members who have already joined
- [`org roles`](/docs/reference/cli/cloud/commands/org.md#org-roles) - the roles an invitation can grant
- [Overview](/docs/reference/cli/cloud.md) - the rest of the reference
- [SurrealDB CLI](/docs/reference/cli/db.md) - for working with the data inside an instance

---

Source: https://surrealdb.com/docs/reference/cli/cloud/commands/misc

# surreal cloud other commands

Reference for the surreal cloud leaf commands - whoami, api, open, status, version and completion.

Six commands sit at the top level rather than inside a noun group. They cover identity, the raw API escape hatch, opening the dashboard, diagnostics, version information and shell completion.

| Command | Purpose | Alias |
| --- | --- | --- |
| [`whoami`](#whoami) | Show who the API thinks you are | |
| [`api`](#api) | Call the API directly | |
| [`open`](#open) | Open a dashboard page in a browser | |
| [`status`](#status) | Check that everything is configured and reachable | `doctor` |
| [`version`](#version) | Output version information | |
| [`completion`](#completion) | Generate shell completions | |

## surreal cloud whoami {#whoami}

Show who the API thinks you are.

<Synopsis>
surreal cloud whoami [OPTIONS]
</Synopsis>

This command takes no arguments and no options of its own.

```bash
surreal cloud whoami
```

```text title="Output"
Email           ana@acme.example
User Id         67upif0m8sh1cn1p2c8t
Name            Ana Silva
Default Org     acme
```

`whoami` spends a request on the API's own profile route, which makes it the counterpart to [`auth status`](/docs/reference/cli/cloud/commands/auth.md#auth-status): that one reports what is on this machine, without touching the network; this one reports what the API believes. When they disagree, the API is right.

In text modes the default organisation is shown by name, which costs a second request. That lookup is skipped under `--json`, where the payload is the profile exactly as the API sent it.

## surreal cloud api {#api}

Call the API directly.

<Synopsis>
surreal cloud api [OPTIONS] <METHOD> <PATH>
</Synopsis>

This is the escape hatch. It signs a request with whatever credential the profile holds, applies the same retries and the same error classification as every other command, and prints the body - so a route that has no dedicated command is still reachable without rebuilding authentication by hand.

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "<METHOD>",
            "required": true,
            "description": "The HTTP method: `get`, `post`, `put`, `patch` or `delete`. Case-insensitive."
        },
        {
            "name": "<PATH>",
            "required": true,
            "description": "The path, such as `/api/cloud/v0/organizations`. A leading `/` is added when absent."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--data",
            "short": "-d",
            "value": "<BODY>",
            "description": "A JSON body, `@FILE` to read a file, or `-` to read standard input."
        },
        {
            "name": "--query",
            "value": "<KEY=VALUE>",
            "description": "A query parameter, as `key=value`. Repeatable."
        },
        {
            "name": "--header",
            "value": "<NAME:VALUE>",
            "description": "An extra request header, as `name:value`. Repeatable."
        },
        {
            "name": "--include",
            "description": "Print the response status and headers to stderr."
        },
        {
            "name": "--raw",
            "description": "Print the body exactly as it arrived, without pretty-printing."
        },
        {
            "name": "--force",
            "description": "Send a write without confirming."
        }
    ]}
/>

```bash title="A GET, pretty-printed"
surreal cloud api get /api/cloud/v0/organizations
```

```bash title="Query parameters and response headers"
surreal cloud api get /api/cloud/v0/organizations --query limit=5 --include
```

```bash title="A write, from a file"
surreal cloud api post /api/cloud/v0/organizations --data @org.json --force
```

```bash title="A write, from stdin"
echo '{"name":"acme"}' | surreal cloud api post /api/cloud/v0/organizations -d - --force
```

`-d` follows curl's spellings: `-` and `@-` mean standard input, `@path` means a file, and anything else is treated as an inline body.

**Confirmation.** Any write method - `POST`, `PUT`, `PATCH` or `DELETE` - confirms first unless `--force` or the global `--yes` is given. Declining prints `Nothing was sent.` and exits `0`. In a non-interactive session with neither, it exits `2` having sent nothing.

**Refusals**, all exit `2`:

- An unknown method:

```text
Ensure the method is one of get, post, put, patch or delete (got `HEAD`)
```

- A URL where a path was expected:

```text
Ensure the path is a path and not a URL; the host comes from --api
```

- A malformed `--query` or `--header`. Both split on their first separator only, so a value containing `=` or `:` survives intact.
- A reserved header. `Authorization`, `X-Cloud-Token` and `X-Request-Id` come from the credential in use:

```text
`authorization` is set from the credential in use and cannot be overridden here. Pass --token or --token-file to change what is sent.
```

- A body on a `GET`: `A GET takes no body. Use --query for parameters, or pick another method.`
- A body that is not valid JSON, naming where it came from.

**Notes.** A path on neither the Cloud nor the accounts surface is sent **without credentials**, and says so first. Retries follow the method: a `GET` is retried freely, a `POST` never, and `PUT`, `PATCH` and `DELETE` only when the connection failed before anything was sent.

`--raw` writes the bytes verbatim, control characters included, which is safe only because it is opt-in. `--json` is unaffected by `--raw`: it always emits one parseable document, turning a non-JSON body into a JSON string and an empty body into `null`. In text mode an empty body prints nothing, and a note on stderr reports the status that answered with none.

## surreal cloud open {#open}

Open a dashboard page in a browser.

<Synopsis>
surreal cloud open [OPTIONS] [SUBJECT] [REF]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[SUBJECT]",
            "default": "dashboard",
            "description": "What to open: `dashboard`, `org`, `instance`, `billing` or `terms`."
        },
        {
            "name": "[REF]",
            "description": "The organisation or instance, by id, slug or name."
        }
    ]}
/>

This command has no options of its own - only the [global flags](/docs/reference/cli/cloud/global-flags.md).

| `[SUBJECT]` | Opens |
| --- | --- |
| `dashboard` | The account's overview page |
| `org` | An organisation's overview |
| `instance` | One instance, by id, slug or name |
| `billing` | An organisation's billing and invoices |
| `terms` | The terms and privacy policy, which this CLI links to and never accepts |

```bash title="The account overview"
surreal cloud open
```

```bash title="One instance"
surreal cloud open instance production
```

```bash title="Billing for the resolved organisation"
surreal cloud open billing
```

**The URL is always printed; it is only sometimes opened.** A browser is attempted when a person is present - which includes a `--json` invocation, since a human may well want machine output and a browser window at the same time - and a failure to open is a warning rather than an error. So the command is still useful over SSH: you get the link, and you paste it yourself.

**Refusals**, exit `2`:

- A `[REF]` alongside `dashboard` or `terms`, which take none:

```text
That subject takes no reference. Try `surreal cloud open org <name>` or `surreal cloud open instance <name>`.
```

- `instance` with no reference:

```text
`open instance` needs to know which one.

Try:  surreal cloud open instance <name>
```

`open terms` links to the legal documents and lists the others as notes. This CLI never accepts terms on your behalf.

## surreal cloud status {#status}

Check that everything is configured and reachable. Also spelled `surreal cloud doctor`.

<Synopsis>
surreal cloud status [OPTIONS]
surreal cloud doctor [OPTIONS]
</Synopsis>

This command takes no positional arguments and no options of its own.

Accepts the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags). Column ids are `check`, `ok` and `detail`.

Six checks run in dependency order, one row each. No check can abort the command, so you always get the whole picture:

| Check | What it covers |
| --- | --- |
| `credential` | Which credential this profile holds, and when it expires. Local only. A failure here is fatal |
| `api` | A version request against the API. An authentication error skips this rather than failing it |
| `version` | The client version the API expects. Reported, never enforced |
| `cloud session` | The Cloud session token. A personal access token is reported as skipped, not passed or failed |
| `organization` | The full precedence chain, picker included. Never fatal |
| `system message` | A platform banner, when a session is available and the API has one. No verdict |

```bash
surreal cloud status
```

```bash title="Just the failures"
surreal cloud status --json | jq -r '.[] | select(.ok == false) | .check + ": " + .detail'
```

The `ok` column is a tri-state. A check either passed, failed, or never ran because something it depended on had already failed - the third case renders as a dash, and under `--json` the `ok` field is `null` rather than `false`.

> [!IMPORTANT]
> This is the one command that prints its table even when it exits non-zero, because the table *is* the diagnosis and a doctor command that goes silent when things break is useless in the one situation it exists for. The exit code comes from the first fatal check - `3` for a credential problem, `9` for an unreachable API - rather than a flat `1`.

`status` checks the control plane only. It does not look for the database, because that is the launcher's concern: `surreal list` lists every installed component. A `version` check that fails names `surreal upgrade cloud` as the remedy.

## surreal cloud version {#version}

Output version information.

<Synopsis>
surreal cloud version [OPTIONS]
</Synopsis>

This command takes no positional arguments.

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--local",
            "description": "Report this build without asking the API for its version."
        }
    ]}
/>

```bash
surreal cloud version
```

```text title="Output"
surreal cloud  0.1.0
Commit         9f3c1ab
Built          2026-08-11
Target         aarch64-apple-darwin
```

```json title="Under --json"
{
  "version": "0.1.0",
  "commit": "9f3c1ab",
  "build_date": "2026-08-11",
  "target": "aarch64-apple-darwin"
}
```

`version` reports the build in front of you. It needs no credential and no organisation, so it works before you have signed in and inside a container with no egress. The flag forms `surreal cloud -V` and `surreal cloud --version` print the version string alone, with the commit, build date and target in parentheses.

To see every component the launcher manages, with the version of each, use `surreal list`. For the API's own version and the client version floor it expects, use [`status`](#status).

## surreal cloud completion {#completion}

Generate shell completions.

<Synopsis>
surreal cloud completion [OPTIONS] <SHELL>
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "<SHELL>",
            "required": true,
            "description": "The shell to generate completions for: `bash`, `elvish`, `fish`, `powershell` or `zsh`."
        }
    ]}
/>

This command has no options of its own.

```bash title="zsh"
surreal cloud completion zsh > "${fpath[1]}/_surreal-cloud"
```

```bash title="bash"
surreal cloud completion bash > /etc/bash_completion.d/surreal-cloud
```

```bash title="fish"
surreal cloud completion fish > ~/.config/fish/completions/surreal-cloud.fish
```

```powershell title="PowerShell"
surreal cloud completion powershell | Out-String | Invoke-Expression
```

This is the one command whose payload is not a view: it emits a shell script, so `--json` does not wrap it. The script is buffered before it is written, so `surreal cloud completion bash | head -1` exits `0` rather than failing on the closed pipe.

The generated script registers completions for the component's own command name, `surreal-cloud`, which is why the file names above use it.

## Related pages

- [Output and exit codes](/docs/reference/cli/cloud/output-and-exit-codes.md) - the `--json` contract and the full exit-code table
- [Authentication](/docs/reference/cli/cloud/authentication.md) - what `whoami` and `status` are reporting on
- [Install](/docs/reference/cli/guides/install.md) - installing the launcher and its components
- [surreal cloud reference](/docs/reference/cli/cloud.md) - the rest of the reference
- [Database commands](/docs/reference/cli/db.md) - for queries, imports, exports and running a server

---

Source: https://surrealdb.com/docs/reference/cli/cloud/commands/org

# surreal cloud org

Reference for surreal cloud org - list, get, create, rename, archive and remember a default organisation, and read its roles, permissions, usage, spend and plans. Includes the --period format, archive confirmation and the scopes this group needs.

`surreal cloud org` manages organisations. An organisation owns instances, members and billing, and almost every other command needs to know which one you mean - so this group is usually the second one you use after [`auth`](/docs/reference/cli/cloud/commands/auth.md).

<Synopsis>
surreal cloud org <COMMAND> [OPTIONS]
surreal cloud orgs <COMMAND> [OPTIONS]
</Synopsis>

| Verb | Purpose | Alias |
| --- | --- | --- |
| [`list`](#org-list) | List the organisations you belong to | `ls` |
| [`get`](#org-get) | Show one organisation | |
| [`create`](#org-create) | Create an organisation | |
| [`update`](#org-update) | Rename an organisation | |
| [`archive`](#org-archive) | Archive an organisation | |
| [`use`](#org-use) | Remember an organisation as the default for this profile | |
| [`roles`](#org-roles) | List the roles an organisation can assign | |
| [`permissions`](#org-permissions) | Show what you are permitted to do in an organisation | |
| [`usage`](#org-usage) | Show resource usage across an organisation's instances | |
| [`spend`](#org-spend) | Show an organisation's billed spend | |
| [`plans`](#org-plans) | List the plans available to an organisation | |

This group declares the scopes `read:cloud` and `write:cloud-organization`, the same pair as [`team`](/docs/reference/cli/cloud/commands/team.md) and [`invite`](/docs/reference/cli/cloud/commands/invite.md). A personal access token is read-only here regardless: the gateway refuses every non-GET Cloud route for one, so the mutating verbs answer 403 and exit `4` even for a token carrying `write:cloud-organization`. See [Authentication](/docs/reference/cli/cloud/authentication.md#what-a-personal-access-token-cannot-do).

## surreal cloud org list {#org-list}

List the organisations you belong to.

<Synopsis>
surreal cloud org list [OPTIONS]
</Synopsis>

This command takes no positional arguments - it lists everything you can see.

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--all",
            "description": "Include archived organisations."
        }
    ]}
/>

Also accepts the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags). Column ids are `name`, `id`, `plan`, `state`, `role` and `members`, with `billing_provider`, `max_free`, `max_paid`, `privatelink`, `locked` and `archived_at` shown only under `--wide`.

```bash
surreal cloud org list
```

```text title="Output"
NAME      ID                    PLAN    STATE   YOUR ROLE  MEMBERS
acme      67upif0m8sh1cn1p2c8t  scale   active  owner            7
contoso   6a2k9lqzt4v8bn3m1x5c  free    active  member           2
```

```bash title="Just the names, for a loop"
surreal cloud org list --columns name --no-header
```

Archived organisations are left out of the table. When any were hidden, a note on stderr says how many and suggests `--all`. `--json` always carries every organisation, because the filter only affects the table. An empty list is a success: exit `0` and an empty array under `--json`.

## surreal cloud org get {#org-get}

Show one organisation.

<Synopsis>
surreal cloud org get [OPTIONS] [ORG]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[ORG]",
            "description": "The organisation, by id or name. Defaults to the resolved one."
        }
    ]}
/>

This command has no options of its own.

```bash
surreal cloud org get acme
```

```bash title="Whichever organisation is in force"
surreal cloud org get
```

The detail view reports the id, plan, state, your role, the member count, free and paid instance allowances, the billing provider and details, the payment method and PrivateLink availability. Two further fields appear only when they apply: `Resources Locked` when true, and `Archived` when the organisation has been archived. Backup retention bounds are shown when the plan defines them.

## surreal cloud org create {#org-create}

Create an organisation.

<Synopsis>
surreal cloud org create [OPTIONS] <NAME>
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "<NAME>",
            "required": true,
            "description": "A name for the organisation. Between 1 and 30 characters."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--use",
            "description": "Remember this organisation as the default for this profile, as if `org use` had been run afterwards."
        }
    ]}
/>

```bash
surreal cloud org create acme --use
```

**Refusals.** A name outside 1 to 30 characters, measured after trimming, is a usage error, exit `2`, raised before any request. The same limit applies to [`org update --name`](#org-update).

On success the command prints the new organisation's detail view. With `--use`, it then records the organisation for the current profile and says so.

## surreal cloud org update {#org-update}

Rename an organisation.

<Synopsis>
surreal cloud org update [OPTIONS] --name <NAME> [ORG]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[ORG]",
            "description": "The organisation, by id or name. Defaults to the resolved one."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--name",
            "value": "<NAME>",
            "required": true,
            "description": "The new name."
        }
    ]}
/>

```bash
surreal cloud org update acme --name "Acme Corporation"
```

The name has the same 1 to 30 character limit as [`org create`](#org-create), checked locally with exit `2` before any request. Renaming does not change the organisation's id, so scripts that address it by id are unaffected.

## surreal cloud org archive {#org-archive}

Archive an organisation.

<Synopsis>
surreal cloud org archive [OPTIONS] [ORG]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[ORG]",
            "description": "The organisation, by id or name. Defaults to the resolved one."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--force",
            "description": "Archive without confirming."
        }
    ]}
/>

```bash
surreal cloud org archive contoso
```

**Refusals.** The command confirms first unless `--force` or the global `--yes` is given. The question names the organisation and how many instances it holds, and archiving cannot be undone from the CLI because there is no unarchive command. In a non-interactive session with neither flag, it exits `2` having sent nothing. Declining the prompt prints `Nothing was archived.` and exits `0`.

An organisation that is already archived is a no-op that exits `0`. It says so and stops before the archive request:

```text
`contoso` is already archived.
```

The document is still emitted, so `org archive <name> --json` answers with the organisation in both cases rather than changing shape with remote state the caller has not seen.

Archived organisations are hidden from [`org list`](#org-list) unless you pass `--all`.

## surreal cloud org use {#org-use}

Remember an organisation as the default for this profile.

<Synopsis>
surreal cloud org use [OPTIONS] [ORG]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[ORG]",
            "description": "The organisation, by id or name. Omit to choose interactively."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--clear",
            "description": "Forget the remembered organisation instead. Conflicts with `[ORG]`."
        }
    ]}
/>

```bash title="Remember one"
surreal cloud org use acme
```

```bash title="Pick from a list"
surreal cloud org use
```

```bash title="Forget it again"
surreal cloud org use --clear
```

The choice is written to the `[profile.<name>.context]` table of `config.toml`, which sits below a hand-written `org` key in the [precedence chain](/docs/reference/cli/cloud/global-flags.md#the-precedence-chain) - so setting `org` yourself is never overwritten by this command.

**Refusals.** Omitting `[ORG]` in a non-interactive session exits `2` and names the flags that would have settled it. The command warns when `SURREAL_CLOUD_ORG` is set, because the variable outranks what it just wrote.

`org use` remembers an organisation *within* a profile. [`context use`](/docs/reference/cli/cloud/commands/context.md#context-use) switches the whole profile.

## surreal cloud org roles {#org-roles}

List the roles an organisation can assign.

<Synopsis>
surreal cloud org roles [OPTIONS] [ORG]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[ORG]",
            "description": "The organisation, by id or name. Defaults to the resolved one."
        }
    ]}
/>

Also accepts the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags). Column ids are `name` and `permissions`.

```bash
surreal cloud org roles
```

The role vocabulary is per organisation, which is why [`team invite`](/docs/reference/cli/cloud/commands/team.md#team-invite) and [`team update`](/docs/reference/cli/cloud/commands/team.md#team-update) point here rather than validating a `--role` value locally.

## surreal cloud org permissions {#org-permissions}

Show what you are permitted to do in an organisation.

<Synopsis>
surreal cloud org permissions [OPTIONS] [ORG]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[ORG]",
            "description": "The organisation, by id or name. Defaults to the resolved one."
        }
    ]}
/>

Also accepts the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags). Column ids are `resource` and `action`.

```bash
surreal cloud org permissions --org acme
```

This is the authorisation model to consult when a command answers 403. [`auth scopes`](/docs/reference/cli/cloud/commands/auth.md#auth-scopes) reports the credential's own scopes, which are a different thing.

## surreal cloud org usage {#org-usage}

Show resource usage across an organisation's instances.

<Synopsis>
surreal cloud org usage [OPTIONS] [ORG]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[ORG]",
            "description": "The organisation, by id or name. Defaults to the resolved one."
        }
    ]}
/>

Also accepts the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags). Column ids are `instance_id`, `metric_type`, `compute_hours`, `disk_used_bytes`, `period_start` and `period_end`, with `instance_type` and `source` under `--wide`.

```bash title="Compute hours per instance, largest first"
surreal cloud org usage --sort compute_hours --reverse
```

For one instance rather than all of them, use [`instance usage`](/docs/reference/cli/cloud/commands/instance.md#instance-usage).

## surreal cloud org spend {#org-spend}

Show an organisation's billed spend.

<Synopsis>
surreal cloud org spend [OPTIONS] [ORG]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[ORG]",
            "description": "The organisation, by id or name. Defaults to the resolved one."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--period",
            "value": "<MM-YYYY>",
            "description": "The billing period, as MM-YYYY. Defaults to the current month."
        }
    ]}
/>

Also accepts the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags). Column ids are `description`, `resource`, `amount`, `units` and `effective_at`, with `instance_id`, `instance_type` and `cloud_usage_units` under `--wide`.

```bash title="Last month's ledger"
surreal cloud org spend --period 07-2026
```

```bash title="The ten largest lines"
surreal cloud org spend --sort amount --reverse --limit 10
```

A total is printed on stderr in text modes, computed before `--limit` is applied, so the total is always the whole bill even when the table is truncated.

**Refusals.** The period is validated locally, exit `2`, and an ISO-ordered value gets a correction rather than a bare rejection:

```text
`2026-03` looks like YYYY-MM. This API wants the month first: use 03-2026.
```

Under `--json`, amounts stay as the API's integers, in millicents, in a field the API spells `amount_millcents`. Formatting them as currency is left to the table view.

## surreal cloud org plans {#org-plans}

List the plans available to an organisation.

<Synopsis>
surreal cloud org plans [OPTIONS] [ORG]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[ORG]",
            "description": "The organisation, by id or name. Defaults to the resolved one."
        }
    ]}
/>

Also accepts the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags). Column ids are `name`, `id`, `regions` and `instance_types`, with `description` under `--wide`.

```bash
surreal cloud org plans
```

This is the organisation-scoped answer, and the one to trust before an [`instance create`](/docs/reference/cli/cloud/commands/instance.md#instance-deploy). The [`catalog`](/docs/reference/cli/cloud/commands/catalog.md) commands list what the platform offers globally, which is always the wider set.

## Related pages

- [`instance` commands](/docs/reference/cli/cloud/commands/instance.md) - the instances an organisation owns
- [`team` commands](/docs/reference/cli/cloud/commands/team.md) - its members
- [`catalog` commands](/docs/reference/cli/cloud/commands/catalog.md) - platform-wide regions, types and versions
- [Global flags](/docs/reference/cli/cloud/global-flags.md) - `--org` and the precedence chain
- [Overview](/docs/reference/cli/cloud.md) - the rest of the reference
- [SurrealDB CLI](/docs/reference/cli/db.md) - for working with the data inside an instance

---

Source: https://surrealdb.com/docs/reference/cli/cloud/commands/team

# surreal cloud team

Reference for surreal cloud team - list and inspect organisation members, invite someone, change a member's role, and remove a membership. Members are matched by username or user id; roles come from org roles.

`surreal cloud team` manages organisation members: the people who already belong. Invitations that have been sent but not accepted live in [`invite`](/docs/reference/cli/cloud/commands/invite.md), and `team list` deliberately does not fold them in - a pending invitation is not a member.

<Synopsis>
surreal cloud team <COMMAND> [OPTIONS]
surreal cloud teams <COMMAND> [OPTIONS]
</Synopsis>

| Verb | Purpose | Alias |
| --- | --- | --- |
| [`list`](#team-list) | List the members of an organisation | `ls` |
| [`get`](#team-get) | Show one member | |
| [`invite`](#team-invite) | Invite someone to an organisation | |
| [`update`](#team-update) | Change a member's role | |
| [`remove`](#team-remove) | End someone's membership of an organisation | `rm` |

Two verbs here break the house grammar on purpose. `remove` is not `delete`, because `delete` invites the reading that the *person* is deleted rather than their membership. `invite` exists because sending one is how a team gains a member and no house verb covers it - and it shares [`invite create`](/docs/reference/cli/cloud/commands/invite.md#invite-create)'s implementation rather than copying it.

The API has no route for a single member, so `get`, `update` and `remove` fetch the member list and match locally, by user id or username, with did-you-mean suggestions when nothing matches. The display name is never a key, because it is neither unique nor stable.

This group declares the scopes `read:cloud` and `write:cloud-organization`, the same pair as [`org`](/docs/reference/cli/cloud/commands/org.md) and [`invite`](/docs/reference/cli/cloud/commands/invite.md), because the API has no separate scope for membership. A personal access token cannot use the mutating verbs: see [Authentication](/docs/reference/cli/cloud/authentication.md#what-a-personal-access-token-cannot-do).

## surreal cloud team list {#team-list}

List the members of an organisation.

<Synopsis>
surreal cloud team list [OPTIONS]
</Synopsis>

This command takes no positional argument. The organisation comes from `--org` and the [precedence chain](/docs/reference/cli/cloud/global-flags.md#the-precedence-chain).

Accepts the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags) and nothing else. Column ids are `username`, `name` and `role`, with `user_id` and `profile_picture` under `--wide`.

```bash
surreal cloud team list
```

```text title="Output"
USERNAME             NAME            ROLE
ana@acme.example     Ana Silva       owner
bo@acme.example      Bo Nakamura     admin
cai@acme.example     Cai Oduya       member
```

```bash title="Owners and admins only"
surreal cloud team list --json | jq -r '.[] | select(.role != "member") | .username'
```

## surreal cloud team get {#team-get}

Show one member.

<Synopsis>
surreal cloud team get [OPTIONS] <MEMBER>
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "<MEMBER>",
            "required": true,
            "description": "The member, by username or user id."
        }
    ]}
/>

This command has no options of its own.

```bash
surreal cloud team get bo@acme.example
```

A reference that does not match any member exits `5`, and lists the near matches it found. The detail view shows the username, role, user id and organisation id.

## surreal cloud team invite {#team-invite}

Invite someone to an organisation.

<Synopsis>
surreal cloud team invite [OPTIONS] --role <ROLE> <EMAIL>
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "<EMAIL>",
            "required": true,
            "description": "The email address to invite."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--role",
            "value": "<ROLE>",
            "required": true,
            "description": "The role to grant. Run `surreal cloud org roles` for the ones this organisation defines."
        }
    ]}
/>

```bash
surreal cloud team invite dee@acme.example --role member
```

The answer is the invitation, not a member - the person appears in [`team list`](#team-list) only once they accept. Track it in the meantime with [`invite list`](/docs/reference/cli/cloud/commands/invite.md#invite-list).

**Refusals**, exit `2`, before any request. The address validator is deliberately shallow - an `@` with something either side and no internal whitespace - because the API is the authority on deliverability:

```text
`dee.acme.example` is not an email address: it has no `@`.
```

The role vocabulary is per organisation, so only an empty value is refused locally:

```text
A role cannot be empty. Run `surreal cloud org roles` to see the ones this organization defines.
```

A role the API rejects as invalid is annotated with a pointer to [`org roles`](/docs/reference/cli/cloud/commands/org.md#org-roles) - but only for that class of error, never for a 403 or a rate limit, where the role is not the problem.

An invitation is not retried automatically, because a repeat would send a second email with a second working code.

## surreal cloud team update {#team-update}

Change a member's role.

<Synopsis>
surreal cloud team update [OPTIONS] --role <ROLE> <MEMBER>
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "<MEMBER>",
            "required": true,
            "description": "The member, by username or user id."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--role",
            "value": "<ROLE>",
            "required": true,
            "description": "The new role. Run `surreal cloud org roles` for the ones this organisation defines."
        }
    ]}
/>

```bash
surreal cloud team update cai@acme.example --role admin
```

The command prints the updated member. The role is compared exactly as written: if the member already holds it, the command prints a note that nothing changed, sends no request and exits `0`.

## surreal cloud team remove {#team-remove}

End someone's membership of an organisation.

<Synopsis>
surreal cloud team remove [OPTIONS] <MEMBER>
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "<MEMBER>",
            "required": true,
            "description": "The member, by username or user id."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--force",
            "description": "Remove without confirming."
        }
    ]}
/>

```bash title="With a confirmation"
surreal cloud team remove cai@acme.example
```

```bash title="From an offboarding script"
surreal cloud team remove cai@acme.example --force --json
```

This ends a membership. It does not delete the person's SurrealDB account, and it does not touch anything they created.

**Refusals.** The confirmation names the person and the organisation, and says that the account is not deleted. Declining prints `Nothing was changed.` and exits `0`. Removing yourself prints a warning first, because only another member can invite you back. In a non-interactive session without `--force` or `--yes`, it exits `2` having sent nothing.

## Related pages

- [`invite` commands](/docs/reference/cli/cloud/commands/invite.md) - pending invitations
- [`org roles`](/docs/reference/cli/cloud/commands/org.md#org-roles) - the roles this organisation defines
- [`org permissions`](/docs/reference/cli/cloud/commands/org.md#org-permissions) - what a role lets you do
- [Overview](/docs/reference/cli/cloud.md) - the rest of the reference
- [SurrealDB CLI](/docs/reference/cli/db.md) - database users, which are a separate concept from organisation members

---

Source: https://surrealdb.com/docs/reference/cli/cloud/commands/token

# surreal cloud token

Reference for surreal cloud token - listing, creating and revoking personal access tokens, and listing the scopes a token can be granted. Covers the login-session requirement, the secret guard, expiry, and the 10-minute revocation lag.

`surreal cloud token` manages personal access tokens: the `sdbp_…` credentials that authenticate CI jobs and automation against the control plane.

<Synopsis>
surreal cloud token <COMMAND> [OPTIONS]
surreal cloud tokens <COMMAND> [OPTIONS]
</Synopsis>

| Verb | Purpose | Alias |
| --- | --- | --- |
| [`list`](#token-list) | List your personal access tokens | `ls` |
| [`create`](#token-create) | Create a personal access token | |
| [`delete`](#token-delete) | Revoke a personal access token | `rm` |
| [`scopes`](#token-scopes) | List the scopes a token can be granted | |

> [!IMPORTANT]
> Every verb in this group needs an interactive login session. A personal access token is refused locally, before any request is sent, and exits `4`. This is deliberate: a leaked token must not be able to mint its own replacements, nor revoke the one an operator would use to clean up after it. The refusal is decided by the credential's kind rather than by its scopes, so no token can be minted carrying something that lifts it.

```text title="What a token gets instead"
Managing personal access tokens needs an interactive login session, so nothing was sent.

Sign in with:  surreal cloud auth login
```

Being signed out is a different answer with a different code: `3`, not `4`. Sign in with [`auth login`](/docs/reference/cli/cloud/commands/auth.md#auth-login).

These tokens are not database credentials. For a token a SurrealDB client can authenticate with, use [`instance token`](/docs/reference/cli/cloud/commands/instance.md#instance-token).

## surreal cloud token list {#token-list}

List your personal access tokens.

<Synopsis>
surreal cloud token list [OPTIONS]
</Synopsis>

This command takes no positional arguments.

Accepts the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags) and nothing else. Column ids are `label`, `id`, `scopes`, `created_at` and `expires_at`, with `user_id` under `--wide`.

```bash
surreal cloud token list
```

```text title="Output"
LABEL              ID                    SCOPES                  CREATED       EXPIRES
build runner       67upif0m8sh1cn1p2c8t  read:cloud              2 months ago  in 4 days
nightly export     6a2k9lqzt4v8bn3m1x5c  read:cloud              3 days ago    never
```

```bash title="Label and expiry of every token"
surreal cloud token list --json | jq -r '.[] | .label + " " + .expires_at'
```

Expired tokens are listed as the API sends them, with a past expiry, because they are the ones to find when a job has stopped authenticating.

Only the label, the id, the scopes and the timestamps are stored - the secret itself exists once, at creation. A token with no expiry shows `never` in the table and carries the `9999-12-31T23:59:59Z` sentinel under `--json`.

## surreal cloud token create {#token-create}

Create a personal access token.

<Synopsis>
surreal cloud token create [OPTIONS] <LABEL>
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "<LABEL>",
            "required": true,
            "description": "What this token is for, shown in every listing. Between 1 and 120 characters."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--scope",
            "value": "<SCOPE>",
            "description": "A scope to grant. Repeat the flag to grant several, up to 32."
        },
        {
            "name": "--expires-in",
            "value": "<DAYS>",
                        "description": "Days until the token expires, between 1 and 365, or the word `never`. When omitted, the API applies its own 30 days."
        },
        {
            "name": "--reveal",
            "description": "Print the secret even when stdout is a terminal."
        }
    ]}
/>

The secret is returned exactly once. Capture it on creation or create another one.

```bash title="Capture the secret into a variable"
TOKEN=$(surreal cloud token create "build runner" --scope read:cloud | tail -1)
```

```bash title="Several scopes, and a shorter life"
surreal cloud token create "nightly export" \
    --scope read:cloud \
    --scope write:cloud-instances \
    --expires-in 90 \
    | tail -1 > /run/secrets/surreal-cloud-token
```

Stdout carries a detail view of the token with the secret removed, then **the bare secret as the last line** - so `| tail -1` is the whole capture recipe. The success line goes to stderr. The follow-up command in the view names the token's id rather than its label, because a label may contain spaces.

> [!WARNING]
> This is the one command in the whole CLI with no `--json` form. Passing `--json` is a usage error, exit `2`, raised before anything is minted.

```text title="Passing --json"
`token create` has no --json form. The secret is returned exactly once, and it can neither go inside
the document nor share stdout with it.
Run it without --json and take the last line:
  surreal cloud token create <label> | tail -1
```

**Refusals**, all exit `2` and all before the request, checked in this order:

- `--json`, as above.
- stdout is a terminal and `--reveal` was not passed:

```text
Refusing to print a secret to a terminal, where it would stay in your scrollback.
Pipe it:  surreal cloud token create <label> | tail -1
Or pass --reveal if you meant to see it.
```

- A label outside 1 to 120 characters, counted after trimming.
- More than 32 scopes, after repeated `--scope` values are collapsed into one: `A token carries at most 32 scopes; 40 were given.`
- An `--expires-in` that is neither a number of days from 1 to 365 nor the word `never`. `never` is matched without regard to case.

**Warnings** before the request, on stderr:

- `--expires-in never` warns, because the API's own schema calls a non-expiring token discouraged.
- No `--scope` at all notes that the token will be permitted nothing, and points at [`token scopes`](#token-scopes).

No command changes a token's scopes or expiry afterwards. To change either, create a new token and [revoke](#token-delete) the old one.

Scopes are not pre-checked against the catalogue. An ungrantable scope answers 403 naming the problem, which is more useful than the bare 400 the API gives for everything else.

## surreal cloud token delete {#token-delete}

Revoke a personal access token.

<Synopsis>
surreal cloud token delete [OPTIONS] <TOKEN>
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "<TOKEN>",
            "required": true,
            "description": "The token, by id or label."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--force",
            "description": "Revoke without confirming."
        }
    ]}
/>

```bash title="By label"
surreal cloud token delete "build runner"
```

```bash title="By id, from a script"
surreal cloud token delete 67upif0m8sh1cn1p2c8t --force --json
```

**Refusals.** The confirmation names the token by label and id, and the lookup lists your tokens first. Declining prints `Nothing was revoked.` and exits `0`. Labels are not unique, so a label shared by two tokens is reported as ambiguous with both ids rather than guessed at. In a non-interactive session without `--force` or `--yes`, it exits `2` having sent nothing.

> [!NOTE]
> Revocation is not instantaneous everywhere. The gateway caches token exchanges for a few minutes, so a revoked token may keep working for up to about ten minutes, and the success message says so. Treat revocation as the start of the process when responding to a leak, and rotate whatever the token could reach.

## surreal cloud token scopes {#token-scopes}

List the scopes a token can be granted.

<Synopsis>
surreal cloud token scopes [OPTIONS]
</Synopsis>

This command takes no positional arguments.

Accepts the [list presentation flags](/docs/reference/cli/cloud/output-and-exit-codes.md#list-presentation-flags) and nothing else. Column ids are `id`, `category` and `label`, with `description` under `--wide`.

```bash
surreal cloud token scopes
```

```bash title="Just the ids, to paste into a create"
surreal cloud token scopes --columns id --no-header
```

This lists what a token *can* be granted. [`auth scopes`](/docs/reference/cli/cloud/commands/auth.md#auth-scopes) lists what the credential in hand actually carries.

## Related pages

- [Authentication](/docs/reference/cli/cloud/authentication.md#personal-access-tokens) - how a token is supplied, and what it cannot do
- [`auth` commands](/docs/reference/cli/cloud/commands/auth.md) - signing in with a login session
- [`instance token`](/docs/reference/cli/cloud/commands/instance.md#instance-token) - database tokens, which are a different credential
- [Output and exit codes](/docs/reference/cli/cloud/output-and-exit-codes.md#the-secret-guard) - the secret guard
- [Overview](/docs/reference/cli/cloud.md) - the rest of the reference
- [SurrealDB CLI](/docs/reference/cli/db.md) - for working with the data inside an instance

---

Source: https://surrealdb.com/docs/reference/cli/cloud/global-flags

# surreal cloud global flags

The sixteen flags every surreal cloud command accepts, the environment variable behind each one, the precedence chain that resolves them, the duration syntax, and the deprecated SURREALCTL_ aliases.

Sixteen flags are accepted by every `surreal cloud` command. They may appear anywhere after `cloud` - before the group, between the group and the verb, or after the verb - so all three of these are the same invocation:

```bash
surreal cloud --json instance list
surreal cloud instance --json list
surreal cloud instance list --json
```

`--help` groups them under four headings, and this page keeps those groups.

## Context

<OptionsTable
    title="Context flags"
    options={[
        {
            "name": "--profile",
            "value": "<PROFILE>",
            "default": "default",
            "env": "SURREAL_CLOUD_PROFILE",
            "description": "The configuration profile to use. A profile bundles a credential, an API base URL and a set of configuration values. When the flag is absent, the file's `active_profile` applies, then `default`."
        },
        {
            "name": "--config",
            "value": "<PATH>",
            "env": "SURREAL_CLOUD_CONFIG",
            "description": "Path to the configuration file, or to the directory that holds it. The directory also becomes the credential directory."
        },
        {
            "name": "--org",
            "value": "<ORG>",
            "env": "SURREAL_CLOUD_ORG",
            "description": "The organisation to operate on, by id or name."
        }
    ]}
/>

## Authentication

<OptionsTable
    title="Authentication flags"
    options={[
        {
            "name": "--token",
            "value": "<TOKEN>",
            "env": "SURREAL_CLOUD_TOKEN",
            "description": "Personal access token to authenticate with. Conflicts with `--token-file`, and is never persisted."
        },
        {
            "name": "--token-file",
            "value": "<PATH>",
            "env": "SURREAL_CLOUD_TOKEN_FILE",
            "description": "Read the personal access token from a file, or `-` for standard input. Conflicts with `--token`."
        },
        {
            "name": "--api",
            "value": "<URL>",
            "default": "https://api.surrealdb.com",
            "env": "SURREAL_CLOUD_API",
            "description": "Base URL of the SurrealDB API. Must be absolute, `http` or `https`, name a host, and carry no path."
        }
    ]}
/>

`--token` has no short form on purpose: `-t` reads as `--type` on the instance commands, and a credential belongs in the environment or a file rather than in `argv`. See [Authentication](/docs/reference/cli/cloud/authentication.md#personal-access-tokens).

A base URL with a path of its own is refused as a usage error, because the client appends its own routes and the path would be silently prepended to every one of them:

```text
Ensure the API base has no path, such as https://api.surrealdb.com
```

## Output

<OptionsTable
    title="Output flags"
    options={[
        {
            "name": "--json",
            "short": "-j",
            "env": "SURREAL_CLOUD_JSON",
            "description": "Emit machine-readable JSON on stdout. See the output contract for what is guaranteed."
        },
        {
            "name": "--plain",
            "env": "SURREAL_CLOUD_PLAIN",
            "description": "Disable tables, spinners and relative times. Output becomes width-independent."
        },
        {
            "name": "--color",
            "value": "<WHEN>",
            "default": "auto",
            "description": "When to use colour in output: `auto`, `always` or `never`."
        },
        {
            "name": "--quiet",
            "short": "-q",
            "description": "Suppress progress and informational output. The data payload on stdout is unaffected."
        },
        {
            "name": "--yes",
            "short": "-y",
            "env": "SURREAL_CLOUD_YES",
            "description": "Assume yes for every confirmation in this invocation."
        },
        {
            "name": "--no-input",
            "env": "SURREAL_CLOUD_NO_INPUT",
            "description": "Never prompt for input; fail instead. Also spelled `--non-interactive`."
        }
    ]}
/>

`--color` is the one flag with no `SURREAL_CLOUD_*` variable. Colour also honours the `NO_COLOR`, `FORCE_COLOR` and `CLICOLOR_FORCE` conventions.

`--json` and `--plain` are independent axes: `--json` chooses the encoding, `--plain` the decoration. Passing both is accepted and `--plain` is ignored, because CI scripts pass both and erroring on that is hostile.

## Logging

`--help` files the request timeout and the retry budget under this heading alongside the log level.

<OptionsTable
    title="Logging flags"
    options={[
        {
            "name": "--log",
            "value": "<FILTER>",
            "default": "warn",
            "env": "SURREAL_CLOUD_LOG",
            "description": "The logging level, or a full set of filter directives."
        },
        {
            "name": "--debug",
            "env": "SURREAL_CLOUD_DEBUG",
            "description": "Log every API request and response to stderr, with the credential reduced to a digest. Also reports which precedence layer supplied each resolved value."
        },
        {
            "name": "--timeout",
            "value": "<DURATION>",
            "default": "30s",
            "env": "SURREAL_CLOUD_TIMEOUT",
            "description": "Maximum time to wait for a single API request."
        },
        {
            "name": "--retries",
            "value": "<N>",
            "default": "3",
            "env": "SURREAL_CLOUD_RETRIES",
            "description": "How many times to retry a failed request. The number of attempts is one more than this."
        }
    ]}
/>

The effective per-request timeout is never shorter than 21 seconds, because the API's own upstream timeout is 20 seconds and giving up sooner abandons requests that are still being worked on.

## The precedence chain

Every value that can come from more than one place is resolved once, before the command runs, in this order - highest first:

1. A command-line flag
2. An environment variable
3. The profile in `config.toml`
4. The persisted context, written by [`org use`](/docs/reference/cli/cloud/commands/org.md#org-use)
5. Your account's default organisation, as the API reports it
6. The only candidate, when exactly one exists
7. An interactive picker, when a person is present
8. An error naming the flag that would have settled it

Layers 5 to 7 apply to the organisation specifically. Exactly one candidate is not a choice, so it is used silently; several candidates in a non-interactive session is an error rather than a guess:

```text
Several organizations are available and none was chosen.
Pass --org, set SURREAL_CLOUD_ORG, or run `surreal cloud org use <name>`.

Available:
  acme
  contoso
```

`--debug` prints which layer won each value, and [`context show`](/docs/reference/cli/cloud/commands/context.md#context-show) reports it as part of its answer:

| Layer | Reported as |
| --- | --- |
| Command-line flag | `command-line flag` |
| Environment variable | `environment variable` |
| Profile in `config.toml` | `profile in config.toml` |
| Persisted context | `persisted context (org use)` |
| Account default | `your account's default organization` |
| Single candidate | `the only candidate` |
| Interactive picker | `interactive choice` |

An organisation reference that already looks like an id is used with no lookup at all. A name or slug costs one request to resolve, and an unrecognised one is answered with did-you-mean candidates.

> [!NOTE]
> A configured `api` value applies only when `--api` was not given. Because the flag has a default, the CLI cannot distinguish "absent" from "passed exactly the default", so passing `--api https://api.surrealdb.com` explicitly leaves the configured value unused.

## Duration syntax

`--timeout` and `--wait-timeout` accept the same syntax. A bare number means seconds.

| Suffix | Unit |
| --- | --- |
| *(none)*, `s`, `sec`, `secs`, `second`, `seconds` | Seconds |
| `ms` | Milliseconds |
| `m`, `min`, `mins`, `minute`, `minutes` | Minutes |
| `h`, `hr`, `hrs`, `hour`, `hours` | Hours |
| `d`, `day`, `days` | Days |

```bash
surreal cloud --timeout 90 instance list
surreal cloud instance create api --type shared-1 --region aws-euw1 --wait-timeout 5m
```

## The `SURREAL_CLOUD_` prefix

Every environment variable this component reads is prefixed `SURREAL_CLOUD_`, and never plain `SURREAL_`.

Reusing the database's prefix would be harmful. `SURREAL_TOKEN` in a shell means a *database* JWT for one instance; reading it as a control-plane credential would send database tokens to `api.surrealdb.com` on every command.

The only `SURREAL_*` variables involved are ones `surreal cloud` *sets* for the database process during the handoff in [`instance sql`, `import` and `export`](/docs/reference/cli/cloud/commands/instance.md#instance-sql): `SURREAL_TOKEN`, and `SURREAL_NAMESPACE` and `SURREAL_DATABASE` when given.

### Variables that mirror a flag

| Variable | Flag |
| --- | --- |
| `SURREAL_CLOUD_PROFILE` | `--profile` |
| `SURREAL_CLOUD_CONFIG` | `--config` |
| `SURREAL_CLOUD_ORG` | `--org` |
| `SURREAL_CLOUD_TOKEN` | `--token` |
| `SURREAL_CLOUD_TOKEN_FILE` | `--token-file` |
| `SURREAL_CLOUD_API` | `--api` |
| `SURREAL_CLOUD_JSON` | `--json` |
| `SURREAL_CLOUD_PLAIN` | `--plain` |
| `SURREAL_CLOUD_YES` | `--yes` |
| `SURREAL_CLOUD_NO_INPUT` | `--no-input` |
| `SURREAL_CLOUD_LOG` | `--log` |
| `SURREAL_CLOUD_DEBUG` | `--debug` |
| `SURREAL_CLOUD_TIMEOUT` | `--timeout` |
| `SURREAL_CLOUD_RETRIES` | `--retries` |

### Variables with no flag

| Variable | Effect |
| --- | --- |
| `SURREAL_CLOUD_CONFIG_DIR` | Overrides the configuration and credential directory |
| `SURREAL_CLOUD_AGENT` | `1` or `0`, forcing agent detection on or off |
| `SURREAL_CLOUD_SESSION_TOKEN` | Supplies an already-minted Cloud session token, for support reproduction |
| `SURREAL_CLOUD_AUTH_CLIENT_ID` | Overrides the OAuth client id, for a non-production tenant |
| `SURREAL_CLOUD_AUTH_ISSUER` | Overrides the OAuth issuer, for a non-production tenant |

### Launcher variables

`surreal cloud` runs under the launcher, which sets `SURREAL_CLI_LAUNCHER` to its own path so that the handoff commands can reach the database through it. `SURREAL_CLI_HOME` (default `~/.surrealdb`) moves the directory that holds both the launcher's files and the `cloud` configuration directory, and `SURREAL_CLI_OFFLINE=1` forbids all network use by the launcher. The [launcher reference](/docs/reference/cli/launcher.md) documents these.

### Conventions it honours

| Variable | Effect |
| --- | --- |
| `NO_COLOR` | Disables colour |
| `FORCE_COLOR`, `CLICOLOR_FORCE` | Enables colour, even when piped |
| `CI` | Selects plain, structural output. `CI=false`, `CI=0` and an empty value all mean *not* CI |
| `TERM=dumb` | Selects plain output with no colour |
| `SSH_CONNECTION`, `SSH_TTY` | Skips the browser login flow |
| `HOME`, `SURREAL_CLI_HOME` | Locate the configuration directory |
| `HTTPS_PROXY`, `NO_PROXY` | Proxy the API connection |
| `VISUAL`, `EDITOR` | Used by [`config edit`](/docs/reference/cli/cloud/commands/config.md#config-edit), in that order |

## Deprecated SURREALCTL_ aliases

Before it became `surreal cloud`, the tool was `surrealctl` and every variable above carried the prefix `SURREALCTL_` instead. The old names keep working, so a CI job that exports `SURREALCTL_TOKEN` does not break when it picks up the new release. The old name is consulted only when the new one is unset, and a run that uses any of them prints one warning on stderr listing each old name with its replacement:

```text
SURREALCTL_* variables are deprecated. Rename SURREALCTL_TOKEN to SURREAL_CLOUD_TOKEN.
```

Two variables are not a plain prefix swap. `SURREALCTL_CLOUD_TOKEN` is now `SURREAL_CLOUD_SESSION_TOKEN`, because `SURREAL_CLOUD_CLOUD_TOKEN` would read as a typo. `SURREALCTL_SURREAL_BINARY` and the `surreal_binary` configuration key no longer exist, because the database is reached only through the launcher. Variables under the old prefix that never had a meaning are not mentioned.

## Configuration file equivalents

Four values can be persisted per profile with [`config set`](/docs/reference/cli/cloud/commands/config.md#config-set). Each is outranked by its environment variable, and `config set` warns when that variable is exported.

| Key | Environment variable |
| --- | --- |
| `org` | `SURREAL_CLOUD_ORG` |
| `api` | `SURREAL_CLOUD_API` |
| `json` | `SURREAL_CLOUD_JSON` |
| `plain` | `SURREAL_CLOUD_PLAIN` |

## Related pages

- [Output and exit codes](/docs/reference/cli/cloud/output-and-exit-codes.md) - what `--json`, `--plain` and `--quiet` actually produce
- [`config` commands](/docs/reference/cli/cloud/commands/config.md) - reading and writing the configuration file
- [`context` commands](/docs/reference/cli/cloud/commands/context.md) - switching profiles
- [surreal cloud reference](/docs/reference/cli/cloud.md) - the rest of the reference
- [Database environment variables](/docs/reference/cli/db/environment-variables.md) - the `SURREAL_*` set this component never reads

---

Source: https://surrealdb.com/docs/reference/cli/cloud/long-running-operations

# surreal cloud long-running operations

How surreal cloud waits for an instance to settle - the wait flags, which commands wait by default, the polling schedule, rate-limit handling, and exit code 10.

Creating, resizing, pausing, resuming and deleting an instance are asynchronous. The API accepts the request, answers `202`, and the resource changes state over the following seconds or minutes.

`surreal cloud` waits for that to finish by default, so the next line of a script can connect to the instance it just created.

## The wait flags

Five commands carry all three flags: [`instance create`](/docs/reference/cli/cloud/commands/instance.md#instance-deploy), [`instance update`](/docs/reference/cli/cloud/commands/instance.md#instance-update), [`instance delete`](/docs/reference/cli/cloud/commands/instance.md#instance-delete), [`instance pause`](/docs/reference/cli/cloud/commands/instance.md#instance-pause) and [`instance resume`](/docs/reference/cli/cloud/commands/instance.md#instance-resume).

<OptionsTable
    title="Wait flags"
    options={[
        {
            "name": "--wait",
            "description": "Wait for the operation to finish. On by default, so this flag is only needed to override an earlier `--no-wait`."
        },
        {
            "name": "--no-wait",
            "description": "Return as soon as the API accepts the request."
        },
        {
            "name": "--wait-timeout",
            "value": "<DURATION>",
            "default": "15m",
            "description": "How long to wait before giving up. Accepts the standard duration syntax, such as `90s` or `5m`."
        }
    ]}
/>

`--wait` and `--no-wait` override each other, so the last one on the command line wins. That makes shell aliases and wrapper scripts composable: appending `--wait` undoes an alias that sets `--no-wait`, without having to know what the alias contained.

Waiting is on in **every** output mode - rich, plain, CI and `--json` alike. A terminal-dependent default would break the obvious script and would mean `CI` changed semantics rather than presentation.

The fifteen-minute default is chosen so that a normal operation never reaches it and a stuck one does not hold a CI job for an hour: a shared-tier instance is ready in about ninety seconds, and a version upgrade on a large instance is the slow case.

Two commands that might look asynchronous are not: [`instance backup create`](/docs/reference/cli/cloud/commands/instance.md#instance-backup-create) carries no wait flags, and [`instance watch`](/docs/reference/cli/cloud/commands/instance.md#instance-watch) carries `--wait-timeout` only, because a watch is nothing but a wait.

```bash title="Create and block until ready - the default"
surreal cloud instance create api --type shared-1 --region aws-euw1
```

```bash title="Fire and forget, then pick the wait up later"
surreal cloud instance create api --type shared-1 --region aws-euw1 --no-wait
surreal cloud instance watch api
```

```bash title="Give up sooner than fifteen minutes"
surreal cloud instance update production --type production-2 --wait-timeout 5m
```

## How the wait works

The API has no job resources, no `Location` header and no idempotency key. A long operation is a `202` plus the mutated resource, so the only way to know it finished is to fetch the resource again. `surreal cloud` therefore polls the instance until it reaches the state the command asked for.

Polling backs off:

| Elapsed | Interval |
| --- | --- |
| Under 30 seconds | 2 seconds |
| 30 seconds to 2 minutes | 5 seconds |
| Over 2 minutes | 10 seconds |

Each interval carries jitter between 0.8× and 1.2× so that concurrent waiters do not convoy, and the result is capped at 15 seconds.

In plain and CI output, one line is printed per state change plus a heartbeat every 60 seconds, so a log stays readable and a stalled wait is still visibly alive. Under `--json`, transitions are [newline-delimited JSON on stderr](/docs/reference/cli/cloud/output-and-exit-codes.md#ndjson-streams) and the final document goes to stdout.

The credential is re-checked before every poll, because a long wait can outlive a Cloud session.

### Rate limiting during a wait

A `429` honours the `Retry-After` header - falling back to five seconds when the header is absent - and extends the deadline by the time it slept, so being throttled cannot itself cause a timeout.

That credit is capped at a cumulative two minutes. Without a ceiling, a poll that answered `429` every time would extend the deadline by exactly the time it slept and loop for ever, and a hang looks like a slow API rather than a bug. Two minutes absorbs any real throttle while guaranteeing the loop reaches its deadline.

### Unrecognised states

A state this build has never seen keeps the wait going and is displayed verbatim. Aborting on one would turn an addition to Cloud's vocabulary into an outage here.

What each state means depends on what the command asked for:

| Waiting for | Ready | Paused | Failed | Gone |
| --- | --- | --- | --- | --- |
| Ready | Success | Settled elsewhere | Failed | Vanished |
| Paused | Settled elsewhere | Success | Failed | Vanished |
| Deleted | Keep waiting | Keep waiting | Failed | Success |

*Settled elsewhere* is its own outcome because the instance reached a stable state the caller did not ask for, and polling on would burn the whole timeout to reach the same conclusion.

For a delete, a `404` while polling is the success condition - there is nothing left to fetch.

## Outcomes and exit codes

| Outcome | Exit code | What happened |
| --- | --- | --- |
| Succeeded | `0` | The instance reached the state the command asked for |
| Timed out | `10` | The wait gave up, and the operation is still running |
| Failed | `6` | The instance entered a failed state |
| Settled elsewhere | `6` | The instance settled in a stable state the command did not ask for |
| Vanished | `5` | The instance was removed while the command was waiting |

Each outcome closes with one sentence naming how long it took:

```text
The instance is ready after 1m 31s.
The instance entered `failed` after 2m 14s.
The instance settled in `paused` after 45s.
The instance was removed while waiting, after 12s.
Gave up after 15m; the instance is still `provisioning` and still working.
```

Exit code `10` deserves its own handling. It means the wait gave up, **not** that the operation failed:

```text
Timed out after 15m waiting for the instance to become ready.
It is still `provisioning`, and the operation is still running server-side.
```

The right response is usually to poll again on the next run rather than to roll anything back:

```bash title="Treat a timeout as 'check again later'"
surreal cloud instance create api --type shared-1 --region aws-euw1 --wait-timeout 3m
case $? in
    0)  echo "ready" ;;
    10) echo "still provisioning; the next run will pick it up" ;;
    *)  exit 1 ;;
esac
```

## Interrupting a wait

Interrupting a wait does not stop the operation - the CLI is only polling, and the change carries on server-side. Pick the state back up with [`instance get`](/docs/reference/cli/cloud/commands/instance.md#instance-get) for a snapshot, or [`instance watch`](/docs/reference/cli/cloud/commands/instance.md#instance-watch) to resume waiting.

```bash
surreal cloud instance watch api --until ready
```

The same applies to a wait that was never started. `--no-wait` and a later `instance watch` are equivalent to waiting inline, which is what makes a two-stage CI pipeline possible: provision in one job, block in the next.

> [!WARNING]
> `instance create` has no idempotency key, because the API's create route accepts none. A retried create is a second instance and a second bill. If a create times out, run [`instance list`](/docs/reference/cli/cloud/commands/instance.md#instance-list) before running it again.

## Related pages

- [`instance` commands](/docs/reference/cli/cloud/commands/instance.md) - every command that waits
- [Output and exit codes](/docs/reference/cli/cloud/output-and-exit-codes.md) - the NDJSON progress stream and the full exit-code table
- [Global flags](/docs/reference/cli/cloud/global-flags.md) - `--timeout` and `--retries`, which govern a single request rather than a wait
- [surreal cloud reference](/docs/reference/cli/cloud.md) - the rest of the reference
- [`surreal db sql`](/docs/reference/cli/db/commands/sql.md) - for connecting to the instance once it is ready

---

Source: https://surrealdb.com/docs/reference/cli/cloud/output-and-exit-codes

# surreal cloud output and exit codes

The surreal cloud --json contract, the stdout and stderr split, NDJSON streams, the shared list presentation flags, the secret and confirmation guards, and every exit code.

`surreal cloud` is driven as often by pipelines and agents as by people. This page is the contract those callers can rely on: which stream carries what, what `--json` guarantees, and what each exit code means.

The rule is that **the exit codes are a contract, and stderr text is not.**

## The stream split

- **stdout** carries the command's data payload, and nothing else, ever.
- **stderr** carries progress, prompts, warnings, hints, errors and debug output.

So `| jq` always works, `--json > out.json` can still prompt you, and a failed command leaves stdout empty. Exactly one document is written to stdout per invocation.

A broken downstream pipe exits `0` silently, so `surreal cloud instance list | head -3` behaves as you expect.

```bash title="Capture the data, keep the diagnostics"
surreal cloud instance list --json > instances.json
```

## `--json`

**On success**, stdout carries the bare wire payload, pretty-printed with a two-space indent and no envelope. An envelope would force `.data[]` on every consumer for ever, and the stream split plus the exit code already answer *did it work*.

```bash
surreal cloud instance get production --json
```

```json title="Output"
{
  "id": "67upif0m8sh1cn1p2c8t",
  "name": "production",
  "slug": "production-6xk2",
  "state": "ready",
  "type": "shared-1",
  "region": "aws-euw1",
  "version": "3.2.4",
  "host": "production-6xk2.aws-euw1.surreal.cloud"
}
```

Because the payload is the API's own body rather than a struct assembled here, a field the API adds this morning appears in `--json` this afternoon with no new release.

**On failure**, stdout gets zero bytes and an enveloped object goes to stderr:

```json title="stderr"
{
  "kind": "conflict",
  "message": "could not pause `api`: Instance is not in a valid state",
  "status": 409,
  "code": null,
  "request_id": "01J8XYZ2QK7M4N0P8R9S1T2V3W",
  "hint": "The instance is busy with another change. Wait for it to settle, then try again.",
  "command": "surreal cloud instance get api",
  "docs": null,
  "retry_after_secs": null,
  "exit_code": 6
}
```

Every key is always present, with an explicit `null` rather than being omitted, so a consumer can index without checking first.

| Key | Type | Meaning |
| --- | --- | --- |
| `kind` | string | The error class. Never `null` |
| `message` | string | The full message chain, including the layer naming which command failed |
| `status` | integer or `null` | The HTTP status, when there was one |
| `code` | string or `null` | The API's own error code, when it sent a non-empty one |
| `request_id` | string or `null` | The request identifier to quote when reporting a problem |
| `hint` | string or `null` | What to do about it |
| `command` | string or `null` | A command to run next |
| `docs` | string or `null` | A documentation link, for authentication and rate-limit failures only |
| `retry_after_secs` | integer or `null` | From the `Retry-After` header |
| `exit_code` | integer | Matches the process exit code exactly |

One further key appears conditionally: `candidates`, an array of strings, when a resource reference could not be resolved and there were near matches to suggest.

`docs` is populated only where a link explains something. Authentication and permission failures link to the authentication documentation; rate limits link to the rate-limit documentation; everything else is `null`, because a link to a generic index in place of an explanation is worse than no link.

### The `kind` vocabulary

Eleven values, and the set is closed:

| `kind` | Exit code | Meaning |
| --- | --- | --- |
| `auth` | `3` | Not authenticated, or the credential could not be renewed |
| `forbidden` | `4` | Authenticated but not allowed |
| `not_found` | `5` | The named resource does not exist |
| `conflict` | `6` | Not in a state that allows this, or a precondition failed |
| `invalid` | `7` | The API rejected the request as invalid |
| `rate_limited` | `8` | Rate limited after the retry budget was spent |
| `upstream` | `9` | The API's upstream failed |
| `network` | `9` | The API could not be reached |
| `not_available` | `9` | The feature is not enabled for this deployment |
| `wait_timeout` | `10` | A wait gave up; the operation is still running |
| `unknown` | `1` | Unclassified |

`not_available` is HTTP 501, and it means nothing is broken - the feature is simply not enabled on this deployment.

### What `--json` guarantees

- **Additions are non-breaking and expected.** Renames, removals and type changes are breaking.
- **Output is byte-identical** regardless of `CI`, `NO_COLOR`, `TERM`, terminal width, or `--color always`. `--json` is never coloured.
- **Money stays in integer minor units** - cents, or millicents where the API uses them. Formatting happens in the view layer only.
- **Timestamps stay verbatim RFC 3339**, including the `9999-12-31T23:59:59Z` sentinel that means "never expires".
- **Presentation flags never reach it.** `--columns`, `--wide`, `--sort`, `--reverse` and `--limit` arrange a table; `--json` always emits the complete payload.
- **Relative times never appear.** "3 days ago" is a rendering, not data.

Two commands are documented exceptions. [`token create`](/docs/reference/cli/cloud/commands/token.md#token-create) has no `--json` form at all, because the secret is returned exactly once and can neither go inside the document nor share stdout with it. [`completion`](/docs/reference/cli/cloud/commands/misc.md#completion) emits a shell script rather than a view, so `--json` does not wrap it.

## Output shapes

| Shape | Produced by | Under `--json` |
| --- | --- | --- |
| **Table** | Every `list` verb, every `catalog` command, `org roles`/`permissions`/`usage`/`spend`/`plans`, `instance jwks`/`metrics`/`logs`/`usage`, `instance backup list`, `token scopes`, `auth scopes`, `config list`, `context list`, `status` | A JSON array |
| **Detail** | Every `get`, `create`, `update`, `delete`, `archive` and `use`, plus `whoami`, `version`, `context show`, `open`, `instance estimate`, `instance capabilities get`/`set`, `instance backup create`, `instance backup policy get`/`set` | The wire body |
| **Scalar** | `instance endpoint`, `config get`, `config path` | The single value |
| **Secret** | `instance token`, `token create` | A one-field document, except `token create`, which refuses `--json` |
| **Composite** | `instance status` - a phase plus a snapshot table, as one document | The whole status body |
| **NDJSON on stdout** | `instance watch`, `instance logs --follow` | One compact object per line |
| **Raw bytes** | `completion`, `api --raw` | Written straight through |

A scalar is the value alone plus a newline, byte-identical in every text mode, with no label and no styling - so `$(…)` captures exactly the value:

```bash
ENDPOINT=$(surreal cloud instance endpoint production)
```

`config get` on an unset key writes zero bytes, so `[ -z "$(surreal cloud config get org)" ]` and `wc -l` agree with each other.

## NDJSON streams

A command that waits reports its progress as newline-delimited JSON on **stderr**, then writes one final document to stdout. The split is what keeps "exactly one document on stdout" true for a command that reports progress.

```json title="stderr, during instance create --json"
{"event":"started","resource":"instance","goal":"ready","state":"pending"}
{"event":"transition","resource":"instance","from":"pending","to":"provisioning","elapsed_secs":4}
{"event":"heartbeat","resource":"instance","state":"provisioning","elapsed_secs":64}
{"event":"finished","resource":"instance","outcome":"succeeded","state":"ready","elapsed_secs":91,"succeeded":true}
```

Two more event shapes appear when the API pushes back: `poll_failed`, carrying a `detail`, and `throttled`, carrying `retry_after_secs`.

[`instance watch`](/docs/reference/cli/cloud/commands/instance.md#instance-watch) inverts the split and writes the same stream to **stdout**, because a watch is a stream by nature and there is no single final object to be the answer. [`instance logs --follow`](/docs/reference/cli/cloud/commands/instance.md#instance-logs) does the same with log lines. Both say so in their own `--help`.

## List presentation flags {#list-presentation-flags}

Every list-shaped command accepts the same six flags.

<OptionsTable
    title="Presentation flags"
    options={[
        {
            "name": "--columns",
            "value": "<IDS>",
            "description": "Show only these columns, comma-separated. Conflicts with `--wide`."
        },
        {
            "name": "--wide",
            "description": "Show every column, including the ones hidden by default."
        },
        {
            "name": "--no-header",
            "description": "Omit the header row."
        },
        {
            "name": "--sort",
            "value": "<ID>",
            "description": "Sort by this column. An unrecognised id is a usage error listing the valid ones."
        },
        {
            "name": "--reverse",
            "description": "Reverse the sort order."
        },
        {
            "name": "--limit",
            "value": "<N>",
            "description": "Show at most this many rows."
        }
    ]}
/>

Sorting, reversing and limiting are always applied on this side, because the API has no pagination, no sort parameter and no search. They are applied in one order - sort, then reverse, then limit - and sorting compares the *rendered* value of each cell, so the display order matches the sort order.

`--wide` reveals the columns a table hides by default. `--columns` takes the column ids, which are what `--sort` also accepts. Run a command with `--wide --no-header` to see everything a row carries.

```bash title="Just the names and states, longest-lived first"
surreal cloud instance list --columns name,state,version --sort name
```

```bash title="Every column, for a spreadsheet"
surreal cloud instance list --wide --plain > instances.tsv
```

An unknown column id is a usage error, exit `2`. It is caught as the rows are arranged for display rather than before the request, so the list has already been fetched by the time it is reported. The message names every column the row carries, including the ones only `--wide` shows:

```text
Unknown sort column `naem`. Available columns: name, state, type, version, region, compute_units, storage, id, slug, host, access_type, organization_id
```

None of these flags reach `--json`, which always emits the complete payload. A `--limit 1` must not silently truncate a pipeline.

> [!NOTE]
> [`auth scopes`](/docs/reference/cli/cloud/commands/auth.md#auth-scopes) is the one list-shaped command that carries only `--no-header`. It has no `--columns`, `--wide`, `--sort`, `--reverse` or `--limit`.

## Output modes

`--json` chooses the encoding; `--plain` chooses the decoration. The encoding is resolved per stream, so `surreal cloud instance list | less` gives plain data on stdout while a terminal on stderr keeps its spinner.

Encoding is decided by the first match:

1. `--json` or `SURREAL_CLOUD_JSON`
2. `--plain` or `SURREAL_CLOUD_PLAIN`
3. An agent environment is detected
4. `CI` is set to something other than `false`, `0` or empty
5. `TERM=dumb`
6. The stream is not a terminal
7. Otherwise, rich output

Colour is decided independently, and deliberately does not depend on `--plain` or `CI` - GitHub Actions sets `CI`, is not a terminal, and renders ANSI perfectly. `--color always` colours piped output; `--json` is never coloured, even then.

Plain output is space-padded to its content width, with uppercase headers, no borders and no truncation, and is byte-identical at any terminal width. `CI=1` is byte-for-byte equivalent to `--plain`.

What `CI` changes is structure, interactivity and progress granularity. What it must never change: colour, `--json` bytes, exit codes, which requests are made, timeouts, poll intervals, `--wait` defaults, or confirmation semantics.

## The secret guard

Every command that mints a credential refuses to write it to a terminal, where it would stay in your scrollback. The check happens **before** the request, so a forgotten `--reveal` never costs a credential nobody can recover.

```text
Refusing to print a secret to a terminal, where it would stay in your scrollback.
Pipe the output, or pass --reveal if you meant to see it.
```

That is exit `2`. Either pipe the output, or pass `--reveal` to say you meant it.

```bash title="Pipe it"
surreal cloud instance token production | pbcopy
```

```bash title="Or ask for it on screen"
surreal cloud instance token production --reveal
```

## The confirmation guard

A destructive command has exactly three outcomes:

- `--yes` (or the command's own `--force`) is set - it proceeds without asking.
- A person is present - it prompts on stderr, defaulting to **no**.
- Neither - it is an error, exit `2`, with nothing sent:

```text
Refusing to delete `production` without confirmation in a non-interactive session.
Pass --yes to confirm, or run this from a terminal.
```

Declining a prompt is not a failure. The command says what it did not do - `Nothing was deleted.` - and exits `0`.

## Exit codes

Codes are never reused, and none exceeds 125 except for the signal convention.

| Code | Meaning |
| --- | --- |
| `0` | The command did what was asked. Includes an empty list |
| `1` | A failure that does not fit any category below |
| `2` | Bad invocation: a usage error, client-side validation, a required value missing in a non-interactive session, or a destructive command that could not confirm |
| `3` | Not authenticated, or the credential expired and could not be renewed |
| `4` | Authenticated but not allowed: insufficient scopes, insufficient role, or a credential kind this operation refuses |
| `5` | The named resource does not exist |
| `6` | The resource is not in a state that allows this, or a precondition failed |
| `7` | The API rejected the request as invalid |
| `8` | Rate limited, after the retry budget was spent |
| `9` | The API or its upstream is unreachable, the feature is not available, or this client is too old |
| `10` | A wait gave up. **The operation is still running** |
| `11` | The credential store could not be read or written |
| `12` | A component the command needs is not installed and was not fetched: offline, nobody present to agree, or the offer declined. The message names the command that installs it |
| `30` | An interactive login flow did not complete |
| `130` | Interrupted |

`0`, `1` and `2` keep their conventional meanings, so `if ! surreal cloud …` behaves exactly as it does with the [database commands](/docs/reference/cli/db.md), and usage errors exit `2` as every other command-line tool does. Everything above `2` is additive.

`12` comes from the launcher rather than from the API. It is what `surreal cloud` itself returns when it is not installed and the session is unattended, and what `instance sql`, `instance import` and `instance export` return when the database is missing. In both cases the message names the install command, and nothing is downloaded silently. `SURREAL_CLI_OFFLINE=1` forbids all network use, so it always produces `12` for a missing component.

`10` has its own code because *still running* is a different answer from *failed*, and a pipeline may reasonably poll again rather than roll back. See [Long-running operations](/docs/reference/cli/cloud/long-running-operations.md).

```bash title="Branch on the outcome"
if surreal cloud instance create api --type shared-1 --region aws-euw1 --json > instance.json; then
    echo "ready: $(jq -r .name instance.json)"
else
    case $? in
        6)  echo "an instance called api already exists" ;;
        8)  echo "rate limited; requeue this job" ;;
        10) echo "still provisioning; poll again next run" ;;
        *)  echo "failed" ; exit 1 ;;
    esac
fi
```

> [!IMPORTANT]
> [`status`](/docs/reference/cli/cloud/commands/misc.md#status) is the single deliberate exception to "stdout is empty on failure". Its table *is* the diagnosis, so it prints even when the command exits non-zero. The exit code comes from the first fatal check - `3` for a credential problem, `9` for an unreachable API.

## Related pages

- [Global flags](/docs/reference/cli/cloud/global-flags.md) - `--json`, `--plain`, `--quiet`, `--color`, `--yes`
- [Long-running operations](/docs/reference/cli/cloud/long-running-operations.md) - waiting, polling and exit code `10`
- [surreal cloud reference](/docs/reference/cli/cloud.md) - the rest of the reference

---

Source: https://surrealdb.com/docs/reference/cli/db

# surreal db

The database component of the surreal CLI, run as surreal db. It can be used to export a dataset as SurrealQL from a local or remote SurrealDB database, import SurrealQL data into a local or remote database, and start a single SurrealDB instance or distributed cluster.

`surreal db` is the database component of the `surreal` CLI. It starts a server, opens an interactive SurrealQL shell, moves data in and out of a database, and reports on the version and readiness of an instance.

<Synopsis>
surreal db [OPTIONS] <COMMAND>
</Synopsis>

> [!IMPORTANT]
> Install the `surreal` CLI first. The installer also installs the database component by default, as described in [Install the CLI](/docs/reference/cli/guides/install.md). To run SurrealDB in other ways, see the [installation](/docs/running/installation.md) pages. To experiment with SurrealDB before installing, see the [SurrealDB Studio sandbox](https://studio.surrealdb.com/) online. To persist your Sandbox data while still experimenting, click on **Deploy to Cloud** in SurrealDB Studio to create a free SurrealDB Cloud instance.

## surreal db and the launcher

The `surreal` command is a launcher that installs, versions and runs components, and `db` is the component that holds the database. The launcher installs and upgrades the database (`surreal install db`, `surreal upgrade db`), and everything after `db` is forwarded to the database unchanged, so the flags on these pages are the database's own flags. See the [launcher reference](/docs/reference/cli/launcher.md) and [Components](/docs/reference/cli/guides/components.md) for how components are installed and selected.

The older top-level forms, such as `surreal start` and `surreal sql`, still run but print a deprecation warning that names the `surreal db` form to use instead. Scripts that call them keep working, and can be moved to `surreal db` at any time.

## Getting started

This documentation provides detailed information on each command, including usage examples and options. For a concise map of every subcommand, see [CLI commands](/docs/reference/cli/db/commands.md).

For a quickstart, [`surreal db start`](/docs/reference/cli/db/commands/start.md) and [`surreal db sql`](/docs/reference/cli/db/commands/sql.md) will be enough to get you started.

```bash
surreal db start --user root --pass secret
```

Unless you specify otherwise, the CLI will start a database [in memory](/docs/running/in-memory.md) that serves at `127.0.0.1:8000` (or `http://localhost:8000`). This database has a single root user named `root` and a password `secret`.

In another window, you can then open up an interactive shell to make queries using the `surreal db sql` command. As of SurrealDB 3.0, the `sql` command will connect to the default 'main' name for both namespace and database.

```bash
# Connect to namespace 'main' and database 'main'
surreal db sql --username root --password secret --pretty

# Connect to a different namespace and database
surreal db sql --namespace ns --database db --username root --password secret --pretty
```

> [!WARNING]
> Using generic usernames and passwords is not recommended for production use. Please replace the authentication credentials with your own.

This will start an interactive shell to make queries. The output below shows what you will see when logged in as the root user inside a namespace called `main` and a database called `main`, with pretty (easily readable) output per query.

You can then try out a few queries and see the output.

```bash
main/main> CREATE person SET age = 20;
main/main> CREATE person SET age = 30;
main/main> SELECT * FROM person WHERE age > 25;
```

```surql title="Output"
[
	{
		age: 20,
		id: person:6jodx8xv39jsxdgykt0t
	}
]

[
	{
		age: 30,
		id: person:10bcq2owseyqqoinjgxl
	}
]

[
	{
		age: 30,
		id: person:10bcq2owseyqqoinjgxl
	}
]
```

## Next steps

- [CLI commands](/docs/reference/cli/db/commands.md) - every subcommand, with its arguments and options.
- [Environment variables](/docs/reference/cli/db/environment-variables.md) - the `SURREAL_*` variables that mirror the flags on this page.
- [Launcher](/docs/reference/cli/launcher.md) - installing, upgrading and selecting versions of the database and other components.
- [surreal cloud](/docs/reference/cli/cloud.md) - managing organisations and Cloud instances from the command line.

---

Source: https://surrealdb.com/docs/reference/cli/db/commands

# surreal db commands

Every surreal db subcommand with its purpose, and how each relates to the launcher commands, with links to each command’s flags and examples.

`surreal db` has **subcommands** for running the server, executing SurrealQL, importing and exporting data, and maintenance tasks. Each page documents that subcommand’s arguments, related environment variables, and typical usage.

<Synopsis>
surreal db [OPTIONS] <COMMAND>
</Synopsis>

| Subcommand | Purpose |
| --- | --- |
| [`surreal db start`](/docs/reference/cli/db/commands/start.md) | Run a SurrealDB server (in memory, on disk, or clustered). |
| [`surreal db sql`](/docs/reference/cli/db/commands/sql.md) | Open an interactive SurrealQL shell or run queries from scripts. |
| [`surreal db export`](/docs/reference/cli/db/commands/export.md) | Dump a database to SurrealQL. |
| [`surreal db fix`](/docs/reference/cli/db/commands/fix.md) | Apply data or schema fixes offline. |
| [`surreal db help`](/docs/reference/cli/db/commands/help.md) | Show help for `surreal db` or a subcommand. |
| [`surreal db import`](/docs/reference/cli/db/commands/import.md) | Load SurrealQL from a file into a database. |
| [`surreal db is-ready`](/docs/reference/cli/db/commands/isready.md) | Health check for readiness probes. |
| [`surreal db mcp`](/docs/reference/cli/db/commands/mcp.md) _(since v3.1.0)_ | Start the Model Context Protocol server on stdio for IDE integrations. |
| `surreal db ml` | Before SurrealDB 4.0, imported and exported SurrealML models. SurrealDB 4.0 removed SurrealML and this command. See [Upgrading from 3.x to 4.0](/docs/operate/upgrading/3x-to-4x.md#surrealml-is-removed). |
| `surreal db module` | Before SurrealDB 4.0, built and ran Surrealism modules. From 4.0 the commands are part of [`surreal ext`](/docs/reference/cli/ext.md), and `surreal db module` only says so. |
| [`surreal upgrade db`](/docs/reference/cli/db/commands/upgrade.md) | Upgrade the database component. Run by the launcher, not by `surreal db`. |
| [`surreal db validate`](/docs/reference/cli/db/commands/validate.md) | Validate SurrealQL or configuration. |
| [`surreal db version`](/docs/reference/cli/db/commands/version.md) | Print the database client version, or the version of a server. |

**Sidebar order:** [`start`](/docs/reference/cli/db/commands/start.md) and [`sql`](/docs/reference/cli/db/commands/sql.md) first, then remaining subcommands alphabetically.

## Shared options

Every `surreal db` subcommand accepts `-h` / `--help`, which prints its arguments and options and exits, and the logging option group (`-l` / `--log`, `--log-format`, `--log-file-*`, and the socket and OpenTelemetry overrides). Each page lists `--log` alongside the command's own flags and shows the full group in its command help output.

Most flags have an equivalent environment variable, listed in the tables on each page and in full on the [environment variables](/docs/reference/cli/db/environment-variables.md#command-environment-variables) page.

## What is not here

These subcommands act on a database that already exists or that you start yourself. Provisioning, pausing, scaling, and deleting SurrealDB Cloud instances is handled by [`surreal cloud instance`](/docs/reference/cli/cloud.md), which calls out to `surreal db` for SQL, imports, and exports, so the pages here still describe what happens once a Cloud instance has been resolved.

Installing, upgrading and selecting versions of the database is done by the launcher, with `surreal install db`, `surreal upgrade db`, `surreal use db@<VERSION>` and `surreal list`, described in the [launcher reference](/docs/reference/cli/launcher.md). The `surreal db upgrade` form is refused, with a message that names `surreal upgrade db`.

For installation and a minimal end-to-end example, see the [surreal db overview](/docs/reference/cli/db.md).

---

Source: https://surrealdb.com/docs/reference/cli/db/commands/export

# export

A command to export data from a SurrealDB database server into a SurrealQL file format.

Export an existing database as a SurrealQL script, either to a file or to stdout, using the [installed](/docs/reference/cli/guides/install.md) `surreal` CLI.

<Synopsis>
surreal db export [OPTIONS] --namespace <NAMESPACE> --database <DATABASE> [FILE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[FILE]",
            "default": "-",
            "description": "Path to the SurrealQL file to write. Use a dash (`-`) to write into stdout, which is the default and can be redirected using `>`."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--endpoint",
            "short": "-e",
            "value": "<ENDPOINT>",
            "default": "http://localhost:8000",
            "description": "Database endpoint to export from."
        },
        {
            "name": "--username",
            "short": "-u",
            "value": "<USERNAME>",
            "env": "SURREAL_USER",
            "description": "Database authentication username to use when connecting. Alias: `--user`."
        },
        {
            "name": "--password",
            "short": "-p",
            "value": "<PASSWORD>",
            "env": "SURREAL_PASS",
            "description": "Database authentication password to use when connecting. Alias: `--pass`."
        },
        {
            "name": "--token",
            "short": "-t",
            "value": "<TOKEN>",
            "env": "SURREAL_TOKEN",
            "description": "Authentication token in JWT format, used instead of a username and password."
        },
        {
            "name": "--auth-level",
            "value": "<AUTH_LEVEL>",
            "default": "root",
            "env": "SURREAL_AUTH_LEVEL",
            "description": "Level on which the authenticating user is defined. Possible values: `root`, `namespace` (`ns`), `database` (`db`)."
        },
        {
            "name": "--namespace",
            "value": "<NAMESPACE>",
            "env": "SURREAL_NAMESPACE",
            "required": true,
            "description": "The namespace to export from. Alias: `--ns`."
        },
        {
            "name": "--database",
            "value": "<DATABASE>",
            "env": "SURREAL_DATABASE",
            "required": true,
            "description": "The database to export from. Alias: `--db`."
        },
        {
            "name": "--log",
            "short": "-l",
            "value": "<LOG>",
            "default": "info",
            "env": "SURREAL_LOG",
            "description": "The logging level for the command-line tool. Possible values: `none`, `full`, `error`, `warn`, `info`, `debug`, `trace`."
        }
    ]}
/>

Authenticate with either `--username` and `--password`, or with `--token`. Neither is needed against a server started with `--unauthenticated`.

## Export options

By default an export contains everything in the database. These flags narrow it down.

<OptionsTable
    title="Export options"
    options={[
        {
            "name": "--only",
            "description": "Whether only specific resources should be exported. When provided, only the resources named by the flags below are exported. The database's own definition is the exception, and is still exported unless `--database-definition false` is given."
        },
        {
            "name": "--database-definition",
            "value": "[<DATABASE_DEFINITION>]",
            "description": "From 3.3.1. Whether the database's own definition - its `STRICT` flag, `COMMENT` and `CHANGEFEED` - should be exported. Restoring it rewrites those clauses on the target database. Possible values: `true`, `false`. A `grpc://` endpoint cannot leave the definition out, and refuses an export that asks it to."
        },
        {
            "name": "--users",
            "value": "[<USERS>]",
            "description": "Whether system users should be exported. Possible values: `true`, `false`."
        },
        {
            "name": "--accesses",
            "value": "[<ACCESSES>]",
            "description": "Whether access methods (record or JWT) should be exported. Possible values: `true`, `false`. A signing key is never exported, so an access that has one has to be defined again after a restore. See "What a dump does not restore" in Backups and recovery."
        },
        {
            "name": "--params",
            "value": "[<PARAMS>]",
            "description": "Whether database parameters should be exported. Possible values: `true`, `false`."
        },
        {
            "name": "--functions",
            "value": "[<FUNCTIONS>]",
            "description": "Whether functions should be exported. Possible values: `true`, `false`."
        },
        {
            "name": "--analyzers",
            "value": "[<ANALYZERS>]",
            "description": "Whether analyzers should be exported. Possible values: `true`, `false`."
        },
        {
            "name": "--tables",
            "value": "[<TABLES>]",
            "description": "Whether tables should be exported, optionally providing a list of tables."
        },
        {
            "name": "--tables-exclude",
            "value": "<TABLES_EXCLUDE>",
            "description": "A comma-separated list of tables to leave out of the export. Cannot be combined with `--tables`."
        },
        {
            "name": "--versions",
            "value": "[<VERSIONS>]",
            "description": "Refused from SurrealDB 3.3.1, because an export holds only the current state of each record. SurrealDB 3.0.0 to 3.3.0 accepted the flag and ignored it."
        },
        {
            "name": "--records",
            "value": "[<RECORDS>]",
            "description": "Whether records should be exported. Possible values: `true`, `false`."
        },
        {
            "name": "--apis",
            "value": "[<APIS>]",
            "description": "Whether API definitions should be exported. Possible values: `true`, `false`."
        },
        {
            "name": "--buckets",
            "value": "[<BUCKETS>]",
            "description": "Whether bucket definitions should be exported. Possible values: `true`, `false`."
        },
        {
            "name": "--modules",
            "value": "[<MODULES>]",
            "description": "Whether extension definitions (`DEFINE EXTENSION`) should be exported. Possible values: `true`, `false`."
        },
        {
            "name": "--configs",
            "value": "[<CONFIGS>]",
            "description": "Whether config definitions should be exported. Possible values: `true`, `false`."
        },
        {
            "name": "--sequences",
            "value": "[<SEQUENCES>]",
            "description": "From 3.3.1. Whether sequences should be exported. Each sequence is exported at the position it has reached, so a restored sequence does not issue a value again. Possible values: `true`, `false`."
        }
    ]}
/>

## Example usage

To perform a SurrealQL database export into a local file, in a terminal run the `surreal db export` command with the required arguments.

```bash
surreal db export --endpoint http://localhost:8000 --user root --pass secret --ns main --db main export.surql
```

Using token-based authentication:

```bash
surreal db export --endpoint http://localhost:8000 --token <token> --ns main --db main export.surql
```

To write the export to standard output instead of a file, for example to pipe it into another command, use `-` as the file name. From SurrealDB 4.0 the command then writes its log lines to standard error, so standard output holds only the export.

```bash
surreal db export --endpoint http://localhost:8000 --user root --pass secret --ns main --db main - > export.surql
```

Before SurrealDB 4.0, add `--log none` to the command above. Without it, the log line `INFO surrealdb::method::export: Exporting bytes` is written to standard output ahead of the export, and importing the result fails with a parse error on that line.

From SurrealDB 4.0, an export over `http://` or `https://` that fails part-way through makes the command fail with an error. Before 4.0, such a failure could end the export early without an error, and leave a file that was cut short, so check the end of an export file taken with an earlier release before you rely on it.

In Windows PowerShell 5, `>` saves the output as UTF-16, which `surreal import` refuses. Write the export to a file with `surreal export <file>` instead, or use PowerShell 7, which writes UTF-8.

## Choosing what to export

`--only` starts from an empty export, and each resource flag after it adds that resource back. The following command exports the table definitions and their records, and leaves out users, access methods, functions and every other definition:

```bash
surreal db export --endpoint http://localhost:8000 --user root --pass secret --ns main --db main --only --tables --records -- export.surql
```

Without `--records`, the same command exports only the table definitions, which gives the schema without the data. `--tables` also takes a comma-separated list, such as `--tables person,order`, to export only those tables.

The resource flags accept an optional value, so a flag directly before the file name reads the file name as its value and the command fails with `invalid value`. Put `--` before the file name, as in the example above, or put the file name before the flags.

### Choosing in SurrealDB Studio

[SurrealDB Studio](/docs/reference/studio.md) builds the same command for you. Open **Export database** and choose **Choose what to include**, then select the tables and the definitions you want. **Record data** corresponds to `--records`, and each other checkbox to the flag of the same name.

<img src="~/assets/img/image/studio/export-database-choose.png" alt="The Export database dialog in SurrealDB Studio with Choose what to include selected, showing a checkbox for each table and for each kind of definition: record data, functions, parameters, users, access methods, analyzers, APIs, buckets, modules, configs and sequences." />

The **Use the CLI instead** section below the checkboxes shows the `surreal db export` command for that selection, with your connection's endpoint, namespace and database filled in. Running it from a terminal is faster for a large database, and it does not depend on the Studio window staying open.

<img src="~/assets/img/image/studio/export-database-cli.png" alt="The same dialog with Use the CLI instead expanded, showing a surreal db export command with the endpoint, namespace, database and credentials, followed by --only and one flag for each selected resource, and the file name after a double hyphen." />

If you select **Sequences**, add `--sequences` to the command yourself: Studio currently leaves that flag out of the command it shows.

## Passwords and credentials in an export

An export holds the password hash and SCRAM verifier of each database user only when the exporting user is allowed to edit the users of that database: an owner on the database, on its namespace or on the root, or any client of a server started with `--unauthenticated`. For any other user, each `DEFINE USER` statement in the export has `PASSHASH '[REDACTED]'` and `PASSSCRAM '[REDACTED]'` in place of the values. Export as an owner when the file has to restore the users' passwords.

A bucket's `BACKEND` URL is exported with the credentials in it replaced by `[REDACTED]`, whoever runs the export. After an import, define the bucket again with its credentials, or give the server its credentials from the environment. See [`DEFINE BUCKET`](/docs/reference/query-language/statements/define/bucket.md#cloud-object-storage-backends).

## Using environment variables

> [!IMPORTANT]
> Most of the flags above have a corresponding [environment variable](/docs/reference/cli/db/environment-variables.md#command-environment-variables).
> For example, the `--username` flag can be configured with the `SURREAL_USER` environment variable instead.

When using the `surreal db export` command, you can also use environment variables to set the values for the command-line flags.

For more on the environment variables available for CLI commands or SurrealDB instances in general, see the [environment variables](/docs/reference/cli/db/environment-variables.md#command-environment-variables) page.

## Managing a Cloud instance

To export from a SurrealDB Cloud instance by name, [`surreal cloud`](/docs/reference/cli/cloud.md) resolves the endpoint and credentials for you and then runs this command. The flags and file-format notes on this page still apply.

## OPTION IMPORT keyword

The output of a database export includes a line that contains the keywords `OPTION IMPORT`. This command is used internally to ensure that side effects do not run when the data is imported, such as [events](/docs/reference/query-language/statements/define/event.md) and [table views](/docs/reference/query-language/statements/define/table.md#pre-computed-table-views).

As of SurrealDB 3.0.4, imports via the [`surreal db import`](/docs/reference/cli/db/commands/import.md) and [`/import`](/docs/reference/protocols/http-protocol.md#import) HTTP endpoint require the automatically generated `OPTION IMPORT` line to be present in order to disable events, live queries, field processing, and result output for optimal import performance. If side effects are desired when importing data, remove the line and use the [`/sql`](/docs/reference/protocols/http-protocol.md#sql) endpoint instead.

## Command help

To see the help information and usage instructions, in a terminal run the `surreal db export --help` command without any further arguments. This command gives general information on the arguments, inputs, and additional options for the export command.

```bash
surreal db export --help
```

The output of the above command:

```text
Export an existing database as a SurrealQL script

Usage: surreal export [OPTIONS] --namespace <NAMESPACE> --database <DATABASE> [FILE]

Arguments:
  [FILE]
          Path to the SurrealQL file to export. Use dash - to write into stdout.

          [default: -]

Options:
  -e, --endpoint <ENDPOINT>
          Database endpoint to export from

          [default: http://localhost:8000]

  -u, --username <USERNAME>
          Database authentication username to use when connecting

          [env: SURREAL_USER]
          [alias: --user]

  -p, --password <PASSWORD>
          Database authentication password to use when connecting

          [env: SURREAL_PASS]
          [alias: --pass]

  -t, --token <TOKEN>
          Authentication token in JWT format to use when connecting

          [env: SURREAL_TOKEN]

      --auth-level <AUTH_LEVEL>
          Level on which the authenticating user is defined

          [env: SURREAL_AUTH_LEVEL]
          [default: root]
          [possible values: root, namespace, ns, database, db]

      --namespace <NAMESPACE>
          The namespace selected for the operation

          [env: SURREAL_NAMESPACE]
          [alias: --ns]

      --database <DATABASE>
          The database selected for the operation

          [env: SURREAL_DATABASE]
          [alias: --db]

      --only
          Whether only specific resources should be exported. Deselects every section the wire format can express leaving out, so that what
          follows on the command line is all the dump carries. The database's own definition is the exception — gRPC has no field for
          excluding it, so it rides along unless `--database-definition false` asks for it to be left out

      --database-definition [<DATABASE_DEFINITION>]
          Whether the database's own definition — its STRICT flag, COMMENT and CHANGEFEED — should be exported. Restoring it rewrites those
          clauses on the target database. Not carried over gRPC, which has no field for the exclusion and refuses the export rather than
          answering with the section anyway.

          Not `--database`, which this command already takes for the database to export from.

          [possible values: true, false]

      --users [<USERS>]
          Whether users should be exported

          [possible values: true, false]

      --accesses [<ACCESSES>]
          Whether access methods should be exported

          [possible values: true, false]

      --params [<PARAMS>]
          Whether params should be exported

          [possible values: true, false]

      --functions [<FUNCTIONS>]
          Whether functions should be exported

          [possible values: true, false]

      --analyzers [<ANALYZERS>]
          Whether analyzers should be exported

          [possible values: true, false]

      --tables [<TABLES>]
          Whether tables should be exported, optionally providing a list of tables

      --tables-exclude <TABLES_EXCLUDE>
          Comma-separated list of tables to exclude from the export

      --versions [<VERSIONS>]
          Whether versions should be exported. Versioned export is not supported: a dump carries the current state of each record only, and
          asking for versions fails the export rather than writing one without them

          [possible values: true, false]

      --records [<RECORDS>]
          Whether records should be exported

          [possible values: true, false]

      --apis [<APIS>]
          Whether apis should be exported

          [possible values: true, false]

      --buckets [<BUCKETS>]
          Whether buckets should be exported

          [possible values: true, false]

      --modules [<MODULES>]
          Whether modules should be exported

          [possible values: true, false]

      --configs [<CONFIGS>]
          Whether configs should be exported

          [possible values: true, false]

      --sequences [<SEQUENCES>]
          Whether sequences should be exported

          [possible values: true, false]

  -h, --help
          Print help (see a summary with '-h')

Logging:
  -l, --log <LOG>
          The logging level for the command-line tool

          [env: SURREAL_LOG]
          [default: info]
          [possible values: none, full, error, warn, info, debug, trace]

      --log-format <LOG_FORMAT>
          The format for terminal log output

          [env: SURREAL_LOG_FORMAT]
          [default: text]
          [possible values: text, json]

      --log-socket <LOG_SOCKET>
          Send logs to the specified host:port

          [env: SURREAL_LOG_SOCKET]

      --log-file-level <LOG_FILE_LEVEL>
          Override the logging level for file output

          [env: SURREAL_LOG_FILE_LEVEL]
          [possible values: none, full, error, warn, info, debug, trace]

      --log-otel-level <LOG_OTEL_LEVEL>
          Override the logging level for OpenTelemetry output

          [env: SURREAL_LOG_OTEL_LEVEL]
          [possible values: none, full, error, warn, info, debug, trace]

      --log-socket-level <LOG_SOCKET_LEVEL>
          Override the logging level for unix socket output

          [env: SURREAL_LOG_SOCKET_LEVEL]
          [possible values: none, full, error, warn, info, debug, trace]

      --log-socket-format <LOG_SOCKET_FORMAT>
          The format for socket output

          [env: SURREAL_LOG_SOCKET_FORMAT]
          [default: text]
          [possible values: text, json]

      --log-file-enabled
          Whether to enable log file output

          [env: SURREAL_LOG_FILE_ENABLED]

      --log-file-path <LOG_FILE_PATH>
          The directory where log files will be stored

          [env: SURREAL_LOG_FILE_PATH]
          [default: logs]

      --log-file-name <LOG_FILE_NAME>
          The name of the log file

          [env: SURREAL_LOG_FILE_NAME]
          [default: surrealdb.log]

      --log-file-format <LOG_FILE_FORMAT>
          The format for log file output

          [env: SURREAL_LOG_FILE_FORMAT]
          [default: text]
          [possible values: text, json]

      --log-file-rotation <LOG_FILE_ROTATION>
          The log file rotation interval

          [env: SURREAL_LOG_FILE_ROTATION]
          [default: daily]
          [possible values: daily, hourly, never]
```

---

Source: https://surrealdb.com/docs/reference/cli/db/commands/fix

# fix

A command to convert SurrealDB version 1.x data into a usable format for versions 2.0 and above.

Convert data written by SurrealDB 1.x into the storage format used by 2.0 and above, using a 2.x version of the database component, which you can run for one command with `surreal +2.6.5 db fix` after `surreal install db@2.6.5`.

> [!IMPORTANT]
> The conversion is only implemented in 2.x binaries. From SurrealDB 3.0.0 the command is still listed, but it exits with `Fix is not implemented` and changes nothing. Run `surreal db fix` with a 2.x binary to move 1.x data to 2.x, then follow [Migrating from 2.x to 3.x](/docs/operate/upgrading/2x-to-3x.md) to reach 3.x.

<Synopsis>
surreal db fix [OPTIONS] [PATH]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[PATH]",
            "default": "memory",
            "env": "SURREAL_PATH",
            "description": "Path to the existing data to convert to the 2.x storage format, for example `surrealkv://mydatabase.db`."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--log",
            "short": "-l",
            "value": "<LOG>",
            "default": "info",
            "env": "SURREAL_LOG",
            "description": "The logging level for the command-line tool. Possible values: `none`, `full`, `error`, `warn`, `info`, `debug`, `trace`."
        }
    ]}
/>

## Example usage

To perform a fix from SurrealDB 1.x to 2.x storage, run the `surreal db fix` command in a terminal with the path to the stored data.

```bash
surreal db fix surrealkv://mydatabase.db

surreal db fix rocksdb:somedatabase
```

## Using environment variables

> [!IMPORTANT]
> Most of the flags above have a corresponding [environment variable](/docs/reference/cli/db/environment-variables.md#command-environment-variables).
> For example, the `--log` flag can be configured with the `SURREAL_LOG` environment variable instead.

When using the `surreal db fix` command, you can also use environment variables to set the values for the command-line flags.

For more on the environment variables available for CLI commands or SurrealDB instances in general, see the [environment variables](/docs/reference/cli/db/environment-variables.md#command-environment-variables) page.

## Command help

To see the help information and usage instructions, in a terminal run the `surreal db fix --help` command without any further arguments. This command gives general information on the arguments, inputs, and additional options for the `fix` command.

```bash
surreal db fix --help
```

The output of the above command:

```text
Fix database storage issues

Usage: surreal fix [OPTIONS] [PATH]

Arguments:
  [PATH]  Database path used for storing data [env: SURREAL_PATH] [default: memory]

Options:
  -h, --help  Print help

Logging:
  -l, --log <LOG>                              The logging level for the command-line tool [env: SURREAL_LOG] [default: info] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-format <LOG_FORMAT>                The format for terminal log output [env: SURREAL_LOG_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-socket <LOG_SOCKET>                Send logs to the specified host:port [env: SURREAL_LOG_SOCKET]
      --log-file-level <LOG_FILE_LEVEL>        Override the logging level for file output [env: SURREAL_LOG_FILE_LEVEL] [possible values:
                                               none, full, error, warn, info, debug, trace]
      --log-otel-level <LOG_OTEL_LEVEL>        Override the logging level for OpenTelemetry output [env: SURREAL_LOG_OTEL_LEVEL] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-socket-level <LOG_SOCKET_LEVEL>    Override the logging level for unix socket output [env: SURREAL_LOG_SOCKET_LEVEL] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-socket-format <LOG_SOCKET_FORMAT>  The format for socket output [env: SURREAL_LOG_SOCKET_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-file-enabled                       Whether to enable log file output [env: SURREAL_LOG_FILE_ENABLED]
      --log-file-path <LOG_FILE_PATH>          The directory where log files will be stored [env: SURREAL_LOG_FILE_PATH] [default: logs]
      --log-file-name <LOG_FILE_NAME>          The name of the log file [env: SURREAL_LOG_FILE_NAME] [default: surrealdb.log]
      --log-file-format <LOG_FILE_FORMAT>      The format for log file output [env: SURREAL_LOG_FILE_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-file-rotation <LOG_FILE_ROTATION>  The log file rotation interval [env: SURREAL_LOG_FILE_ROTATION] [default: daily] [possible
                                               values: daily, hourly, never]
```

---

Source: https://surrealdb.com/docs/reference/cli/db/commands/help

# help

surreal db help and surreal db <COMMAND> --help print the database help. surreal help and surreal --help print the launcher help, which lists components and version commands instead.

Print the help information for `surreal db`, or for one of its subcommands.

`surreal db help` and `surreal help` print different things. `surreal db help` is the database's own help, described on this page, because everything after `db` is forwarded to the database. `surreal help` and `surreal --help` are the launcher's help, which lists the components and the commands that manage what is installed. See [Launcher help](#launcher-help).

<Synopsis>
surreal db help [COMMAND]
surreal db <COMMAND> --help
</Synopsis>

<OptionsTable
    title="Global options"
    options={[
        {
            "name": "--online-version-check",
            "env": "SURREAL_ONLINE_VERSION_CHECK",
            "description": "Whether to allow a web check for client version upgrades at start."
        },
        {
            "name": "--help",
            "short": "-h",
            "description": "Print help. Accepted by the binary and by every subcommand."
        },
        {
            "name": "--version",
            "short": "-V",
            "description": "Print the version of the database component."
        },
        {
            "name": "--log",
            "short": "-l",
            "value": "<LOG>",
            "default": "info",
            "env": "SURREAL_LOG",
            "description": "The logging level for the command-line tool. Possible values: `none`, `full`, `error`, `warn`, `info`, `debug`, `trace`."
        }
    ]}
/>

## Show the command-line help information

To see the general help information for the database, run `surreal db help` without any further arguments. This command lists the subcommands of `surreal db`.

```bash
surreal db help
```

The output of the above command:

```text
Start, query, import and export SurrealDB from the command line

Usage: surreal [OPTIONS] <COMMAND>

Commands:
  start     Start the database server
  import    Import a SurrealQL script into an existing database
  export    Export an existing database as a SurrealQL script
  version   Output the command-line tool and remote server version information
  sql       Start an SQL REPL in your terminal with pipe support
  mcp       Start the MCP server over stdio for AI assistant integration
  is-ready  Check if the SurrealDB server is ready to accept connections [alias: isready]
  validate  Validate SurrealQL query files
  fix       Fix database storage issues
  help      Print this message or the help of the given subcommand(s)

Options:
  -v, --version  Print version
  -j, --json     Emit machine-readable JSON on stdout
  -h, --help     Print help

Logging:
  -l, --log <LOG>                              The logging level for the command-line tool [env: SURREAL_LOG] [default: info] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-format <LOG_FORMAT>                The format for terminal log output [env: SURREAL_LOG_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-socket <LOG_SOCKET>                Send logs to the specified host:port [env: SURREAL_LOG_SOCKET]
      --log-file-level <LOG_FILE_LEVEL>        Override the logging level for file output [env: SURREAL_LOG_FILE_LEVEL] [possible values:
                                               none, full, error, warn, info, debug, trace]
      --log-otel-level <LOG_OTEL_LEVEL>        Override the logging level for OpenTelemetry output [env: SURREAL_LOG_OTEL_LEVEL] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-socket-level <LOG_SOCKET_LEVEL>    Override the logging level for unix socket output [env: SURREAL_LOG_SOCKET_LEVEL] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-socket-format <LOG_SOCKET_FORMAT>  The format for socket output [env: SURREAL_LOG_SOCKET_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-file-enabled                       Whether to enable log file output [env: SURREAL_LOG_FILE_ENABLED]
      --log-file-path <LOG_FILE_PATH>          The directory where log files will be stored [env: SURREAL_LOG_FILE_PATH] [default: logs]
      --log-file-name <LOG_FILE_NAME>          The name of the log file [env: SURREAL_LOG_FILE_NAME] [default: surrealdb.log]
      --log-file-format <LOG_FILE_FORMAT>      The format for log file output [env: SURREAL_LOG_FILE_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-file-rotation <LOG_FILE_ROTATION>  The log file rotation interval [env: SURREAL_LOG_FILE_ROTATION] [default: daily] [possible
                                               values: daily, hourly, never]
```

The `upgrade` entry appears in the database's own list, but `surreal db upgrade` is refused. Use [`surreal upgrade db`](/docs/reference/cli/db/commands/upgrade.md).

## Launcher help {#launcher-help}

`surreal help` and `surreal --help` print the launcher's help. It lists the components (`db`, `cloud`), the commands that manage what is installed (`version`, `install`, `upgrade`, `use`, `uninstall`), and the `+VERSION` option that runs another version for one command. Run `surreal <COMPONENT> help`, such as `surreal cloud help`, for the help of a component. The `--no-banner` option, or `SURREAL_CLI_NO_BANNER`, prints the launcher help without the banner. See the [launcher reference](/docs/reference/cli/launcher.md) for each of these commands.

## Getting help on individual commands

For individual commands, such as `surreal db start` and `surreal db sql`, a help prompt can be displayed by adding the `--help` flag. This flag overrides all other flags, and thus can be added to the end of any command regardless of length.

```bash
surreal db start --help
surreal db start --user root --pass secret --log debug --help
```

---

Source: https://surrealdb.com/docs/reference/cli/db/commands/import

# import

A command that imports a file in SurrealQL format into a local or remote SurrealDB database server.

Import a SurrealQL script into an existing database, on a local or remote server, using the [installed](/docs/reference/cli/guides/install.md) `surreal` CLI.

<Synopsis>
surreal db import [OPTIONS] --namespace <NAMESPACE> --database <DATABASE> <FILE>
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "<FILE>",
            "required": true,
            "description": "Path to the SurrealQL file to import."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--endpoint",
            "short": "-e",
            "value": "<ENDPOINT>",
            "default": "http://localhost:8000",
            "description": "Database endpoint to import to."
        },
        {
            "name": "--username",
            "short": "-u",
            "value": "<USERNAME>",
            "env": "SURREAL_USER",
            "description": "Database authentication username to use when connecting. Alias: `--user`."
        },
        {
            "name": "--password",
            "short": "-p",
            "value": "<PASSWORD>",
            "env": "SURREAL_PASS",
            "description": "Database authentication password to use when connecting. Alias: `--pass`."
        },
        {
            "name": "--token",
            "short": "-t",
            "value": "<TOKEN>",
            "env": "SURREAL_TOKEN",
            "description": "Authentication token in JWT format, used instead of a username and password."
        },
        {
            "name": "--auth-level",
            "value": "<AUTH_LEVEL>",
            "default": "root",
            "env": "SURREAL_AUTH_LEVEL",
            "description": "Level on which the authenticating user is defined. Possible values: `root`, `namespace` (`ns`), `database` (`db`)."
        },
        {
            "name": "--namespace",
            "value": "<NAMESPACE>",
            "env": "SURREAL_NAMESPACE",
            "required": true,
            "description": "The namespace to import into. Alias: `--ns`."
        },
        {
            "name": "--database",
            "value": "<DATABASE>",
            "env": "SURREAL_DATABASE",
            "required": true,
            "description": "The database to import into. Alias: `--db`."
        },
        {
            "name": "--log",
            "short": "-l",
            "value": "<LOG>",
            "default": "info",
            "env": "SURREAL_LOG",
            "description": "The logging level for the command-line tool. Possible values: `none`, `full`, `error`, `warn`, `info`, `debug`, `trace`."
        }
    ]}
/>

Authenticate with either `--username` and `--password`, or with `--token`. Neither is needed against a server started with `--unauthenticated`.

## Example usage

To perform a SurrealQL database import from a local file, in a terminal run the `surreal db import` command with the required arguments.

```bash
surreal db import --endpoint http://localhost:8000 --user root --pass secret \
  --ns main --db main downloads/surreal_deal_v1.surql
```

Using token-based authentication:

```bash
surreal db import --endpoint http://localhost:8000 --token <token> --ns main \
  --db main downloads/surreal_deal_v1.surql
```

> [!NOTE]
> If you are using SurrealDB Studio, you can import files into your database by using the `Import database` button in the Explorer view. See the [SurrealDB Studio documentation](/docs/reference/studio.md) for more information.

## Size limits and partial imports

An import against a remote endpoint goes through the [`/import`](/docs/reference/protocols/http-protocol.md#import) endpoint, which accepts up to 4 GiB per request by default. The limit is cumulative for the whole request rather than per chunk, so a single file larger than the cap fails no matter how it is transferred - split the dataset across several files instead.

The import is applied as it is parsed, statement by statement, and each statement commits as it goes. An import that exceeds the limit or is interrupted therefore leaves everything applied up to that point in the database, with nothing rolled back.

A statement that fails does not stop the import, and the statements after it are still applied. When the import finishes, the command logs the failure and exits with code `1`, so a script can tell a partial import from a complete one.

Before importing a large file, decide how a failed run would be retried. Either write the file so that running it twice is safe, or import into a fresh namespace or database and switch over once the import has completed.

See [request size limits](/docs/reference/protocols/http-protocol.md#request-size-limits) for the caps on every endpoint, and [environment variables](/docs/reference/cli/db/environment-variables.md#http-server-config) for changing them on a self-hosted server.

## File encoding

An import file is read as UTF-8, and a UTF-8 byte order mark at the start of the file is ignored. From SurrealDB 4.0, a UTF-16 file is refused with an error that names the encoding:

```text title="Error output"
The import is UTF-16 text, and SurrealQL is read as UTF-8. Save it as UTF-8; an export is written as UTF-8 by `surreal export <file>`, but not by redirecting standard output in Windows PowerShell
```

Windows PowerShell 5 saves redirected output as UTF-16, so save the file as UTF-8 before importing it, or write the export with `surreal export <file>`.

## Field definitions are checked

From SurrealDB 4.0, an import checks each `DEFINE FIELD` statement in the same way as a `DEFINE FIELD` statement that is run interactively. For example, a field whose `DEFAULT` value does not coerce to its `TYPE` is refused:

```surql
DEFINE TABLE item SCHEMAFULL;
-- Refused: an empty object is not a set<string>
DEFINE FIELD ops ON item TYPE set<string> DEFAULT {};
```

```surql title="Error output"
'Cannot change field `ops` of table `item`: its DEFAULT does not coerce to `set<string>`'
```

Earlier releases accepted such a definition on import, after which every write to the table failed. When an export from an earlier release contains one, that statement fails with an error such as ``Cannot change field `ops` of table `item`: its DEFAULT does not coerce to `set<string>` ``, and the import exits with code `1`. Correct the definition in the source database, or in the export file, before you import it into 4.0.

## Validating files before import

A good practice before importing for the first time is to use the [`surreal db validate`](/docs/reference/cli/db/commands/validate.md) command to ensure that the statements therein are valid SurrealQL. This allows you to save time by failing quickly on the command line if there is invalid SurrealQL instead of starting a full database instance that will eventually fail in the middle of the import process.

## Importing data from other databases and sources

To import data from other sources besides `.surql` files (such as PostgreSQL, MongoDB, CSV data, Kafka, etc.), see the [migrations](/docs/integrate/migrating.md) section of the documentation.

## Using environment variables

When using the `surreal db import` command, you can also use environment variables to set the values for the command-line flags.

> [!IMPORTANT]
> Most of the flags above have a corresponding [environment variable](/docs/reference/cli/db/environment-variables.md#command-environment-variables).
> For example, the `--username` flag can be configured with the `SURREAL_USER` environment variable instead.

For more on the environment variables available for CLI commands or SurrealDB instances in general, see the [environment variables](/docs/reference/cli/db/environment-variables.md#command-environment-variables) page.

## Managing a Cloud instance

To import into a SurrealDB Cloud instance by name, [`surreal cloud`](/docs/reference/cli/cloud.md) resolves the endpoint and credentials for you and then runs this command. The size limits and partial-import behaviour described above apply there too.

## OPTION IMPORT

The output of a database export includes a line that contains the keywords `OPTION IMPORT`. This command is used internally to ensure that side effects do not run when the data is imported, such as [events](/docs/reference/query-language/statements/define/event.md) and [table views](/docs/reference/query-language/statements/define/table.md#pre-computed-table-views).

As of SurrealDB 3.0.4, this line must be present in order to use the `/import` endpoint. If side effects when importing a `.surql` file are desired, remove the `OPTION IMPORT` line and use the [`/sql`](/docs/reference/protocols/http-protocol.md#sql) endpoint instead.

## Command help

To see the help information and usage instructions, in a terminal run the `surreal db import --help` command without any further arguments. This command gives general information on the arguments, inputs, and additional options for the `import` command.

```bash
surreal db import --help
```

The output of the above command:

```text
Import a SurrealQL script into an existing database

Usage: surreal import [OPTIONS] --namespace <NAMESPACE> --database <DATABASE> <FILE>

Arguments:
  <FILE>  Path to the SurrealQL file to import

Options:
  -e, --endpoint <ENDPOINT>      Database endpoint to import to [default: http://localhost:8000]
  -u, --username <USERNAME>      Database authentication username to use when connecting [env: SURREAL_USER] [alias: --user]
  -p, --password <PASSWORD>      Database authentication password to use when connecting [env: SURREAL_PASS] [alias: --pass]
  -t, --token <TOKEN>            Authentication token in JWT format to use when connecting [env: SURREAL_TOKEN]
      --auth-level <AUTH_LEVEL>  Level on which the authenticating user is defined [env: SURREAL_AUTH_LEVEL] [default: root] [possible
                                 values: root, namespace, ns, database, db]
      --namespace <NAMESPACE>    The namespace selected for the operation [env: SURREAL_NAMESPACE] [alias: --ns]
      --database <DATABASE>      The database selected for the operation [env: SURREAL_DATABASE] [alias: --db]
  -h, --help                     Print help

Logging:
  -l, --log <LOG>                              The logging level for the command-line tool [env: SURREAL_LOG] [default: info] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-format <LOG_FORMAT>                The format for terminal log output [env: SURREAL_LOG_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-socket <LOG_SOCKET>                Send logs to the specified host:port [env: SURREAL_LOG_SOCKET]
      --log-file-level <LOG_FILE_LEVEL>        Override the logging level for file output [env: SURREAL_LOG_FILE_LEVEL] [possible values:
                                               none, full, error, warn, info, debug, trace]
      --log-otel-level <LOG_OTEL_LEVEL>        Override the logging level for OpenTelemetry output [env: SURREAL_LOG_OTEL_LEVEL] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-socket-level <LOG_SOCKET_LEVEL>    Override the logging level for unix socket output [env: SURREAL_LOG_SOCKET_LEVEL] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-socket-format <LOG_SOCKET_FORMAT>  The format for socket output [env: SURREAL_LOG_SOCKET_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-file-enabled                       Whether to enable log file output [env: SURREAL_LOG_FILE_ENABLED]
      --log-file-path <LOG_FILE_PATH>          The directory where log files will be stored [env: SURREAL_LOG_FILE_PATH] [default: logs]
      --log-file-name <LOG_FILE_NAME>          The name of the log file [env: SURREAL_LOG_FILE_NAME] [default: surrealdb.log]
      --log-file-format <LOG_FILE_FORMAT>      The format for log file output [env: SURREAL_LOG_FILE_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-file-rotation <LOG_FILE_ROTATION>  The log file rotation interval [env: SURREAL_LOG_FILE_ROTATION] [default: daily] [possible
                                               values: daily, hourly, never]
```

---

Source: https://surrealdb.com/docs/reference/cli/db/commands/isready

# isready

A command that determines whether a SurrealDB server has started and is able to accept connections.

Check whether a SurrealDB server has started and is able to accept connections, using the [installed](/docs/reference/cli/guides/install.md) `surreal` CLI. The command is named `is-ready` and also accepts the alias `isready`.

<Synopsis>
surreal db is-ready [OPTIONS]
</Synopsis>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--endpoint",
            "short": "-e",
            "value": "<ENDPOINT>",
            "default": "ws://localhost:8000",
            "description": "Remote database server URL to connect to."
        },
        {
            "name": "--json",
            "short": "-j",
            "description": "From 4.0.0. Print one JSON document on stdout instead of `OK`: `{\"ready\":true,\"endpoint\":\"<ENDPOINT>\"}`. A failure prints a JSON error object on stderr instead, and stdout stays empty."
        },
        {
            "name": "--log",
            "short": "-l",
            "value": "<LOG>",
            "default": "info",
            "env": "SURREAL_LOG",
            "description": "The logging level for the command-line tool. Possible values: `none`, `full`, `error`, `warn`, `info`, `debug`, `trace`."
        }
    ]}
/>

## Example usage

To check whether a server has started and is accepting connections, in a terminal run the `surreal db isready` command against its endpoint.

```bash
surreal db isready --endpoint http://localhost:8000
```

The output of the command will either be a simple `OK` if ready, or some sort of error depending on the situation.

```text
# Server is running and ready
OK

# Output if server not started yet
2026-02-10T04:12:10.274572Z ERROR surrealdb_server::cli: There was an error processing a WebSocket request: IO error: Connection refused (os error 61)
```

## Command help

To see the help information and usage instructions, in a terminal run the `surreal db isready --help` command without any further arguments. This command gives general information on the arguments, inputs, and additional options for the `isready` command.

```bash
surreal db isready --help
```

The output of the above command:

```text
Check if the SurrealDB server is ready to accept connections

Usage: surreal is-ready [OPTIONS]

Options:
  -e, --endpoint <ENDPOINT>  Remote database server url to connect to [default: ws://localhost:8000]
  -j, --json                 Emit machine-readable JSON on stdout
  -h, --help                 Print help

Logging:
  -l, --log <LOG>                              The logging level for the command-line tool [env: SURREAL_LOG] [default: info] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-format <LOG_FORMAT>                The format for terminal log output [env: SURREAL_LOG_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-socket <LOG_SOCKET>                Send logs to the specified host:port [env: SURREAL_LOG_SOCKET]
      --log-file-level <LOG_FILE_LEVEL>        Override the logging level for file output [env: SURREAL_LOG_FILE_LEVEL] [possible values:
                                               none, full, error, warn, info, debug, trace]
      --log-otel-level <LOG_OTEL_LEVEL>        Override the logging level for OpenTelemetry output [env: SURREAL_LOG_OTEL_LEVEL] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-socket-level <LOG_SOCKET_LEVEL>    Override the logging level for unix socket output [env: SURREAL_LOG_SOCKET_LEVEL] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-socket-format <LOG_SOCKET_FORMAT>  The format for socket output [env: SURREAL_LOG_SOCKET_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-file-enabled                       Whether to enable log file output [env: SURREAL_LOG_FILE_ENABLED]
      --log-file-path <LOG_FILE_PATH>          The directory where log files will be stored [env: SURREAL_LOG_FILE_PATH] [default: logs]
      --log-file-name <LOG_FILE_NAME>          The name of the log file [env: SURREAL_LOG_FILE_NAME] [default: surrealdb.log]
      --log-file-format <LOG_FILE_FORMAT>      The format for log file output [env: SURREAL_LOG_FILE_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-file-rotation <LOG_FILE_ROTATION>  The log file rotation interval [env: SURREAL_LOG_FILE_ROTATION] [default: daily] [possible
                                               values: daily, hourly, never]
```

---

Source: https://surrealdb.com/docs/reference/cli/db/commands/mcp

# mcp

Start SurrealDB's Model Context Protocol server over stdio for local IDE and agent integrations.

_(since v3.1.0)_

The `surreal db mcp` subcommand starts the built-in [Model Context Protocol](https://modelcontextprotocol.io) server on **stdio**, suitable for Cursor, VS Code, Claude Desktop, and other MCP clients. It opens an embedded datastore at the path you pass (default `memory`) and runs every tool call with owner-level access.

From SurrealDB 4.0, the command writes its log lines to standard error at every log level, so standard output carries only the MCP messages that the client reads.

For HTTP-based clients against a running server, use [`surreal db start`](/docs/reference/cli/db/commands/start.md) and connect to the **`/mcp`** endpoint instead. See [When to use `surreal db mcp` vs `surreal db start`](/docs/integrate/ai-agents/mcp/embedded.md#when-to-use-surreal-db-mcp-vs-surreal-db-start) for the comparison, and [Embedded MCP](/docs/integrate/ai-agents/mcp/embedded.md) for transports, editor setup, and security.

> [!WARNING]
> Stdio MCP is intended for a trusted operator on the same machine. Do not expose this process to untrusted users - there is no per-call HTTP authentication surface to re-bind credentials.

<Synopsis>
surreal db mcp [OPTIONS] [PATH]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[PATH]",
            "default": "memory",
            "env": "SURREAL_PATH",
            "description": "Database path for the embedded datastore."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--ns",
            "value": "<NAMESPACE>",
            "env": "SURREAL_MCP_NS",
            "description": "Initial namespace."
        },
        {
            "name": "--db",
            "value": "<DATABASE>",
            "env": "SURREAL_MCP_DB",
            "description": "Initial database."
        },
        {
            "name": "--username",
            "short": "-u",
            "value": "<USERNAME>",
            "env": "SURREAL_USER",
            "description": "Root username. Requires `--password`, and applies only if no root user exists yet."
        },
        {
            "name": "--password",
            "short": "-p",
            "value": "<PASSWORD>",
            "env": "SURREAL_PASS",
            "description": "Root password."
        }
    ]}
/>

Database tuning flags from `surreal db start` are also available via the shared `dbs` option group (see `surreal db mcp --help`).

## Usage

```bash
surreal db mcp --ns main --db main memory
```

Optional root credentials apply only when no root user exists yet (same semantics as `surreal db start`):

```bash
surreal db mcp -u root -p secret --ns main --db main memory
```

## Limits

Process-wide MCP limits use the `SURREAL_MCP_*` variables documented in [Environment variables](/docs/reference/cli/db/environment-variables.md) and on [Embedded MCP](/docs/integrate/ai-agents/mcp/embedded.md#configuration). For HTTP `/mcp` on a non-loopback hostname, set `SURREAL_MCP_ALLOWED_HOSTS` (or `SURREAL_MCP_ALLOW_ALL_HOSTS` behind a trusted proxy). See those pages for details.

---

Source: https://surrealdb.com/docs/reference/cli/db/commands/ml

# ml

The ML command can be used to import and export machine learning models.

> [!NOTE]
> SurrealML was removed in SurrealDB 4.0. This page describes SurrealDB 3.x and earlier. To upgrade a database that holds a model, see [SurrealML is removed](/docs/operate/upgrading/3x-to-4x.md#surrealml-is-removed).

Manage SurrealML models within an existing database. The command has two subcommands: one imports a trained model into a database, the other exports a model that is already stored there.

> [!NOTE]
> **Before you begin** - make sure you’ve [installed SurrealDB](/docs/running/installation.md).

<Synopsis>
surreal db ml [OPTIONS] <COMMAND>
</Synopsis>

| Subcommand | Purpose |
| --- | --- |
| [`surreal db ml import`](#ml-import) | Import a SurrealML model into an existing database. |
| [`surreal db ml export`](#ml-export) | Export a SurrealML model from an existing database. |
| `surreal db ml help` | Print this message or the help of the given subcommand. |

## Command help

To see the help information and usage instructions, in a terminal run the `surreal db ml --help` command without any further arguments. This command gives general information on the arguments, inputs, and additional options for the `ml` command.

```bash
surreal db ml --help
```

The output of the above command:

```text
Manage SurrealML models within an existing database

Usage: surreal ml [OPTIONS] <COMMAND>

Commands:
  import  Import a SurrealML model into an existing database
  export  Export a SurrealML model from an existing database
  help    Print this message or the help of the given subcommand(s)

Options:
  -h, --help  Print help

Logging:
  -l, --log <LOG>                              The logging level for the command-line tool [env: SURREAL_LOG] [default: info] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-format <LOG_FORMAT>                The format for terminal log output [env: SURREAL_LOG_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-socket <LOG_SOCKET>                Send logs to the specified host:port [env: SURREAL_LOG_SOCKET]
      --log-file-level <LOG_FILE_LEVEL>        Override the logging level for file output [env: SURREAL_LOG_FILE_LEVEL] [possible values:
                                               none, full, error, warn, info, debug, trace]
      --log-otel-level <LOG_OTEL_LEVEL>        Override the logging level for OpenTelemetry output [env: SURREAL_LOG_OTEL_LEVEL] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-socket-level <LOG_SOCKET_LEVEL>    Override the logging level for unix socket output [env: SURREAL_LOG_SOCKET_LEVEL] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-socket-format <LOG_SOCKET_FORMAT>  The format for socket output [env: SURREAL_LOG_SOCKET_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-file-enabled                       Whether to enable log file output [env: SURREAL_LOG_FILE_ENABLED]
      --log-file-path <LOG_FILE_PATH>          The directory where log files will be stored [env: SURREAL_LOG_FILE_PATH] [default: logs]
      --log-file-name <LOG_FILE_NAME>          The name of the log file [env: SURREAL_LOG_FILE_NAME] [default: surrealdb.log]
      --log-file-format <LOG_FILE_FORMAT>      The format for log file output [env: SURREAL_LOG_FILE_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-file-rotation <LOG_FILE_ROTATION>  The log file rotation interval [env: SURREAL_LOG_FILE_ROTATION] [default: daily] [possible
                                               values: daily, hourly, never]
```

## surreal db ml export {#ml-export}

The ML export command is used to export an existing machine learning model from SurrealDB.

<Synopsis>
surreal db ml export [OPTIONS] --name <NAME> --version <VERSION> --namespace <NAMESPACE> --database <DATABASE> [FILE]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[FILE]",
            "default": "-",
            "description": "Path to the SurrealML file to write. Use a dash (`-`) to write into stdout. From SurrealDB 4.0, log lines then go to standard error, so standard output holds only the model."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--name",
            "value": "<NAME>",
            "env": "SURREAL_ML_EXPORT_MODEL_NAME",
            "required": true,
            "description": "The name of the model to export."
        },
        {
            "name": "--version",
            "value": "<VERSION>",
            "env": "SURREAL_ML_EXPORT_MODEL_VERSION",
            "required": true,
            "description": "The version of the model to export."
        },
        {
            "name": "--endpoint",
            "short": "-e",
            "value": "<ENDPOINT>",
            "default": "ws://localhost:8000",
            "description": "Remote database server URL to connect to."
        },
        {
            "name": "--username",
            "short": "-u",
            "value": "<USERNAME>",
            "env": "SURREAL_USER",
            "description": "Database authentication username to use when connecting. Alias: `--user`."
        },
        {
            "name": "--password",
            "short": "-p",
            "value": "<PASSWORD>",
            "env": "SURREAL_PASS",
            "description": "Database authentication password to use when connecting. Alias: `--pass`."
        },
        {
            "name": "--token",
            "short": "-t",
            "value": "<TOKEN>",
            "env": "SURREAL_TOKEN",
            "description": "Authentication token in JWT format, used instead of a username and password."
        },
        {
            "name": "--auth-level",
            "value": "<AUTH_LEVEL>",
            "default": "root",
            "env": "SURREAL_AUTH_LEVEL",
            "description": "Level on which the authenticating user is defined. Possible values: `root`, `namespace` (`ns`), `database` (`db`)."
        },
        {
            "name": "--namespace",
            "value": "<NAMESPACE>",
            "env": "SURREAL_NAMESPACE",
            "required": true,
            "description": "The namespace holding the model. Alias: `--ns`."
        },
        {
            "name": "--database",
            "value": "<DATABASE>",
            "env": "SURREAL_DATABASE",
            "required": true,
            "description": "The database holding the model. Alias: `--db`."
        },
        {
            "name": "--log",
            "short": "-l",
            "value": "<LOG>",
            "default": "info",
            "env": "SURREAL_LOG",
            "description": "The logging level for the command-line tool. Possible values: `none`, `full`, `error`, `warn`, `info`, `debug`, `trace`."
        }
    ]}
/>

### Example usage

To export a stored model to a local file, in a terminal run the `surreal db ml export` command with the required arguments.

```bash
surreal db ml export --endpoint http://localhost:8000 --user root --pass secret --ns main --db main --name my-surrealml-model --version 1.0.0 my-surrealml-model.surml
```

Using token-based authentication:

```bash
surreal db ml export --endpoint http://localhost:8000 --token <token> --ns main --db main --name my-surrealml-model --version 1.0.0 my-surrealml-model.surml
```

### Command help

To see the help information and usage instructions, in a terminal run the `surreal db ml export --help` command without any further arguments. This command gives general information on the arguments, inputs, and additional options for the `ml export` command.

```bash
surreal db ml export --help
```

The output of the above command:

```text
Export a SurrealML model from an existing database

Usage: surreal ml export [OPTIONS] --name <NAME> --version <VERSION> --namespace <NAMESPACE> --database <DATABASE> [FILE]

Arguments:
  [FILE]  Path to the SurrealML file to export. Use dash - to write into stdout. [default: -]

Options:
      --name <NAME>              The name of the model [env: SURREAL_ML_EXPORT_MODEL_NAME]
      --version <VERSION>        The version of the model [env: SURREAL_ML_EXPORT_MODEL_VERSION]
  -e, --endpoint <ENDPOINT>      Remote database server url to connect to [default: ws://localhost:8000]
  -u, --username <USERNAME>      Database authentication username to use when connecting [env: SURREAL_USER] [alias: --user]
  -p, --password <PASSWORD>      Database authentication password to use when connecting [env: SURREAL_PASS] [alias: --pass]
  -t, --token <TOKEN>            Authentication token in JWT format to use when connecting [env: SURREAL_TOKEN]
      --auth-level <AUTH_LEVEL>  Level on which the authenticating user is defined [env: SURREAL_AUTH_LEVEL] [default: root] [possible
                                 values: root, namespace, ns, database, db]
      --namespace <NAMESPACE>    The namespace selected for the operation [env: SURREAL_NAMESPACE] [alias: --ns]
      --database <DATABASE>      The database selected for the operation [env: SURREAL_DATABASE] [alias: --db]
  -h, --help                     Print help

Logging:
  -l, --log <LOG>                              The logging level for the command-line tool [env: SURREAL_LOG] [default: info] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-format <LOG_FORMAT>                The format for terminal log output [env: SURREAL_LOG_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-socket <LOG_SOCKET>                Send logs to the specified host:port [env: SURREAL_LOG_SOCKET]
      --log-file-level <LOG_FILE_LEVEL>        Override the logging level for file output [env: SURREAL_LOG_FILE_LEVEL] [possible values:
                                               none, full, error, warn, info, debug, trace]
      --log-otel-level <LOG_OTEL_LEVEL>        Override the logging level for OpenTelemetry output [env: SURREAL_LOG_OTEL_LEVEL] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-socket-level <LOG_SOCKET_LEVEL>    Override the logging level for unix socket output [env: SURREAL_LOG_SOCKET_LEVEL] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-socket-format <LOG_SOCKET_FORMAT>  The format for socket output [env: SURREAL_LOG_SOCKET_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-file-enabled                       Whether to enable log file output [env: SURREAL_LOG_FILE_ENABLED]
      --log-file-path <LOG_FILE_PATH>          The directory where log files will be stored [env: SURREAL_LOG_FILE_PATH] [default: logs]
      --log-file-name <LOG_FILE_NAME>          The name of the log file [env: SURREAL_LOG_FILE_NAME] [default: surrealdb.log]
      --log-file-format <LOG_FILE_FORMAT>      The format for log file output [env: SURREAL_LOG_FILE_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-file-rotation <LOG_FILE_ROTATION>  The log file rotation interval [env: SURREAL_LOG_FILE_ROTATION] [default: daily] [possible
                                               values: daily, hourly, never]
```

## surreal db ml import {#ml-import}

The ML import command is used to import a new machine learning model into SurrealDB.

<Synopsis>
surreal db ml import [OPTIONS] --namespace <NAMESPACE> --database <DATABASE> <FILE>
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "<FILE>",
            "required": true,
            "description": "Path to the SurrealML file to import."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--endpoint",
            "short": "-e",
            "value": "<ENDPOINT>",
            "default": "ws://localhost:8000",
            "description": "Remote database server URL to connect to."
        },
        {
            "name": "--username",
            "short": "-u",
            "value": "<USERNAME>",
            "env": "SURREAL_USER",
            "description": "Database authentication username to use when connecting. Alias: `--user`."
        },
        {
            "name": "--password",
            "short": "-p",
            "value": "<PASSWORD>",
            "env": "SURREAL_PASS",
            "description": "Database authentication password to use when connecting. Alias: `--pass`."
        },
        {
            "name": "--token",
            "short": "-t",
            "value": "<TOKEN>",
            "env": "SURREAL_TOKEN",
            "description": "Authentication token in JWT format, used instead of a username and password."
        },
        {
            "name": "--auth-level",
            "value": "<AUTH_LEVEL>",
            "default": "root",
            "env": "SURREAL_AUTH_LEVEL",
            "description": "Level on which the authenticating user is defined. Possible values: `root`, `namespace` (`ns`), `database` (`db`)."
        },
        {
            "name": "--namespace",
            "value": "<NAMESPACE>",
            "env": "SURREAL_NAMESPACE",
            "required": true,
            "description": "The namespace to import the model into. Alias: `--ns`."
        },
        {
            "name": "--database",
            "value": "<DATABASE>",
            "env": "SURREAL_DATABASE",
            "required": true,
            "description": "The database to import the model into. Alias: `--db`."
        },
        {
            "name": "--log",
            "short": "-l",
            "value": "<LOG>",
            "default": "info",
            "env": "SURREAL_LOG",
            "description": "The logging level for the command-line tool. Possible values: `none`, `full`, `error`, `warn`, `info`, `debug`, `trace`."
        }
    ]}
/>

### Example usage

To import a model from a local file, in a terminal run the `surreal db ml import` command with the required arguments.

```bash
surreal db ml import --endpoint http://localhost:8000 --user root --pass secret \
  --ns main --db main my-surrealml-model.surml
```

Using token-based authentication:

```bash
surreal db ml import --endpoint http://localhost:8000 --token <token> --ns main --db main my-surrealml-model.surml
```

### Command help

To see the help information and usage instructions, in a terminal run the `surreal db ml import --help` command without any further arguments. This command gives general information on the arguments, inputs, and additional options for the `ml import` command.

```bash
surreal db ml import --help
```

The output of the above command:

```text
Import a SurrealML model into an existing database

Usage: surreal ml import [OPTIONS] --namespace <NAMESPACE> --database <DATABASE> <FILE>

Arguments:
  <FILE>  Path to the SurrealML file to import

Options:
  -e, --endpoint <ENDPOINT>      Remote database server url to connect to [default: ws://localhost:8000]
  -u, --username <USERNAME>      Database authentication username to use when connecting [env: SURREAL_USER] [alias: --user]
  -p, --password <PASSWORD>      Database authentication password to use when connecting [env: SURREAL_PASS] [alias: --pass]
  -t, --token <TOKEN>            Authentication token in JWT format to use when connecting [env: SURREAL_TOKEN]
      --auth-level <AUTH_LEVEL>  Level on which the authenticating user is defined [env: SURREAL_AUTH_LEVEL] [default: root] [possible
                                 values: root, namespace, ns, database, db]
      --namespace <NAMESPACE>    The namespace selected for the operation [env: SURREAL_NAMESPACE] [alias: --ns]
      --database <DATABASE>      The database selected for the operation [env: SURREAL_DATABASE] [alias: --db]
  -h, --help                     Print help

Logging:
  -l, --log <LOG>                              The logging level for the command-line tool [env: SURREAL_LOG] [default: info] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-format <LOG_FORMAT>                The format for terminal log output [env: SURREAL_LOG_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-socket <LOG_SOCKET>                Send logs to the specified host:port [env: SURREAL_LOG_SOCKET]
      --log-file-level <LOG_FILE_LEVEL>        Override the logging level for file output [env: SURREAL_LOG_FILE_LEVEL] [possible values:
                                               none, full, error, warn, info, debug, trace]
      --log-otel-level <LOG_OTEL_LEVEL>        Override the logging level for OpenTelemetry output [env: SURREAL_LOG_OTEL_LEVEL] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-socket-level <LOG_SOCKET_LEVEL>    Override the logging level for unix socket output [env: SURREAL_LOG_SOCKET_LEVEL] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-socket-format <LOG_SOCKET_FORMAT>  The format for socket output [env: SURREAL_LOG_SOCKET_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-file-enabled                       Whether to enable log file output [env: SURREAL_LOG_FILE_ENABLED]
      --log-file-path <LOG_FILE_PATH>          The directory where log files will be stored [env: SURREAL_LOG_FILE_PATH] [default: logs]
      --log-file-name <LOG_FILE_NAME>          The name of the log file [env: SURREAL_LOG_FILE_NAME] [default: surrealdb.log]
      --log-file-format <LOG_FILE_FORMAT>      The format for log file output [env: SURREAL_LOG_FILE_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-file-rotation <LOG_FILE_ROTATION>  The log file rotation interval [env: SURREAL_LOG_FILE_ROTATION] [default: daily] [possible
                                               values: daily, hourly, never]
```

---

Source: https://surrealdb.com/docs/reference/cli/db/commands/sql

# sql

Open a SurrealQL REPL, or pipe queries in from a script.

Start a SurrealQL REPL in your terminal with the [installed](/docs/reference/cli/guides/install.md) `surreal` CLI, with pipe support for one-shot queries.

<Synopsis>
surreal db sql [OPTIONS]
</Synopsis>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--endpoint",
            "short": "-e",
            "value": "<ENDPOINT>",
            "default": "ws://localhost:8000",
            "description": "Remote database server URL to connect to, or an embedded storage path such as `memory` or `surrealkv://mydb`."
        },
        {
            "name": "--username",
            "short": "-u",
            "value": "<USERNAME>",
            "env": "SURREAL_USER",
            "description": "Database authentication username to use when connecting. Alias: `--user`."
        },
        {
            "name": "--password",
            "short": "-p",
            "value": "<PASSWORD>",
            "env": "SURREAL_PASS",
            "description": "Database authentication password to use when connecting. Alias: `--pass`."
        },
        {
            "name": "--token",
            "short": "-t",
            "value": "<TOKEN>",
            "env": "SURREAL_TOKEN",
            "description": "Authentication token in JWT format, used instead of a username and password. Cannot be combined with `--username`, `--password` or `--auth-level`."
        },
        {
            "name": "--auth-level",
            "value": "<AUTH_LEVEL>",
            "default": "root",
            "env": "SURREAL_AUTH_LEVEL",
            "description": "Level on which the authenticating user is defined. Possible values: `root`, `namespace` (`ns`), `database` (`db`)."
        },
        {
            "name": "--namespace",
            "value": "<NAMESPACE>",
            "env": "SURREAL_NAMESPACE",
            "description": "The namespace to select. Alias: `--ns`. Defaults to `main` from SurrealDB 3.0."
        },
        {
            "name": "--database",
            "value": "<DATABASE>",
            "env": "SURREAL_DATABASE",
            "description": "The database to select. Alias: `--db`. Defaults to `main` from SurrealDB 3.0."
        },
        {
            "name": "--pretty",
            "description": "Whether database responses should be pretty printed."
        },
        {
            "name": "--json",
            "description": "Whether to emit results in JSON."
        },
        {
            "name": "--multi",
            "description": "Whether omitting a semicolon causes a newline instead of submitting the statement."
        },
        {
            "name": "--hide-welcome",
            "env": "SURREAL_HIDE_WELCOME",
            "description": "Whether to hide the welcome message, which is useful when piping statements in."
        },
        {
            "name": "--allow-experimental",
            "value": "<TARGETS>",
            "env": "SURREAL_CAPS_ALLOW_EXPERIMENTAL",
            "description": "Experimental capabilities to enable, as a comma-separated list. Possible values: `surrealism`, `kvexport`."
        },
        {
            "name": "--deny-experimental",
            "value": "<TARGETS>",
            "env": "SURREAL_CAPS_DENY_EXPERIMENTAL",
            "description": "Experimental capabilities to deny, as a comma-separated list. A capability in both this list and `--allow-experimental` is denied."
        },
        {
            "name": "--log",
            "short": "-l",
            "value": "<LOG>",
            "default": "info",
            "env": "SURREAL_LOG",
            "description": "The logging level for the command-line tool. Possible values: `none`, `full`, `error`, `warn`, `info`, `debug`, `trace`."
        }
    ]}
/>

`surreal db sql` also accepts the capability flags shown under `Capabilities` in the [command help](#command-help) - `--allow-all`, `--allow-funcs`, `--deny-net`, and the rest. Where they take effect depends on how you connect; see [Capabilities and remote connections](#capabilities-and-remote-connections).

## Example usage

To start an interactive REPL, run the `surreal db sql` command with the required arguments. Once you see the `>` character you can type SurrealQL, followed by the `enter` key. The command has support for `↑` and `↓` arrows for selecting previous SQL statements, and stores the statement history in a `history.txt` file. To exit the REPL, use the `ctrl + c` or `ctrl + d` key combinations.

```bash
surreal db sql --endpoint http://localhost:8000 --namespace main --database main --auth-level root --username username --password password
```

For a one-shot query without staying in the REPL, pipe SurrealQL into `surreal db sql`. This is only for a small number of statements; for larger scripts use the [import command](/docs/reference/cli/db/commands/import.md).

**Bash**

```bash
echo 'INFO FOR DB;' | surreal db sql --endpoint http://localhost:8000 --username root --password secret --namespace main --database main --pretty --hide-welcome
```

**PowerShell**

```powershell
'INFO FOR DB;' | surreal db sql --endpoint http://localhost:8000 --username root --password secret --namespace main --database main --pretty --hide-welcome
```

You can also pipe a file:

```bash
cat myfile.surql | surreal db sql --endpoint http://localhost:8000 --username root --password secret --namespace main --database main
```

### Default namespace and database

_(since v3.0.0)_

As the `surreal db start` command defaults to defining a namespace and database by the name `main` upon starting up, the `surreal db sql` command also connects to these two by default. As such, a command like `surreal db sql --user root --pass secret` or even just `surreal db sql` (for an instance with authentication disabled) is all that is needed to connect and begin using an instance via the CLI.

A [`USE`](/docs/reference/query-language/statements/use.md) statement changes the namespace and database for every statement after it in the same session, in the REPL and in piped input, so it does not need to be repeated on each line. The REPL prompt shows the current namespace and database, and the `USE` statement itself [returns them](/docs/reference/query-language/statements/use.md#value-returned-by-use-statement):

```text
main/main> USE NS shop DB sales;
[{ database: 'sales', namespace: 'shop' }]

shop/sales> CREATE person:one;
[[{ id: person:one }]]
```

## Using environment variables

> [!IMPORTANT]
> Most of the flags above have a corresponding [environment variable](/docs/reference/cli/db/environment-variables.md#command-environment-variables).
> For example, the `--database` flag can be configured with the `SURREAL_DATABASE` environment variable instead.

When using the `surreal db sql` command, you can also use environment variables to set the values for the command-line flags.

For more on the environment variables available for CLI commands or SurrealDB instances in general, see the [environment variables](/docs/reference/cli/db/environment-variables.md#command-environment-variables) page.

## `--auth-level` option

The `--auth-level` option sets the authentication level to use when connecting to the database. The option has three possible values: `root`, `namespace`, and `database`. The `root` value is the highest level of authentication, while the `namespace` and `database` values are used for authenticating as users defined on a specific namespace or database.

There are a few things to keep in mind when using the `--auth-level` option:

- The `root` value is used to access the database server as a root user, and if not specified is the default value.

```bash
surreal db sql --endpoint http://localhost:8000 --namespace main --database main --auth-level root --username username --password password
```

- The `namespace` value is used for accessing a specific namespace and all databases within that namespace. When this level is specified, a namespace must be provided via `--namespace`.

```bash
surreal db sql --endpoint http://localhost:8000 --namespace main --database main --auth-level namespace --username username --password password
```

- The `database` value is used for accessing a specific database within a namespace. When this level is specified, a namespace and a database must be provided via `--namespace` and `--database`.

```bash
surreal db sql --endpoint http://localhost:8000 --namespace main --database main --auth-level database --username username --password password
```

## `--token` option

The `--token` option sets the authentication token to use when connecting to the server. This option allows you to connect to SurrealDB using a JWT instead of user credentials. The token is used to authenticate the user and provide access to the database server which means it cannot be provided at the same time as `--username`, `--password` or `--auth-level`.

```bash
surreal db sql --endpoint http://localhost:8000 --namespace main --database main --token <token>
```

## Capabilities and remote connections

Both `surreal db sql` and [`surreal db start`](/docs/reference/cli/db/commands/start.md) accept the same capability flags (`--allow-funcs`, `--allow-eval-query`, `--allow-experimental`, and so on). **Where those flags take effect depends on how you connect.**

| Connection | Examples | Where capabilities are enforced |
| --- | --- | --- |
| **Remote server** | `ws://localhost:8000`, `http://…`, `grpc://…` with sign-in | On the **server** process started with `surreal db start` |
| **Embedded engine** | `memory`, `surrealkv://…` (no separate server) | On the **`surreal db sql` process** itself |

> [!NOTE]
> `grpc://` and `grpcs://` endpoints are accepted from SurrealDB 3.3.0. The server always mounts the gRPC transport, and the `surreal` binary now ships the client, so `surreal db sql --endpoint grpc://127.0.0.1:8000` connects without a custom build. On earlier versions the endpoint was rejected as an invalid connection string or an invalid URI.

When you use `surreal db sql` against a **running instance**, flags on the REPL command do **not** change what the server allows at execution time. Configure [`surreal db start`](/docs/reference/cli/db/commands/start.md) (or the server's environment variables) instead - including for [`eval::*`](/docs/reference/query-language/functions/database-functions/eval.md), arbitrary-query gates, and experimental features such as extensions (CLI flag: `surrealism`).

Capability flags on `surreal db sql` still matter in two cases:

- **Embedded storage** - there is no separate server; pass the flags on `surreal db sql` directly.
- **REPL syntax validation** - the client uses its capability set when checking whether a line parses before you submit it. That can affect experimental syntax in the prompt; it is **not** the security boundary for remote execution.

## Connecting to a Cloud instance

`surreal cloud instance sql <name>` wraps this command: it resolves the endpoint and credentials of a SurrealDB Cloud instance and then hands off to `surreal db sql`, passing through any flags given after `--`. Everything on this page applies to that session. See the [surreal cloud reference](/docs/reference/cli/cloud.md) for the control-plane side.

## Experimental capabilities

> [!NOTE]
> The experimental capability is completely hidden in the CLI help command, and `--allow-all` will not enable the experimental capabilities by default.

To use experimental capabilities, set the `SURREAL_CAPS_ALLOW_EXPERIMENTAL` [environment variable](/docs/reference/cli/db/environment-variables.md) to the experimental capability you want to allow.

For **embedded** `surreal db sql` (for example `surreal db sql memory`), set the variable or flag on the REPL command. For a **remote** server, set it on [`surreal db start`](/docs/reference/cli/db/commands/start.md#experimental-capabilities) instead - see [Capabilities and remote connections](#capabilities-and-remote-connections).

For example, to use [SurrealDB extensions](/docs/learn/extensions/plugins/overview.md) in an embedded session:

**Bash**

```bash
SURREAL_CAPS_ALLOW_EXPERIMENTAL=surrealism surreal db sql ...
```

**PowerShell**

```powershell
$env:SURREAL_CAPS_ALLOW_EXPERIMENTAL = "surrealism"
surreal db sql ...
```

or, using the `--allow-experimental` flag:

```bash
surreal db sql -e [CONNECTION_STRING] --allow-experimental surrealism
```

Multiple experimental capabilities can be enabled by separating them with a comma.

**Bash**

```bash
SURREAL_CAPS_ALLOW_EXPERIMENTAL=surrealism,kvexport surreal db sql ...

-- OR

surreal db sql -e [CONNECTION_STRING] --allow-experimental surrealism,kvexport
```

**PowerShell**

```powershell
$env:SURREAL_CAPS_ALLOW_EXPERIMENTAL = "surrealism,kvexport"
surreal db sql ...

-- OR

surreal db sql -e [CONNECTION_STRING] --allow-experimental surrealism,kvexport
```

The current experimental targets are `surrealism` and `kvexport`. [ISO GQL](/docs/learn/querying/gql/overview.md) is enabled by default from 3.3.0, and buckets and files are enabled by default from 4.0, so neither uses an experimental target. From 4.0, the tags `gql` and `files` are refused as invalid names, so the command does not start. 3.3 accepted `gql` and ignored it, and needed `files` to use buckets and files.

| Example feature/statement | Tag |
| --- | --- |
| [DEFINE EXTENSION](/docs/reference/query-language/statements/define/extension.md) | `surrealism` |

> [!NOTE]
> When connecting to a **remote** server (`ws://`, `http://`, …), experimental features are enforced on the server. Configure them with [`surreal db start`](/docs/reference/cli/db/commands/start.md#experimental-capabilities) (or the server's `SURREAL_CAPS_ALLOW_EXPERIMENTAL`). Flags on `surreal db sql` only affect [embedded connections](#capabilities-and-remote-connections) or REPL parse validation. From 3.3.0, [ISO GQL](/docs/learn/querying/gql/overview.md) does not need an experimental flag; `eval::gql` still needs [`--allow-eval-query`](/docs/learn/security/authorization/capabilities.md#eval-queries) on the server.

## Command help

To see the help information and usage instructions, in a terminal run the `surreal db sql --help` command without any further arguments. This command gives general information on the arguments, inputs, and additional options for the `sql` command.

```bash
surreal db sql --help
```

The output of the above command:

```text
Start an SQL REPL in your terminal with pipe support

Usage: surreal sql [OPTIONS]

Options:
  -e, --endpoint <ENDPOINT>
          Remote database server url to connect to

          [default: ws://localhost:8000]

  -u, --username <USERNAME>
          Database authentication username to use when connecting

          [env: SURREAL_USER]
          [alias: --user]

  -p, --password <PASSWORD>
          Database authentication password to use when connecting

          [env: SURREAL_PASS]
          [alias: --pass]

  -t, --token <TOKEN>
          Authentication token in JWT format to use when connecting

          [env: SURREAL_TOKEN]

      --auth-level <AUTH_LEVEL>
          Level on which the authenticating user is defined

          [env: SURREAL_AUTH_LEVEL]
          [default: root]
          [possible values: root, namespace, ns, database, db]

      --namespace <NAMESPACE>
          The selected namespace

          [env: SURREAL_NAMESPACE]
          [alias: --ns]

      --database <DATABASE>
          The selected database

          [env: SURREAL_DATABASE]
          [alias: --db]

      --pretty
          Whether database responses should be pretty printed

      --json
          Whether to emit results in JSON

      --multi
          Whether omitting semicolon causes a newline

      --hide-welcome
          Whether to show welcome message

          [env: SURREAL_HIDE_WELCOME]

  -h, --help
          Print help (see a summary with '-h')

Capabilities:
  -A, --allow-all
          Allow all capabilities except for those more specifically denied

          [env: SURREAL_CAPS_ALLOW_ALL]

      --allow-scripting
          Allow execution of embedded scripting functions

          [env: SURREAL_CAPS_ALLOW_SCRIPT]

      --allow-guests
          Allow guest users to execute queries

          [env: SURREAL_CAPS_ALLOW_GUESTS]

      --allow-funcs [<ALLOW_FUNCS>...]
          Allow execution of all functions except for functions that are specifically denied. Alternatively, you can provide a
          comma-separated list of function names to allow
          Specifically denied functions and function families prevail over any other allowed function execution.
          Function names must be in the form <family>[::<name>]. For example:
           - 'http' or 'http::*' -> Include all functions in the 'http' family
           - 'http::get' -> Include only the 'get' function in the 'http' family

          [env: SURREAL_CAPS_ALLOW_FUNC]

      --allow-arbitrary-query [<ALLOW_ARBITRARY_QUERY>...]
          Allow execution of arbitrary queries by certain user groups except when specifically denied. Alternatively, you can provide a
          comma-separated list of user groups to allow
          Specifically denied user groups prevail over any other allowed user group.
          User groups must be one of "guest", "record" or "system".

          [env: SURREAL_CAPS_ALLOW_ARBITRARY_QUERY]

      --allow-eval-query [<ALLOW_EVAL_QUERY>...]
          Allow the eval::surql / eval::gql functions to be invoked by certain user groups. Provide a comma-separated list of user groups to
          allow. This is an additive gate on top of arbitrary-query: an eval invocation must also satisfy the arbitrary-query capability.
          Specifically denied user groups prevail over any other allowed user group.
          User groups must be one of "guest", "record" or "system".
          Denied for everyone by default (even under --allow-all); must be explicitly enabled.

          [env: SURREAL_CAPS_ALLOW_EVAL_QUERY]

      --allow-net [<ALLOW_NET>...]
          Allow all outbound network connections except for network targets that are specifically denied. Alternatively, you can provide a
          comma-separated list of network targets to allow
          Specifically denied network targets prevail over any other allowed outbound network connections.
          Targets must be in the form of <host>[:<port>], *.<domain>[:<port>], <ipv4|ipv6>[/<mask>]. For example:
           - 'surrealdb.com', '127.0.0.1' or 'fd00::1' -> Match outbound connections to these hosts on any port
           - 'surrealdb.com:80', '127.0.0.1:80' or 'fd00::1:80' -> Match outbound connections to these hosts on port 80
           - '*.surrealdb.com' -> Match outbound connections to any subdomain of surrealdb.com (such as 'api.surrealdb.com' or
           'a.b.surrealdb.com', but not 'surrealdb.com' itself) on any port
           - '*.surrealdb.com:443' -> Match outbound connections to any subdomain of surrealdb.com on port 443
           - '10.0.0.0/8' or 'fd00::/8' -> Match outbound connections to any host in these networks
          A wildcard is only allowed as the whole leftmost label and must be followed by a domain of at least two labels; it never matches
          an IP address.

          [env: SURREAL_CAPS_ALLOW_NET]

      --allow-rpc [<ALLOW_RPC>...]
          Allow all RPC methods to be called except for routes that are specifically denied. Alternatively, you can provide a
          comma-separated list of RPC methods to allow.

          [env: SURREAL_CAPS_ALLOW_RPC]
          [default: ""]

      --allow-http [<ALLOW_HTTP>...]
          Allow all HTTP routes to be requested except for routes that are specifically denied. Alternatively, you can provide a
          comma-separated list of HTTP routes to allow.

          [env: SURREAL_CAPS_ALLOW_HTTP]
          [default: ""]

      --allow-mcp [<ALLOW_MCP>...]
          Allow all MCP tools to be called except for tools that are specifically denied. Alternatively, you can provide a comma-separated
          list of MCP tool names to allow.

          [env: SURREAL_CAPS_ALLOW_MCP]
          [default: ""]

  -D, --deny-all
          Deny all capabilities except for those more specifically allowed

          [env: SURREAL_CAPS_DENY_ALL]

      --deny-scripting
          Deny execution of embedded scripting functions

          [env: SURREAL_CAPS_DENY_SCRIPT]

      --deny-guests
          Deny guest users to execute queries

          [env: SURREAL_CAPS_DENY_GUESTS]

      --deny-funcs [<DENY_FUNCS>...]
          Deny execution of all functions except for functions that are specifically allowed. Alternatively, you can provide a
          comma-separated list of function names to deny.
          Specifically allowed functions and function families prevail over a general denial of function execution.
          Function names must be in the form <family>[::<name>]. For example:
           - 'http' or 'http::*' -> Include all functions in the 'http' family
           - 'http::get' -> Include only the 'get' function in the 'http' family

          [env: SURREAL_CAPS_DENY_FUNC]

      --deny-arbitrary-query [<DENY_ARBITRARY_QUERY>...]
          Deny execution of arbitrary queries by certain user groups except when specifically allowed. Alternatively, you can provide a
          comma-separated list of user groups to deny
          Specifically allowed user groups prevail over a general denial of user group.
          User groups must be one of "guest", "record" or "system".

          [env: SURREAL_CAPS_DENY_ARBITRARY_QUERY]

      --deny-eval-query [<DENY_EVAL_QUERY>...]
          Deny the eval::surql / eval::gql functions for certain user groups. Provide a comma-separated list of user groups to deny.
          Specifically denied user groups prevail over any allowed user group.
          User groups must be one of "guest", "record" or "system".

          [env: SURREAL_CAPS_DENY_EVAL_QUERY]

      --deny-net [<DENY_NET>...]
          Deny all outbound network connections except for network targets that are specifically allowed. Alternatively, you can provide a
          comma-separated list of network targets to deny.
          Specifically allowed network targets prevail over a general denial of outbound network connections.
          Targets must be in the form of <host>[:<port>], *.<domain>[:<port>], <ipv4|ipv6>[/<mask>]. For example:
           - 'surrealdb.com', '127.0.0.1' or 'fd00::1' -> Match outbound connections to these hosts on any port
           - 'surrealdb.com:80', '127.0.0.1:80' or 'fd00::1:80' -> Match outbound connections to these hosts on port 80
           - '*.surrealdb.com' -> Match outbound connections to any subdomain of surrealdb.com (such as 'api.surrealdb.com' or
           'a.b.surrealdb.com', but not 'surrealdb.com' itself) on any port
           - '*.surrealdb.com:443' -> Match outbound connections to any subdomain of surrealdb.com on port 443
           - '10.0.0.0/8' or 'fd00::/8' -> Match outbound connections to any host in these networks
          A wildcard is only allowed as the whole leftmost label and must be followed by a domain of at least two labels; it never matches
          an IP address.

          [env: SURREAL_CAPS_DENY_NET]

      --deny-rpc [<DENY_RPC>...]
          Deny all RPC methods from being called except for methods that are specifically allowed. Alternatively, you can provide a
          comma-separated list of RPC methods to deny.

          [env: SURREAL_CAPS_DENY_RPC]

      --deny-http [<DENY_HTTP>...]
          Deny all HTTP routes from being requested except for routes that are specifically allowed. Alternatively, you can provide a
          comma-separated list of HTTP routes to deny.

          [env: SURREAL_CAPS_DENY_HTTP]

      --deny-mcp [<DENY_MCP>...]
          Deny all MCP tools from being called except for tools that are specifically allowed. Alternatively, you can provide a
          comma-separated list of MCP tool names to deny.

          [env: SURREAL_CAPS_DENY_MCP]

Logging:
  -l, --log <LOG>
          The logging level for the command-line tool

          [env: SURREAL_LOG]
          [default: info]
          [possible values: none, full, error, warn, info, debug, trace]

      --log-format <LOG_FORMAT>
          The format for terminal log output

          [env: SURREAL_LOG_FORMAT]
          [default: text]
          [possible values: text, json]

      --log-socket <LOG_SOCKET>
          Send logs to the specified host:port

          [env: SURREAL_LOG_SOCKET]

      --log-file-level <LOG_FILE_LEVEL>
          Override the logging level for file output

          [env: SURREAL_LOG_FILE_LEVEL]
          [possible values: none, full, error, warn, info, debug, trace]

      --log-otel-level <LOG_OTEL_LEVEL>
          Override the logging level for OpenTelemetry output

          [env: SURREAL_LOG_OTEL_LEVEL]
          [possible values: none, full, error, warn, info, debug, trace]

      --log-socket-level <LOG_SOCKET_LEVEL>
          Override the logging level for unix socket output

          [env: SURREAL_LOG_SOCKET_LEVEL]
          [possible values: none, full, error, warn, info, debug, trace]

      --log-socket-format <LOG_SOCKET_FORMAT>
          The format for socket output

          [env: SURREAL_LOG_SOCKET_FORMAT]
          [default: text]
          [possible values: text, json]

      --log-file-enabled
          Whether to enable log file output

          [env: SURREAL_LOG_FILE_ENABLED]

      --log-file-path <LOG_FILE_PATH>
          The directory where log files will be stored

          [env: SURREAL_LOG_FILE_PATH]
          [default: logs]

      --log-file-name <LOG_FILE_NAME>
          The name of the log file

          [env: SURREAL_LOG_FILE_NAME]
          [default: surrealdb.log]

      --log-file-format <LOG_FILE_FORMAT>
          The format for log file output

          [env: SURREAL_LOG_FILE_FORMAT]
          [default: text]
          [possible values: text, json]

      --log-file-rotation <LOG_FILE_ROTATION>
          The log file rotation interval

          [env: SURREAL_LOG_FILE_ROTATION]
          [default: daily]
          [possible values: daily, hourly, never]
```

---

Source: https://surrealdb.com/docs/reference/cli/db/commands/start

# start

Run a server in memory, on disk, or as a node in a cluster.

The start command starts a SurrealDB server in memory, on disk, or in a distributed setup, using the [installed](/docs/reference/cli/guides/install.md) `surreal` CLI.

This page is divided into two views: the details of the `surreal db start` command itself, and a builder that creates a command based on the options you choose.

**surreal db start details**

<Synopsis>
surreal db start [OPTIONS] [PATH]
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[PATH]",
            "default": "memory",
            "env": "SURREAL_PATH",
            "description": "Where the server stores data. Combine a backend name with `:` or `://` and an address or filename, for example `surrealkv://mydb` or `surrealkv:database`. See the Positional argument section below."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--bind",
            "short": "-b",
            "value": "<LISTEN_ADDRESSES>",
            "default": "127.0.0.1:8000",
            "env": "SURREAL_BIND",
            "description": "The hostname or IP address to listen for connections on."
        },
        {
            "name": "--postgres-bind",
            "description": "The hostname or IP address to listen for Postgres wire protocol connections on, for example `127.0.0.1:5432`. The listener is disabled when omitted."
        },
        {
            "name": "--mysql-bind",
            "env": "SURREAL_MYSQL_BIND",
            "description": "From SurrealDB 4.0, the hostname or IP address to listen for MySQL wire protocol connections on, for example `127.0.0.1:3306`. The listener is disabled when omitted."
        },
        {
            "name": "--client-ip",
            "value": "<CLIENT_IP>",
            "default": "socket",
            "env": "SURREAL_CLIENT_IP",
            "description": "The method of detecting the client's IP address. Possible values: `none`, `socket`, `CF-Connecting-IP`, `Fly-Client-IP`, `True-Client-IP`, `X-Real-IP`, `X-Forwarded-For`, `Forwarded`."
        },
        {
            "name": "--import-file",
            "value": "<IMPORT_FILE>",
            "env": "SURREAL_IMPORT_FILE",
            "description": "Path to a SurrealQL (`.surql`) file that is imported when starting the server."
        },
        {
            "name": "--username",
            "short": "-u",
            "value": "<USERNAME>",
            "env": "SURREAL_USER",
            "description": "The username for the initial database root user, applied only if no other root user exists. An empty value, or one made only of whitespace, is refused. Alias: `--user`."
        },
        {
            "name": "--password",
            "short": "-p",
            "value": "<PASSWORD>",
            "env": "SURREAL_PASS",
            "description": "The password for the initial database root user, applied only if no other root user exists. An empty value, or one made only of whitespace, is refused. Alias: `--pass`."
        },
        {
            "name": "--default-namespace",
            "value": "<DEFAULT_NAMESPACE>",
            "env": "SURREAL_DEFAULT_NAMESPACE",
            "default": "main",
            "description": "The namespace to create when the datastore is new."
        },
        {
            "name": "--default-database",
            "value": "<DEFAULT_DATABASE>",
            "env": "SURREAL_DEFAULT_DATABASE",
            "default": "main",
            "description": "The database to create in that namespace when the datastore is new."
        },
        {
            "name": "--no-defaults",
            "env": "SURREAL_NO_DEFAULTS",
            "description": "Create no namespace or database when the datastore is new."
        },
        {
            "name": "--unauthenticated",
            "env": "SURREAL_UNAUTHENTICATED",
            "description": "Whether to allow unauthenticated access. See Unauthenticated mode below."
        },
        {
            "name": "--no-identification-headers",
            "env": "SURREAL_NO_IDENTIFICATION_HEADERS",
            "description": "Whether to suppress the server name and version headers."
        },
        {
            "name": "--allow-origin",
            "value": "<ALLOW_ORIGIN>",
            "env": "SURREAL_ALLOW_ORIGIN",
            "description": "The origins allowed to make cross-origin (CORS) requests, as a comma-separated list. When it is not set, every origin is allowed. When it lists origins and no `*`, a WebSocket connection to `/rpc` that sends an `Origin` header is accepted only from a listed origin or with `Sec-Fetch-Site: same-origin`, and is otherwise refused with `403`. A client that sends no `Origin` header, which is usual outside a browser, is not affected."
        },
        {
            "name": "--cookie-auth",
            "env": "SURREAL_COOKIE_AUTH",
            "default": "false",
            "description": "From 4.0.0. Issue the access token as an `HttpOnly` cookie through `/signin/cookie` and `/signup/cookie`, and accept the cookie from the origins in `--allow-origin`. When the record access method has `WITH REFRESH`, the refresh token is issued as a second `HttpOnly` cookie, and `POST /refresh/cookie` rotates both. The cookies are `Secure`, so a browser stores them only over HTTPS or on a loopback address. Requires an `--allow-origin` list without `*`. See "Cookie authentication" in the HTTP protocol reference."
        },
        {
            "name": "--temporary-directory",
            "value": "<TEMPORARY_DIRECTORY>",
            "env": "SURREAL_TEMPORARY_DIRECTORY",
            "description": "The directory for storing temporary database files, including the files that queries spill to when they pass their memory budget. From 4.0.0 it defaults to a `surrealdb` folder in the system temporary directory, and a value that is not a directory is refused at startup."
        },
        {
            "name": "--allow-experimental",
            "value": "<TARGETS>",
            "env": "SURREAL_CAPS_ALLOW_EXPERIMENTAL",
            "description": "Experimental capabilities to enable, as a comma-separated list. Possible values from 4.0: `surrealism`, `kvexport`. On 3.x the values are `files`, `surrealism` and `gql`, and the server refuses to start with `kvexport`; 4.0 refuses `files` and `gql`. Takes several values, so use `--allow-experimental=surrealism,kvexport` when a storage path follows it."
        },
        {
            "name": "--deny-experimental",
            "value": "<TARGETS>",
            "env": "SURREAL_CAPS_DENY_EXPERIMENTAL",
            "description": "Experimental capabilities to deny, as a comma-separated list. A capability in both this list and `--allow-experimental` is denied."
        },
        {
            "name": "--durable-sessions",
            "env": "SURREAL_DURABLE_SESSIONS",
            "description": "Has no effect from 4.0.0, where every attached HTTP RPC session is stored in the datastore. The flag is still accepted, and logs a deprecation warning. Before 4.0.0 it turns on durable sessions, which are off by default."
        },
        {
            "name": "--durable-session-ttl",
            "value": "<DURABLE_SESSION_TTL>",
            "default": "24h",
            "env": "SURREAL_DURABLE_SESSION_TTL",
            "description": "Idle lifetime of an attached HTTP RPC session before it expires. Each use refreshes the expiry."
        },
        {
            "name": "--durable-session-gc-interval",
            "value": "<DURABLE_SESSION_GC_INTERVAL>",
            "default": "1h",
            "env": "SURREAL_DURABLE_SESSION_GC_INTERVAL",
            "description": "Interval for purging expired attached HTTP RPC sessions from the datastore. Set `0` to disable the sweep. The default is `60s` before 4.0.0."
        },
        {
            "name": "--log",
            "short": "-l",
            "value": "<LOG>",
            "default": "info",
            "env": "SURREAL_LOG",
            "description": "The logging level for the database server. Possible values: `none`, `full`, `error`, `warn`, `info`, `debug`, `trace`. In a release build, `trace` and `full` give the same output as `debug`, because the TRACE level is compiled only into debug builds."
        }
    ]}
/>

The root user from `--username` and `--password`, and the default namespace and database, are created only when the datastore is new, and are stored in it. Starting the same datastore again with other values changes nothing: the existing root user keeps its password, and no new namespace or database is created. To change the password of an existing root user, use [`ALTER USER`](/docs/reference/query-language/statements/alter/user.md) or [`DEFINE USER OVERWRITE`](/docs/reference/query-language/statements/define/user.md).

`surreal db start` has more options than any other subcommand, and the table above covers the ones described on this page. The remaining groups - database tuning, datastore TLS, HTTP server, capabilities, and logging - are listed in full in the [command help](#command-help) below, and mapped to their variables on the [environment variables](/docs/reference/cli/db/environment-variables.md) page.

Three of the flags above are documented in more detail elsewhere: `--postgres-bind` exposes the [Postgres wire protocol](/docs/reference/protocols/postgres-protocol.md), `--mysql-bind` exposes the [MySQL wire protocol](/docs/reference/protocols/mysql-protocol.md), and the `--durable-*` flags are explained under [Durable HTTP RPC sessions](#durable-http-rpc-sessions). From SurrealDB 3.1, the `Forwarded` value for `--client-ip` reads the RFC 7239 `Forwarded` header.

The `--query-timeout` flag in the [command help](#command-help) sets the maximum duration that a batch of statements can run for, and is off by default. From 3.3.0 the same value is also a hard wall-clock limit on each HTTP `/sql`, `/gql` and `/graphql` request and on each RPC method call. An HTTP `/sql` or `/gql` request that exceeds it is answered with `504 Gateway Timeout`, and a `/graphql` request with a GraphQL error. The `begin`, `commit` and `cancel` RPC methods are exempt, but the calls made inside the transaction they control are still limited individually. See [`SURREAL_QUERY_TIMEOUT`](/docs/reference/cli/db/environment-variables.md#command-environment-variables).

## Getting started

This example will show how to host a SurrealDB server with the `surreal db start` command, and then access the Surreal DB server using the [`surreal db sql` command](/docs/reference/cli/db/commands/sql.md).

To start a SurrealDB server, run the `surreal db start` command, using the options below. This example stores the database in memory, with a username and password, hosted at `127.0.0.1:8000` (the default location).

```bash
surreal db start memory --user my_username --pass my_password
```

The server is actively running, and can be left alone until you want to stop hosting the SurrealDB server.

> [!NOTE]
> The message "Started web server on 127.0.0.1:8000", indicates where the server is being hosted and can be accessed by clients. The location `127.0.0.1:8000` is the default, and can be manually changed by specifying the `--bind` option of the `surreal db start` command.

To access the SurrealDB server that you have started hosting, open a new terminal which will act as the client, while the previous terminal is still running the `surreal db start` command described above. This is done using a separate [`surreal db sql`](/docs/reference/cli/db/commands/sql.md) command. Ensure that the hosting location indicated by the output of the `surreal db start` command is passed to the `--endpoint` argument, and that you specify the same `--username` and `--password` as in the `surreal db start` command.

A particular namespace and database can be specified at this point, as seen below.

```bash
surreal db sql --endpoint http://127.0.0.1:8000 --namespace my_namespace \
  --database my_database --username my_username --password my_password
```

## Positional argument

> [!WARNING]
> FoundationDB support was removed in SurrealDB 3.0.0, so `fdb://` paths are only accepted by 2.x. Migrate a FoundationDB deployment to one of the backends below before upgrading.

In the `surreal db start` command, the path argument is used to specify the location of the database. If no argument is given, the default of `memory` for storage [in memory](/docs/running/in-memory.md) is assumed.

Arguments for persistent backends are a combination of the backend name, a `:` or `://`, and an address or filename - for example `surrealkv://mydb` or `surrealkv:database`. The available backends are:

**SurrealDB 4.x**

- `memory` (or no argument) for in-memory storage
- `surrealkv` for SurrealKV, the on-disk backend
- `tikv` for TiKV, in `surreal-tikv`, a separate build of the server. The `surreal` binary and the `surrealdb/surrealdb` container images do not include TiKV, and stop with an error on a `tikv://` path.

SurrealDB 4.0 removed the `rocksdb` and `indxdb` backends. The `rocksdb://` and `indxdb://` schemes are kept as deprecated spellings of `surrealkv://`: a path that names either is opened with SurrealKV, and the server logs a warning to use `surrealkv://` instead. Starting the server on a RocksDB data directory, with either scheme, converts it to SurrealKV. See [Moving a RocksDB database to SurrealKV](/docs/operate/self-hosted/deployment-models.md#moving-a-rocksdb-database-to-surrealkv).

**SurrealDB 3.x**

- `memory` (or no argument) for in-memory storage
- `surrealkv` for SurrealKV
- `rocksdb` for RocksDB, the recommended on-disk backend
- `indxdb` for IndexedDB
- `tikv` for TiKV

### Absolute vs. relative paths

The datastorage flavour (`surrealkv`, `tikv`, etc.) followed by `:` or `://` will be recognised as a relative path, which is resolved from the directory you run `surreal db start` in. Running `surreal db start surrealkv:mydb` from `/home/ann/projects` stores the data in `/home/ann/projects/mydb`, and running the same command from another directory creates a new, empty database there. Use an absolute path for a server that is started from different places, such as by a service manager. Any other number of slashes such as `surrealkv:/path` or `surrealkv:///path` will be interpreted as an absolute path. As a short absolute path of this nature will often require elevated permissions, the output for this command may end in this sort of error.

```text
There was a problem with the datastore: IO error: Read-only file system (os error 30)
```

If you see this error without having intended to start the server on an absolute path, it is likely that the path passed in unintentionally contains either one slash or more than two slashes.

> [!NOTE]
> Be sure not to point two storage backends at the same location. As storage is entirely delegated to the backend, the CLI is not aware of the structure of the data itself. While each backend uses its own file names and directory structure to store data, it is possible that data overwrite or other issues may occur. The one deliberate exception is a RocksDB directory from before 4.0, which SurrealKV converts when it opens it.

> [!IMPORTANT]
> **TiKV** (`tikv://…`) is supported for local multi-node experimentation with the Community edition. From SurrealDB 4.0 it needs the separate `surreal-tikv` build. See [TiKV runs from a separate build](/docs/operate/upgrading/3x-to-4x.md#tikv-runs-from-a-separate-build). Production multi-node HA uses distributed storage on [SurrealDB Cloud Scale](https://surrealdb.com/pricing) or [SurrealDB Enterprise](https://surrealdb.com/enterprise). See [Run a multi-node cluster](/docs/running/multi-node.md) and [Deployment](/docs/operate/self-hosted/deployment-models.md). To provision and scale those instances from a script rather than a browser, see [`surreal cloud`](/docs/reference/cli/cloud.md).

## Datastore configuration

**SurrealDB 4.x**

Configuring a datastore is done by passing in a string that begins with the datastore name, a path if persistent storage is needed, and optional parameters. Some examples:

```bash
surreal db start --user root --pass secret "surrealkv://path/to/db?versioned=true&sync=every&retention=30d"
surreal db start --user root --pass secret "mem://tmp/data?aol=sync&snapshot=60s&sync=5s"
```

Each database store supports different parameters.

### Supported parameters for Memory (SurrealMX)

The memory backend does not support versioned queries. From 3.3.0 a server started on it with `versioned=true` or a non-zero `retention`, whether through the parameters or the matching `SURREAL_DATASTORE_VERSIONED` and `SURREAL_DATASTORE_RETENTION` environment variables, fails to start. `versioned=false` and a zero retention are accepted. To use the [`VERSION` clause](/docs/reference/query-language/statements/select.md#the-version-clause), start the server on SurrealKV instead.

- `aol` (`never`, `sync`, or `async`), for writing changes to an append-only log file
- `snapshot` (a duration string, e.g. `60s`), for periodically writing a snapshot of the database to the file system
- `sync` (`never`, `every`, or a duration string like `5s`), for specifying when to flush the append-only log file to the file system
  - `never` - (default) leave flushing to the OS (least durable)
  - `every` - sync on every commit (most durable)
  - `interval` - periodic background flushing at the given interval

Persistence for the memory backend is used for the following:

- Append-Only Log (AOL) - Synchronous/asynchronous modes for durability
- Snapshots - Periodic full database state capture
- Data Recovery - Automatic recovery from snapshots + AOL on startup
- AOL Truncation - Automatic cleanup after snapshots

### Supported parameters for SurrealKV
- `versioned` (`true` or `false`)
- `retention` (a duration string, e.g. `30d`, `24h`, `30m`)
- `sync` (`never`, `every`, or a duration string like `5s`), for specifying when to flush the database to the file system
  - `every` - (default) sync each transaction to disk before it is confirmed (most durable)
  - `never` - leave flushing to the OS (least durable)
  - `interval` - periodic background flushing at the given interval

With `sync=every`, a commit becomes visible to other transactions only once it is durable on disk.

### Storage engine settings

Any setting of the storage engine can also go in the path, named without its `SURREAL_<ENGINE>_` prefix. For SurrealKV, `block_cache_capacity` sets [`SURREAL_SURREALKV_BLOCK_CACHE_CAPACITY`](/docs/reference/cli/db/environment-variables.md#surrealkv-environment-variables) and `max_memtable_size` sets `SURREAL_SURREALKV_MAX_MEMTABLE_SIZE`. This caps the block cache at 256 MiB and each memtable at 64 MiB:

```bash
surreal db start --user root --pass secret "surrealkv://path/to/db?block_cache_capacity=268435456&max_memtable_size=67108864"
```

A setting in the path takes precedence over the same setting made by an environment variable. At startup the server logs the values SurrealKV uses, as in `Setting block cache capacity: 268435456`, so the log shows which one applied.

**SurrealDB 3.x**

Configuring a datastore is done by passing in a string that begins with the datastore name, a path if persistent storage is needed, and optional parameters. Some examples:

```bash
surreal db start --user root --pass secret "surrealkv://path/to/db?versioned=true&sync=every&retention=30d"
surreal db start --user root --pass secret "rocksdb://path/to/rocksdb?versioned=true&retention=30d"
surreal db start --user root --pass secret "mem://tmp/data?aol=sync&snapshot=60s&sync=5s"
```

Each database store supports different parameters.

### Supported parameters for Memory (SurrealMX)

The memory backend does not support versioned queries. From 3.3.0 a server started on it with `versioned=true` or a non-zero `retention`, whether through the parameters or the matching `SURREAL_DATASTORE_VERSIONED` and `SURREAL_DATASTORE_RETENTION` environment variables, fails to start. `versioned=false` and a zero retention are accepted. To use the [`VERSION` clause](/docs/reference/query-language/statements/select.md#the-version-clause), start the server on SurrealKV or RocksDB instead.

- `aol` (`never`, `sync`, or `async`), for writing changes to an append-only log file
- `snapshot` (a duration string, e.g. `60s`), for periodically writing a snapshot of the database to the file system
- `sync` (`never`, `every`, or a duration string like `5s`), for specifying when to flush the append-only log file to the file system
  - `never` - (default) leave flushing to the OS (least durable)
  - `every` - sync on every commit (most durable)
  - `interval` - periodic background flushing at the given interval

Persistence for the memory backend is used for the following:

- Append-Only Log (AOL) - Synchronous/asynchronous modes for durability
- Snapshots - Periodic full database state capture
- Data Recovery - Automatic recovery from snapshots + AOL on startup
- AOL Truncation - Automatic cleanup after snapshots

### Supported parameters for SurrealKV
- `versioned` (`true` or `false`)
- `retention` (a duration string, e.g. `30d`, `24h`, `30m`)
- `sync` (`never`, `every`, or a duration string like `5s`), for specifying when to flush the database to the file system
  - `every` - (default) sync before completing and confirming each transaction (most durable)
  - `never` - leave flushing to the OS (least durable)
  - `interval` - periodic background flushing at the given interval

### Supported parameters for RocksDB
- `versioned` (`true` or `false`)
- `retention` (a duration string, e.g. `30d`, `24h`, `30m`)
- `sync` (`never`, `every`, or a duration string like `5s`), for specifying when to flush the database to the file system
  - `every` - (default) sync before completing and confirming each transaction (most durable)
  - `never` - leave flushing to the OS (least durable)
  - `interval` - periodic background flushing at the given interval

## Authentication

When starting a SurrealDB instance, authentication is enabled by default, and your user credentials will be required to connect. If you are starting a new instance, the user credentials you use to run the `start` command will [define a new root user](/docs/reference/query-language/statements/define/user.md#roles) with the [`OWNER`](/docs/reference/query-language/statements/define/user.md#roles) role.

```bash
surreal db start --user root --password secret
```

## Unauthenticated mode

> [!NOTE]
> We recommend enabling authentication when running SurrealDB in production or in publicly exposed ways. Failure to do so may result in unauthorised access.

Using the `--unauthenticated` flag, you can also start a SurrealDB instance in unauthenticated mode. By doing so, authentication will be disabled. In this mode, any guest user is considered to have the same permissions as a root user with the [`OWNER`](/docs/reference/query-language/statements/define/user.md#roles) role.

To start a SurrealDB instance in unauthenticated mode, run the following command:

```bash
surreal db start --unauthenticated
```

## Using environment variables

> [!IMPORTANT]
> Most of the flags above have a corresponding [environment variable](/docs/reference/cli/db/environment-variables.md#command-environment-variables).
> For example, the `--temporary-directory` flag can be configured with the `SURREAL_TEMPORARY_DIRECTORY` environment variable instead.

When using the `surreal db start` command, you can also use environment variables to set the values for the command-line flags. This is useful when you want to set the values for the command-line flags without having to pass them directly on the command line.

For more on the environment variables available for CLI commands or SurrealDB instances in general, see the [environment variables](/docs/reference/cli/db/environment-variables.md#command-environment-variables) page.

## Stopping the server

To stop the server, press `Ctrl+C` in its terminal, or send it `SIGTERM` (as `docker stop`, `kill` and `systemctl stop` do). Either signal starts a graceful shutdown: the server stops accepting connections, the storage engine writes out what it holds in memory, and the process exits with status `0`.

```text
WARN surrealdb::net: SIGINT received. Waiting for a graceful shutdown. A second signal will force an immediate shutdown.
INFO surrealdb::net: Web server stopped. Bye!
```

A second signal during the shutdown stops the process at once, without waiting. On a persistent backend such as SurrealKV, data from committed transactions is kept either way, subject to the backend's [`sync` setting](#datastore-configuration). On the in-memory backend, all data is lost when the process stops unless [persistence](#supported-parameters-for-memory-surrealmx) is configured.

## Enabling capabilities

> [!NOTE]
> If using SurrealDB Cloud, capabilities can be set from [SurrealDB Studio](/docs/operate/instances/configure.md#capabilities) or with [`surreal cloud`](/docs/reference/cli/cloud.md).

Capabilities arguments such as `allow-scripting` or `deny-net` can also be passed into the `surreal db start` command. These arguments, the order in which they are evaluated, and other notes on security are presented in detail in a [separate page on capabilities](/docs/learn/security/authorization/capabilities.md). From SurrealDB 4.0, the server logs the capabilities it starts with, and logs a warning at startup for `--allow-all`, guest access, scripting and network access to every target, as described in [Capabilities in the startup log](/docs/learn/security/authorization/capabilities.md#capabilities-in-the-startup-log).

A production-oriented example of the `surreal db start` command that begins with the `--deny-all` flag and only thereafter sets which capabilities will be allowed:

```bash
surreal db start --deny-all --allow-funcs "array, string, crypto::argon2, http::get" --allow-net api.example.com
```

## Strict mode

Versions before SurrealDB 3.0 contained a flag to start the entire server in strict mode. When running in strict mode, no `NAMESPACE`, `DATABASE`, or `TABLE` definitions were enacted automatically when data is inserted. Any queries would return an error if the selected namespace, database, or table were not specifically defined in advance.

```bash
surreal db start --strict --log debug memory
```

Since SurrealDB 3.0, strict mode is now enacted on the database level via a [`DEFINE DATABASE`](/docs/reference/query-language/statements/define/database.md) statement.

```surql
DEFINE DATABASE my_anything_goes_db;
DEFINE DATABASE my_strict_db STRICT;
```

## Experimental capabilities

> [!NOTE]
> The experimental capability is completely hidden in the CLI help command, and `--allow-all` will not enable the experimental capabilities by default.

To use experimental capabilities, set the `SURREAL_CAPS_ALLOW_EXPERIMENTAL` [environment variable](/docs/reference/cli/db/environment-variables.md) to the experimental capability you want to allow.

For example, to use [SurrealDB extensions](/docs/learn/extensions/plugins/overview.md), set the `SURREAL_CAPS_ALLOW_EXPERIMENTAL` environment variable to `surrealism` - or pass it in via the `--allow-experimental` flag.

**Bash**

```bash
# Allow experimental via an env var
SURREAL_CAPS_ALLOW_EXPERIMENTAL=surrealism surreal db start

# Allow experimental via a flag
surreal db start --allow-experimental surrealism
```

**PowerShell**

```powershell
# Allow experimental via an env var
$env:SURREAL_CAPS_ALLOW_EXPERIMENTAL = "surrealism"
surreal db start

# Allow experimental via a flag
surreal db start --allow-experimental surrealism
```

Multiple experimental capabilities can be enabled by separating them with a comma.

**Bash**

```bash
SURREAL_CAPS_ALLOW_EXPERIMENTAL=surrealism,kvexport surreal db start
surreal db start --allow-experimental surrealism,kvexport
```

**PowerShell**

```powershell
$env:SURREAL_CAPS_ALLOW_EXPERIMENTAL = "surrealism,kvexport"
surreal db start
surreal db start --allow-experimental surrealism,kvexport
```

`--allow-experimental` accepts several values, so a storage path written after it is read as one more capability name, and the server refuses to start with `invalid experimental target name`. Join the value to the flag with `=`, or put the path before the flag:

```bash
surreal db start --allow-experimental=surrealism,kvexport surrealkv:mydatabase.db
surreal db start surrealkv:mydatabase.db --allow-experimental surrealism,kvexport
```

> [!NOTE]
> Experimental capabilities are enforced on the **server** for remote clients. If you use [`surreal db sql`](/docs/reference/cli/db/commands/sql.md) against `ws://` or `http://`, configure flags here - not only on the REPL. See [Capabilities and remote connections](/docs/reference/cli/db/commands/sql.md#capabilities-and-remote-connections).

> [!NOTE]
> From **3.3.0**, [ISO GQL](/docs/learn/querying/gql/overview.md) is enabled by default and no longer uses an experimental capability. From 4.0, `--allow-experimental gql` is refused with `invalid experimental target name` and the server does not start, so remove `gql` from the list. On 3.3.x the tag is accepted and has no effect, and on **3.2.x** it enables GQL.

> [!NOTE]
> From 4.0, [buckets](/docs/reference/query-language/statements/define/bucket.md) and [file functions](/docs/reference/query-language/functions/database-functions/file.md) are available without an experimental capability. `files` is refused with `invalid experimental target name` in `--allow-experimental`, `--deny-experimental`, `SURREAL_CAPS_ALLOW_EXPERIMENTAL` and `SURREAL_CAPS_DENY_EXPERIMENTAL`, and the server does not start, so remove `files` from the list. Before 4.0, `files` was required to use buckets and files.

| Example feature/statement | Tag |
| --- | --- |
| [DEFINE EXTENSION](/docs/reference/query-language/statements/define/extension.md) | `surrealism` |
| The `POST /kvexport` HTTP route, which streams the stored keyspace to the root owner | `kvexport` |

## Identification headers

By default, SurrealDB includes headers in the HTTP response that identify the server name and version. You can suppress these headers by using the `--no-identification-headers` flag.

```bash
surreal db start --no-identification-headers
```

## Durable HTTP RPC sessions

_(since v3.2.2)_

**SurrealDB 4.x**

Every client-attached session on the HTTP [`/rpc`](/docs/reference/protocols/rpc-protocol.md) endpoint is stored in the datastore. A session survives a restart, and any node that shares the same storage can serve it, so a load-balanced deployment does not need sticky routing. Requests from several nodes on the same session can run at the same time: each request writes its changes back only if the stored session has not changed meanwhile, and otherwise merges them onto the newer copy.

A session expires between one and one and a half times `--durable-session-ttl` (default `24h`) after its last request. An expired session is refused when it is loaded. A background task removes expired entries from the datastore (`--durable-session-gc-interval`, default `1h`; set `0` to disable the sweep).

```bash
surreal db start --durable-session-ttl 12h surrealkv://mydb
```

The `--durable-sessions` flag and `SURREAL_DURABLE_SESSIONS` are still accepted so that existing configurations keep starting, but have no effect, and the server logs a deprecation warning. Each node keeps at most [`SURREAL_HTTP_MAX_ATTACHED_SESSIONS`](/docs/reference/cli/db/environment-variables.md#http-server-config) sessions attached through it.

> [!WARNING]
> The stored session includes its authentication state and is stored **unencrypted** in the datastore.

**SurrealDB 3.x**

Client-attached sessions on the HTTP [`/rpc`](/docs/reference/protocols/rpc-protocol.md) endpoint normally live only in the process memory of the node that created them. After a restart, or when a later request is routed to a different node, the client receives a session-not-found error.

The `--durable-sessions` flag can be used to store those sessions in the datastore so they survive restarts and can be resumed on any node that shares the same storage. Each use refreshes a sliding idle TTL (`--durable-session-ttl`, default `24h`). A background task removes expired entries (`--durable-session-gc-interval`, default `60s`; set `0` to disable the sweep). Expired sessions are still dropped when loaded.

```bash
surreal db start --durable-sessions --durable-session-ttl 12h surrealkv://mydb
```

> [!WARNING]
> The durable copy includes the session's authentication state and is stored **unencrypted** in the datastore. Sticky routing is recommended so a given session is used on one node at a time. Concurrent use from multiple nodes is best-effort.

WebSocket connections keep in-memory sessions only. Durable sessions do not change WebSocket behaviour.

## Further examples

As `surreal db start` is the command with by far the largest number of options, a few more examples will help give an idea of what sort of configurations are available.

An instance with a single root user, able to connect to the internet but unable to use three functions:

```bash
surreal db start --user root --pass secret --allow-net --deny-funcs "crypto::md5, http::post, http::delete"
```

An instance with more verbose logging that uses SurrealKV as its storage engine:

```bash
surreal db start --log debug surrealkv:mydatabase.db
```

An instance with all capabilities denied except a few functions and a single endpoint:

```bash
surreal db start --deny-all --allow-funcs "array, string, crypto::argon2, http::get" --allow-net api.example.com
```

An instance with a different default address, less verbose logging level, and ability to use JavaScript functions:

```bash
surreal db start --bind 0.0.0.0:2218 --log warn --allow-scripting
```

## Command help

To see the help information and usage instructions, in a terminal run the `surreal db start --help` command without any further arguments. This command gives general information on the arguments, inputs, and additional options for the `start` command.

```bash
surreal db start --help
```

The output of the above command:

```text
Start the database server

Usage: surreal start [OPTIONS] [PATH]

Arguments:
  [PATH]
          Database path used for storing data

          [env: SURREAL_PATH]
          [default: memory]

Options:
      --index-compaction-interval <INDEX_COMPACTION_INTERVAL>
          [env: SURREAL_INDEX_COMPACTION_INTERVAL]
          [default: 5s]

      --async-event-interval <EVENT_PROCESSING_INTERVAL>
          [env: SURREAL_ASYNC_EVENT_PROCESSING_INTERVAL]
          [default: 5s]

      --reclaim-interval <RECLAIM_INTERVAL>
          [env: SURREAL_RECLAIM_INTERVAL]
          [default: 60s]

  -h, --help
          Print help (see a summary with '-h')

Database:
      --node-membership-refresh-interval <NODE_MEMBERSHIP_REFRESH_INTERVAL>
          The interval at which to refresh node registration information

          [env: SURREAL_NODE_MEMBERSHIP_REFRESH_INTERVAL]
          [default: 3s]

      --node-membership-check-interval <NODE_MEMBERSHIP_CHECK_INTERVAL>
          The interval at which to process and archive inactive nodes

          [env: SURREAL_NODE_MEMBERSHIP_CHECK_INTERVAL]
          [default: 15s]

      --node-membership-cleanup-interval <NODE_MEMBERSHIP_CLEANUP_INTERVAL>
          The interval at which to process and cleanup archived nodes

          [env: SURREAL_NODE_MEMBERSHIP_CLEANUP_INTERVAL]
          [default: 300s]

      --changefeed-gc-interval <CHANGEFEED_GC_INTERVAL>
          The interval at which to perform changefeed garbage collection

          [env: SURREAL_CHANGEFEED_GC_INTERVAL]
          [default: 30s]

      --graph-fold-interval <GRAPH_FOLD_INTERVAL>
          The interval at which to fold graph adjacency keys into packed blocks

          [env: SURREAL_GRAPH_FOLD_INTERVAL]
          [default: 5s]

      --index-build-resume-interval <INDEX_BUILD_RESUME_INTERVAL>
          The interval at which to resume index builds left unfinished by a crashed node (0 to disable)

          [env: SURREAL_INDEX_BUILD_RESUME_INTERVAL]
          [default: 30s]

      --reclaim-grace <RECLAIM_GRACE>
          Minimum age a removed namespace/database/index must reach before its data is physically reclaimed (snapshot-safety grace;
          effective value is max(this, --tikv-gc-lifetime))

          [env: SURREAL_RECLAIM_GRACE]
          [default: 10m]

      --tikv-gc-interval <TIKV_GC_INTERVAL>
          The interval at which the TiKV MVCC garbage collector runs

          [env: SURREAL_TIKV_GC_INTERVAL]
          [default: 10m]

      --tikv-gc-lifetime <TIKV_GC_LIFETIME>
          How far behind the current TSO the TiKV GC safepoint is allowed to sit

          [env: SURREAL_TIKV_GC_LIFETIME]
          [default: 10m]

      --tikv-lock-cleanup-interval <TIKV_LOCK_CLEANUP_INTERVAL>
          The interval at which TiKV stale transactional locks are resolved

          [env: SURREAL_TIKV_LOCK_CLEANUP_INTERVAL]
          [default: 60s]

      --durable-session-ttl <DURABLE_SESSION_TTL>
          How long an attached HTTP RPC session survives without being used: it expires between one and one and a half times this long after
          its last request. Attached sessions are stored in the datastore, including their authentication state, so they survive restarts
          and any node can serve them

          [env: SURREAL_DURABLE_SESSION_TTL]
          [default: 24h]

      --durable-session-gc-interval <DURABLE_SESSION_GC_INTERVAL>
          The interval at which expired attached HTTP RPC sessions are purged from the datastore (0 to disable). An expired session is
          refused whether or not it has been purged

          [env: SURREAL_DURABLE_SESSION_GC_INTERVAL]
          [default: 1h]

      --query-timeout <QUERY_TIMEOUT>
          The maximum duration that a set of statements can run for

          [env: SURREAL_QUERY_TIMEOUT]

      --transaction-timeout <TRANSACTION_TIMEOUT>
          The maximum duration that any single transaction can run for

          [env: SURREAL_TRANSACTION_TIMEOUT]

      --startup-operation-timeout <STARTUP_OPERATION_TIMEOUT>
          The maximum duration that each built-in startup datastore operation can retry for

          [env: SURREAL_STARTUP_OPERATION_TIMEOUT]
          [default: 60s]

Authentication:
  -u, --username <USERNAME>
          The username for the initial database root user. Only if no other root user exists

          [env: SURREAL_USER]
          [alias: --user]

  -p, --password <PASSWORD>
          The password for the initial database root user. Only if no other root user exists

          [env: SURREAL_PASS]
          [alias: --pass]

      --unauthenticated
          Whether to allow unauthenticated access

          [env: SURREAL_UNAUTHENTICATED]

Datastore connection:
      --kvs-ca <KVS_CA>
          Path to the CA file used when connecting to the remote KV store

          [env: SURREAL_KVS_CA]

      --kvs-crt <KVS_CRT>
          Path to the certificate file used when connecting to the remote KV store

          [env: SURREAL_KVS_CRT]

      --kvs-key <KVS_KEY>
          Path to the private key file used when connecting to the remote KV store

          [env: SURREAL_KVS_KEY]

HTTP server:
      --web-crt <WEB_CRT>
          Path to the certificate file for encrypted client connections

          [env: SURREAL_WEB_CRT]

      --web-key <WEB_KEY>
          Path to the private key file for encrypted client connections

          [env: SURREAL_WEB_KEY]

      --client-ip <CLIENT_IP>
          The method of detecting the client's IP address

          Possible values:
          - none:             Don't use client IP
          - socket:           Raw socket IP
          - CF-Connecting-IP: Cloudflare connecting IP
          - Fly-Client-IP:    Fly.io client IP
          - True-Client-IP:   Akamai, Cloudflare true client IP
          - X-Real-IP:        Nginx real IP
          - X-Forwarded-For:  Industry standard header used by many proxies
          - Forwarded:        RFC 7239 `Forwarded` header; the first `for=` parameter is used

          [env: SURREAL_CLIENT_IP]
          [default: socket]

  -b, --bind <LISTEN_ADDRESSES>
          The hostname or IP address to listen for connections on

          [env: SURREAL_BIND]
          [default: 127.0.0.1:8000]

      --no-identification-headers
          Whether to suppress the server name and version headers

          [env: SURREAL_NO_IDENTIFICATION_HEADERS]

      --allow-origin <ALLOW_ORIGIN>
          The allowed origins for CORS requests. Defaults to allow all origins

          [env: SURREAL_ALLOW_ORIGIN]

      --cookie-auth
          Issue the access token as an HttpOnly cookie on request, and accept it from the allowed origins. Requires --allow-origin. The
          cookie is Secure, so a browser stores it only over HTTPS or on a loopback address

          [env: SURREAL_COOKIE_AUTH]

Postgres server:
      --postgres-bind <POSTGRES_BIND>
          The hostname or IP address to listen for Postgres wire protocol connections on

          [env: SURREAL_POSTGRES_BIND]

MySQL server:
      --mysql-bind <MYSQL_BIND>
          The hostname or IP address to listen for MySQL wire protocol connections on

          [env: SURREAL_MYSQL_BIND]

Capabilities:
  -A, --allow-all
          Allow all capabilities except for those more specifically denied

          [env: SURREAL_CAPS_ALLOW_ALL]

      --allow-scripting
          Allow execution of embedded scripting functions

          [env: SURREAL_CAPS_ALLOW_SCRIPT]

      --allow-guests
          Allow guest users to execute queries

          [env: SURREAL_CAPS_ALLOW_GUESTS]

      --allow-funcs [<ALLOW_FUNCS>...]
          Allow execution of all functions except for functions that are specifically denied. Alternatively, you can provide a
          comma-separated list of function names to allow
          Specifically denied functions and function families prevail over any other allowed function execution.
          Function names must be in the form <family>[::<name>]. For example:
           - 'http' or 'http::*' -> Include all functions in the 'http' family
           - 'http::get' -> Include only the 'get' function in the 'http' family

          [env: SURREAL_CAPS_ALLOW_FUNC]

      --allow-arbitrary-query [<ALLOW_ARBITRARY_QUERY>...]
          Allow execution of arbitrary queries by certain user groups except when specifically denied. Alternatively, you can provide a
          comma-separated list of user groups to allow
          Specifically denied user groups prevail over any other allowed user group.
          User groups must be one of "guest", "record" or "system".

          [env: SURREAL_CAPS_ALLOW_ARBITRARY_QUERY]

      --allow-eval-query [<ALLOW_EVAL_QUERY>...]
          Allow the eval::surql / eval::gql functions to be invoked by certain user groups. Provide a comma-separated list of user groups to
          allow. This is an additive gate on top of arbitrary-query: an eval invocation must also satisfy the arbitrary-query capability.
          Specifically denied user groups prevail over any other allowed user group.
          User groups must be one of "guest", "record" or "system".
          Denied for everyone by default (even under --allow-all); must be explicitly enabled.

          [env: SURREAL_CAPS_ALLOW_EVAL_QUERY]

      --allow-net [<ALLOW_NET>...]
          Allow all outbound network connections except for network targets that are specifically denied. Alternatively, you can provide a
          comma-separated list of network targets to allow
          Specifically denied network targets prevail over any other allowed outbound network connections.
          Targets must be in the form of <host>[:<port>], *.<domain>[:<port>], <ipv4|ipv6>[/<mask>]. For example:
           - 'surrealdb.com', '127.0.0.1' or 'fd00::1' -> Match outbound connections to these hosts on any port
           - 'surrealdb.com:80', '127.0.0.1:80' or 'fd00::1:80' -> Match outbound connections to these hosts on port 80
           - '*.surrealdb.com' -> Match outbound connections to any subdomain of surrealdb.com (such as 'api.surrealdb.com' or
           'a.b.surrealdb.com', but not 'surrealdb.com' itself) on any port
           - '*.surrealdb.com:443' -> Match outbound connections to any subdomain of surrealdb.com on port 443
           - '10.0.0.0/8' or 'fd00::/8' -> Match outbound connections to any host in these networks
          A wildcard is only allowed as the whole leftmost label and must be followed by a domain of at least two labels; it never matches
          an IP address.

          [env: SURREAL_CAPS_ALLOW_NET]

      --allow-rpc [<ALLOW_RPC>...]
          Allow all RPC methods to be called except for routes that are specifically denied. Alternatively, you can provide a
          comma-separated list of RPC methods to allow.

          [env: SURREAL_CAPS_ALLOW_RPC]
          [default: ""]

      --allow-http [<ALLOW_HTTP>...]
          Allow all HTTP routes to be requested except for routes that are specifically denied. Alternatively, you can provide a
          comma-separated list of HTTP routes to allow.

          [env: SURREAL_CAPS_ALLOW_HTTP]
          [default: ""]

      --allow-mcp [<ALLOW_MCP>...]
          Allow all MCP tools to be called except for tools that are specifically denied. Alternatively, you can provide a comma-separated
          list of MCP tool names to allow.

          [env: SURREAL_CAPS_ALLOW_MCP]
          [default: ""]

  -D, --deny-all
          Deny all capabilities except for those more specifically allowed

          [env: SURREAL_CAPS_DENY_ALL]

      --deny-scripting
          Deny execution of embedded scripting functions

          [env: SURREAL_CAPS_DENY_SCRIPT]

      --deny-guests
          Deny guest users to execute queries

          [env: SURREAL_CAPS_DENY_GUESTS]

      --deny-funcs [<DENY_FUNCS>...]
          Deny execution of all functions except for functions that are specifically allowed. Alternatively, you can provide a
          comma-separated list of function names to deny.
          Specifically allowed functions and function families prevail over a general denial of function execution.
          Function names must be in the form <family>[::<name>]. For example:
           - 'http' or 'http::*' -> Include all functions in the 'http' family
           - 'http::get' -> Include only the 'get' function in the 'http' family

          [env: SURREAL_CAPS_DENY_FUNC]

      --deny-arbitrary-query [<DENY_ARBITRARY_QUERY>...]
          Deny execution of arbitrary queries by certain user groups except when specifically allowed. Alternatively, you can provide a
          comma-separated list of user groups to deny
          Specifically allowed user groups prevail over a general denial of user group.
          User groups must be one of "guest", "record" or "system".

          [env: SURREAL_CAPS_DENY_ARBITRARY_QUERY]

      --deny-eval-query [<DENY_EVAL_QUERY>...]
          Deny the eval::surql / eval::gql functions for certain user groups. Provide a comma-separated list of user groups to deny.
          Specifically denied user groups prevail over any allowed user group.
          User groups must be one of "guest", "record" or "system".

          [env: SURREAL_CAPS_DENY_EVAL_QUERY]

      --deny-net [<DENY_NET>...]
          Deny all outbound network connections except for network targets that are specifically allowed. Alternatively, you can provide a
          comma-separated list of network targets to deny.
          Specifically allowed network targets prevail over a general denial of outbound network connections.
          Targets must be in the form of <host>[:<port>], *.<domain>[:<port>], <ipv4|ipv6>[/<mask>]. For example:
           - 'surrealdb.com', '127.0.0.1' or 'fd00::1' -> Match outbound connections to these hosts on any port
           - 'surrealdb.com:80', '127.0.0.1:80' or 'fd00::1:80' -> Match outbound connections to these hosts on port 80
           - '*.surrealdb.com' -> Match outbound connections to any subdomain of surrealdb.com (such as 'api.surrealdb.com' or
           'a.b.surrealdb.com', but not 'surrealdb.com' itself) on any port
           - '*.surrealdb.com:443' -> Match outbound connections to any subdomain of surrealdb.com on port 443
           - '10.0.0.0/8' or 'fd00::/8' -> Match outbound connections to any host in these networks
          A wildcard is only allowed as the whole leftmost label and must be followed by a domain of at least two labels; it never matches
          an IP address.

          [env: SURREAL_CAPS_DENY_NET]

      --deny-rpc [<DENY_RPC>...]
          Deny all RPC methods from being called except for methods that are specifically allowed. Alternatively, you can provide a
          comma-separated list of RPC methods to deny.

          [env: SURREAL_CAPS_DENY_RPC]

      --deny-http [<DENY_HTTP>...]
          Deny all HTTP routes from being requested except for routes that are specifically allowed. Alternatively, you can provide a
          comma-separated list of HTTP routes to deny.

          [env: SURREAL_CAPS_DENY_HTTP]

      --deny-mcp [<DENY_MCP>...]
          Deny all MCP tools from being called except for tools that are specifically allowed. Alternatively, you can provide a
          comma-separated list of MCP tool names to deny.

          [env: SURREAL_CAPS_DENY_MCP]

      --temporary-directory <TEMPORARY_DIRECTORY>
          Sets the directory for storing temporary database files

          [env: SURREAL_TEMPORARY_DIRECTORY]

      --import-file <IMPORT_FILE>
          Path to a SurrealQL file that will be imported when starting the server

          [env: SURREAL_IMPORT_FILE]

      --slow-log-threshold <SLOW_LOG_THRESHOLD>
          The minimum execution time in milliseconds to trigger slow query logging

          [env: SURREAL_SLOW_QUERY_LOG_THRESHOLD]

      --slow-log-param-allow <SLOW_LOG_PARAM_ALLOW>...
          A comma-separated list of parameter names to include in the params of slow query logs. No parameter value is logged unless its name is listed here

          [env: SURREAL_SLOW_QUERY_LOG_PARAM_ALLOW]

      --slow-log-param-deny <SLOW_LOG_PARAM_DENY>...
          A comma-separated list of parameter names to leave out of the params of slow query logs, even if they are also allowed

          [env: SURREAL_SLOW_QUERY_LOG_PARAM_DENY]

      --default-namespace <DEFAULT_NAMESPACE>
          The default namespace for a new instance

          [env: SURREAL_DEFAULT_NAMESPACE]

      --default-database <DEFAULT_DATABASE>
          The default database for a new instance

          [env: SURREAL_DEFAULT_DATABASE]

      --no-defaults
          Whether to disable default namespace and database creation

          [env: SURREAL_NO_DEFAULTS]

      --lazy-surrealism
          Load SurrealDB extensions lazily on first use instead of eagerly at startup

          [env: SURREAL_LAZY_SURREALISM]

Logging:
  -l, --log <LOG>
          The logging level for the command-line tool

          [env: SURREAL_LOG]
          [default: info]
          [possible values: none, full, error, warn, info, debug, trace]

      --log-format <LOG_FORMAT>
          The format for terminal log output

          [env: SURREAL_LOG_FORMAT]
          [default: text]
          [possible values: text, json]

      --log-socket <LOG_SOCKET>
          Send logs to the specified host:port

          [env: SURREAL_LOG_SOCKET]

      --log-file-level <LOG_FILE_LEVEL>
          Override the logging level for file output

          [env: SURREAL_LOG_FILE_LEVEL]
          [possible values: none, full, error, warn, info, debug, trace]

      --log-otel-level <LOG_OTEL_LEVEL>
          Override the logging level for OpenTelemetry output

          [env: SURREAL_LOG_OTEL_LEVEL]
          [possible values: none, full, error, warn, info, debug, trace]

      --log-socket-level <LOG_SOCKET_LEVEL>
          Override the logging level for unix socket output

          [env: SURREAL_LOG_SOCKET_LEVEL]
          [possible values: none, full, error, warn, info, debug, trace]

      --log-socket-format <LOG_SOCKET_FORMAT>
          The format for socket output

          [env: SURREAL_LOG_SOCKET_FORMAT]
          [default: text]
          [possible values: text, json]

      --log-file-enabled
          Whether to enable log file output

          [env: SURREAL_LOG_FILE_ENABLED]

      --log-file-path <LOG_FILE_PATH>
          The directory where log files will be stored

          [env: SURREAL_LOG_FILE_PATH]
          [default: logs]

      --log-file-name <LOG_FILE_NAME>
          The name of the log file

          [env: SURREAL_LOG_FILE_NAME]
          [default: surrealdb.log]

      --log-file-format <LOG_FILE_FORMAT>
          The format for log file output

          [env: SURREAL_LOG_FILE_FORMAT]
          [default: text]
          [possible values: text, json]

      --log-file-rotation <LOG_FILE_ROTATION>
          The log file rotation interval

          [env: SURREAL_LOG_FILE_ROTATION]
          [default: daily]
          [possible values: daily, hourly, never]
```

**Build your own command**

Select the storage, authentication, network and capability options you want, and the builder writes the matching `surreal db start` command. Every other option is under **Advanced options**. Notes under the command describe what the chosen combination means, such as which data is lost when the server stops, or who can reach the server without signing in. The **surreal db start details** tab describes each option in full.

<DemoEmbed title="Start command builder" height={760} pages={[{ "label": "Start command builder", "src": "/docs/start-builder/builder" }]} />

---

Source: https://surrealdb.com/docs/reference/cli/db/commands/upgrade

# surreal upgrade db

How to upgrade the database component with the launcher command surreal upgrade db, to the latest release, a specific version, or an alpha, beta or nightly build. surreal db upgrade is refused.

The launcher upgrades the database, so the command is `surreal upgrade db`, not a `surreal db` subcommand. It replaces the installed database component with another version: the latest stable release, a specific version, or a pre-release build. This page sits with the database commands because it is the way to change the version of `surreal db`.

<Synopsis>
surreal upgrade db[@<VERSION>] [OPTIONS]
</Synopsis>

`surreal db upgrade` is refused, and exits with status 2 and a message that points to the launcher command:

```text
error: The CLI manages the database's versions, so `surreal db upgrade` is not run. Use `surreal upgrade db`, or `surreal upgrade db@<VERSION>` for a particular release.
```

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--nightly",
            "description": "Upgrade the database to the latest nightly build. Equivalent to `db@nightly`."
        },
        {
            "name": "--alpha",
            "description": "Upgrade the database to the latest alpha release. Equivalent to `db@alpha`."
        },
        {
            "name": "--beta",
            "description": "Upgrade the database to the latest beta release. Equivalent to `db@beta`."
        },
        {
            "name": "--version",
            "value": "<VERSION>",
            "description": "Upgrade the database to this version. Equivalent to `db@<VERSION>`."
        },
        {
            "name": "--dry-run",
            "description": "Say what would change without changing it."
        }
    ]}
/>

The launcher's other options, such as `--json`, `--plain`, `--yes` and `--no-input`, apply as well. They are listed in the [launcher reference](/docs/reference/cli/launcher.md).

## Example usage

Upgrade the database to the newest release on the channel it already follows, a stable release along its major line or a pre-release along its own channel.

```bash
surreal upgrade db
```

Running `surreal upgrade` with no component upgrades the launcher and every component that has a default version, the database included. Use `surreal upgrade cli` to upgrade the launcher alone.

## Install a specific version

Name the version after `db@`, or use the `--version` flag.

```bash
surreal upgrade db@3.2.4

# The same, with the flag
surreal upgrade db --version 3.2.4
```

For a list of available versions and their release notes, see the [releases](/releases) page. To keep an older version installed beside a newer one, use `surreal install db@<VERSION>` and choose between them with `surreal use`, as described in [Components](/docs/reference/cli/guides/components.md).

## Install the alpha, beta or nightly release

Use the `--alpha`, `--beta` or `--nightly` flag, or the matching `db@alpha`, `db@beta` or `db@nightly` form.

```bash
surreal upgrade db --alpha
surreal upgrade db --beta
surreal upgrade db --nightly
```

## Preview an upgrade

Use `--dry-run` to see what would change without changing it.

```bash
surreal upgrade db --dry-run
```

## Where the database is installed

The launcher keeps each installed version of the database under its home directory, `~/.surrealdb` by default or the directory in `SURREAL_CLI_HOME`, and an upgrade installs the new version there. [`surreal cloud`](/docs/reference/cli/cloud.md) uses this same installation when `surreal cloud instance sql`, `import` or `export` needs the database, and offers to install it if it is missing.

## Command help

To see the help information and usage instructions, run `surreal upgrade --help` in a terminal.

```bash
surreal upgrade --help
```

The output of the above command:

```text
Upgrade the CLI and every installed component

Usage: surreal upgrade [OPTIONS] [COMPONENT[@VERSION] | cli]...

Arguments:
  [COMPONENT[@VERSION] | cli]...  Upgrade only these, each to the newest release on the channel its
                                   default follows - a stable release along its major line, a
                                   prerelease along its own channel - or to the version named,
                                   either way. `cli` is the launcher. Without any: the launcher and
                                   every component with a default version

Options:
      --nightly            Upgrade the database to the latest nightly build: `db@nightly`
      --alpha              Upgrade the database to the latest alpha release: `db@alpha`
      --beta               Upgrade the database to the latest beta release: `db@beta`
      --version <VERSION>  Upgrade the database to this version: `db@<VERSION>`
      --dry-run            Say what would change without changing it
      --json               Print one JSON document on stdout
      --plain              Plain text: no tables, no colour, no animation
      --color <WHEN>       When to use colour [default: auto] [possible values: auto, always, never]
  -q, --quiet              Print only results and errors
  -y, --yes                Answer yes to every question
      --no-input           Never prompt; fail where a question would be asked
  -h, --help               Print help
```

---

Source: https://surrealdb.com/docs/reference/cli/db/commands/validate

# validate

A command to confirm whether one or more SurrealQL files are valid or not.

Validate SurrealQL query files, or a query read from standard input, with the [installed](/docs/reference/cli/guides/install.md) `surreal` CLI and without connecting to a server.

<Synopsis>
surreal db validate [OPTIONS] [PATTERNS]...
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[PATTERNS]...",
            "default": "**/*.surql",
            "description": "Glob pattern for the files to validate. Several paths or patterns can be given at once."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--stdin",
            "description": "Read the query from standard input instead of from files."
        },
        {
            "name": "--json",
            "short": "-j",
            "description": "From 4.0.0. Print one JSON document on stdout, with `valid` and a `files` array holding the `path` and `valid` of each file, and the `error` of a file that is not valid. When a file is not valid, the document is a JSON error object on stderr instead, with the same `files` array."
        },
        {
            "name": "--log",
            "short": "-l",
            "value": "<LOG>",
            "default": "info",
            "env": "SURREAL_LOG",
            "description": "The logging level for the command-line tool. Possible values: `none`, `full`, `error`, `warn`, `info`, `debug`, `trace`."
        }
    ]}
/>

## Example usage

To perform validation on a SurrealQL local file, in a terminal run the `surreal db validate` command with the required argument.

Using the command on its own will validate all the `.surql` files in the current directory and its subdirectories.

```bash
surreal db validate
```

```text
user1.surql: OK
user2.surql: OK
user3.surql: OK
```

You can perform validation on a single file, regardless of extension.

```bash
surreal db validate user.surql
surreal db validate user.txt
```

You can also perform validation on multiple files using a single glob pattern:

```bash
# equivalent to "surreal db validate"
surreal db validate **/*.surql
```

Finally, you can also perform validation on multiple files using multiple paths/patterns:

```bash
surreal db validate index.surql schemas/*.surql queries/*.surql
surreal db validate *.(txt|surql)
```

The command checks every file, and exits with an error if any of them is invalid.

```bash
surreal db validate
```

```text
user1.surql: OK
user2.surql: FAIL
Parse error: Unexpected token `an identifier`, expected Eof
 --> [1:15]
  |
1 | CREATE person SE name = "Billy";
  |               ^^
```

## Validating input from stdin

_(since v3.1.0)_

In addition to files, this command can also be used on the terminal with the `--stdin` flag to validate input from stdin.

An example of a valid query:

```bash
echo "SELECT * FROM example;" | surreal db validate --stdin
```

```text
<stdin>: OK
```

An example of an invalid query:

```bash
echo "CREATE WHERE value = ''" | surreal db validate --stdin
```

```text
<stdin>: FAIL
Parse error: Unexpected token `VALUE`, expected Eof
 --> [1:14]
  |
1 | CREATE WHERE value = ''
  |              ^^^^^
```

## Command help

To see the help information and usage instructions, in a terminal run the `surreal db validate --help` command without any further arguments. This command gives general information on the arguments, inputs, and additional options for the `validate` command.

```bash
surreal db validate --help
```

The output of the above command:

```text
Validate SurrealQL query files

Usage: surreal validate [OPTIONS] [PATTERNS]...

Arguments:
  [PATTERNS]...  Glob pattern for the files to validate [default: **/*.surql]

Options:
      --stdin  Read query from standard input
  -j, --json   Emit machine-readable JSON on stdout
  -h, --help   Print help

Logging:
  -l, --log <LOG>                              The logging level for the command-line tool [env: SURREAL_LOG] [default: info] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-format <LOG_FORMAT>                The format for terminal log output [env: SURREAL_LOG_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-socket <LOG_SOCKET>                Send logs to the specified host:port [env: SURREAL_LOG_SOCKET]
      --log-file-level <LOG_FILE_LEVEL>        Override the logging level for file output [env: SURREAL_LOG_FILE_LEVEL] [possible values:
                                               none, full, error, warn, info, debug, trace]
      --log-otel-level <LOG_OTEL_LEVEL>        Override the logging level for OpenTelemetry output [env: SURREAL_LOG_OTEL_LEVEL] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-socket-level <LOG_SOCKET_LEVEL>    Override the logging level for unix socket output [env: SURREAL_LOG_SOCKET_LEVEL] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-socket-format <LOG_SOCKET_FORMAT>  The format for socket output [env: SURREAL_LOG_SOCKET_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-file-enabled                       Whether to enable log file output [env: SURREAL_LOG_FILE_ENABLED]
      --log-file-path <LOG_FILE_PATH>          The directory where log files will be stored [env: SURREAL_LOG_FILE_PATH] [default: logs]
      --log-file-name <LOG_FILE_NAME>          The name of the log file [env: SURREAL_LOG_FILE_NAME] [default: surrealdb.log]
      --log-file-format <LOG_FILE_FORMAT>      The format for log file output [env: SURREAL_LOG_FILE_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-file-rotation <LOG_FILE_ROTATION>  The log file rotation interval [env: SURREAL_LOG_FILE_ROTATION] [default: daily] [possible
                                               values: daily, hourly, never]
```

---

Source: https://surrealdb.com/docs/reference/cli/db/commands/version

# version

surreal db version prints the database component version with its platform and architecture, or the version of a remote server with --endpoint. The launcher has its own surreal list and surreal --version.

Output the version of the database component, or the version of a remote server. The launcher has its own version commands, described [below](#launcher-versions).

<Synopsis>
surreal db version [OPTIONS]
</Synopsis>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--endpoint",
            "short": "-e",
            "value": "<ENDPOINT>",
            "description": "Remote database server URL to connect to. When given, only the server's version number is printed."
        },
        {
            "name": "--json",
            "short": "-j",
            "description": "From 4.0.0. Print the version as one JSON document on stdout, with the keys `arch`, `os` and `version`, and a `server` object holding the server's `version` when `--endpoint` is given."
        },
        {
            "name": "--log",
            "short": "-l",
            "value": "<LOG>",
            "default": "info",
            "env": "SURREAL_LOG",
            "description": "The logging level for the command-line tool. Possible values: `none`, `full`, `error`, `warn`, `info`, `debug`, `trace`."
        }
    ]}
/>

## Example usage

To display the version of the database component, along with the platform and architecture, run `surreal db version` without any further arguments.

```bash
surreal db version
```

Example output:

```text
4.0.0 for macos on aarch64
```

If an endpoint is specified, only the version number of the server is displayed.

```bash
surreal db version --endpoint http://localhost:8000
```

Output:

```text
4.0.0
```

## Launcher versions {#launcher-versions}

`surreal list` and `surreal --version` belong to the launcher and do not forward to the database. `surreal list` prints a table with each component, the version that runs, where that version came from, and its path. `surreal --version` prints the launcher's own version.

```bash
surreal list
```

```text title="Example output"
COMPONENT  VERSION  SOURCE  INSTALLED  PATH
cli        1.0.0    cli                /usr/local/bin/surreal
db         4.0.0    pinned  4.0.0      /home/you/.surrealdb/components/db/4.0.0/surreal-db
ext
cloud      1.0.0    pinned  1.0.0      /home/you/.surrealdb/components/cloud/1.0.0/surreal-cloud
lsp
memory
```

```bash
surreal --version
```

```text title="Example output"
1.0.0 for macos on aarch64
```

A component that is not installed has a blank row in the table. To query a server, or to print the database version alone, use `surreal db version`. `surreal version` without `db` is the deprecated form of `surreal db version`, so it prints the database version and a warning that names the replacement. See the [launcher reference](/docs/reference/cli/launcher.md) for the other version commands, including `surreal install`, `surreal use` and `surreal upgrade`.

## Command help

To see the help information and usage instructions, in a terminal run the `surreal db version --help` command without any further arguments. This command gives general information on the arguments, inputs, and additional options for the `version` command.

```bash
surreal db version --help
```

The output of the above command:

```text
Output the command-line tool and remote server version information

Usage: surreal version [OPTIONS]

Options:
  -e, --endpoint <ENDPOINT>  Remote database server url to connect to
  -j, --json                 Emit machine-readable JSON on stdout
  -h, --help                 Print help

Logging:
  -l, --log <LOG>                              The logging level for the command-line tool [env: SURREAL_LOG] [default: info] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-format <LOG_FORMAT>                The format for terminal log output [env: SURREAL_LOG_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-socket <LOG_SOCKET>                Send logs to the specified host:port [env: SURREAL_LOG_SOCKET]
      --log-file-level <LOG_FILE_LEVEL>        Override the logging level for file output [env: SURREAL_LOG_FILE_LEVEL] [possible values:
                                               none, full, error, warn, info, debug, trace]
      --log-otel-level <LOG_OTEL_LEVEL>        Override the logging level for OpenTelemetry output [env: SURREAL_LOG_OTEL_LEVEL] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-socket-level <LOG_SOCKET_LEVEL>    Override the logging level for unix socket output [env: SURREAL_LOG_SOCKET_LEVEL] [possible
                                               values: none, full, error, warn, info, debug, trace]
      --log-socket-format <LOG_SOCKET_FORMAT>  The format for socket output [env: SURREAL_LOG_SOCKET_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-file-enabled                       Whether to enable log file output [env: SURREAL_LOG_FILE_ENABLED]
      --log-file-path <LOG_FILE_PATH>          The directory where log files will be stored [env: SURREAL_LOG_FILE_PATH] [default: logs]
      --log-file-name <LOG_FILE_NAME>          The name of the log file [env: SURREAL_LOG_FILE_NAME] [default: surrealdb.log]
      --log-file-format <LOG_FILE_FORMAT>      The format for log file output [env: SURREAL_LOG_FILE_FORMAT] [default: text] [possible
                                               values: text, json]
      --log-file-rotation <LOG_FILE_ROTATION>  The log file rotation interval [env: SURREAL_LOG_FILE_ROTATION] [default: daily] [possible
                                               values: daily, hourly, never]
```

---

Source: https://surrealdb.com/docs/reference/cli/db/environment-variables

# Environment variables

Every SURREAL_ variable, with its default and allowed values.

Environment variables can be used to tailor the behaviour of a running SurrealDB instance.

Environment variables are divided into four types:

* **SurrealDB environment variables**: environment variables that pertain to the overall running of a SurrealDB server. Example: `SURREAL_DEFAULT_DATABASE`. Includes an [operator and internal config](#operator-and-internal-config) subsection for advanced settings.
* **Command environment variables**: environment variables that can be used in lieu of a command flag. Example: `SURREAL_CAPS_ALLOW_ALL=true surreal db start`, equivalent to `surreal db start --allow-all`.
* **Storage backend environment variables**: environment variables that pertain to a certain storage backend. Example: `SURREAL_SURREALKV_ENABLE_VLOG`.
* **SurrealDB Cloud environment variables**: environment variables that are set via the [Configure instance](/docs/operate/instances/configure.md) sidebar for a SurrealDB Cloud instance.

> [!IMPORTANT]
> Every variable on this page belongs to the database and starts with `SURREAL_`. They are read by `surreal db`, and by the server in a container that runs `surreal start` directly. The launcher has its own variables, which start with `SURREAL_CLI_` and are documented in the [launcher reference](/docs/reference/cli/launcher.md). The `surreal cloud` component reads `SURREAL_CLOUD_*` variables, described in the [Cloud reference](/docs/reference/cli/cloud.md). The prefixes are kept apart deliberately: a database credential such as `SURREAL_TOKEN` is not a Cloud credential, and must not be sent to the SurrealDB Cloud API.

Many environment variables have a maximum value equivalent to the greatest possible `usize`, which is an unsigned integer with a number of bytes depending on the target that the database runs on. For most systems this will be 64 bits, leading to a maximum size of 18_446_744_073_709_551_615 (2<sup>64</sup>), while for 32 bits the maximum will be 4_294_967_296 (2<sup>32</sup>).

## Byte size suffixes

_(since v3.0.0)_

Environment variables that set a size in bytes, such as `SURREAL_HTTP_MAX_SQL_BODY_SIZE` and `SURREAL_WEBSOCKET_MAX_MESSAGE_SIZE`, accept either a raw byte count or a number with a suffix. Suffixes are case-insensitive, and all of them are powers of 1024, so `4GB` and `4GiB` both mean 4,294,967,296 bytes.

| Suffix | Multiplier |
| ------ | ---------- |
| none, `b` | 1 |
| `k`, `kb`, `kib` | 1024 |
| `m`, `mb`, `mib` | 1024<sup>2</sup> |
| `g`, `gb`, `gib` | 1024<sup>3</sup> |

> [!WARNING]
> A value that cannot be parsed is discarded and the default is used instead - the server does not fail to start. On 2.x these variables take a raw byte count only, so a suffixed value such as `16MiB` is silently ignored there and the default remains in effect.

## SurrealDB environment variables

These environment variables can be used to configure a SurrealDB server to configure areas such as the HTTP server and client, limits, telemetry, and so on.

### Batch config

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '40%'}}>Environment variable</th>
      <th scope="col" style={{width: '20%'}}>Default</th>
      <th scope="col" style={{width: '20%'}}>Allowed values</th>
      <th scope="col" style={{width: '20%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_NORMAL_FETCH_SIZE</code></td>
      <td scope="row" data-label="Default">500</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum number of keys that should be scanned at once in general queries. Read only before 3.1.0; later versions use a fixed batch of 500.</td>
    </tr>
        <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_EXPORT_BATCH_SIZE</code></td>
      <td scope="row" data-label="Default">1000</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum number of keys that should be scanned at once for export queries.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_COUNT_BATCH_SIZE</code>_(since v2.2.0)_</td>
      <td scope="row" data-label="Default">50,000 (10,000 on 2.x)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum number of keys that should be scanned at once for count queries. Read only before 3.1.0; later versions use a fixed batch of 50,000.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_INDEXING_BATCH_SIZE</code></td>
      <td scope="row" data-label="Default">250</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum number of keys to scan at once per concurrent indexing batch. Read only before 3.1.0; later versions use a fixed batch of 250.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TABLE_DOC_IDS_BATCH_SIZE</code>_(since v3.3.0)_</td>
      <td scope="row" data-label="Default">1000</td>
      <td scope="row" data-label="Allowed values">A u32</td>
      <td scope="row" data-label="Notes">The number of document ids allocated at once from a table's shared document id sequence, which full-text, HNSW and DiskANN indexes use. Larger batches reduce coordination on the distributed sequence, at the cost of larger gaps in the ids when a node is lost before it uses up its current batch. Replaces <code>SURREAL_FTS_DOC_IDS_BATCH_SIZE</code>, which 3.3.0 no longer reads.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_GRAPH_FOLD_BATCH</code>_(since v3.3.0)_</td>
      <td scope="row" data-label="Default">1024</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">How many graph adjacency keys one background fold pass packs into blocks per transaction. This bounds the transaction size on a vertex with many edges, which is then folded over several passes. See <code>SURREAL_GRAPH_FOLD_INTERVAL</code>.</td>
    </tr>
  </tbody>
</table>

### Cache config

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '40%'}}>Environment variable</th>
      <th scope="col" style={{width: '20%'}}>Default</th>
      <th scope="col" style={{width: '20%'}}>Allowed values</th>
      <th scope="col" style={{width: '20%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>
<tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TRANSACTION_CACHE_SIZE</code></td>
      <td scope="row" data-label="Default">512 (10,000 before 3.1.0)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Specifies the number of items which can be cached within a single transaction.</td>
    </tr>
<tr>
      <td scope="row" data-label="Env var"><code>SURREAL_DATASTORE_CACHE_SIZE</code></td>
      <td scope="row" data-label="Default">1,000</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The number of definitions which can be cached across transactions.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HNSW_CACHE_SIZE</code></td>
      <td scope="row" data-label="Default">268,435,456 (256 MiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum total size, in bytes, of the HNSW vector cache, shared across all HNSW indexes in the process. This bounds the cached element <em>vectors</em> used for distance computation - it is not a cap on total HNSW memory: the adjacency graph is loaded into resident memory on first use and stays there, outside this budget. Contrast <code>SURREAL_DISKANN_CACHE_SIZE</code>, which does page graph structure.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_DISKANN_CACHE_SIZE</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">268,435,456 (256 MiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum total size, in bytes, of the DISKANN index cache, shared across all DISKANN indexes in the process. DISKANN graph data lives in the key-value store and is paged through this bounded cache. The DISKANN counterpart of <code>SURREAL_HNSW_CACHE_SIZE</code>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_FULLTEXT_CACHE_SIZE</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">134,217,728 (128 MiB)</td>
      <td scope="row" data-label="Allowed values">A u64</td>
      <td scope="row" data-label="Notes">The maximum total size, in bytes, of the cache of compacted full-text terms, which every read-only full-text query on the node shares. Changes that are not compacted yet are always read from storage, and write transactions do not use the cache. <code>0</code> turns it off.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_GRAPH_RESOLVE_CACHE_SIZE</code>_(since v3.3.0)_</td>
      <td scope="row" data-label="Default">67,108,864 (64 MiB)</td>
      <td scope="row" data-label="Allowed values">A u64</td>
      <td scope="row" data-label="Notes">The maximum total size, in bytes, of the cache that maps document ids back to record keys when a traversal reads numeric-encoded graph adjacency entries. Only relevant once <code>SURREAL_GRAPH_NUMERIC_IDS</code> has written numeric blocks.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_COMPILED_UNIT_CACHE_SIZE</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">1024</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">How many compiled units of each kind, such as function bodies, closure bodies and catalog units, a node keeps for later queries to reuse. The least recently used is evicted first. <code>0</code> keeps none, and each unit is compiled with the query that needs it.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_STATEMENT_CACHE_SIZE</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">1024</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">How many top-level statements a node keeps compiled for later requests. The least recently used is evicted first. A read-only statement that uses its parameters only as the key of a record in a named table reuses the compilation of the same statement text, under the same namespace, database, kind of user and capabilities. <code>0</code> keeps none, and each statement is compiled with its request.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SPECIALISED_BODY_CACHE_SIZE</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">256</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">How many function bodies a node keeps that were compiled for the argument values of a call. A function whose body needs the value of an argument to compile is compiled for the values each call passes. The least recently used is evicted first. <code>0</code> keeps none.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SPECIALISED_BODY_MAX_ARG_BYTES</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">4096</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The largest argument values, measured in bytes of their encoding, that a node keeps a function body compiled for. A body compiled for larger values is used for its own call only and is not kept.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SPECIALISED_BODY_VALUES</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">32</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">How many different argument values one function is compiled for. After this many, its calls run a body that reads the arguments when it runs.</td>
    </tr>
  </tbody>
</table>

### File config

Server-side filesystem access for features that read paths from disk (notably the `mapper()` filter and the `segment()` tokenizer on [`DEFINE ANALYZER`](/docs/reference/query-language/statements/define/analyzer.md)). This is separate from `SURREAL_BUCKET_FOLDER_ALLOWLIST` (below), which gates the experimental [files](/docs/learn/schema-management/files/buckets.md) feature.

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '40%'}}>Environment variable</th>
      <th scope="col" style={{width: '20%'}}>Default</th>
      <th scope="col" style={{width: '20%'}}>Allowed values</th>
      <th scope="col" style={{width: '20%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>
  <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_FILE_ALLOWLIST</code></td>
      <td scope="row" data-label="Default">none (deny all)</td>
      <td scope="row" data-label="Allowed values">Colon-separated paths on Unix; semicolon-separated on Windows</td>
      <td scope="row" data-label="Notes">Directories the server may read when an analyzer uses <code>mapper('&lt;path&gt;')</code>. An empty or unset value denies every path. Each mapper file must resolve under one of the listed directories. See <a href="/docs/reference/query-language/statements/define/analyzer.md#mapperpath">DEFINE ANALYZER - mapper</a>.</td>
    </tr>
  <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SEGMENT_DICTIONARY_PATH</code>_(since v3.3.0)_</td>
      <td scope="row" data-label="Default">none (use the dictionaries built into the binary)</td>
      <td scope="row" data-label="Allowed values">A path to a directory</td>
      <td scope="row" data-label="Notes">Directory holding the morphological dictionaries the <code>segment(&lt;language&gt;)</code> tokenizer reads, one subdirectory per language: <code>chinese</code>, <code>japanese</code>, <code>korean</code>. The released binaries already carry all three, so this is only needed to replace them with a custom or updated dictionary, or for a build made without them. Each language is overridden only if the directory holds a dictionary for it; the rest keep using the built-in one. See <a href="/docs/reference/query-language/statements/define/analyzer.md#segmentlanguage">DEFINE ANALYZER - segment</a>.</td>
    </tr>
  <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_BUCKET_FOLDER_ALLOWLIST</code></td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">Comma-separated paths</td>
      <td scope="row" data-label="Notes">Specifies a list of paths in which files can be accessed.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_GLOBAL_BUCKET</code></td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">A string</td>
      <td scope="row" data-label="Notes">The backend URL of the global bucket, in the same form as the <code>BACKEND</code> of a bucket, such as <code>memory</code>, <code>file:/path</code> or an object storage URL. A bucket uses part of it through a <code>global://</code> backend. See <a href="/docs/reference/query-language/statements/define/bucket.md#global-backend">Global backend</a>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_GLOBAL_BUCKET_ENFORCED</code></td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether every bucket must use the global bucket. When <code>true</code>, <code>global://</code> is the only backend a bucket can have, and only a root user can give a bucket that backend.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_BUCKET_PRESIGN_SECRET</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">none (presigned URLs off)</td>
      <td scope="row" data-label="Allowed values">A string of at least 32 bytes</td>
      <td scope="row" data-label="Notes">The secret that signs <a href="/docs/learn/schema-management/files/presigned-urls.md">presigned URLs</a>. Without it, or with a shorter value, <code>file::presign_get</code> and <code>file::presign_put</code> fail and a signed request is refused. Set the same value on every node of a cluster. Changing it revokes every URL already issued.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_BUCKET_PRESIGN_MAX_TTL</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">1h</td>
      <td scope="row" data-label="Allowed values">A duration, up to 7d</td>
      <td scope="row" data-label="Notes">The longest <code>expires</code> a presigned URL can have. A larger value is reduced to 7 days.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_BUCKET_PRESIGN_MAX_SIZE</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">5 GiB</td>
      <td scope="row" data-label="Allowed values">A byte size, such as <code>100MiB</code></td>
      <td scope="row" data-label="Notes">The largest <code>max_size</code> a presigned upload URL can have, and the <code>max_size</code> of one created without it.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_PUBLIC_ORIGIN</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">An origin with a scheme and no path, such as <code>https://db.example.com</code></td>
      <td scope="row" data-label="Notes">The address at which clients reach the server, returned as the <code>origin</code> of a presigned URL and placed before its <code>path</code> in <code>href</code>. A value without a scheme or with a path is ignored, and <code>origin</code> is then <code>NONE</code>.</td>
    </tr>
  </tbody>
</table>

### HTTP client config

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '40%'}}>Environment variable</th>
      <th scope="col" style={{width: '20%'}}>Default</th>
      <th scope="col" style={{width: '20%'}}>Allowed values</th>
      <th scope="col" style={{width: '20%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>

  <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MAX_HTTP_REDIRECTS</code></td>
      <td scope="row" data-label="Default">10</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum number of HTTP redirects allowed within http functions.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MAX_HTTP_IDLE_CONNECTIONS_PER_HOST</code></td>
      <td scope="row" data-label="Default">128</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum number of idle HTTP connections to maintain per host.</td>
    </tr>
        <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MAX_HTTP_IDLE_CONNECTIONS</code></td>
      <td scope="row" data-label="Default">1000</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum number of idle HTTP connections to maintain. Has no effect: earlier versions read the value without applying it to the HTTP client, and 3.3.0 no longer reads it. Use <code>SURREAL_MAX_HTTP_IDLE_CONNECTIONS_PER_HOST</code> instead.</td>
    </tr>
<tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HTTP_IDLE_TIMEOUT_SECS</code></td>
      <td scope="row" data-label="Default">90</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The timeout for idle HTTP connections before closing.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HTTP_CONNECT_TIMEOUT_SECS</code></td>
      <td scope="row" data-label="Default">30</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The timeout for connecting to HTTP endpoints.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALDB_USER_AGENT</code></td>
      <td scope="row" data-label="Default">SurrealDB</td>
      <td scope="row" data-label="Allowed values">A string</td>
      <td scope="row" data-label="Notes">The USER-AGENT string used by HTTP requests. Before 3.1.0 this variable was named <code>SURREAL_USER_AGENT</code>, which later versions ignore.</td>
    </tr>
  </tbody>
</table>

### HTTP server config

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '40%'}}>Environment variable</th>
      <th scope="col" style={{width: '20%'}}>Default</th>
      <th scope="col" style={{width: '20%'}}>Allowed values</th>
      <th scope="col" style={{width: '20%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>

<tr>
      <td scope="row" data-label="Env var"><code>SURREAL_NET_MAX_CONCURRENT_REQUESTS</code></td>
      <td scope="row" data-label="Default">1,048,576</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">How many concurrent network requests can be handled at once</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HTTP_MAX_MCP_BODY_SIZE</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">4,194,304 (4 MiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Maximum HTTP body size of the HTTP <code>/mcp</code> endpoint. See [Embedded MCP](/docs/integrate/ai-agents/mcp/embedded.md).</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HTTP_MAX_SQL_BODY_SIZE</code></td>
      <td scope="row" data-label="Default">1,048,576 (1 MiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Maximum HTTP body size of the HTTP /sql endpoint</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HTTP_MAX_GQL_BODY_SIZE</code>_(since v3.2.0)_</td>
      <td scope="row" data-label="Default">1,048,576 (1 MiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Maximum HTTP body size of the HTTP <code>/gql</code> endpoint. See <a href="/docs/learn/querying/gql/via-http.md">GQL via HTTP</a>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HTTP_MAX_GRAPHQL_BODY_SIZE</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">1,048,576 (1 MiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Maximum HTTP body size of the HTTP <code>/graphql</code> endpoint. See <a href="/docs/learn/querying/graphql/overview.md">GraphQL</a>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HTTP_MAX_API_BODY_SIZE</code></td>
      <td scope="row" data-label="Default">4,194,304 (4 MiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum HTTP body size of the HTTP /api endpoint.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HTTP_MAX_BUCKET_BODY_SIZE</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">5,368,709,120 (5 GiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum size of an upload to the HTTP <a href="/docs/reference/protocols/http-protocol.md#bucket"><code>/bucket</code></a> route, whether it uses a session or a presigned URL.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HTTP_MAX_RPC_BODY_SIZE</code></td>
      <td scope="row" data-label="Default">4,194,304 (4 MiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Maximum HTTP body size of the HTTP /rpc endpoint.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HTTP_MAX_ATTACHED_SESSIONS</code></td>
      <td scope="row" data-label="Default">16384</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum number of attached HTTP RPC sessions that a node keeps. A session counts against the node it was attached through until it is detached or expires, wherever it is used. When the limit is reached, the node first releases the sessions that were detached or expired through other nodes, and then refuses the attach.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_GRAPHQL_SUBSCRIPTION_CHANNEL_CAPACITY</code></td>
      <td scope="row" data-label="Default">1024</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">How many notifications can be buffered for one GraphQL subscription. When the buffer is full, new notifications for that subscription are dropped.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_GRPC_MAX_MESSAGE_SIZE</code></td>
      <td scope="row" data-label="Default">The value of <code>SURREAL_HTTP_MAX_RPC_BODY_SIZE</code>, so 4,194,304 (4 MiB) unless that is raised</td>
      <td scope="row" data-label="Allowed values">A usize, clamped to a ceiling of 4,294,967,295 (4 GiB less one byte), the largest size a gRPC length prefix can express. A value below the floor needed to carry one streaming file chunk is raised to it.</td>
      <td scope="row" data-label="Notes">From 3.3.0. The largest single gRPC message the server will accept or emit, also reported to clients as <code>Limits.max_message_bytes</code>. This is the gRPC counterpart of <code>SURREAL_WEBSOCKET_MAX_MESSAGE_SIZE</code>: raise it for a transaction that writes a large batch in one request.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_GRPC_MAX_ATTACHED_SESSIONS</code>_(since v3.3.0)_</td>
      <td scope="row" data-label="Default">16384</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum number of explicitly attached sessions the gRPC transport keeps at once. The count is for the whole process rather than per connection, because a gRPC channel reconnects transparently and one session's requests can arrive on different connections. Per-request sessions do not count towards it.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_GRPC_NOTIFICATION_BUFFER</code>_(since v3.3.0)_</td>
      <td scope="row" data-label="Default">1024</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">How many live query notifications can be buffered for a gRPC subscription whose client is not keeping up. When the buffer is full, the server ends that subscription with a <code>RESOURCE_EXHAUSTED</code> status instead of waiting.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HTTP_MAX_KEY_BODY_SIZE</code></td>
      <td scope="row" data-label="Default">16,384 (16 KiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Maximum HTTP body size of the HTTP /key endpoints</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HTTP_MAX_SIGNUP_BODY_SIZE</code></td>
      <td scope="row" data-label="Default">1024 (1 KiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Maximum HTTP body size of the HTTP /signup endpoint.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HTTP_MAX_IMPORT_BODY_SIZE</code></td>
      <td scope="row" data-label="Default">4,294,967,296 (4 GiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Maximum HTTP body size of the HTTP <code>/import</code> endpoint. Counted cumulatively across the whole request, not per chunk. Also enforced on the gRPC import stream. See [Request size limits](/docs/reference/protocols/http-protocol.md#request-size-limits).</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HTTP_MAX_SIGNIN_BODY_SIZE</code></td>
      <td scope="row" data-label="Default">1024 (1 KiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum HTTP body size of the HTTP /signin endpoints</td>
    </tr>
  </tbody>
</table>

> [!NOTE]
> Before SurrealDB 3.3.0, `SURREAL_HTTP_MAX_SIGNUP_BODY_SIZE` and `SURREAL_HTTP_MAX_SIGNIN_BODY_SIZE` were applied to each other's endpoint. Both default to 1 KiB, so no default deployment was affected, but raising one of them had no effect on the endpoint it names and the other endpoint kept returning `413 Payload Too Large`. If you worked around this by tuning the opposite variable, move the value back to the one that matches the endpoint.

### MCP config

_(since v3.1.0)_

Used by the built-in [Model Context Protocol](/docs/integrate/ai-agents/mcp/embedded.md) server (`/mcp` on `surreal db start`, `surreal db mcp` on stdio). Stdio namespace/database selection uses `SURREAL_MCP_NS` and `SURREAL_MCP_DB` on the [`mcp`](/docs/reference/cli/db/commands/mcp.md) subcommand.

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '40%'}}>Environment variable</th>
      <th scope="col" style={{width: '20%'}}>Default</th>
      <th scope="col" style={{width: '20%'}}>Allowed values</th>
      <th scope="col" style={{width: '20%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MCP_QUERY_TIMEOUT_SECS</code></td>
      <td scope="row" data-label="Default">60</td>
      <td scope="row" data-label="Allowed values">Seconds (integer); <code>0</code> disables</td>
      <td scope="row" data-label="Notes">Outer timeout on each MCP tool execution.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MCP_MAX_RESULT_BYTES</code></td>
      <td scope="row" data-label="Default">262,144 (256 KiB)</td>
      <td scope="row" data-label="Allowed values">Bytes (integer); <code>0</code> disables</td>
      <td scope="row" data-label="Notes">Maximum serialised tool / resource response size; larger results are truncated with a marker.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MCP_RUN_MAX_ARGS</code></td>
      <td scope="row" data-label="Default">64</td>
      <td scope="row" data-label="Allowed values">A positive integer</td>
      <td scope="row" data-label="Notes">Maximum arguments for a single <code>run</code> tool call.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MCP_PARAMS_MAX_KEYS</code></td>
      <td scope="row" data-label="Default">256</td>
      <td scope="row" data-label="Allowed values">A positive integer</td>
      <td scope="row" data-label="Notes">Maximum top-level keys in MCP parameter / data objects.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MCP_PARAMS_MAX_QL_BYTES</code></td>
      <td scope="row" data-label="Default">4,096 (4 KiB)</td>
      <td scope="row" data-label="Allowed values">A positive integer; values ≤ 0 fall back to the default</td>
      <td scope="row" data-label="Notes">Maximum byte length of a single <code>$ql</code> SurrealQL pass-through string inside a <code>*_data</code> payload.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MCP_SCHEMA_RESOURCE_MAX_TABLES</code></td>
      <td scope="row" data-label="Default">200</td>
      <td scope="row" data-label="Allowed values">A positive integer; values ≤ 0 fall back to the default</td>
      <td scope="row" data-label="Notes">Maximum tables the database-level schema resource enriches with per-table fields / indexes / events. Tables beyond the cap keep a bare <code>DEFINE TABLE</code> and the body includes a <code>tables_truncated_at</code> marker.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MCP_ALLOWED_HOSTS</code> _(since v3.2.1)_</td>
      <td scope="row" data-label="Default">loopback only (<code>localhost</code>, <code>127.0.0.1</code>, <code>::1</code>)</td>
      <td scope="row" data-label="Allowed values">Comma-separated exact hostnames</td>
      <td scope="row" data-label="Notes">Hostnames accepted in the HTTP <code>Host</code> header for <code>/mcp</code> (DNS-rebinding guard). A non-empty list <strong>replaces</strong> the loopback default, so include <code>localhost</code> yourself if you still need it. Entries without a port match any port. Ignored when <code>SURREAL_MCP_ALLOW_ALL_HOSTS</code> is set.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MCP_ALLOW_ALL_HOSTS</code> _(since v3.2.1)_</td>
      <td scope="row" data-label="Default"><code>false</code></td>
      <td scope="row" data-label="Allowed values"><code>true</code> / <code>1</code> to enable</td>
      <td scope="row" data-label="Notes">Disables the <code>Host</code>-header allowlist (accept any <code>Host</code>). Escape hatch for a trusted proxy or load balancer. Takes precedence over <code>SURREAL_MCP_ALLOWED_HOSTS</code>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MCP_NS</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">A string</td>
      <td scope="row" data-label="Notes">The namespace that <code>surreal db mcp</code> uses when it starts. The same as its <code>--ns</code> flag.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MCP_DB</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">A string</td>
      <td scope="row" data-label="Notes">The database that <code>surreal db mcp</code> uses when it starts. The same as its <code>--db</code> flag.</td>
    </tr>
  </tbody>
</table>

### GQL config

_(since v3.2.0)_

Resource limits for [ISO GQL](/docs/learn/querying/gql/overview.md) `MATCH` execution. Errors name the limit when it is exceeded. From **3.3.0**, GQL is enabled by default; on **3.2.x**, enable it with [`--allow-experimental gql`](/docs/reference/cli/db/commands/start.md#experimental-capabilities).

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '40%'}}>Environment variable</th>
      <th scope="col" style={{width: '20%'}}>Default</th>
      <th scope="col" style={{width: '20%'}}>Allowed values</th>
      <th scope="col" style={{width: '20%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_GQL_MAX_PATH_ROWS</code></td>
      <td scope="row" data-label="Default">1,000,000</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Per source row, bounds live and emitted rows during variable-length path expansion in a GQL <code>MATCH</code>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_GQL_MAX_JOIN_BUILD_ROWS</code></td>
      <td scope="row" data-label="Default">1,000,000</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Bounds the in-memory build side of hash joins between GQL match patterns (and distinct-operator working sets).</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_GQL_MAX_OUTPUT_ROWS</code></td>
      <td scope="row" data-label="Default">1,000,000</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Bounds cumulative rows emitted by GQL hash-join operators (including cross joins).</td>
    </tr>
  </tbody>
</table>

### Limits config

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '40%'}}>Environment variable</th>
      <th scope="col" style={{width: '20%'}}>Default</th>
      <th scope="col" style={{width: '20%'}}>Allowed values</th>
      <th scope="col" style={{width: '20%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>

    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_GRAPH_INLINE_PROPS_CAP</code> _(since v3.3.0)_</td>
      <td scope="row" data-label="Default">64</td>
      <td scope="row" data-label="Allowed values">A number of bytes, without a unit suffix</td>
      <td scope="row" data-label="Notes">Largest encoded payload an <a href="/docs/reference/query-language/statements/define/field.md#using-inline-to-filter-a-traversal-during-the-scan"><code>INLINE</code></a> field set may occupy inside a graph adjacency entry. A larger payload spills, leaving the values on the edge record only.</td>
    </tr>

    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_BITMAP_BRANCH_BUDGET</code>_(since v3.3.0)_</td>
      <td scope="row" data-label="Default">250,000</td>
      <td scope="row" data-label="Allowed values">A usize; <code>0</code> disables the budget</td>
      <td scope="row" data-label="Notes">How many index entries one range branch of a bitmap plan, which combines several indexes into a bitmap of candidate records, may read before that branch is abandoned. The abandoned branch's condition is then checked as an ordinary <code>WHERE</code> filter, so an unselective range cannot make the bitmap plan slower than scanning. The same budget is the upper limit for the allow-list built for a pre-filtered vector search, which from 4.0 has a smaller limit when the search width is small (see <a href="#vector-search-config">Vector search config</a>).</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_EXTERNAL_SORTING_BUFFER_LIMIT</code></td>
      <td scope="row" data-label="Default">50000</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The number of result records which will trigger on-disk sorting.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_STRING_SIMILARITY_LIMIT</code></td>
      <td scope="row" data-label="Default">16384</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum input string length for similarity/distance functions</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_FAN_OUT_ROW_THRESHOLD</code>_(since v3.3.0)_</td>
      <td scope="row" data-label="Default">4</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">A batch with fewer items than this is evaluated one item at a time. A larger batch has its items evaluated concurrently, but only when the evaluation is read-only. Set it above the batch size to turn concurrent evaluation off.</td>
    </tr>
     <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_GENERATION_ALLOCATION_LIMIT</code></td>
      <td scope="row" data-label="Default">20 (2<sup>20</sup> = 1,048,576 bytes)</td>
      <td scope="row" data-label="Allowed values">A power of two, as its exponent: an integer up to 28 (256 MiB); larger values are treated as 28</td>
      <td scope="row" data-label="Notes">Limits the memory that a single call to <code>array::combine</code>, <code>array::concat</code>, <code>array::range</code>, <code>array::repeat</code>, <code>array::sequence</code>, <code>array::transpose</code>, <code>array::windows</code>, <code>string::concat</code>, <code>string::join</code>, <code>string::repeat</code> or <code>string::replace</code> can allocate for its result, and the number of values that a scripting function can return. A call over the limit fails with an error. The value is an exponent, not a byte count: the limit is 2 to the power of the value, so the default of <code>20</code> allows 1,048,576 bytes. Setting a byte count such as <code>1048576</code> sets the limit to its maximum of 2<sup>28</sup> bytes.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_IDIOM_RECURSION_LIMIT</code></td>
      <td scope="row" data-label="Default">256</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum recursive idiom path depth allowed. Read only before 3.1.0; later versions use a fixed limit of 256.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MEMORY_LIMIT</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">0 (half of <code>SURREAL_MEMORY_THRESHOLD</code> if set, otherwise 2 GiB)</td>
      <td scope="row" data-label="Allowed values">A usize or suffixed integer</td>
      <td scope="row" data-label="Notes">The bytes that all queries on the node may hold in sorts, grouped aggregates, <code>DISTINCT</code> and join builds before they spill to disk. See <a href="#memory-limits-and-spilling-to-disk">Memory limits and spilling to disk</a>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_QUERY_MEMORY_MAX</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">0 (the node memory limit)</td>
      <td scope="row" data-label="Allowed values">A usize or suffixed integer</td>
      <td scope="row" data-label="Notes">The bytes that a single query may hold which it cannot spill, such as gathered values and its transaction buffers. A query that passes it fails with the memory threshold error, and other queries are not affected.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_QUERY_MEMORY_MINIMUM</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">4 MiB</td>
      <td scope="row" data-label="Allowed values">A usize or suffixed integer</td>
      <td scope="row" data-label="Notes">The bytes that every query holding a sort, group, <code>DISTINCT</code> or join build is guaranteed, in addition to what spilling takes.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MEMORY_WAIT</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">1000</td>
      <td scope="row" data-label="Allowed values">A number of milliseconds</td>
      <td scope="row" data-label="Notes">The longest that a query waits in total for other queries to release memory before it continues past the node limit. <code>0</code> never waits.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SPILL_PART_SIZE</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">1 MiB</td>
      <td scope="row" data-label="Allowed values">A suffixed integer greater than zero</td>
      <td scope="row" data-label="Notes">The size of the parts in which a spilled run is written and read.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SPILL_MERGE_FAN_IN</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">8</td>
      <td scope="row" data-label="Allowed values">A usize, at least 2</td>
      <td scope="row" data-label="Notes">The number of spilled runs that a merge reads at once. A merge of more runs takes several passes.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MEMORY_RESERVE_CHUNK</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">256 KiB</td>
      <td scope="row" data-label="Allowed values">A suffixed integer greater than zero</td>
      <td scope="row" data-label="Notes">The bytes that a sort, group, <code>DISTINCT</code> or join build reserves from its query at a time.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_STREAM_STAGE_BYTES</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">No limit</td>
      <td scope="row" data-label="Allowed values">A byte count, or a size such as <code>64KiB</code></td>
      <td scope="row" data-label="Notes">The estimated bytes of result rows that a write statement streaming its results, in a transaction of its own, holds back until it commits. Held rows let a statement that meets a retryable conflict at commit run again without its client receiving the rows of the failed attempt. Past this size the held rows are sent and the rest stream as they are produced, and the statement is no longer run again on a conflict. <code>0</code> holds nothing back. By default every row is held until the commit.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MAX_COMPUTATION_DEPTH</code></td>
      <td scope="row" data-label="Default">120</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Specifies how deep recursive computation will go before erroring.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MAX_CONCURRENT_TASKS</code></td>
      <td scope="row" data-label="Default">64</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Specifies how many concurrent jobs can be buffered in the worker channel. Removed in 4.0.0, which no longer reads it, so setting it has no effect. _(since v4.0.0)_</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MAX_EXPRESSION_PARSING_DEPTH</code>_(since v3.3.0)_</td>
      <td scope="row" data-label="Default">128</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">How deep the parser will build an expression operator tree. This bounds long operator chains such as <code>1 + 1 + 1 + …</code> and prefix/postfix chains, which consume neither of the other two parsing budgets.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MAX_OBJECT_PARSING_DEPTH</code></td>
      <td scope="row" data-label="Default">100</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">How deep the parser will parse nested objects and arrays. Type annotations such as <code>array&lt;option&lt;array&lt;int&gt;&gt;&gt;</code> count against it as well. For data arriving over an SDK or RPC this is the governing limit. For a query written as text, see <a href="#nesting-depth-in-queries-versus-data">Nesting depth in queries versus data</a>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MAX_ORDER_LIMIT_PRIORITY_QUEUE_SIZE</code>_(since v2.2.0)_</td>
      <td scope="row" data-label="Default">1000</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum size of the priority queue triggering usage of the priority queue for the result collector.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MAX_QUERY_PARSING_DEPTH</code></td>
      <td scope="row" data-label="Default">20</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">How deep the parser will parse recursive queries (queries within queries). Object and array literals written into a query count against this budget as well as against <code>SURREAL_MAX_OBJECT_PARSING_DEPTH</code>, and this one is the smaller of the two - see <a href="#nesting-depth-in-queries-versus-data">Nesting depth in queries versus data</a>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_OPERATOR_BUFFER_SIZE</code></td>
      <td scope="row" data-label="Default">2</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The number of batches each operator buffers ahead of downstream demand. Set to 0 to disable operator-level pipeline buffering.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_REGEX_SIZE_LIMIT</code></td>
      <td scope="row" data-label="Default">10,485,760 (10 MiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Limits the maximum allowed size (in bytes) for regular expressions. This prevents excessive memory consumption when building complex or very large regex patterns.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SCAN_BATCH_SIZE</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">1000</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">How many records a scan collects before it passes them on as a batch, for table, index, record ID, graph and reference scans. The unit is records, not bytes. A lower value uses less memory for each query on a small node, at the cost of more work for each batch. A graph scan that checks permissions can hold about twice this many records at once, plus one batch of the records it resolves.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SCAN_BATCH_BYTES</code>_(since v3.3.1)_</td>
      <td scope="row" data-label="Default">2,097,152 (2 MiB)</td>
      <td scope="row" data-label="Allowed values">A byte count, or a size such as <code>512KiB</code></td>
      <td scope="row" data-label="Notes">The approximate decoded size of each batch of records that a query fetches from an index result, such as the matches of a full-text search. A batch also holds at most 1,000 records. Every operator after the scan holds whole batches, so the memory a query uses grows with this value. Lower it to limit memory on a small node, or raise it for fewer, larger batches. <code>0</code> and values that cannot be parsed are ignored.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TOPK_THRESHOLD_PUSHDOWN_ENABLED</code>_(since v3.2.0)_</td>
      <td scope="row" data-label="Default">true</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether a table scan for an <code>ORDER BY ... LIMIT</code> query can skip decoding a record that cannot rank among the records kept so far. Set it to <code>false</code> to turn the optimisation off.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TRANSACTION_MAX_WRITE_KEYS</code>_(since v3.2.4)_</td>
      <td scope="row" data-label="Default">0 (disabled)</td>
      <td scope="row" data-label="Allowed values">A <code>u64</code>; <code>0</code> disables</td>
      <td scope="row" data-label="Notes">Maximum number of key writes a single statement transaction may buffer before it is aborted and rolled back. Cascaded deletes, full-text index maintenance, graph-edge cleanup, and commit-time changefeed / live-query events all count toward the limit; each range delete counts as one write. Tripping the guard poisons the transaction so an explicit client <code>COMMIT</code> cannot persist a partial statement. Internal maintenance transactions (index builds, compaction, GC) are not bounded. On TiKV, range deletes may expand further inside the storage layer - size distributed clusters with both this limit and <code>SURREAL_TIKV_DELR_MAX_KEYS</code> in mind. Scale / multi-node deployments often use a limit in the 50,000-100,000 range; leave at <code>0</code> for typical single-node use.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_READ_SNAPSHOT_MAX_STALENESS_SECS</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">3600 (one hour)</td>
      <td scope="row" data-label="Allowed values">A u64 (seconds)</td>
      <td scope="row" data-label="Notes">The largest <code>MAX STALENESS</code> that a <a href="/docs/reference/query-language/statements/begin.md#read-only-transactions">read-only transaction</a> can ask for. A larger request fails when the transaction begins, with <code>The requested MAX STALENESS of 5s is above the maximum of 1s this datastore allows</code>. It also limits how long a permission that has been revoked can still apply to a stale read.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_READ_SNAPSHOT_FALLBACK</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">allow</td>
      <td scope="row" data-label="Allowed values"><code>allow</code>, <code>deny</code>, <code>rate:&lt;n&gt;</code></td>
      <td scope="row" data-label="Notes">What a read-only transaction with <code>MAX STALENESS</code> does when no published snapshot is recent enough: read the current state (<code>allow</code>), fail (<code>deny</code>), or read the current state at most <code>n</code> times a second. <code>STRICT</code> on the statement fails in that case whatever this setting says. A datastore that publishes no snapshots, which includes every storage engine of the open-source release, always reads the current state, which meets every bound.</td>
    </tr>
  </tbody>
</table>

### Memory limits and spilling to disk

_(since v4.0.0)_

From SurrealDB 4.0, each node holds its queries to a memory limit, set by `SURREAL_MEMORY_LIMIT`. By default the limit is half of `SURREAL_MEMORY_THRESHOLD` where that is set, and 2 GiB otherwise. Each query is guaranteed a minimum share, set by `SURREAL_QUERY_MEMORY_MINIMUM`.

When a sort, a grouped aggregate, a `DISTINCT` or a join build outgrows its share, it writes sorted runs to temporary files and merges them. The query is slower, but it does not fail, and it does not need the `TEMPFILES` clause. If memory is short, a query first spills, then waits for other queries to release memory for up to `SURREAL_MEMORY_WAIT` milliseconds in total, and then continues past the limit.

Values that a query cannot spill, such as a gathered subquery result or a value bound with `LET`, are bounded for each query by `SURREAL_QUERY_MEMORY_MAX`. A query that passes it fails with the memory threshold error, and other queries are not affected.

Spill files go to the directory in `SURREAL_TEMPORARY_DIRECTORY`, or to a `surrealdb` folder in the system temporary directory. SurrealDB clears the files left by a process that has stopped the next time it opens the directory. There is no disk quota on this directory, so give it enough space and, in a container, mount it on a volume of suitable size. If the directory cannot be created, the server logs `Queries will not spill to disk` and starts with no memory limit on its queries.

> [!IMPORTANT]
> `SURREAL_MEMORY_THRESHOLD` is a separate guard over the whole process. Spilling does not exempt a query from it, so a query is still refused when the tracked memory of the process passes the threshold, whatever `SURREAL_MEMORY_LIMIT` is set to.

The following command lowers the node limit to 512 MiB and spills to a dedicated volume:

```bash
SURREAL_MEMORY_LIMIT=512MiB SURREAL_TEMPORARY_DIRECTORY=/var/lib/surrealdb/spill surreal db start --user root --pass secret surrealkv://mydb
```

#### Nesting depth in queries versus data

Four separate budgets bound recursion, and which one a deeply nested value hits depends on how it reaches the server.

A value written into query text is read by the SurrealQL parser, and each level of an object or array costs one level of `SURREAL_MAX_QUERY_PARSING_DEPTH` as well as one of `SURREAL_MAX_OBJECT_PARSING_DEPTH`. Since the query budget defaults to `20` against the object budget's `100`, the query budget is what a nested literal runs out of first.

A value arriving as **data** (the body of an SDK call, an RPC message, or a WebSocket frame) is never parsed as SurrealQL, so it spends only the object budget and nests roughly five times deeper for the same default configuration.

The practical effect is that one document can be accepted through an SDK and rejected as a literal in `surreal db sql`, which reads as an inconsistency but is two budgets doing their own jobs. A structure alternating object and array, as in `{ inner: [{ inner: [ … ] }] }`, spends two levels per step:

| Path | Governing default | Levels of `{ inner: [ … ] }` |
| --- | --- | --- |
| Query text (`surreal db sql`, `/sql`) | `SURREAL_MAX_QUERY_PARSING_DEPTH` = 20 | 9 |
| SDK, RPC, WebSocket | `SURREAL_MAX_OBJECT_PARSING_DEPTH` = 100 | 49 |

Exceeding either is a parse error, not a crash, giving the error `Exceeded query recursion depth limit` for the first, `Exceeded object recursion depth limit` for the second. To send deep literals as text, raise `SURREAL_MAX_QUERY_PARSING_DEPTH` - raising the object budget alone changes nothing on that path.

> [!NOTE]
> Two further depth limits are fixed and cannot be configured: recursive idiom paths stop at 256, and the binary protocol's decoder rejects frames nested beyond 512. Neither is reachable before the parsing budgets above under a default configuration.

### Runtime config

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '40%'}}>Environment variable</th>
      <th scope="col" style={{width: '20%'}}>Default</th>
      <th scope="col" style={{width: '20%'}}>Allowed values</th>
      <th scope="col" style={{width: '20%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_KVS_THREADPOOL_SIZE</code> _(since v3.1.1)_</td>
      <td scope="row" data-label="Default">Number of CPU cores (minimum 16)</td>
      <td scope="row" data-label="Allowed values">A usize, at least 4</td>
      <td scope="row" data-label="Notes">Number of worker threads the in-memory and SurrealKV engines use for storage work. A value below 4 or a value that is not a number logs a warning and the default is used.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_RUNTIME_MAX_BLOCKING_THREADS</code></td>
      <td scope="row" data-label="Default">512</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Number of threads which can be started for blocking operations.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_RUNTIME_STACK_SIZE</code></td>
      <td scope="row" data-label="Default">10,485,760 (10 MiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Runtime thread memory stack size. Default stack size is doubled if compiled from source in Debug mode.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_RUNTIME_WORKER_THREADS</code></td>
      <td scope="row" data-label="Default">Number of CPU cores (minimum 4)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Number of runtime worker threads used to start. See <a href="/docs/learn/querying/performance/performance-best-practices.md#cpu-cores-and-concurrent-queries">CPU cores and concurrent queries</a>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MORSEL_PLACES</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">No limit</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The most places of the node's worker pool that one statement can hold at once to scan in parallel. The pool has one place for each core beyond the one a statement's own task runs on. <code>0</code> runs every statement on its own task. Index builds and background index compaction draw on the same pool.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MORSEL_OLTP_RESERVE</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">1</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The places of the worker pool that parallel scans never take, so that short statements keep a core. On a host with two cores or fewer, the default leaves no place to share, so index builds and compaction run on one task unless this is set to <code>0</code>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MORSEL_PLACE_QUANTUM</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">8</td>
      <td scope="row" data-label="Allowed values">A u32</td>
      <td scope="row" data-label="Notes">How many chunks of its work a parallel worker finishes while another statement waits for a place, before it hands what is left of its work back and frees the place.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MORSEL_SPLIT_PASS_PPM</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">50000</td>
      <td scope="row" data-label="Allowed values">A u32</td>
      <td scope="row" data-label="Notes">The most records in a million that a scan's <code>WHERE</code> conditions can keep for the scan to be split into parts that run in parallel. The default is one record in twenty. A scan that keeps a larger share of the records it reads stays on one task, because most of its time is spent reading records, which more workers do not make faster. The share is measured from the records the scan has read so far. With <code>1000000</code>, a scan with a <code>WHERE</code> condition can be split whatever share of its records the condition keeps.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MORSEL_SPLIT_ROWS</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">256</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">How many entries a scan reads before the rest of it can be split into parts that run in parallel, and the fewest records in a batch that a parallel worker receives. Below this, the whole scan runs on the statement's own task, because starting a worker costs more than a small part saves.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MORSEL_TARGET_BYTES</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">1,048,576 (1 MiB)</td>
      <td scope="row" data-label="Allowed values">A byte count, or a size such as <code>512KiB</code></td>
      <td scope="row" data-label="Notes">The size that each part of a key range aims at when a scan is split to run in parallel. <code>1</code> makes every entry a part of its own. <code>0</code> and values that cannot be parsed are ignored.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MORSEL_WINDOW_BYTES</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">1,048,576 (1 MiB)</td>
      <td scope="row" data-label="Allowed values">A byte count, or a size such as <code>512KiB</code></td>
      <td scope="row" data-label="Notes">How many bytes of output a parallel part that is not at the front of its pipeline holds before it pauses and frees its place in the worker pool. <code>0</code> and values that cannot be parsed are ignored.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MORSEL_EXPLAIN_ANALYZE</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether <code>EXPLAIN ANALYZE</code> shows the counters of a statement's parallel parts. When it is off, the output is the same however many workers a node has.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_VM_QUANTUM</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">4096</td>
      <td scope="row" data-label="Allowed values">A u32</td>
      <td scope="row" data-label="Notes">How many units of work a running query does between two yields to the scheduler. A unit is a record, a loop iteration or a host step, and walking an array costs one unit for each element. A statement's timeout and cancellation are checked once in each quantum, so this also limits how long a statement can run past either. <code>0</code> is read as <code>1</code>.</td>
    </tr>
  </tbody>
</table>

### Scripting config

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '40%'}}>Environment variable</th>
      <th scope="col" style={{width: '20%'}}>Default</th>
      <th scope="col" style={{width: '20%'}}>Allowed values</th>
      <th scope="col" style={{width: '20%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SCRIPTING_MAX_STACK_SIZE</code></td>
      <td scope="row" data-label="Default">262_144 (256 KiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Maximum stack size of the JavaScript function runtime.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SCRIPTING_MAX_MEMORY_LIMIT</code></td>
      <td scope="row" data-label="Default">2,097,152 (2 MiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Maximum memory limit of the JavaScript function runtime.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SCRIPTING_MAX_TIME_LIMIT</code></td>
      <td scope="row" data-label="Default">5000 (5000 milliseconds or 5 seconds)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Maximum allowed time in milliseconds that a JavaScript function is allowed to run for.</td>
    </tr>
  </tbody>
</table>

### Security config

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '40%'}}>Environment variable</th>
      <th scope="col" style={{width: '20%'}}>Default</th>
      <th scope="col" style={{width: '20%'}}>Allowed values</th>
      <th scope="col" style={{width: '20%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_INSECURE_FORWARD_ACCESS_ERRORS</code></td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Forward all signup/signin/authenticate query errors to a client performing authentication. Do not use in production.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_JWKS_CACHE_COOLDOWN_SECONDS</code></td>
      <td scope="row" data-label="Default">300</td>
      <td scope="row" data-label="Allowed values">seconds</td>
      <td scope="row" data-label="Notes">The shortest time between two fetches of a <a href="/docs/reference/query-language/statements/define/access/jwt.md#json-web-key-set-jwks">JWKS</a> object that a token with an unknown key identifier (<code>kid</code>) can cause.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_JWKS_CACHE_EXPIRATION_SECONDS</code></td>
      <td scope="row" data-label="Default">43200</td>
      <td scope="row" data-label="Allowed values">seconds</td>
      <td scope="row" data-label="Notes">How long a fetched JWKS object stays in the cache before it is fetched again. The default is 12 hours.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_JWKS_REMOTE_TIMEOUT_MILLISECONDS</code></td>
      <td scope="row" data-label="Default">1000</td>
      <td scope="row" data-label="Allowed values">milliseconds</td>
      <td scope="row" data-label="Notes">How long a request for a JWKS object from its URL may take before it fails. Raise it for an identity provider that answers slowly.</td>
    </tr>
  </tbody>
</table>

### Extension config

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '40%'}}>Environment variable</th>
      <th scope="col" style={{width: '20%'}}>Default</th>
      <th scope="col" style={{width: '20%'}}>Allowed values</th>
      <th scope="col" style={{width: '20%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_LAZY_SURREALISM</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether to lazy-load SurrealDB extensions instead of eagerly compiling them at server startup.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALISM_CACHE_SIZE</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Default">100</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The number of SurrealDB extensions which can be cached across transactions.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALISM_MAX_POOL_SIZE</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Default">8</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Per-module controller pool size ceiling for SurrealDB WASM extensions. Has no effect: the server does not read this variable, so the ceiling stays at 8. Removed in 4.0.0, which runs each call on a fresh instance; see <code>SURREAL_SURREALISM_MAX_CONCURRENT_INVOCATIONS</code>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALISM_MAX_MEMORY</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Default">None (unlimited)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Per-module WASM linear memory ceiling in bytes. From 4.0.0, an extension's <code>CAPABILITIES</code> can set a lower limit, and the smaller of the two applies.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALISM_MAX_EXECUTION_TIME</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Default">None (unlimited)</td>
      <td scope="row" data-label="Allowed values">A u64 (milliseconds)</td>
      <td scope="row" data-label="Notes">Per-invocation execution time ceiling for SurrealDB WASM extensions. From 4.0.0, an extension's <code>CAPABILITIES</code> and the query's timeout can set a lower limit, and the smallest applies.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALISM_MAX_CONCURRENT_INVOCATIONS</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">64</td>
      <td scope="row" data-label="Allowed values">A u32</td>
      <td scope="row" data-label="Notes">How many extension calls can run at once across the datastore. Each call runs on a fresh instance in one of these slots, and each slot reserves about 4 GiB of virtual address space (not resident memory) on 64-bit hosts, which a virtual memory limit such as <code>RLIMIT_AS</code> must allow. A quarter of the slots is kept for calls made from inside another extension. A call that finds no free slot waits, within its query's timeout.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALISM_MAX_FS_BYTES</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">104857600 (100 MiB)</td>
      <td scope="row" data-label="Allowed values">A u64</td>
      <td scope="row" data-label="Notes">The largest total size, in bytes, of the files that an extension archive bundles in its read-only filesystem. Applied when an archive is unpacked by <code>DEFINE EXTENSION</code> or at startup.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALISM_ALLOW_UNBOUNDED_EXECUTION</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether an extension defined with <code>CAPABILITIES { strict_timeout: false }</code> runs without time checks. Without this setting, every call is stopped by the execution time ceiling and the query's timeout, whatever the definition says. With it, such an extension holds its slot and its worker thread until it returns.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALISM_MAX_KV_ENTRIES</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Default">None (unlimited)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Per-module KV store entry count ceiling. Has no effect from 4.0.0, which removes the module KV store.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALISM_MAX_KV_VALUE_BYTES</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Default">None (unlimited)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Per-module KV store maximum value size in bytes. Has no effect from 4.0.0, which removes the module KV store.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALISM_LOG_LEVEL</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">debug</td>
      <td scope="row" data-label="Allowed values">none, full, error, warn, info, debug, trace</td>
      <td scope="row" data-label="Notes">Controls the tracing level at which stdout of SurrealDB extensions is emitted.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALISM_SILO_ENDPOINT</code>_(since v3.3.0)_</td>
      <td scope="row" data-label="Default"><code>https://silo.surrealdb.com</code></td>
      <td scope="row" data-label="Allowed values">A URL</td>
      <td scope="row" data-label="Notes">Not read from 4.0.0, where <code>silo::</code> packages always come from <code>https://silo.surrealdb.com</code>. Before 4.0.0: the base URL that a <code>silo::</code> package in <a href="/docs/reference/query-language/statements/define/extension.md">DEFINE EXTENSION</a> is fetched from, as <code>{endpoint}/{organisation}/{package}/{major}.{minor}.{patch}.surli</code>. A trailing slash is removed. Set it to a mirror to serve packages from somewhere else.</td>
    </tr>
  </tbody>
</table>

### Telemetry config

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '40%'}}>Environment variable</th>
      <th scope="col" style={{width: '20%'}}>Default</th>
      <th scope="col" style={{width: '20%'}}>Allowed values</th>
      <th scope="col" style={{width: '20%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_METRICS_ENABLED</code></td>
      <td scope="row" data-label="Default">true</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether the Prometheus <code>/metrics</code> endpoint is served on the HTTP port. When <code>false</code>, the route returns <code>404</code>. See <a href="/docs/operate/observability/metrics.md">Metrics</a>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_PROCESS_METRICS_REFRESH_INTERVAL</code></td>
      <td scope="row" data-label="Default">5</td>
      <td scope="row" data-label="Allowed values">Seconds (integer); values below 1 are raised to 1</td>
      <td scope="row" data-label="Notes">How often the process memory and CPU snapshot is refreshed. The <code>surrealdb.process.*</code> gauges and <code>INFO FOR ROOT</code> read this snapshot.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SLOW_QUERY_METRIC_THRESHOLD_MS</code></td>
      <td scope="row" data-label="Default">1000</td>
      <td scope="row" data-label="Allowed values">Milliseconds (integer); <code>0</code> disables the counter</td>
      <td scope="row" data-label="Notes">The duration above which a completed statement is also counted by the <code>surrealdb.slow_query.total</code> metric.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TELEMETRY_DISABLE_METRICS</code></td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether to disable sending metrics to the GRPC OTEL collector.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TELEMETRY_DISABLE_TRACING</code></td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether to disable sending traces to the GRPC OTEL collector.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TELEMETRY_NAMESPACE</code></td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">A string</td>
      <td scope="row" data-label="Notes">If set then use this as value for the namespace label when sending telemetry</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TELEMETRY_PROVIDER</code></td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">otlp</td>
      <td scope="row" data-label="Notes">If set to "otlp" then telemetry is sent to the GRPC OTEL collector.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TOKIO_CONSOLE_ENABLED</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether to enable [tokio console](https://github.com/tokio-rs/console).</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TOKIO_CONSOLE_RETENTION</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Default">60</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">How long, in seconds, to retain data for completed events.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TOKIO_CONSOLE_SOCKET_ADDR</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">String to a socket address</td>
      <td scope="row" data-label="Notes">The socket address that Tokio Console will bind to.</td>
    </tr>
  </tbody>
</table>

### Vector search config

_(since v3.3.0)_

These variables tune vector search on HNSW and DiskANN indexes. Most of them tune pre-filtered vector search: when a KNN query on an HNSW or DiskANN index has `WHERE` conditions that other indexes can answer, SurrealDB first evaluates those conditions into an allow-list of matching records and restricts the vector search to it. See [How the filter is applied](/docs/learn/data-models/vector-search/similarity-search.md#how-the-filter-is-applied).

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '40%'}}>Environment variable</th>
      <th scope="col" style={{width: '20%'}}>Default</th>
      <th scope="col" style={{width: '20%'}}>Allowed values</th>
      <th scope="col" style={{width: '20%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HNSW_BUILD_PARALLELISM</code></td>
      <td scope="row" data-label="Default">auto</td>
      <td scope="row" data-label="Allowed values"><code>auto</code>, <code>serial</code>, or a number of tasks (<code>0</code> means <code>auto</code>)</td>
      <td scope="row" data-label="Notes">How many tasks one batch of HNSW index compaction builds its graph changes on. <code>auto</code> uses as many tasks as the machine reports available parallelism, and <code>serial</code> uses one. A batch that removes vectors always runs on one task.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_INDEX_BUILD_PARALLELISM</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">auto</td>
      <td scope="row" data-label="Allowed values"><code>auto</code>, <code>serial</code>, or a number of tasks (<code>0</code> means <code>auto</code>)</td>
      <td scope="row" data-label="Notes">How many batches of records the initial scan of a standard or <code>UNIQUE</code> index build indexes at the same time, each in a transaction of its own. <code>auto</code> uses the machine's available parallelism, up to 16, and <code>serial</code> indexes one batch at a time.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_DISKANN_FILTER_PREFETCH_MIN_CHUNK</code></td>
      <td scope="row" data-label="Default">64</td>
      <td scope="row" data-label="Allowed values">A usize greater than zero</td>
      <td scope="row" data-label="Notes">The first and smallest number of candidate records that a filtered KNN search on a DiskANN index reads at once. Each following read doubles, up to <code>SURREAL_DISKANN_FILTER_PREFETCH_MAX_CHUNK</code>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_DISKANN_FILTER_PREFETCH_MAX_CHUNK</code></td>
      <td scope="row" data-label="Default">4096</td>
      <td scope="row" data-label="Allowed values">A usize greater than zero</td>
      <td scope="row" data-label="Notes">The largest number of candidate records that a filtered KNN search on a DiskANN index reads at once.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_KNN_PREFILTER_ENABLED</code></td>
      <td scope="row" data-label="Default">true</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether KNN queries build an allow-list from their <code>WHERE</code> conditions. When <code>false</code>, the conditions are checked for each candidate during the index traversal instead, as before 3.3.0.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_KNN_PREFILTER_EXACT_THRESHOLD</code></td>
      <td scope="row" data-label="Default">2000</td>
      <td scope="row" data-label="Allowed values">A u64</td>
      <td scope="row" data-label="Notes">The allow-list size at or below which the search does not use the index graph at all, and instead scores every allowed record exactly. At this size an exact search is cheaper than a traversal and always finds the true nearest neighbours.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_KNN_PREFILTER_EXACT_COST</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">5</td>
      <td scope="row" data-label="Allowed values">A u32</td>
      <td scope="row" data-label="Notes">How strongly an HNSW search above <code>SURREAL_KNN_PREFILTER_EXACT_THRESHOLD</code> favours walking the graph over scoring the allowed records exactly. The search scores them exactly when the number of allowed records, squared and multiplied by this value, is at most <code>ef</code> multiplied by the index's <code>M0</code> and by the number of nodes in the graph. A larger value keeps more searches on the graph.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_KNN_PREFILTER_EF_BOOST</code></td>
      <td scope="row" data-label="Default">4</td>
      <td scope="row" data-label="Allowed values">A u32</td>
      <td scope="row" data-label="Notes">The multiplier applied to the search width (<code>ef</code>) of a DiskANN traversal restricted to an allow-list. From 4.0, an HNSW traversal reads <code>SURREAL_KNN_PREFILTER_HNSW_EF_BOOST</code> instead. A selective allow-list rejects most candidates, and a wider search recovers the recall that loses. The result is capped by <code>SURREAL_KNN_PREFILTER_EF_MAX</code> and is never lower than the <code>ef</code> the query asks for.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_KNN_PREFILTER_HNSW_EF_BOOST</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">1</td>
      <td scope="row" data-label="Allowed values">A u32</td>
      <td scope="row" data-label="Notes">The multiplier applied to the search width (<code>ef</code>) of an HNSW traversal restricted to an allow-list. The traversal already continues past the candidates the allow-list rejects, so the default of <code>1</code> does not widen it. Set it to <code>4</code> for the width that 3.x used.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_KNN_PREFILTER_EF_BOOST_THRESHOLD</code></td>
      <td scope="row" data-label="Default">100,000</td>
      <td scope="row" data-label="Allowed values">A u64</td>
      <td scope="row" data-label="Notes">The allow-list size above which the traversal stops multiplying <code>ef</code>, because a large allow-list rejects few candidates. Results are still restricted to the allow-list at every size.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_KNN_PREFILTER_EF_MAX</code></td>
      <td scope="row" data-label="Default">1024</td>
      <td scope="row" data-label="Allowed values">A u32</td>
      <td scope="row" data-label="Notes">The ceiling for the multiplied <code>ef</code>. It never lowers the <code>ef</code> a query asks for.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_DISKANN_QUANTIZED_SEARCH</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">true</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether a KNN search on a DiskANN index of <code>TYPE F32</code> or <code>TYPE F16</code> compares candidates using an 8-bit code of each vector, and then ranks its nearest results from the full vectors. The distances a query returns are exact either way. <code>false</code> compares full vectors throughout. Only an index defined or rebuilt on SurrealDB 4.0 keeps the codes, and other indexes ignore the setting.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_DISKANN_SEARCH_BEAM_WIDTH</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">1</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">How many candidates a DiskANN search expands in each step. A wider beam reads the neighbours of all of them in one batched read, so the search makes fewer storage round trips, but it also expands some candidates that a narrower beam would skip. The value is limited to between 1 and the search size of the query.</td>
    </tr>
  </tbody>
</table>

The allow-list is built within an entry budget for each index it reads. From SurrealDB 4.0 the budget is 512 entries for each unit of the search width `ef`, never less than twice `SURREAL_KNN_PREFILTER_EXACT_THRESHOLD` or 4,096, and never more than [`SURREAL_BITMAP_BRANCH_BUDGET`](#limits-config). Before 4.0 the budget is `SURREAL_BITMAP_BRANCH_BUDGET`. When the budget is exceeded, the query falls back to checking the conditions during the traversal. A vector index created before 3.3.0 uses the allow-list only after it is rebuilt with [`REBUILD INDEX`](/docs/reference/query-language/statements/rebuild.md).

### WebSocket config

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '40%'}}>Environment variable</th>
      <th scope="col" style={{width: '20%'}}>Default</th>
      <th scope="col" style={{width: '20%'}}>Allowed values</th>
      <th scope="col" style={{width: '20%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_WEBSOCKET_MAX_MESSAGE_SIZE</code></td>
      <td scope="row" data-label="Default">134,217,728 (128 MiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum WebSocket message size, which is also used as the maximum frame size. From 3.0.0 this replaces <code>SURREAL_WEBSOCKET_MAX_FRAME_SIZE</code>, which no longer exists and has no effect if set.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_WEBSOCKET_MAX_WRITE_BUFFER_SIZE</code></td>
      <td scope="row" data-label="Default">Greatest possible usize value</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum write buffer size before backpressure is applied.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_WEBSOCKET_READ_BUFFER_SIZE</code></td>
      <td scope="row" data-label="Default">131,072 (128 KiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The size of the read buffer for WebSocket connections. This controls how much data can be buffered when reading from WebSocket connections. Larger values can improve performance for high-throughput connections but consume more memory per connection.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_WEBSOCKET_WRITE_BUFFER_SIZE</code></td>
      <td scope="row" data-label="Default">131,072 (128 KiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The size of the write buffer for WebSocket connections. This controls how much data can be buffered when writing to WebSocket connections. Larger values can improve performance for high-throughput connections but consume more memory per connection.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_WEBSOCKET_RESPONSE_BUFFER_SIZE</code></td>
      <td scope="row" data-label="Default">0</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">How many responses can be buffered when delivering to the client.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_WEBSOCKET_RESPONSE_CHANNEL_SIZE</code></td>
      <td scope="row" data-label="Default">100</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Number of messages that can be queued for sending via WebSocket. From 3.3.0, replies and live query notifications have separate queues on each connection, each holding this many messages, and a value below 2 is raised to 2. A connection whose notification queue is full is closed, with a close frame giving the reason, rather than dropping notifications.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_WEBSOCKET_RESPONSE_FLUSH_PERIOD</code></td>
      <td scope="row" data-label="Default">3</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">How often (in milliseconds) any buffered responses are flushed to the WebSocket client.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_WEBSOCKET_MAX_CONCURRENT_STREAMS</code>_(since v3.3.0)_</td>
      <td scope="row" data-label="Default">32</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Maximum number of streaming queries (the <code>query_stream</code> RPC method) running at once on a single WebSocket connection. Each open stream holds an executing query, with its read snapshot or transaction, for as long as the client keeps reading. A request over the limit is refused with an error rather than queued.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_WEBSOCKET_STREAM_SEND_TIMEOUT</code>_(since v3.3.0)_</td>
      <td scope="row" data-label="Default">30</td>
      <td scope="row" data-label="Allowed values">Seconds (integer), clamped to 1-86,400</td>
      <td scope="row" data-label="Notes">How long a streaming query may wait to hand one frame to the connection before the stream is stopped. The wait resets for every frame, so it limits a stalled client rather than the length of a stream, and it applies even when <code>SURREAL_QUERY_TIMEOUT</code> is not set.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_WEBSOCKET_MAX_ATTACHED_SESSIONS</code></td>
      <td scope="row" data-label="Default">256</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum number of explicitly attached sessions that a single WebSocket connection can hold at once. The sessions of a connection end when it closes.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MAX_TRANSACTIONS_PER_CONNECTION</code>_(since v3.2.2)_</td>
      <td scope="row" data-label="Default">64</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Maximum concurrently open client-managed transactions (<code>begin</code> RPC) on a WebSocket connection's implicit default session. Further <code>begin</code> calls return <code>Too many open transactions</code> until a slot is freed by <code>commit</code>, <code>cancel</code>, <code>reset</code>, or disconnect. Does not apply to attached sessions (see <code>SURREAL_MAX_TRANSACTIONS_PER_SESSION</code>).</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MAX_TRANSACTIONS_PER_SESSION</code>_(since v3.2.2)_</td>
      <td scope="row" data-label="Default">64</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Maximum concurrently open client-managed transactions within a single attached WebSocket session. Counted per session and independent of the connection default-session limit. Detaching or resetting a session cancels its open transactions and frees their slots.</td>
    </tr>
  </tbody>
</table>

### Operator and internal config

_(since v3.2.0)_

These settings are for operators, benchmarks, and advanced debugging - not typical application configuration. They are documented so core contributors and self-hosted deployments can find configuration options that already exist in the engine. Changing them can affect performance, reproducibility, or live-query behaviour; leave defaults in place unless you have a specific reason to tune them.

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '40%'}}>Environment variable</th>
      <th scope="col" style={{width: '20%'}}>Default</th>
      <th scope="col" style={{width: '20%'}}>Allowed values</th>
      <th scope="col" style={{width: '20%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_RAND_SEED</code></td>
      <td scope="row" data-label="Default">none (non-deterministic)</td>
      <td scope="row" data-label="Allowed values">A <code>u64</code></td>
      <td scope="row" data-label="Notes">Seeds the engine-wide RNG for reproducible runs in benchmarks and tests. Do not use in production.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_LIVE_QUERY_ENGINE</code></td>
      <td scope="row" data-label="Default"><code>inline</code></td>
      <td scope="row" data-label="Allowed values"><code>inline</code>, <code>router</code></td>
      <td scope="row" data-label="Notes">Selects the live-query execution engine. <code>inline</code> is the historical behaviour: each write evaluates every live query on its table, so write cost grows with the number of live queries. <code>router</code> delivers notifications after the write returns, in passes about every 100 ms, so write cost does not depend on the number of live queries (experimental rollout). See <a href="/docs/learn/querying/real-time/live-queries.md#live-query-engines">Live query engines</a>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_LIVE_QUERY_RETENTION</code></td>
      <td scope="row" data-label="Default">1h</td>
      <td scope="row" data-label="Allowed values">A duration</td>
      <td scope="row" data-label="Notes">How long the router engine retains live-query event history for subscriber resume. Only applies when <code>SURREAL_LIVE_QUERY_ENGINE=router</code>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HNSW_BUILD_SEED</code></td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">A <code>u64</code></td>
      <td scope="row" data-label="Notes">Seeds HNSW index construction for reproducible graph layouts in benchmarks. Do not use in production.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_GRAPH_NUMERIC_IDS</code>_(since v3.3.0)_</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether background graph folds write numeric-encoded adjacency blocks, which store each entry's record id as a compact table-level document id. Existing blocks are converted on their next fold, and reads handle both encodings. Size the lookup cache with <code>SURREAL_GRAPH_RESOLVE_CACHE_SIZE</code>.</td>
    </tr>
  </tbody>
</table>

### Other environment variables

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '40%'}}>Environment variable</th>
      <th scope="col" style={{width: '20%'}}>Default</th>
      <th scope="col" style={{width: '20%'}}>Allowed values</th>
      <th scope="col" style={{width: '20%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_BUILD_METADATA</code></td>
      <td scope="row" data-label="Default">Automatically populated</td>
      <td scope="row" data-label="Allowed values">A string</td>
      <td scope="row" data-label="Notes">The version identifier of this build. Defaults to the CARGO_PKG_VERSION environment variable if not specified.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_DATASTORE_AOL</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Default">never</td>
      <td scope="row" data-label="Allowed values">never|sync|async</td>
      <td scope="row" data-label="Notes">Append-only log mode. Only used by the memory engine.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_DATASTORE_PERSIST</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">String to a file path</td>
      <td scope="row" data-label="Notes">Filesystem path for persistence. Only used by the memory engine.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_DATASTORE_RETENTION</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Default">0 (unlimited)</td>
      <td scope="row" data-label="Allowed values">A duration</td>
      <td scope="row" data-label="Notes">Version retention period as a duration string. Used by the surrealkv engine. From 3.3.0 the memory engine refuses a non-zero value and the server does not start. _(since v3.3.0)_</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_DATASTORE_SNAPSHOT</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Default">never</td>
      <td scope="row" data-label="Allowed values">never|duration</td>
      <td scope="row" data-label="Notes">Snapshot interval. Only used by the memory engine.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_DATASTORE_SYNC</code></td>
      <td scope="row" data-label="Default">every (never on the memory engine)</td>
      <td scope="row" data-label="Allowed values">never|every|duration</td>
      <td scope="row" data-label="Notes">The sync mode for the database, the same setting as the <code>sync</code> path parameter. Used by the memory and surrealkv engines. When both are set, it takes precedence over <code>SURREAL_DATASTORE_SYNC_DATA</code>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_DATASTORE_SYNC_DATA</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Default">every (never on the memory engine)</td>
      <td scope="row" data-label="Allowed values">never|every|duration</td>
      <td scope="row" data-label="Notes">The sync mode for the database. Used by the memory and surrealkv engines.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_DATASTORE_VERSIONED</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true|false|0|1</td>
      <td scope="row" data-label="Notes">Whether MVCC versioning is enabled, for use with the <a href="/docs/reference/query-language/statements/select.md#the-version-clause"><code>VERSION</code> clause</a>. Used by the surrealkv engine. From 3.3.0 the memory engine does not support versioned queries, and refuses <code>true</code> so that the server does not start. _(since v3.3.0)_</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_EXPERIMENTAL_UPGRADE_FROM_3X</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true|false|0|1</td>
      <td scope="row" data-label="Notes">Lets a 4.0 node open a datastore that a 3.x release wrote, and upgrade it in place. The upgrade is experimental. Without this variable, the node refuses to start on such a datastore and leaves the data unchanged. A datastore that 4.0 has already upgraded opens without it. An embedded SDK reads the <code>experimental_upgrade_from_3x</code> datastore option instead. See <a href="/docs/operate/upgrading/3x-to-4x.md#opting-in-to-the-upgrade">Opting in to the upgrade</a>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_FEATURE_LEVEL</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">4.0|current</td>
      <td scope="row" data-label="Notes">The record format release a datastore is switched to when a node starts. A datastore in memory or SurrealKV switches to the 4.0 format on its first 4.0 start without it. A TiKV datastore keeps the 3.x format until a node starts with this set, and the switch is refused, with a warning, while a node that runs an older release is still running. It never moves a datastore back to an earlier format. See <a href="/docs/operate/upgrading/3x-to-4x.md#the-40-record-format">The 4.0 record format</a>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MEMORY_THRESHOLD</code></td>
      <td scope="row" data-label="Default">0 (disabled)</td>
      <td scope="row" data-label="Allowed values">A usize or suffixed integer</td>
      <td scope="row" data-label="Notes">The tracked memory, in bytes, above which queries are refused with <code>The query was not executed due to the memory threshold being reached</code>. The value can be specified as bytes (b, or without any suffix), kibibytes (k, kb, or kib), mebibytes (m, mb, or mib), or gibibytes (g, gb, or gib); Kubernetes-style <code>Gi</code> and <code>Mi</code> are not accepted. Unset or <code>0</code> disables the guard, and any other value is raised to at least 1 MiB. Tracked memory is the size the allocator reserves for each live heap allocation, which includes the SurrealKV block cache and is less than the process's resident memory, so set the threshold below the container's memory limit and above <code>SURREAL_SURREALKV_BLOCK_CACHE_CAPACITY</code>: at or below the cache size, a full cache refuses every query until the server restarts. Before 4.0, the RocksDB block cache was counted in the same way, and the threshold had to be above <code>SURREAL_ROCKSDB_BLOCK_CACHE_SIZE</code>. From 3.3.0 the reserved size rather than the requested size is counted, so a threshold carried over from an earlier release refuses queries at a lighter workload and may need raising. _(since v3.3.0)_ From 3.3.1 the threshold also stops a query that is already running: a query that reads records checks it after each batch, and fails with the same error once tracked memory is above it, rather than growing until the operating system stops the server. _(since v3.3.1)_ From 4.0.0 it also sets the default node memory limit, which is half of the threshold when <code>SURREAL_MEMORY_LIMIT</code> is not set. The threshold still refuses queries when the whole process passes it, whether or not their sorts and groups would spill. See <a href="#memory-limits-and-spilling-to-disk">Memory limits and spilling to disk</a>. _(since v4.0.0)_</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MEMORY_THRESHOLD_UNHEALTHY_AFTER</code>_(since v3.3.5)_</td>
      <td scope="row" data-label="Default">60</td>
      <td scope="row" data-label="Allowed values">Seconds (integer); <code>0</code> disables the check</td>
      <td scope="row" data-label="Notes">How long the memory threshold may refuse requests without a break before <code>/health</code> answers <code>503 Service Unavailable</code>, so that a liveness probe restarts the process. Any observation below the threshold resets the clock. Has no effect while <code>SURREAL_MEMORY_THRESHOLD</code> is not set.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_OBJECT_STORE</code></td>
      <td scope="row" data-label="Default">a <code>store</code> folder in the current directory</td>
      <td scope="row" data-label="Allowed values">A URL, such as <code>file:///var/lib/surrealdb/store</code></td>
      <td scope="row" data-label="Notes">Where SurrealML model files were stored. SurrealDB 4.0 removed SurrealML, so a 4.0 server stores nothing here. The folder is created when it does not exist.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CACHE_STORE</code></td>
      <td scope="row" data-label="Default">a <code>cache</code> folder in the current directory</td>
      <td scope="row" data-label="Allowed values">A URL, such as <code>file:///var/lib/surrealdb/cache</code></td>
      <td scope="row" data-label="Notes">Where SurrealML model files were cached. SurrealDB 4.0 removed SurrealML, so a 4.0 server caches nothing here. The folder is created when it does not exist.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_REGEX_CACHE_SIZE</code></td>
      <td scope="row" data-label="Default">1000</td>
      <td scope="row" data-label="Allowed values">An integer from 10 to 100,000; a value outside that range is treated as the nearest end of it</td>
      <td scope="row" data-label="Notes">The number of computed regexes which can be cached in the engine.</td>
    </tr>
  </tbody>
</table>

## Command environment variables

Many of the arguments passed into [the CLI](/docs/reference/cli/db/commands/start.md) can be set using the above environment variables instead.

As each of these environment variables correspond to a flag or a required argument passed into a command, it is good practice to put together a command that matches the environment variables you wish to set. Once the database server conforms to your expected behaviour, you can then pull out the values passed into each flag for your environment variables.

For example, take the following command to start the database.

```bash
surreal db start --user root --pass secret --allow-net --deny-funcs "crypto::md5, http::post, http::delete"
```

If we now wanted to use environment variables instead of the `--allow-net` and `--deny-funcs` flags, we would use the `SURREAL_CAPS_ALLOW_NET` and `SURREAL_CAPS_DENY_FUNC` environment variables.

As the `--allow-net` flag was passed in without a following value, the same will be the case with the `SURREAL_CAPS_ALLOW_NET` environment variable, becoming `SURREAL_CAPS_ALLOW_NET=`. The `--deny-funcs` flag can also be used on its own to deny execution of all functions, but in this case is followed by a string to indicate which exact functions are not allowed to be executed. As such, the `SURREAL_CAPS_DENY_FUNC` environment variable must also be followed by a string, becoming `SURREAL_CAPS_DENY_FUNC="crypto::md5, http::post, http::delete"`.

The command would then look like the following:

**Bash**

```bash
export SURREAL_CAPS_ALLOW_NET=
export SURREAL_CAPS_DENY_FUNC="crypto::md5, http::post, http::delete"
surreal db start --user root --pass secret
```

**PowerShell**

```powershell
$env:SURREAL_CAPS_ALLOW_NET
$env:SURREAL_CAPS_DENY_FUNC="crypto::md5, http::post, http::delete"
surreal db start --user root --pass secret
```

A command environment variable that takes a boolean will be set to true if the flag is present, and following it with `true` will cause an error.

For example, the `SURREAL_CAPS_ALLOW_ALL` environment variable is used to set whether to allow all capabilities such as scripting and allowing network access. The flag `--allow-all` is all that is needed to set to `true`. But as an environment variable, the value `true` must be included to override its default `false` value.

**Bash**

```bash title="SURREAL_CAPS_ALLOW_ALL example"
# set to default false
surreal db start

# Same, but implicitly shown
SURREAL_CAPS_ALLOW_ALL=false surreal db start

# Set to true
SURREAL_CAPS_ALLOW_ALL=true surreal db start

# Set to true
surreal db start --allow-all

# Error: only --allow-all needed to set to true
surreal db start --allow-all true
```

**PowerShell**

```powershell title="SURREAL_CAPS_ALLOW_ALL example"
# set to default false
surreal db start

# Same, but implicitly shown
$env:SURREAL_CAPS_ALLOW_ALL = "false"
surreal db start

# Set to true
$env:SURREAL_CAPS_ALLOW_ALL = "true"
surreal db start

# Set to true
surreal db start --allow-all

# Error: only --allow-all needed to set to true
surreal db start --allow-all true
```

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '25%'}}>Environment variable</th>
      <th scope="col" style={{width: '15%'}}>Command arg</th>
      <th scope="col" style={{width: '12%'}}>For command(s)</th>
      <th scope="col" style={{width: '12%'}}>Default</th>
      <th scope="col" style={{width: '18%'}}>Allowed values</th>
      <th scope="col" style={{width: '18%'}}>Details</th>
    </tr>
  </thead>
  <tbody>
  <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ALLOW_ORIGIN</code></td>
      <td scope="row" data-label="Command arg"><code>allow-origin</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">All origins</td>
      <td scope="row" data-label="Allowed values">A comma-separated list of origins</td>
      <td scope="row" data-label="Notes">The origins allowed to make cross-origin (CORS) requests, such as <code>https://app.example.com</code>. When it is not set, every origin is allowed. When it lists origins and no <code>*</code>, a WebSocket connection to <code>/rpc</code> that sends an <code>Origin</code> header is accepted only from a listed origin or with <code>Sec-Fetch-Site: same-origin</code>.</td>
    </tr>
  <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ASYNC_EVENT_PROCESSING_INTERVAL</code>_(since v3.0.0)_ </td>
      <td scope="row" data-label="Command arg"><code>async-event-interval</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">5s</td>
      <td scope="row" data-label="Allowed values">A duration</td>
      <td scope="row" data-label="Notes">The interval at which to process async events.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_AUTH_LEVEL</code></td>
      <td scope="row" data-label="Command arg"><code>auth-level</code></td>
      <td scope="row" data-label="Command">`export`, `import`, `sql`</td>
      <td scope="row" data-label="Default">root</td>
      <td scope="row" data-label="Allowed values">root, namespace, ns, database, db</td>
      <td scope="row" data-label="Notes">Authentication level to use when connecting.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_BIND</code></td>
      <td scope="row" data-label="Command arg"><code>bind</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">127.0.0.1:8000</td>
      <td scope="row" data-label="Allowed values">String to an address</td>
      <td scope="row" data-label="Notes">The hostname or IP address(es) to listen for connections on.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_POSTGRES_BIND</code></td>
      <td scope="row" data-label="Command arg"><code>postgres-bind</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">(disabled)</td>
      <td scope="row" data-label="Allowed values">String to an address</td>
      <td scope="row" data-label="Notes">The hostname or IP address to listen for <a href="/docs/reference/protocols/postgres-protocol.md">Postgres wire protocol</a> connections on.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_MYSQL_BIND</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Command arg"><code>mysql-bind</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">(disabled)</td>
      <td scope="row" data-label="Allowed values">String to an address</td>
      <td scope="row" data-label="Notes">The hostname or IP address to listen for <a href="/docs/reference/protocols/mysql-protocol.md">MySQL wire protocol</a> connections on, for example <code>127.0.0.1:3306</code>. The listener is disabled when this is not set.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_ALLOW_ALL</code></td>
      <td scope="row" data-label="Command arg"><code>allow-all</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Allow all capabilities.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_ALLOW_ARBITRARY_QUERY</code></td>
      <td scope="row" data-label="Command arg"><code>allow-arbitrary-query</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">guest, record, system (comma-separated)</td>
      <td scope="row" data-label="Notes">Allows arbitrary queries to be used by user groups except when specifically denied. Alternatively, you can provide a comma-separated list of user groups to allow specifically denied user groups to prevail over any other allowed user group.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_ALLOW_EVAL_QUERY</code>_(since v3.2.0)_</td>
      <td scope="row" data-label="Command arg"><code>allow-eval-query</code></td>
      <td scope="row" data-label="Command">`start`, `sql`</td>
      <td scope="row" data-label="Default">none (denied for all subjects)</td>
      <td scope="row" data-label="Allowed values">guest, record, system (comma-separated)</td>
      <td scope="row" data-label="Notes">Allow <code>eval::surql</code> and <code>eval::gql</code> for listed subject groups. Not enabled by <code>--allow-all</code>. Still subject to <a href="/docs/learn/security/authorization/capabilities.md#arbitrary-queries">arbitrary-query</a> restrictions - <code>--deny-arbitrary-query</code> blocks <code>eval</code> for that subject even when eval is allowed here. For remote clients, set on the <code>start</code> process only. See <a href="/docs/reference/cli/db/commands/sql.md#capabilities-and-remote-connections">Capabilities and remote connections</a>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_ALLOW_EXPERIMENTAL</code></td>
      <td scope="row" data-label="Command arg"><code>allow-experimental</code></td>
      <td scope="row" data-label="Command">`start`, `sql`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">surrealism, kvexport (comma-separated)</td>
      <td scope="row" data-label="Notes">Allow execution of experimental features. For remote clients, set on the <code>start</code> process. On <code>surreal db sql</code>, affects embedded engines and REPL parse validation only. See <a href="/docs/reference/cli/db/commands/start.md#experimental-capabilities">experimental capabilities</a>. <code>kvexport</code> turns on the <code>POST /kvexport</code> route. From 3.3.0, ISO GQL is on by default and does not need this variable, and from 4.0 the same applies to buckets and files. From 4.0, the values <code>gql</code> and <code>files</code> are refused as invalid names, and the server does not start.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_DENY_EXPERIMENTAL</code></td>
      <td scope="row" data-label="Command arg"><code>deny-experimental</code></td>
      <td scope="row" data-label="Command">`start`, `sql`, `mcp`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">surrealism, kvexport (comma-separated)</td>
      <td scope="row" data-label="Notes">Deny execution of the listed experimental features. A feature in both <code>SURREAL_CAPS_ALLOW_EXPERIMENTAL</code> and this list is denied. For remote clients, set on the <code>start</code> process.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_ALLOW_FUNC</code></td>
      <td scope="row" data-label="Command arg"><code>allow-funcs</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">all functions allowed</td>
      <td scope="row" data-label="Allowed values">Empty, <code>*</code>, or comma-separated function paths</td>
      <td scope="row" data-label="Notes">Allow execution of all functions except for functions that are specifically denied. Set to an empty value or <code>*</code> to allow all functions. Use a comma-separated list (for example, <code>array,string::len,http::get</code>) to allow specific function families or names. Values such as <code>true</code> are not valid. The environment variable name is singular (<code>FUNC</code>), matching the <code>--allow-funcs</code> flag.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_ALLOW_GUESTS</code></td>
      <td scope="row" data-label="Command arg"><code>allow-guests</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Allow guest users to execute queries.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_ALLOW_HTTP</code></td>
      <td scope="row" data-label="Command arg"><code>allow-http</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">all routes allowed</td>
      <td scope="row" data-label="Allowed values">Empty, or a comma-separated list of HTTP routes</td>
      <td scope="row" data-label="Notes">Allow all HTTP routes except those specifically denied, or only the listed routes. Route names: <code>health</code>, <code>export</code>, <code>kvexport</code>, <code>import</code>, <code>rpc</code>, <code>version</code>, <code>sync</code>, <code>sql</code>, <code>signin</code>, <code>signup</code>, <code>key</code>, <code>bucket</code>, <code>graphql</code>, <code>api</code>, <code>mcp</code>, <code>gql</code>, <code>postgres</code>, <code>mysql</code>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_ALLOW_MCP</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Command arg"><code>allow-mcp</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">all tools allowed</td>
      <td scope="row" data-label="Allowed values">Empty, or a comma-separated list of MCP tool names</td>
      <td scope="row" data-label="Notes">Allow all tools of the built-in MCP server except those specifically denied, or only the listed tools.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_ALLOW_NET</code></td>
      <td scope="row" data-label="Command arg"><code>allow-net</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">Comma-separated list of paths</td>
      <td scope="row" data-label="Notes">Allow all or certain outbound network access.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_ALLOW_RPC</code></td>
      <td scope="row" data-label="Command arg"><code>allow-rpc</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">all methods allowed</td>
      <td scope="row" data-label="Allowed values">Empty, or a comma-separated list of RPC methods</td>
      <td scope="row" data-label="Notes">Allow all RPC methods except those specifically denied, or only the listed methods.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_ALLOW_SCRIPT</code></td>
      <td scope="row" data-label="Command arg"><code>allow-scripting</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Allow execution of embedded scripting functions.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_ALLOW_INSECURE_STORABLE_CLOSURES</code>_(since v2.5.0)_</td>
      <td scope="row" data-label="Command arg"><code>allow-insecure-storable-closures</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Takes a boolean. From 2.5.0, closures cannot be stored, which removes a potential attack surface; on 2.5.x and 2.6.x this capability allows them again. Removed in 3.0.0, where closures can never be stored and the flag is rejected.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_DENY_ALL</code></td>
      <td scope="row" data-label="Command arg"><code>deny-all</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Deny all capabilities.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_DENY_ARBITRARY_QUERY</code></td>
      <td scope="row" data-label="Command arg"><code>deny-arbitrary-query</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">guest, record, system (comma-separated)</td>
      <td scope="row" data-label="Notes">Deny arbitrary queries for the listed user groups, or for all of them when no value is given. Specifically allowed user groups prevail over a general denial.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_DENY_EVAL_QUERY</code>_(since v3.2.0)_</td>
      <td scope="row" data-label="Command arg"><code>deny-eval-query</code></td>
      <td scope="row" data-label="Command">`start`, `sql`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">guest, record, system (comma-separated)</td>
      <td scope="row" data-label="Notes">Deny <code>eval::surql</code> and <code>eval::gql</code> for listed subject groups. Deny prevails over allow at the same specificity. For remote clients, set on the <code>start</code> process.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_DENY_FUNC</code></td>
      <td scope="row" data-label="Command arg"><code>deny-funcs</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false, comma-separated list</td>
      <td scope="row" data-label="Notes">Deny execution of all or certain functions.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_DENY_GUESTS</code></td>
      <td scope="row" data-label="Command arg"><code>deny-guests</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">true</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Deny guest users from executing queries.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_DENY_HTTP</code></td>
      <td scope="row" data-label="Command arg"><code>deny-http</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">Empty, or a comma-separated list of HTTP routes</td>
      <td scope="row" data-label="Notes">Deny all HTTP routes except those specifically allowed, or only the listed routes. Uses the same route names as <code>SURREAL_CAPS_ALLOW_HTTP</code>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_DENY_MCP</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Command arg"><code>deny-mcp</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">Empty, or a comma-separated list of MCP tool names</td>
      <td scope="row" data-label="Notes">Deny all tools of the built-in MCP server except those specifically allowed, or only the listed tools.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_DENY_NET</code></td>
      <td scope="row" data-label="Command arg"><code>deny-net</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">true</td>
      <td scope="row" data-label="Allowed values">true, false, comma-separated list</td>
      <td scope="row" data-label="Notes">Deny all or certain outbound access paths.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_DENY_RPC</code></td>
      <td scope="row" data-label="Command arg"><code>deny-rpc</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">Empty, or a comma-separated list of RPC methods</td>
      <td scope="row" data-label="Notes">Deny all RPC methods except those specifically allowed, or only the listed methods.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CAPS_DENY_SCRIPT</code></td>
      <td scope="row" data-label="Command arg"><code>deny-scripting</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">true</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Deny execution of embedded scripting functions.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_COOKIE_AUTH</code>_(since v4.0.0)_</td>
      <td scope="row" data-label="Command arg"><code>cookie-auth</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Issue the access token as an <code>HttpOnly</code> cookie through <code>/signin/cookie</code> and <code>/signup/cookie</code>, and accept the cookie from the origins in <code>SURREAL_ALLOW_ORIGIN</code>. When the record access method has <code>WITH REFRESH</code>, the refresh token is issued as a second <code>HttpOnly</code> cookie, and <code>POST /refresh/cookie</code> rotates both. Requires <code>SURREAL_ALLOW_ORIGIN</code> with no <code>*</code> entry. See <a href="/docs/reference/protocols/http-protocol.md#cookie-authentication">Cookie authentication</a>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CHANGEFEED_GC_INTERVAL</code></td>
      <td scope="row" data-label="Command arg"><code>changefeed-gc-interval</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">30s</td>
      <td scope="row" data-label="Allowed values">A duration</td>
      <td scope="row" data-label="Notes">The interval at which to perform changefeed garbage collection.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_CLIENT_IP</code></td>
      <td scope="row" data-label="Command arg"><code>client-ip</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">socket</td>
      <td scope="row" data-label="Allowed values">none, socket, CF-Connecting-IP, Fly-Client-IP, True-Client-IP, X-Real-IP, X-Forwarded-For, Forwarded</td>
      <td scope="row" data-label="Notes">The method of detecting the client's IP address. _(since v3.1.0)_ <code>Forwarded</code> parses the RFC 7239 <code>Forwarded</code> header (<code>for=</code> parameter).</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_DATABASE</code></td>
      <td scope="row" data-label="Command arg"><code>database</code></td>
      <td scope="row" data-label="Command">`sql`</td>
      <td scope="row" data-label="Default">main</td>
      <td scope="row" data-label="Allowed values">A string</td>
      <td scope="row" data-label="Notes">The database selected when starting the REPL.</td>
    </tr>
<tr>
      <td scope="row" data-label="Env var"><code>SURREAL_DATABASE</code></td>
      <td scope="row" data-label="Command arg"><code>database</code></td>
      <td scope="row" data-label="Command">`export`, `import`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">A string</td>
      <td scope="row" data-label="Notes">The database selected for the import or export.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_DEFAULT_DATABASE</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Command arg"><code>default-database</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">main</td>
      <td scope="row" data-label="Allowed values">A string</td>
      <td scope="row" data-label="Notes">The default database to use when starting a SurrealDB instance.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_DEFAULT_NAMESPACE</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Command arg"><code>default-namespace</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">main</td>
      <td scope="row" data-label="Allowed values">A string</td>
      <td scope="row" data-label="Notes">The default namespace to use when starting a SurrealDB instance.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_DURABLE_SESSIONS</code>_(since v3.2.2)_</td>
      <td scope="row" data-label="Command arg"><code>durable-sessions</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">From 4.0.0 this variable has no effect: every attached HTTP RPC session is stored in the datastore, and the server still accepts the flag and the variable, and logs a deprecation warning. Before 4.0.0 it persists client-attached HTTP RPC sessions in the datastore so they survive restarts and can be resumed on any node sharing the storage, and is off by default. WebSocket sessions are not durable. The persisted copy includes authentication state and is stored unencrypted. See <a href="/docs/reference/cli/db/commands/start.md#durable-http-rpc-sessions">Durable HTTP RPC sessions</a>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_DURABLE_SESSION_GC_INTERVAL</code>_(since v3.2.2)_</td>
      <td scope="row" data-label="Command arg"><code>durable-session-gc-interval</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">1h (60s before 4.0.0)</td>
      <td scope="row" data-label="Allowed values">A duration; <code>0</code> disables the background sweep</td>
      <td scope="row" data-label="Notes">How often expired attached HTTP RPC sessions are purged from the datastore. An expired session is refused whether or not it has been purged, so the sweep only reclaims storage. Before 4.0.0 it applies only when durable sessions are enabled.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_DURABLE_SESSION_TTL</code>_(since v3.2.2)_</td>
      <td scope="row" data-label="Command arg"><code>durable-session-ttl</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">24h</td>
      <td scope="row" data-label="Allowed values">A duration of at least 1ms</td>
      <td scope="row" data-label="Notes">Idle lifetime of an attached HTTP RPC session; each use refreshes the expiry (sliding TTL). From 4.0.0 a session expires between one and one and a half times this value after its last request, and applies to every attached HTTP RPC session. Before 4.0.0 it applies only when durable sessions are enabled.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_GRAPH_FOLD_INTERVAL</code>_(since v3.3.0)_</td>
      <td scope="row" data-label="Command arg"><code>graph-fold-interval</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">5s</td>
      <td scope="row" data-label="Allowed values">A duration</td>
      <td scope="row" data-label="Notes">The interval between background passes that fold a vertex's per-edge graph adjacency keys into packed blocks. A pass also starts early when a write queues fold work or a traversal meets a vertex with many unfolded keys. See also <code>SURREAL_GRAPH_FOLD_BATCH</code>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HIDE_WELCOME</code></td>
      <td scope="row" data-label="Command arg"><code>hide-welcome</code></td>
      <td scope="row" data-label="Command">`sql`</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether to show the welcome message when starting the REPL.</td>
    </tr>
<tr>
      <td scope="row" data-label="Env var"><code>SURREAL_IMPORT_FILE</code></td>
      <td scope="row" data-label="Command arg"><code>import-file</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">A file path</td>
      <td scope="row" data-label="Notes">Path to a SurrealQL file that will be imported when starting the server.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_INDEX_BUILD_RESUME_INTERVAL</code></td>
      <td scope="row" data-label="Command arg"><code>index-build-resume-interval</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">30s</td>
      <td scope="row" data-label="Allowed values">A duration; <code>0</code> disables it</td>
      <td scope="row" data-label="Notes">The interval at which a node looks for index builds that a node which stopped left unfinished, and resumes them.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_INDEX_COMPACTION_INTERVAL</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Command arg"><code>index-compaction-interval</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">5s</td>
      <td scope="row" data-label="Allowed values">A duration</td>
      <td scope="row" data-label="Notes">The interval at which to compact queued index updates. Writes to a full-text, count, or vector index enqueue pending updates that a background task folds into the index; this controls how often that task runs. One node in a cluster performs the work for the whole cluster. Lengthening the interval allows the pending backlog to grow, which increases the work each subsequent query must do to read through it.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_KEY</code></td>
      <td scope="row" data-label="Command arg"><code>key</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">A string 16, 24, or 32 bytes long</td>
      <td scope="row" data-label="Notes">Encryption key to use for on-disk encryption. Not currently in use.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_KVS_CA</code></td>
      <td scope="row" data-label="Command arg"><code>kvs-ca</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">String to a path</td>
      <td scope="row" data-label="Notes">Path to the CA file used when connecting to the remote KV store.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_KVS_CRT</code></td>
      <td scope="row" data-label="Command arg"><code>kvs-crt</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">String to a path</td>
      <td scope="row" data-label="Notes">Path to the certificate file used when connecting to the remote KV store.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_KVS_KEY</code></td>
      <td scope="row" data-label="Command arg"><code>kvs-key</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">String to a path</td>
      <td scope="row" data-label="Notes">Path to the private key file used when connecting to the remote KV store.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_LAZY_SURREALISM</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Command arg"><code>lazy-surrealism</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether to lazy-load SurrealDB extensions instead of eagerly compiling them at server startup.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_LOG</code></td>
      <td scope="row" data-label="Command arg"><code>log</code></td>
      <td scope="row" data-label="Command">`start`, `fix`</td>
      <td scope="row" data-label="Default">info</td>
      <td scope="row" data-label="Allowed values">none, full, error, warn, info, debug, trace</td>
      <td scope="row" data-label="Notes">The logging level for the database server. In a release build, <code>trace</code> and <code>full</code> give the same output as <code>debug</code>, because the TRACE level is compiled only into debug builds.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_LOG_FILE_ENABLED</code>_(since v2.4.0)_</td>
      <td scope="row" data-label="Command arg"><code>log-file-enabled</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Toggles file output.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_LOG_FILE_FORMAT</code>_(since v2.4.0)_</td>
      <td scope="row" data-label="Command arg"><code>log-file-format</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">text</td>
      <td scope="row" data-label="Allowed values">text, json</td>
      <td scope="row" data-label="Notes">The format for log file output.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_LOG_FILE_LEVEL</code>_(since v2.4.0)_</td>
      <td scope="row" data-label="Command arg"><code>log-file-level</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">none, full, error, warn, info, debug, trace</td>
      <td scope="row" data-label="Notes">Override the logging level for file output. In a release build, <code>trace</code> and <code>full</code> give the same output as <code>debug</code>, because the TRACE level is compiled only into debug builds.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_LOG_FILE_NAME</code>_(since v2.4.0)_</td>
      <td scope="row" data-label="Command arg"><code>log-file-name</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">surrealdb.log</td>
      <td scope="row" data-label="Allowed values">String to a file</td>
      <td scope="row" data-label="Notes">Filename for logs (default: `surrealdb.log`)</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_LOG_FILE_PATH</code>_(since v2.4.0)_</td>
      <td scope="row" data-label="Command arg"><code>log-file-path</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">logs</td>
      <td scope="row" data-label="Allowed values">String to a path</td>
      <td scope="row" data-label="Notes">Sets the directory for logs</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_LOG_FILE_ROTATION</code>_(since v2.4.0)_</td>
      <td scope="row" data-label="Command arg"><code>log-file-rotation</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">daily</td>
      <td scope="row" data-label="Allowed values">daily, hourly, never</td>
      <td scope="row" data-label="Notes">Sets the rotation duration for logs.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_LOG_FORMAT</code>_(since v2.4.0)_</td>
      <td scope="row" data-label="Command arg"><code>log-format</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">text</td>
      <td scope="row" data-label="Allowed values">text, json</td>
      <td scope="row" data-label="Notes">Sets the format for logs.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_LOG_OTEL_LEVEL</code><br />_(since v2.4.0)_</td>
      <td scope="row" data-label="Command arg"><code>log-otel-level</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">SURREAL_LOG logging level</td>
      <td scope="row" data-label="Allowed values">none, full, error, warn, info, debug, trace</td>
      <td scope="row" data-label="Notes">Override the logging level for OpenTelemetry. In a release build, <code>trace</code> and <code>full</code> give the same output as <code>debug</code>, because the TRACE level is compiled only into debug builds.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_LOG_SOCKET</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Command arg"><code>log-socket</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">String to a host:port</td>
      <td scope="row" data-label="Notes">Send logs to the specified host:port</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_LOG_SOCKET_FORMAT</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Command arg"><code>log-socket-format</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">text</td>
      <td scope="row" data-label="Allowed values">text, json</td>
      <td scope="row" data-label="Notes">  Set the format of the logs to the socket.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_LOG_SOCKET_LEVEL</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Command arg"><code>log-socket-level</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">SURREAL_LOG logging level</td>
      <td scope="row" data-label="Allowed values">none, full, error, warn, info, debug, trace</td>
      <td scope="row" data-label="Notes">Override the logging level for socket logs. In a release build, <code>trace</code> and <code>full</code> give the same output as <code>debug</code>, because the TRACE level is compiled only into debug builds.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_NAMESPACE</code></td>
      <td scope="row" data-label="Command arg"><code>namespace</code></td>
      <td scope="row" data-label="Command">`sql`</td>
      <td scope="row" data-label="Default">main</td>
      <td scope="row" data-label="Allowed values">A string</td>
      <td scope="row" data-label="Notes">The namespace to connect to via the REPL.</td>
    </tr>
<tr>
      <td scope="row" data-label="Env var"><code>SURREAL_NAMESPACE</code></td>
      <td scope="row" data-label="Command arg"><code>namespace</code></td>
      <td scope="row" data-label="Command">`export`, `import`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">A string</td>
      <td scope="row" data-label="Notes">The namespace selected for the import/export operation.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_NO_BANNER</code></td>
      <td scope="row" data-label="Command arg"><code>no-banner</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether to hide the startup banner.</td>
    </tr>
<tr>
      <td scope="row" data-label="Env var"><code>SURREAL_NO_DEFAULTS</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Command arg"><code>no-defaults</code></td>
      <td scope="row" data-label="Command"><code>`start`</code></td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether to disable default namespace and database creation. Conflicts with SURREAL_DEFAULT_DATABASE and SURREAL_DEFAULT_NAMESPACE, which set a default value for namespace and database for a new instance.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_NO_IDENTIFICATION_HEADERS</code></td>
      <td scope="row" data-label="Command arg"><code>no-identification-headers</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether to suppress the server name and version headers.</td>
    </tr>
<tr>
      <td scope="row" data-label="Env var"><code>SURREAL_NODE_MEMBERSHIP_CHECK_INTERVAL</code></td>
      <td scope="row" data-label="Command arg"><code>node-membership-check-interval</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">15s</td>
      <td scope="row" data-label="Allowed values">A duration</td>
      <td scope="row" data-label="Notes">The interval at which to process and archive inactive nodes.</td>
    </tr>
  <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_NODE_MEMBERSHIP_CLEANUP_INTERVAL</code></td>
      <td scope="row" data-label="Command arg"><code>node-membership-cleanup-interval</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">300s</td>
      <td scope="row" data-label="Allowed values">A duration</td>
      <td scope="row" data-label="Notes">The interval at which to process and cleanup archived nodes.</td>
    </tr>
  <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_NODE_MEMBERSHIP_REFRESH_INTERVAL</code></td>
      <td scope="row" data-label="Command arg"><code>node-membership-refresh-interval</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">3s</td>
      <td scope="row" data-label="Allowed values">A duration</td>
      <td scope="row" data-label="Notes">The interval at which to refresh node registration information. The <a href="/docs/reference/protocols/http-protocol.md#ready"><code>/ready</code></a> endpoint reports the node unhealthy when its cluster heartbeat is older than three times this interval (9s by default). The multiple is fixed and cannot be configured. From SurrealDB 4.0, on a datastore that several nodes write, such as TiKV, a value above 10s stops the node from starting.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_PASS</code></td>
      <td scope="row" data-label="Command arg"><code>pass</code></td>
      <td scope="row" data-label="Command">`export`, `import`, `sql`, `start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">A string</td>
      <td scope="row" data-label="Notes">Database authentication password to use when connecting. For <code>start</code>, the password of the initial root user, which cannot be empty or only whitespace.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var">SURREAL_PATH</td>
      <td scope="row" data-label="Command arg"><code>path</code></td>
      <td scope="row" data-label="Command">`fix`, `mcp`, `start`</td>
      <td scope="row" data-label="Default">memory</td>
      <td scope="row" data-label="Allowed values">A string</td>
      <td scope="row" data-label="Notes">Database path used for storing data. As a required argument (albeit with a default), it is not passed in via `--path`.</td>
    </tr>
<tr>
      <td scope="row" data-label="Env var"><code>SURREAL_PLANNER_STRATEGY</code>_(since v3.0.0)_</td>
      <td scope="row" data-label="Command arg"><code>planner-strategy</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">None (before 4.0.0, best-effort)</td>
      <td scope="row" data-label="Allowed values">best-effort|compute-only|all-read-only</td>
      <td scope="row" data-label="Notes">Deprecated, and has no effect from 4.0.0 as queries run on a single execution engine. The server still accepts the three values so that an existing configuration keeps starting, logs a deprecation warning and ignores them, and refuses to start on any other value. Remove it from your configuration. Before 4.0.0 it chose how far to use the query planner introduced in 3.0: the default used the new planner for read-only statements and fell back to the earlier compute planner on paths it did not implement, and compute-only skipped the new planner entirely.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_QUERY_TIMEOUT</code></td>
      <td scope="row" data-label="Command arg"><code>query-timeout</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">A duration</td>
      <td scope="row" data-label="Notes">The maximum duration that a batch of statements can run for. From 3.3.0 it is also a hard wall-clock limit on each HTTP <code>/sql</code>, <code>/gql</code> and <code>/graphql</code> request and on each RPC method call. An HTTP <code>/sql</code> or <code>/gql</code> request that exceeds it is answered with <code>504 Gateway Timeout</code>, and a <code>/graphql</code> request with a GraphQL error. The <code>begin</code>, <code>commit</code> and <code>cancel</code> RPC methods are exempt, but the calls made inside the transaction they control are still limited individually. _(since v3.3.0)_</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_RECLAIM_INTERVAL</code>_(since v3.2.0)_</td>
      <td scope="row" data-label="Command arg"><code>reclaim-interval</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">60s</td>
      <td scope="row" data-label="Allowed values">A duration</td>
      <td scope="row" data-label="Notes">How often the background reaper scans for tombstoned namespace, database, and index data to physically delete after a <code>REMOVE</code> statement. On the 2.x line it is available from 2.7.0 and covers namespaces and databases only.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_RECLAIM_GRACE</code>_(since v3.2.0)_</td>
      <td scope="row" data-label="Command arg"><code>reclaim-grace</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">10m</td>
      <td scope="row" data-label="Allowed values">A duration</td>
      <td scope="row" data-label="Notes">Minimum age a removed namespace, database, or index must reach before its data is reclaimed. The effective grace is the maximum of this value and <code>--tikv-gc-lifetime</code> on TiKV backends. Not available on 2.x.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SLOW_QUERY_LOG_THRESHOLD</code><br />_(since v2.3.8)_</td>
      <td scope="row" data-label="Command arg"><code>slow-log-threshold</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">A duration</td>
      <td scope="row" data-label="Notes">A duration specifying the minimum execution time after which a log is made to indicate a slow query</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SLOW_QUERY_LOG_PARAM_ALLOW</code>_(since v2.3.9)_</td>
      <td scope="row" data-label="Command arg"><code>slow-log-param-allow</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">Comma-separated strings</td>
      <td scope="row" data-label="Notes">A comma-separated list of parameter names whose values are listed in slow query logs. No parameter value is logged unless its name is listed here. See <a href="/docs/operate/observability/logging.md">Logging</a>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SLOW_QUERY_LOG_PARAM_DENY</code>_(since v2.3.9)_</td>
      <td scope="row" data-label="Command arg"><code>slow-log-param-deny</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">Comma-separated strings</td>
      <td scope="row" data-label="Notes">A comma-separated list of parameter names whose values are left out of slow query logs, even when <code>SURREAL_SLOW_QUERY_LOG_PARAM_ALLOW</code> also names them.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_STRICT</code></td>
      <td scope="row" data-label="Command arg"><code>strict</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether strict mode is enabled on this database instance. Ignored since SurrealDB 3.0 after which strictness is defined [per database](/docs/reference/query-language/statements/define/database.md#defining-a-strict-database) instead of instance.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_STARTUP_OPERATION_TIMEOUT</code></td>
      <td scope="row" data-label="Command arg"><code>startup-operation-timeout</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">60s</td>
      <td scope="row" data-label="Allowed values">A duration</td>
      <td scope="row" data-label="Notes">How long each built-in startup datastore operation may keep retrying before the server gives up. It is a per-operation budget rather than a total for startup, and it covers initialising the default namespace and database, initialising the root credentials, and registering this node in the cluster. Raise it where the storage backend is slow to accept the first writes.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TEMPORARY_DIRECTORY</code></td>
      <td scope="row" data-label="Command arg"><code>temporary-directory</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">A <code>surrealdb</code> folder in the system temporary directory _(since v4.0.0)_</td>
      <td scope="row" data-label="Allowed values">String to a directory</td>
      <td scope="row" data-label="Notes">Sets the directory for storing temporary database files, including the files that queries spill to when they pass their memory budget. Before 4.0.0 there was no default and the directory was used only by queries with <code>TEMPFILES</code>. A value that is not a directory is refused at startup. See <a href="#memory-limits-and-spilling-to-disk">Memory limits and spilling to disk</a>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TIKV_GC_INTERVAL</code></td>
      <td scope="row" data-label="Command arg"><code>tikv-gc-interval</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">10m</td>
      <td scope="row" data-label="Allowed values">A duration</td>
      <td scope="row" data-label="Notes">The interval at which the TiKV MVCC garbage collector runs. Only used with a TiKV datastore.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TIKV_GC_LIFETIME</code></td>
      <td scope="row" data-label="Command arg"><code>tikv-gc-lifetime</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">10m</td>
      <td scope="row" data-label="Allowed values">A duration</td>
      <td scope="row" data-label="Notes">How far behind the current timestamp the TiKV garbage collection safepoint may sit. Only used with a TiKV datastore. The effective <code>SURREAL_RECLAIM_GRACE</code> is never shorter than this value.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TIKV_LOCK_CLEANUP_INTERVAL</code></td>
      <td scope="row" data-label="Command arg"><code>tikv-lock-cleanup-interval</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">60s</td>
      <td scope="row" data-label="Allowed values">A duration</td>
      <td scope="row" data-label="Notes">The interval at which stale TiKV transaction locks are resolved. Only used with a TiKV datastore.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TOKEN</code></td>
      <td scope="row" data-label="Command arg"><code>token</code></td>
      <td scope="row" data-label="Command">`export`, `import`, `sql`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">A string</td>
      <td scope="row" data-label="Notes">Authentication token in JWT format to use when connecting.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TRANSACTION_TIMEOUT</code></td>
      <td scope="row" data-label="Command arg"><code>transaction-timeout</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">A duration</td>
      <td scope="row" data-label="Notes">The maximum duration that any single transaction can run for.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_UNAUTHENTICATED</code></td>
      <td scope="row" data-label="Command arg"><code>unauthenticated</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether to allow unauthenticated access.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_USER</code></td>
      <td scope="row" data-label="Command arg"><code>user</code></td>
      <td scope="row" data-label="Command">`export`, `import`, `sql`, start</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">A string</td>
      <td scope="row" data-label="Notes">Database authentication username to use when connecting. For <code>start</code>, the username of the initial root user, which cannot be empty or only whitespace.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_WEB_CRT</code></td>
      <td scope="row" data-label="Command arg"><code>web-crt</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">String to a path</td>
      <td scope="row" data-label="Notes">Path to the certificate file for encrypted client connections.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_WEB_KEY</code></td>
      <td scope="row" data-label="Command arg"><code>web-key</code></td>
      <td scope="row" data-label="Command">`start`</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">String to a path</td>
      <td scope="row" data-label="Notes">Path to the private key file for encrypted client connections.</td>
    </tr>
  </tbody>
</table>

### Authentication rate limiting environment variables

_(since v3.3.0)_

These variables throttle authentication attempts on the HTTP `/signin` and `/signup` endpoints, per client address. Both endpoints draw on one shared budget. A request to any other endpoint that carries HTTP Basic credentials (`Authorization: Basic ...`) is counted as a sign-in attempt and draws on the same budget. The limiter is off by default, and setting any of the burst, rate, or tracked-client values to `0` also turns it off.

An attempt that exceeds the budget is answered with `429 Too Many Requests` and a `Retry-After` header giving the seconds to wait.

> [!IMPORTANT]
> The limiter keys on the address resolved by [`--client-ip`](/docs/reference/cli/db/commands/start.md), so it needs a strategy that yields one address per client. With `--client-ip socket` behind a proxy, every request resolves to the proxy's address and shares a single budget, which throttles all authentication collectively. With `--client-ip none` no address is available and the limiter does nothing. A header strategy is only as trustworthy as the proxy setting the header: a request arriving without it yields no address and is admitted unchecked, so a header strategy protects only a deployment where every request to these endpoints passes through that proxy.

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '50%'}}>Environment variable</th>
      <th scope="col" style={{width: '15%'}}>Default</th>
      <th scope="col" style={{width: '15%'}}>Allowed values</th>
      <th scope="col" style={{width: '30%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HTTP_AUTH_RATE_LIMIT_ENABLED</code></td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether to rate limit authentication attempts on the HTTP <code>/signin</code> and <code>/signup</code> endpoints per client address. Only <code>true</code> and <code>false</code> are accepted; any other value is ignored and the default applies.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HTTP_AUTH_RATE_LIMIT_BURST</code></td>
      <td scope="row" data-label="Default">60</td>
      <td scope="row" data-label="Allowed values">A u32</td>
      <td scope="row" data-label="Notes">How many authentication attempts a single client address may make before being throttled. Set to <code>0</code> to disable the limiter.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HTTP_AUTH_RATE_LIMIT_PER_MINUTE</code></td>
      <td scope="row" data-label="Default">60</td>
      <td scope="row" data-label="Allowed values">A u32</td>
      <td scope="row" data-label="Notes">The sustained rate, in attempts per minute, at which a client address's budget refills. The default of 60 is one attempt per second. Set to <code>0</code> to disable the limiter.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_HTTP_AUTH_RATE_LIMIT_MAX_TRACKED_CLIENTS</code></td>
      <td scope="row" data-label="Default">16384</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">How many client addresses the limiter tracks at once. Unauthenticated callers write to this store, so it is a bounded cache: at capacity a new address evicts an existing entry rather than the store growing or the limiter switching off. An evicted address starts again from a full burst, so the sustained rate binds an address only while it stays tracked. Size this above the number of distinct addresses the instance authenticates. Set to <code>0</code> to disable the limiter.</td>
    </tr>
  </tbody>
</table>

## Storage backend environment variables

These environment variables are used to configure the storage backend for SurrealDB.

Some defaults below depend on system memory. That is the memory available to the SurrealDB process: the host's memory, lowered to the tightest memory limit of the cgroup the process runs in, whether that limit comes from a container or from a systemd unit's `MemoryMax`. Before SurrealDB 4.0, only a limit at the root of the process's cgroup hierarchy was read, which covers containers but not a systemd unit, so a server capped by systemd sized its caches from the whole host.

### SurrealKV environment variables

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '50%'}}>Environment variable</th>
      <th scope="col" style={{width: '15%'}}>Default</th>
      <th scope="col" style={{width: '15%'}}>Allowed values</th>
      <th scope="col" style={{width: '30%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALKV_BLOCK_CACHE_CAPACITY</code></td>
      <td scope="row" data-label="Default">Dynamically calculated via greater of ((system memory / 2) - 1 GiB) and 16MiB</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The capacity of the block cache in bytes. The cache holds recently read data blocks in memory. From 4.0 a compaction does not add the blocks it reads to the cache, and it removes the cached blocks of the tables it merged, so the cache holds blocks of live tables only.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALKV_BLOCK_SIZE</code></td>
      <td scope="row" data-label="Default">65_536 (64 KiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The block size in bytes.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALKV_ENABLE_VLOG</code></td>
      <td scope="row" data-label="Default">true</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether to enable value log separation.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALKV_GROUPED_COMMIT_MAX_BATCH_SIZE</code></td>
      <td scope="row" data-label="Default">4096</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum number of transactions in a single grouped commit batch. This prevents unbounded memory growth while still allowing large batches for efficiency. Larger batches improve throughput but increase memory usage and commit latency. From 4.0 the setting has no effect, because SurrealKV groups the syncs of concurrent commits itself, and the server logs a warning and ignores it.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALKV_GROUPED_COMMIT_TIMEOUT</code></td>
      <td scope="row" data-label="Default">5ms</td>
      <td scope="row" data-label="Allowed values">A duration in nanoseconds</td>
      <td scope="row" data-label="Notes">The maximum wait time in nanoseconds before forcing a grouped commit. Ensures that transactions do not wait indefinitely under low concurrency and balances commit latency against write throughput. From 4.0 the setting has no effect, because SurrealKV groups the syncs of concurrent commits itself, and the server logs a warning and ignores it.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALKV_GROUPED_COMMIT_WAIT_THRESHOLD</code></td>
      <td scope="row" data-label="Default">12</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Threshold for deciding whether to wait for more transactions. If the current batch size is greater or equal to this threshold (and below SURREAL_SURREALKV_GROUPED_COMMIT_MAX_BATCH_SIZE), then the coordinator will wait up to SURREAL_SURREALKV_GROUPED_COMMIT_TIMEOUT to collect more transactions. Smaller batches are flushed immediately to preserve low latency. From 4.0 the setting has no effect, because SurrealKV groups the syncs of concurrent commits itself, and the server logs a warning and ignores it.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALKV_MAX_MEMTABLE_SIZE</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">Depends on system memory: 64 MiB below 1 GiB, 128 MiB below 4 GiB, 256 MiB below 16 GiB, 1 GiB below 64 GiB, and 4 GiB otherwise</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The most memory a memtable holds before it is flushed to disk. The memtable holds recent writes. The limit counts the values the memtable holds as well as the memory area that indexes them, so a large load flushes to disk while it runs. From 4.0 it bounds the memory the memtable holds, not the size of a transaction: a commit too large for the memtable is written directly to a level-0 table. Before 4.0 a transaction larger than this fails, so raise it for large transactions.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALKV_VERSIONED_INDEX</code></td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether to enable versioned index. Only applies when versioning is enabled. From 4.0 the setting has no effect, because SurrealKV 1.0 reads versions without a separate index, and the server logs a warning and ignores it.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALKV_VLOG_MAX_FILE_SIZE</code></td>
      <td scope="row" data-label="Default">64 MiB (systems under 4 GiB), 128 MiB (up to 16 GiB), 256 MiB (up to 64 GiB), 512 MiB (others)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum size of a value log file in bytes.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SURREALKV_VLOG_THRESHOLD</code></td>
      <td scope="row" data-label="Default">4096 (4 KiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The value log threshold in bytes. Values larger than this are stored in the value log.</td>
    </tr>
  </tbody>
</table>

### TiKV environment variables

> [!IMPORTANT]
> These variables apply when SurrealDB is started with a `tikv://` endpoint for **local Community experimentation**. From SurrealDB 4.0, only the separate `surreal-tikv` build accepts a `tikv://` endpoint, and it reads the same variables. They are not the configuration surface for production multi-node HA. Prefer a managed cluster on [SurrealDB Cloud Scale](https://surrealdb.com/pricing) or a self-hosted cluster with [SurrealDB Enterprise](https://surrealdb.com/enterprise). See [Run a multi-node cluster](/docs/running/multi-node.md).

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '50%'}}>Environment variable</th>
      <th scope="col" style={{width: '15%'}}>Default</th>
      <th scope="col" style={{width: '15%'}}>Allowed values</th>
      <th scope="col" style={{width: '30%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TIKV_API_VERSION</code></td>
      <td scope="row" data-label="Default">1</td>
      <td scope="row" data-label="Allowed values">A u8</td>
      <td scope="row" data-label="Notes">Which TiKV cluster API version to use.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TIKV_ASYNC_COMMIT</code></td>
      <td scope="row" data-label="Default">true</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether to use asynchronous transactions.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TIKV_KEYSPACE</code></td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">A string</td>
      <td scope="row" data-label="Notes">A string specifying the keyspace identifier for data isolation.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TIKV_DELR_MAX_KEYS</code></td>
      <td scope="row" data-label="Default">1,000,000</td>
      <td scope="row" data-label="Allowed values">A u32</td>
      <td scope="row" data-label="Notes">The most keys that one range delete in a TiKV transaction may remove. A larger range fails with an error rather than growing the transaction without bound.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TIKV_GC_ENABLED</code></td>
      <td scope="row" data-label="Default">true</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether the background TiKV garbage collection runs. When <code>false</code>, the stale lock cleanup is skipped as well. The interval and lifetime are set with <code>SURREAL_TIKV_GC_INTERVAL</code> and <code>SURREAL_TIKV_GC_LIFETIME</code>, described under <a href="#command-environment-variables">Command environment variables</a>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TIKV_GRPC_MAX_DECODING_MESSAGE_SIZE</code></td>
      <td scope="row" data-label="Default">4,194,304 (4 MiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Sets the maximum size of a gRPC message that SurrealDB receives from TiKV, which limits how much one read can return. A single record or a batch of records larger than this fails with <code>decoded message length too large</code>. Raise it together with <code>SURREAL_TIKV_GRPC_MAX_ENCODING_MESSAGE_SIZE</code>, so that a record that can be written can also be read back.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TIKV_GRPC_MAX_ENCODING_MESSAGE_SIZE</code></td>
      <td scope="row" data-label="Default">4,194,304 (4 MiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Sets the maximum size of a gRPC message that SurrealDB sends to TiKV, which limits the size of a single write. A record larger than this fails with an <code>h2 protocol error</code>. TiKV refuses a single write above its own entry limit of 8 MiB whatever this is set to, with <code>The transaction is too large</code>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TIKV_HEALTH_PROBE</code></td>
      <td scope="row" data-label="Default">true</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether the server checks that the TiKV cluster answers when it connects at startup, so that an unreachable cluster fails the start rather than the first query.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TIKV_ONE_PHASE_COMMIT</code></td>
      <td scope="row" data-label="Default">true</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether to use one-phase transaction commit.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TIKV_REQUEST_TIMEOUT</code></td>
      <td scope="row" data-label="Default">10</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The duration in seconds for requests before they time out.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TIKV_SHUTDOWN_GRACE</code></td>
      <td scope="row" data-label="Default">30</td>
      <td scope="row" data-label="Allowed values">Seconds (integer)</td>
      <td scope="row" data-label="Notes">How long a shutdown waits for running transactions to finish before it continues.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TIKV_SHUTDOWN_GC_TIMEOUT</code></td>
      <td scope="row" data-label="Default">10</td>
      <td scope="row" data-label="Allowed values">Seconds (integer)</td>
      <td scope="row" data-label="Notes">The longest that the last garbage collection pass at shutdown may take, so that a slow pass does not hold up the exit.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TIKV_TLS_CA_PATH</code>_(since v3.3.0)_</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">A file path</td>
      <td scope="row" data-label="Notes">Path to the CA certificate used to verify the TiKV and PD servers. Setting all three <code>SURREAL_TIKV_TLS_*</code> variables switches the connection to mutual TLS (mTLS).</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TIKV_TLS_CERT_PATH</code>_(since v3.3.0)_</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">A file path</td>
      <td scope="row" data-label="Notes">Path to the client certificate that SurrealDB presents during mTLS. It must be set together with the CA and key paths.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_TIKV_TLS_KEY_PATH</code>_(since v3.3.0)_</td>
      <td scope="row" data-label="Default">none</td>
      <td scope="row" data-label="Allowed values">A file path</td>
      <td scope="row" data-label="Notes">Path to the private key that matches the client certificate. It must be set together with the CA and certificate paths. If only some of the three paths are set, SurrealDB refuses to connect and reports which are missing.</td>
    </tr>
  </tbody>
</table>

### RocksDB environment variables

> [!WARNING]
> RocksDB support was removed in SurrealDB 4.0. These variables apply to 3.x and earlier only. See [Moving a RocksDB database to SurrealKV](/docs/operate/self-hosted/deployment-models.md#moving-a-rocksdb-database-to-surrealkv).

Many RocksDB environment variables pertain to memory use. The default configuration results in the following rough estimates of RocksDB memory use on different instances:

| Instance memory size  | Estimate
| ------------- |:-------------:|
| 512 MiB | ~ 80MiB |
| 1 GiB | ~ 80MiB
| 2 GiB | ~ 640MiB
| 4 GiB | ~ 1.25GiB
| 8 GiB | ~ 3.25GiB
| 24 GiB | ~ 12GiB
| 128 GiB | ~ 67GiB

The available environment variables for configuring a RocksDB instance are:

<table>
  <thead>
    <tr>
      <th scope="col" style={{width: '50%'}}>Environment variable</th>
      <th scope="col" style={{width: '15%'}}>Default</th>
      <th scope="col" style={{width: '15%'}}>Allowed values</th>
      <th scope="col" style={{width: '30%'}}>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_BACKGROUND_FLUSH</code></td>
      <td scope="row" data-label="Default">true</td>
      <td scope="row" data-label="Allowed values">false, true</td>
      <td scope="row" data-label="Notes">Whether to enable background WAL file flushing. 2.x only: from 3.0.0, set a duration on <code>SURREAL_DATASTORE_SYNC_DATA</code> instead.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_BACKGROUND_FLUSH_INTERVAL</code></td>
      <td scope="row" data-label="Default">200 (milliseconds)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The interval in milliseconds between background flushes. 2.x only: from 3.0.0, set a duration on <code>SURREAL_DATASTORE_SYNC_DATA</code> instead.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_BLOB_COMPACTION_READAHEAD_SIZE</code></td>
      <td scope="row" data-label="Default">0</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Readahead size for blob compaction/GC.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_BLOB_COMPRESSION_TYPE</code></td>
      <td scope="row" data-label="Default">snappy</td>
      <td scope="row" data-label="Allowed values">none, snappy, lz4, zstd</td>
      <td scope="row" data-label="Notes">Compression type used for blob files.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_BLOB_FILE_SIZE</code></td>
      <td scope="row" data-label="Default">268,435,456 (256 MiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The target blob file size for RocksDB.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_BLOB_GC_AGE_CUTOFF</code></td>
      <td scope="row" data-label="Default">0.5</td>
      <td scope="row" data-label="Allowed values">Float between 0 and 1</td>
      <td scope="row" data-label="Notes">Fractional age cutoff for blob GC.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_BLOB_GC_FORCE_THRESHOLD</code></td>
      <td scope="row" data-label="Default">0.5</td>
      <td scope="row" data-label="Allowed values">Float between 0 and 1</td>
      <td scope="row" data-label="Notes">Discardable ratio threshold to force GC.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_BLOCK_CACHE_SIZE</code></td>
      <td scope="row" data-label="Default">Dynamically calculated via greater of ((system memory / 2) - 1 GiB) and 16MiB</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">RocksDB <a href="https://github.com/facebook/rocksdb/wiki/memory-usage-in-rocksdb">block cache size</a> in bytes</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_BLOCK_SIZE</code></td>
      <td scope="row" data-label="Default">65,536 (64 KiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The size of each uncompressed data block in bytes.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_COMPACTION_READAHEAD_SIZE</code></td>
      <td scope="row" data-label="Default">4 MiB (systems under 4 GiB), 8 MiB (up to 16 GiB), 16 MiB (others)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The readahead buffer size used during compaction.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_COMPACTION_STYLE</code> </td>
      <td scope="row" data-label="Default">level</td>
      <td scope="row" data-label="Allowed values">level, universal</td>
      <td scope="row" data-label="Notes">Use to specify the database compaction style.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_COMPACT_ON_SHUTDOWN</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">false</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether a graceful shutdown runs a full compaction of the database after flushing the memtables, as <code>ALTER SYSTEM COMPACT</code> does. On a large database this can take minutes or hours, which can be longer than the shutdown grace period of a container orchestrator.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_DELETION_FACTORY_DELETE_COUNT</code></td>
      <td scope="row" data-label="Default">50</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The number of deletions to track in the window.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_DELETION_FACTORY_RATIO</code></td>
      <td scope="row" data-label="Default">0.5</td>
      <td scope="row" data-label="Allowed values">A float</td>
      <td scope="row" data-label="Notes">The ratio of deletions to track in the window.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_DELETION_FACTORY_WINDOW_SIZE</code></td>
      <td scope="row" data-label="Default">1000</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The size of the window used to track deletions.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_ENABLE_BLOB_FILES</code></td>
      <td scope="row" data-label="Default">true</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether to enable separate key and value file storage.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_ENABLE_BLOB_GC</code></td>
      <td scope="row" data-label="Default">true</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether to enable blob garbage collection for RocksDB.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_ENABLE_PIPELINED_WRITES</code></td>
      <td scope="row" data-label="Default">true</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether to use separate queues for WAL writes and memtable writes.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_FILE_COMPACTION_TRIGGER</code></td>
      <td scope="row" data-label="Default">4</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The number of files needed to trigger level 0 compaction.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_FILE_READS_FOR_AUTO_READAHEAD</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">2</td>
      <td scope="row" data-label="Allowed values">A u64</td>
      <td scope="row" data-label="Notes">The number of sequential reads an iterator makes on one SST file before RocksDB starts to prefetch. Set to <code>0</code> to prefetch from the first read.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_GROUPED_COMMIT_MAX_BATCH_SIZE</code></td>
      <td scope="row" data-label="Default">4096</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum number of transactions in a single grouped commit batch. Used to prevent unbounded memory growth while still allowing large batches for efficiency. Larger batches improve throughput but increase memory usage and commit latency.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_GROUPED_COMMIT_TIMEOUT</code></td>
      <td scope="row" data-label="Default">5ms</td>
      <td scope="row" data-label="Allowed values">A duration</td>
      <td scope="row" data-label="Notes">The maximum wait time in nanosecond before forcing a grouped commit. Used to ensure that transactions do not wait indefinitely when concurrency is low, and to balance between transaction latency and write throughput.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_GROUPED_COMMIT_WAIT_THRESHOLD</code></td>
      <td scope="row" data-label="Default">12</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">Threshold for deciding whether to wait for more transactions. If the current batch size is greater or equal to this threshold (and below ROCKSDB_GROUPED_COMMIT_MAX_BATCH_SIZE), then the coordinator will wait up to ROCKSDB_GROUPED_COMMIT_TIMEOUT to collect more transactions. Smaller batches are flushed immediately to preserve low latency.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_INITIAL_AUTO_READAHEAD_SIZE</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">8,192 (8 KiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The size of the first prefetch. Each following read doubles it, up to <code>SURREAL_ROCKSDB_MAX_AUTO_READAHEAD_SIZE</code>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_JOBS_COUNT</code></td>
      <td scope="row" data-label="Default">Number of CPUs * 2</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum number of threads to use for flushing and compaction.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_KEEP_LOG_FILE_NUM</code></td>
      <td scope="row" data-label="Default">10</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum number of information log files to keep.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_LEVEL0_SLOWDOWN_WRITES_TRIGGER</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">8</td>
      <td scope="row" data-label="Allowed values">An i32</td>
      <td scope="row" data-label="Notes">The number of level-0 files at which RocksDB starts to slow down writes. The RocksDB default is 20.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_LEVEL0_STOP_WRITES_TRIGGER</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">12</td>
      <td scope="row" data-label="Allowed values">An i32</td>
      <td scope="row" data-label="Notes">The number of level-0 files at which RocksDB stops writes until compaction reduces the count. Keep it above <code>SURREAL_ROCKSDB_LEVEL0_SLOWDOWN_WRITES_TRIGGER</code>. The RocksDB default is 36.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_MAX_AUTO_READAHEAD_SIZE</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">262,144 (256 KiB)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The largest prefetch an iterator grows to. A larger value can make long range scans faster, but uses more memory for each iterator, so many concurrent scans multiply the cost.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_MAX_CONCURRENT_SUBCOMPACTIONS</code></td>
      <td scope="row" data-label="Default">4</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum number threads which will perform compactions.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_MAX_OPEN_FILES</code></td>
      <td scope="row" data-label="Default">1024</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum number of open files which can be opened by RocksDB.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_MAX_WRITE_BUFFER_NUMBER</code></td>
      <td scope="row" data-label="Default">2 (systems under 4 GiB), 4 (up to 16 GiB), 8 (up to 64 GiB), 32 (others)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum number of write buffers which can be used.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_MEMTABLE_PREFIX_BLOOM_RATIO</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">0.1</td>
      <td scope="row" data-label="Allowed values">An f64</td>
      <td scope="row" data-label="Notes">The size of the prefix bloom filter in each memtable, as a ratio of the write buffer size. RocksDB caps it at 0.25. Set to <code>0</code> to disable it. Only used when <code>SURREAL_ROCKSDB_PREFIX_EXTRACTOR_ENABLED</code> is true.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_MIN_BLOB_SIZE</code></td>
      <td scope="row" data-label="Default">4096</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The minimum size in bytes of a value for it to be stored in blob files.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_MIN_WRITE_BUFFER_NUMBER_TO_MERGE</code></td>
      <td scope="row" data-label="Default">2</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The minimum number of write buffers to merge before writing to disk.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_PERIODIC_COMPACTION_SECONDS</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">3600</td>
      <td scope="row" data-label="Allowed values">A u64</td>
      <td scope="row" data-label="Notes">The interval in seconds after which RocksDB rewrites an SST file that no other compaction has touched. This removes old versions and tombstones from data that is rarely written. Set to <code>0</code> to disable.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_PREFIX_EXTRACTOR_ENABLED</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">true</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether SST bloom filters are built on table and key-type prefixes, so that a scan can skip SST files that hold nothing from the table it reads.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_RUNTIME_RESERVE</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">2</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The number of runtime worker threads kept free for asynchronous work while other transactions wait on a storage call. A larger value keeps more threads free under load, but lowers the number of storage calls that can run at once. See <code>SURREAL_RUNTIME_WORKER_THREADS</code>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_SCAN_VERIFY_CHECKSUMS</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">true</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether scans and counts verify the checksum of each block when it is first read from disk. Disabling it makes cold scans faster, and is only safe on trusted storage.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_SHUTDOWN_WAIT_FOR_COMPACT_SECONDS</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">30</td>
      <td scope="row" data-label="Allowed values">A u64</td>
      <td scope="row" data-label="Notes">How long a graceful shutdown waits in seconds for a compaction that started after the final flush, so that the next start does not have to repeat it. Set to <code>0</code> to wait without a limit.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_SST_MAX_ALLOWED_SPACE_USAGE</code></td>
      <td scope="row" data-label="Default">0</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The maximum allowed space usage for SST files in bytes. The default of 0 means unlimited and disables space monitoring. When this limit is reached, the datastore enters read-and-deletion-only mode, where only read and delete operations are allowed. This allows gradual space recovery through data deletion.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_STORAGE_LOG_LEVEL</code></td>
      <td scope="row" data-label="Default">warn</td>
      <td scope="row" data-label="Allowed values">none, full, error, warn, info, debug, trace</td>
      <td scope="row" data-label="Notes">The information log level of the RocksDB library.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_TARGET_FILE_SIZE_BASE</code></td>
      <td scope="row" data-label="Default">67,108,864 (64 MiB)</td>
      <td scope="row" data-label="Allowed values">-</td>
      <td scope="row" data-label="Notes">The target file size for compaction in bytes.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_TARGET_FILE_SIZE_MULTIPLIER</code></td>
      <td scope="row" data-label="Default">2</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The target file size multiplier for each compaction level.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_THREAD_COUNT</code></td>
      <td scope="row" data-label="Default">Number of CPUs on machine</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The number of threads to start for flushing and compaction.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_UNIVERSAL_COMPRESSION_SIZE_PERCENT</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">-1</td>
      <td scope="row" data-label="Allowed values">An i32</td>
      <td scope="row" data-label="Notes">The percentage of output files to compress. <code>-1</code> compresses all of them. Only used when <code>SURREAL_ROCKSDB_COMPACTION_STYLE</code> is <code>universal</code>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_UNIVERSAL_MAX_MERGE_WIDTH</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">4,294,967,295 (no limit)</td>
      <td scope="row" data-label="Allowed values">A u32</td>
      <td scope="row" data-label="Notes">The largest number of files in a single merge. Only used when <code>SURREAL_ROCKSDB_COMPACTION_STYLE</code> is <code>universal</code>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_UNIVERSAL_MAX_SIZE_AMPLIFICATION_PERCENT</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">200</td>
      <td scope="row" data-label="Allowed values">A u32</td>
      <td scope="row" data-label="Notes">The largest acceptable storage amplification, as a percentage of the size of the live data. Only used when <code>SURREAL_ROCKSDB_COMPACTION_STYLE</code> is <code>universal</code>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_UNIVERSAL_MIN_MERGE_WIDTH</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">2</td>
      <td scope="row" data-label="Allowed values">A u32</td>
      <td scope="row" data-label="Notes">The smallest number of files in a single merge. Only used when <code>SURREAL_ROCKSDB_COMPACTION_STYLE</code> is <code>universal</code>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_UNIVERSAL_SIZE_RATIO</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">1</td>
      <td scope="row" data-label="Allowed values">An i32</td>
      <td scope="row" data-label="Notes">How much larger, as a percentage, a file can be than the files before it and still be picked for the same merge. Only used when <code>SURREAL_ROCKSDB_COMPACTION_STYLE</code> is <code>universal</code>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_UNIVERSAL_STOP_STYLE</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">total</td>
      <td scope="row" data-label="Allowed values">similar_size, total</td>
      <td scope="row" data-label="Notes">How RocksDB decides that a merge has collected enough files. Only used when <code>SURREAL_ROCKSDB_COMPACTION_STYLE</code> is <code>universal</code>.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_WAL_SIZE_LIMIT</code></td>
      <td scope="row" data-label="Default">0</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The write-ahead-log size limit in MiB.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_WHOLE_KEY_FILTERING</code>_(since v3.1.0)_</td>
      <td scope="row" data-label="Default">true</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether SST bloom filters also hold whole keys as well as prefixes. Whole keys make point lookups faster, at the cost of larger filters. Disabling it can suit a workload that mostly scans. Only used when <code>SURREAL_ROCKSDB_PREFIX_EXTRACTOR_ENABLED</code> is true.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_ROCKSDB_WRITE_BUFFER_SIZE</code></td>
      <td scope="row" data-label="Default">32 MiB (systems under 1 GiB), 64 MiB (up to 16 GiB), 128 MiB (others)</td>
      <td scope="row" data-label="Allowed values">A usize</td>
      <td scope="row" data-label="Notes">The amount of data each write buffer can build up in memory.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_SYNC_DATA</code></td>
      <td scope="row" data-label="Default">true</td>
      <td scope="row" data-label="Allowed values">true, false</td>
      <td scope="row" data-label="Notes">Whether to sync writes to disk before acknowledgement. 2.x only: replaced in 3.0.0 by <code>SURREAL_DATASTORE_SYNC_DATA</code>.</td>
    </tr>
  </tbody>
</table>

### FoundationDB environment variables

> [!WARNING]
> FoundationDB support was removed in SurrealDB 3.0.0. These variables apply to 2.x only.

<table>
  <thead>
    <tr>
      <th scope="col">Environment variable</th>
      <th scope="col">Default value</th>
      <th scope="col">Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_FOUNDATIONDB_TRANSACTION_MAX_RETRY_DELAY</code></td>
      <td scope="row" data-label="Default">500</td>
      <td scope="row" data-label="Notes">The maximum delay between transaction retries in milliseconds.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_FOUNDATIONDB_TRANSACTION_RETRY_LIMIT</code></td>
      <td scope="row" data-label="Default">5</td>
      <td scope="row" data-label="Notes">The maximum number of times a transaction can be retried.</td>
    </tr>
    <tr>
      <td scope="row" data-label="Env var"><code>SURREAL_FOUNDATIONDB_TRANSACTION_TIMEOUT</code></td>
      <td scope="row" data-label="Default">5000</td>
      <td scope="row" data-label="Notes">The maximum transaction timeout in milliseconds.</td>
    </tr>
  </tbody>
</table>

## SurrealDB Cloud environment variables

Instances on SurrealDB Cloud are not started with a CLI command or environment variables. Instead, they can be set from [SurrealDB Studio](/docs/operate/instances/configure.md) or with [`surreal cloud`](/docs/reference/cli/cloud.md).

---

Source: https://surrealdb.com/docs/reference/cli/db/version-history

# Environment variables and flags by version

Which SURREAL_ environment variables and surreal db command-line flags existed in each SurrealDB release from 1.0.0 to 4.0.1, when each was added or removed, and how defaults changed.

This page shows which environment variables and command-line flags each SurrealDB release had, from 1.0.0 in September 2023 to 4.0.1. Use it to check whether a setting exists in the version you run, to find what changed between two versions before an upgrade, or to see when a default changed. The [environment variables](/docs/reference/cli/db/environment-variables.md) page and the [CLI command](/docs/reference/cli/db/commands/start.md) pages describe each setting in the current release.

## Environment variables and flags

Each row is one environment variable or flag, marking the releases that had it, with the newest release on the left. Filter by name, such as `ROCKSDB` or `mcp`, and hover a row for its help text, its exact first and last versions, and the flag or environment variable it pairs with.

<DemoEmbed title="Environment variables and flags by version" height={780} pages={[{ "label": "Environment variables and flags", "src": "/docs/cli-history/history?view=timeline" }]} />

## Release contents

Select a release to list every environment variable and flag it has, with defaults and help text. Select a second release under **Compare with** to list only what is added, removed or given a new default when moving from the first release to the second. Pick the version you run first and the target version second, so that the list matches an upgrade or a downgrade.

<DemoEmbed title="Release contents" height={780} pages={[{ "label": "Release contents", "src": "/docs/cli-history/history?view=contents" }]} />

## Scope

The lists on this page are read from the SurrealDB source code at each release tag, so they include settings that are not described elsewhere in the documentation. They cover every final release from 1.0.0 onwards, and the alpha, beta and release candidate tags of each release after 1.0.0. The 1.0.0 pre-releases are left out. Dates are the publication dates of the GitHub releases.

- **Environment variables** are the `SURREAL_` names that the server reads, including those that set a command-line flag.
- **Flags and arguments** are those of the `surreal` command and each of its subcommands. A flag declared once on the `surreal` command and accepted by every subcommand, such as `--log` from 2.2.0, counts as present on each subcommand.
- **Defaults** are shown as they are written in the source code. A default that the server works out when it starts, such as a buffer size based on the available memory, is shown as computed at run time.
- **Maintenance releases** of an older line, such as 1.5.6 after the 2.0.0 pre-releases, do not count as removing anything that the newer line added.

Environment variable names that the server builds while it runs, and variables set only in Docker images or deployment files, are not listed.

## Counts by release

| Release | Published | Environment variables | Flags and arguments |
| --- | --- | ---: | ---: |
| 1.0.0 | 2023-09-13 | 33 | 58 |
| 1.1.0 | 2024-01-09 | 65 | 83 |
| 1.2.0 | 2024-02-13 | 68 | 83 |
| 1.3.0 | 2024-03-12 | 69 | 77 |
| 1.4.0 | 2024-04-09 | 69 | 77 |
| 1.5.0 | 2024-05-14 | 71 | 78 |
| 2.0.0 | 2024-09-17 | 89 | 89 |
| 2.1.0 | 2024-11-21 | 104 | 94 |
| 2.2.0 | 2025-02-11 | 131 | 99 |
| 2.3.0 | 2025-05-01 | 135 | 126 |
| 2.4.0 | 2025-11-24 | 168 | 138 |
| 2.5.0 | 2026-01-22 | 170 | 142 |
| 2.6.0 | 2026-01-27 | 170 | 143 |
| 2.7.0 | 2026-09-28 | 171 | 145 |
| 3.0.0 | 2026-02-17 | 192 | 155 |
| 3.1.0 | 2026-06-05 | 249 | 213 |
| 3.2.0 | 2026-07-06 | 268 | 222 |
| 3.3.0 | 2026-09-28 | 298 | 227 |
| 4.0.0 | 2026-11-03 | 278 | 210 |

Across all releases from 1.0.0, 409 environment variables and 263 flags and arguments have existed. Of these, 131 environment variables and 53 flags and arguments are no longer present in 4.0.0. Of the 77 environment variables that 3.3.0 had and 4.0.0 does not, 52 are RocksDB settings, which 4.0.0 removed together with RocksDB. The 2.x releases from 2.3.0 onwards were published alongside the 3.0.0 pre-releases and 3.x, so their dates overlap with the 3.x releases.

From 3.1.0, part of the count is settings read from the configuration map rather than declared one by one: 45 in 3.1.0, 53 in 3.2.0, 62 in 3.3.0 and 74 in 4.0.0. Each of them can be set with an environment variable whose name is the setting's key in capitals with a `SURREAL_` prefix, such as `SURREAL_ROCKSDB_MEMTABLE_PREFIX_BLOOM_RATIO` for `rocksdb_memtable_prefix_bloom_ratio`.

<DemoEmbed title="Totals per release" height={400} pages={[{ "label": "Totals per release", "src": "/docs/cli-history/history?view=totals" }]} />

---

Source: https://surrealdb.com/docs/reference/cli/ext

# surreal ext

The ext component of the Surreal CLI scaffolds, builds, inspects, runs, signs, installs and upgrades SurrealDB extensions packaged as .surli archives, and edits a project's package.toml.

_(since v4.0.0)_

`ext` is the component of the [Surreal CLI](/docs/reference/cli.md) for [SurrealDB extensions](/docs/learn/extensions/plugins/overview.md): it scaffolds a project, builds it into a `.surli` archive, inspects and runs the archive, signs it, and installs it into a database. The component has its own version numbers, starting at `1.0.0`, separate from the database's. Its version describes the tool itself, meaning its commands, flags and package formats, and does not say which database releases it works with. Its executable is `surreal-ext`.

<Synopsis>
surreal ext [OPTIONS] <COMMAND>
</Synopsis>

> [!NOTE]
> Before SurrealDB 4.0, the same commands were part of the database as `surreal db module`, also run as `surreal module`. In 4.0, `surreal db module`, `surreal db extension` and `surreal module` only print where the commands have moved.

| Subcommand | Purpose |
| --- | --- |
| [`init`](#ext-init) | Scaffold a new extension project. |
| [`build`](#ext-build) | Build the project into a `.surli` archive. |
| [`run`](#ext-run) | Run a function of an archive with arguments. |
| [`sig`](#ext-sig) | Show a function's signature. |
| [`info`](#ext-info) | List the functions an archive exports. |
| [`config`](#ext-config) | Read and change the project's `package.toml`. |
| [`sign`](#ext-sign) | Sign an archive with an SSH key or through Sigstore. |
| [`install`](#ext-install) | Check an archive's signer and capabilities, and define it in a database. |
| [`upgrade`](#ext-upgrade) | Redefine an installed extension from a new archive. |

## Writing an extension

An extension is a Rust library whose functions are marked with the `#[surrealism]` attribute. The commands on this page create the project, compile it and package it, but the functions themselves are Rust code that you write. Building one needs the [Rust toolchain](https://www.rust-lang.org/tools/install) and its WebAssembly target:

```bash
rustup target add wasm32-wasip2
```

[`init`](#ext-init) creates a project whose `src/lib.rs` holds three example functions:

```rust title="src/lib.rs"
use surrealism::surrealism;

#[surrealism(default)]
fn hello() -> String {
	format!("Hello from Surrealism!")
}

#[surrealism]
fn greet(name: String) -> String {
	format!("Hello, {name}!")
}

#[surrealism]
fn add(a: i64, b: i64) -> i64 {
	a + b
}
```

Replace them with your own functions, using any Rust crate that compiles to WebAssembly, then [`build`](#ext-build) the project. Once the extension is defined in a database as `demo`, `greet` is called as `ext::demo::greet('Ada')`, and the function marked `default` as `ext::demo()`. The [quick tutorial](/docs/learn/extensions/plugins/quick-tutorial.md) walks through a complete extension, and the [attribute reference](/docs/learn/extensions/guides/extension-attribute-reference.md) covers database access through a `Transaction`, `init`, comments and namespaced exports.

## surreal ext init {#ext-init}

Scaffold a new extension project: a Rust crate with a `package.toml`, a `.cargo/config.toml` and the starter `src/lib.rs` shown in [Writing an extension](#writing-an-extension).

<Synopsis>
surreal ext init [OPTIONS] [PATH]
</Synopsis>

<OptionsTable
    title="Options"
    options={[
        { "name": "[PATH]", "description": "Directory to create the project in. The current directory is used when omitted." },
        { "name": "--headless", "description": "Scaffold without prompting, for use in scripts and CI. Requires `--org`." },
        { "name": "--org", "value": "<ORG>", "description": "Organisation the extension belongs to." },
        { "name": "--name", "value": "<NAME>", "description": "Name of the extension. The directory name is used when omitted." }
    ]}
/>

```bash
surreal ext init --headless --org acme --name demo ./demo
```

The `package.toml` it writes names the package, and lists under `[capabilities]` what the extension will ask for when it is installed:

```toml title="package.toml"
target = "rust"
abi = 5

[package]
organisation = "acme"
name = "demo"
version = "1.0.0"

[capabilities]
allow_scripting = false
allow_arbitrary_queries = false
allow_write = false
allow_functions = []
allow_net = []
strict_timeout = true
```

A `[bindings]` table, which `init` does not write, declares the values that a definition gives the extension by name. See [`BINDINGS`](/docs/reference/query-language/statements/define/extension.md#bindings).

A project from SurrealDB 3.3 or earlier has a `surrealism.toml` instead, which is still read when there is no `package.toml`. The `.cargo/config.toml` holds the `tokio_unstable` flag, commented out. Uncomment it when a dependency needs Tokio's `net` feature.

## surreal ext build {#ext-build}

Compile the project's Rust code to WebAssembly (`wasm32-wasip2`), package it into a `.surli` archive, and print the archive's digest. The build needs the Rust toolchain described in [Writing an extension](#writing-an-extension).

<Synopsis>
surreal ext build [OPTIONS] [SOURCE_PATH]
</Synopsis>

<OptionsTable
    title="Options"
    options={[
        { "name": "[SOURCE_PATH]", "description": "Path to the project. The current directory is used when omitted." },
        { "name": "--out", "short": "-o", "value": "<OUT>", "description": "Path or file name of the archive. Defaults to `<organisation>-<name>-<version>.surli` in the project directory." },
        { "name": "--debug", "description": "Build in debug mode, which skips the optimisation pass for a faster build." }
    ]}
/>

```bash
surreal ext build
```

```text title="Example output"
Building WASM module (target: wasm32-wasip2, profile: release)...
Optimizing bundle...
Pre-initialising...
Extracting function signatures...
Packed ./acme-demo-1.0.0.surli (digest sha256:7b36da7d8386c1561b7d61f83f39a3bf590e25b774d935d9f8252604e80134b5)
```

The build writes the extension ABI into the archive's `package.toml`, whatever the project's file says. It writes the oldest ABI that has everything the extension uses, so the archive also loads on servers that know only that ABI: `4` for an extension that reads no bindings, and `5` for one that reads bindings or declares `[bindings]`.

The build runs the extension's `init` function once and stores the result in the archive, so every call starts from that state with fresh memory. The digest is the SHA-256 hash of the archive's `MANIFEST`, which lists every file in the archive with its own hash. A definition's [`DIGEST`](/docs/reference/query-language/statements/define/extension.md#digest) pins this value.

## surreal ext run {#ext-run}

Run one function of an archive, without a database. Repeat `--arg` for each argument, written as a SurrealQL value, and `--bind` for each binding the function reads.

<Synopsis>
surreal ext run [OPTIONS] --fnc <FNC> <FILE>
</Synopsis>

<OptionsTable
    title="Options"
    options={[
        { "name": "<FILE>", "required": true, "description": "Path to the `.surli` archive." },
        { "name": "--fnc", "value": "<FNC>", "required": true, "description": "Name of the function to run." },
        { "name": "--arg", "value": "<ARGS>", "description": "A value passed to the function. Repeat it for each argument." },
        { "name": "--bind", "value": "<NAME=VALUE>", "description": "The value of a name that `package.toml` declares under `[bindings]`, written as a SurrealQL value. Repeat it for each name. A declared name left out reads as `NONE`." }
    ]}
/>

```bash
surreal ext run --fnc greet --arg '"Ada"' acme-demo-1.0.0.surli
```

```text title="Output"
✅ 'Hello, Ada!'
```

A `--bind` value is passed to the extension as given, without the type check that a database applies, and a name that `package.toml` does not declare is refused:

```bash
surreal ext run --fnc send --arg '"ada@example.com"' --bind 'api_key="test-key"' acme-mailer-1.2.0.surli
```

## surreal ext sig {#ext-sig}

Show the signature of one function in an archive.

<Synopsis>
surreal ext sig [OPTIONS] --fnc <FNC> <FILE>
</Synopsis>

```bash
surreal ext sig --fnc greet acme-demo-1.0.0.surli
```

```text title="Output"
Signature:
 - greet(name: string) -> string [readonly]
```

## surreal ext info {#ext-info}

List the package and the functions an archive exports. `<mod>` stands for the name the extension is given when it is defined.

<Synopsis>
surreal ext info [OPTIONS] <FILE>
</Synopsis>

Add `--json` (`-j`) to print the exports as a JSON document, for use in scripts. `sig` takes `--json` too.

```bash
surreal ext info acme-demo-1.0.0.surli
```

```text title="Output"
Info for @acme/demo@1.0.0
===========================

- <mod>::greet(name: string) -> string [readonly]
- <mod>::add(a: int, b: int) -> int [readonly]
- <mod>() -> string [readonly]
```

## surreal ext config {#ext-config}

Read and change the project's `package.toml`. Each subcommand takes `--path` to name the project directory, which defaults to the current directory, and keeps the file's comments and ordering.

| Subcommand | Purpose |
| --- | --- |
| `show` | Print the package file. |
| `get <KEY>` | Print one value, such as `package.version` or `capabilities.allow_net`. |
| `set <KEY> <VALUE>` | Set one value. |
| `add <KEY> <VALUE>` | Add a value to `capabilities.allow_net` or `capabilities.allow_functions`. |
| `remove <KEY> <VALUE>` | Remove a value from one of those lists. |
| `signer ssh <FILE>` | Name an SSH public key as the package's signer. |
| `signer github --repo <OWNER/NAME> --workflow <FILE>` | Name a GitHub Actions workflow as the signer, for Sigstore keyless signing. |
| `signer gitlab` | Name a GitLab CI pipeline as the signer. |
| `signer remove` | Remove the signer. |
| `fs add <DIR> [--as <PATH>]` | Bundle a directory into the archive's read-only filesystem. |
| `fs remove <PATH>` | Remove a bundled directory. |

The capabilities requested in `package.toml` are what [`install`](#ext-install) shows and asks to grant. An extension receives only the capabilities that its definition grants.

```bash
surreal ext config add capabilities.allow_net api.colour.io:443
surreal ext config add capabilities.allow_functions http::get
surreal ext config set capabilities.allow_write true
```

## surreal ext sign {#ext-sign}

Sign an archive, which adds a `SIGNATURE` file to it. The project's `package.toml` must name a signer first, with `config signer`, and the archive must be built after that, so that the signer is part of the signed `MANIFEST`.

<Synopsis>
surreal ext sign [OPTIONS] <FILE>
</Synopsis>

<OptionsTable
    title="Options"
    options={[
        { "name": "<FILE>", "required": true, "description": "The `.surli` archive to sign." },
        { "name": "--key", "value": "<KEY>", "description": "Sign with an SSH private key, through `ssh-keygen -Y sign`, instead of Sigstore." },
        { "name": "--bundle", "value": "<FILE>", "description": "Import a Sigstore bundle made over the archive's `MANIFEST`." },
        { "name": "--trusted-root", "value": "<FILE>", "description": "A Sigstore `trusted_root.json` to verify the signature against. Required with `--bundle` and with a private Sigstore instance." },
        { "name": "--fulcio-url", "value": "<URL>", "default": "https://fulcio.sigstore.dev", "description": "Certificate authority for keyless signing." },
        { "name": "--rekor-url", "value": "<URL>", "default": "https://log2025-1.rekor.sigstore.dev", "description": "Transparency log for keyless signing." },
        { "name": "--tsa-url", "value": "<URL>", "default": "https://timestamp.sigstore.dev/api/v1/timestamp", "description": "Timestamp authority for keyless signing." },
        { "name": "--out", "short": "-o", "value": "<FILE>", "description": "Write the signed archive here instead of replacing the input." }
    ]}
/>

Without `--key` or `--bundle`, the command signs keyless through Sigstore, which needs the identity of a CI workflow, such as GitHub Actions. With an SSH key:

```bash
surreal ext config signer ssh ~/.ssh/release.pub
surreal ext build
surreal ext sign --key ~/.ssh/release acme-demo-1.0.0.surli
```

```text title="Example output"
Signed acme-demo-1.0.0.surli (sha256:7b36da7d8386c1561b7d61f83f39a3bf590e25b774d935d9f8252604e80134b5)
```

Signing does not change the digest, because the signature is a separate file that the `MANIFEST` does not list.

## surreal ext install {#ext-install}

Install an archive into a database. The command reads the archive, shows its package, signer, digest, functions and the capabilities it requests, and asks which to accept. It then runs [`DEFINE EXTENSION`](/docs/reference/query-language/statements/define/extension.md) with the `DIGEST`, `SIGNER`, `CAPABILITIES` and `BINDINGS` filled in.

<Synopsis>
surreal ext install [OPTIONS] --as <NAME> --namespace <NAMESPACE> --database <DATABASE> <SOURCE>
</Synopsis>

<OptionsTable
    title="Options"
    options={[
        { "name": "<SOURCE>", "required": true, "description": "`silo::<org>::<pkg><x.y.z>`, or `f\"<bucket>:/<path>.surli\"` for an archive that is already in a bucket of the database." },
        { "name": "--as", "value": "<NAME>", "required": true, "description": "The name to call the extension by, as in `ext::<name>::<function>()`." },
        { "name": "--trust-signer", "value": "<SIGNER>", "description": "The signer to accept without asking: `any`, an SSH key fingerprint (`SHA256:…`), or a Sigstore identity (the workflow URL), optionally followed by its issuer. Any other signer is refused." },
        { "name": "--with-capability", "value": "<CAP>", "description": "Grant one requested capability without asking: `net:<target>`, `functions:<pattern>`, `queries`, `scripting`, `write`, `no-strict-timeout`, `memory=<bytes>` or `timeout=<duration>`. Repeat it for each. It cannot grant more than the archive requests." },
        { "name": "--bind", "value": "<NAME=EXPR>", "description": "The SurrealQL expression for a name that the archive declares under `[bindings]`. Repeat it for each name. A name it leaves out is asked for in a terminal." },
        { "name": "--unsigned", "description": "Install without verifying a signature, and record the extension as `UNSIGNED`. The only way to install an unsigned archive." },
        { "name": "--dry-run", "description": "Show the review and ask the same questions, then print the statement instead of running it." },
        { "name": "--offline", "description": "Skip the online checks of a Sigstore signature. The offline verification still runs." },
        { "name": "--trust-root", "value": "<FILE>", "description": "A Sigstore `trusted_root.json` to verify a signature against, for a private Sigstore or an air-gapped install." }
    ]}
/>

The command also takes the usual connection options: `--endpoint`, `--username` and `--password` or `--token`, `--auth-level`, `--namespace` and `--database`, or the matching `SURREAL_*` environment variables. The user needs permission to define extensions in the database, and read access to the bucket for a bucket source.

```bash
surreal ext install 'f"extensions:/acme-colour-1.0.0.surli"' --as colour \
    -e ws://localhost:8000 -u root -p secret --ns app --db main \
    --trust-signer SHA256:WAbQymSgov5xQFo9qtOeZGglO/HWeqqovf6ztZ0HM7U \
    --with-capability net:api.colour.io:443
```

```text title="Example output"
  Package     acme/colour 1.0.0 from f"extensions:/acme-colour-1.0.0.surli"
  Signed by   key ssh-ed25519 SHA256:WAbQymSgov5xQFo9qtOeZGglO/HWeqqovf6ztZ0HM7U
              ✓ matches package.toml [signer]: key SHA256:WAbQymSgov5xQFo9qtOeZGglO/HWeqqovf6ztZ0HM7U
  Anchor      the key itself (confirm its fingerprint with the publisher)
  Digest      sha256:8be7b49f1f3116e0f723c55ca0c9658452165fd2338995ab36a9ecf3b29c79fa
  Adds        ext::colour::blend, ext::colour::recolour
  Needs       network     api.colour.io:443
  · functions http::get                           requested, not granted (--with-capability grants it)

Trust this signer? yes (--trust-signer)
Capabilities: as granted by --with-capability

Installed ext::colour
```

### Bindings

When the archive declares `[bindings]`, each name needs an expression, which `install` writes into the definition's [`BINDINGS`](/docs/reference/query-language/statements/define/extension.md#bindings). Give it with `--bind NAME=EXPR`, or answer the prompt in a terminal, which shows the name's description and type. A name whose type is `option<...>` can be left out. The expression is checked as SurrealQL before anything is written:

```bash
surreal ext install 'f"extensions:/acme-mailer-1.2.0.surli"' --as mailer \
    -e ws://localhost:8000 -u root -p secret --ns app --db main --unsigned \
    --bind 'api_key=(SELECT VALUE key FROM ONLY vault:mailgun)'
```

The review lists each binding on a `Binds` line with its expression. The database evaluates the expression when the extension reads the name, so `INFO FOR DB` and exports show the expression and not the value. For a name marked `sensitive`, a literal value such as `--bind 'api_key="key-123"'` prints a warning, because the literal is stored in the definition where `INFO` and exports show it.

Without a terminal, a required name that no `--bind` gives fails:

```text title="Error output"
the extension requires the binding `api_key` (string): pass --bind 'api_key=<expression>'
```

A `--bind` for a name that the archive does not declare is refused as well.

### Running without a terminal

Every decision is a named flag, and there is no option that accepts everything. Without a terminal, a run that leaves a decision open fails and names the flag it needs:

```text title="Error output"
Trust this signer? needs an answer: run in a terminal, or pass --trust-signer <signer|any>
```

## surreal ext upgrade {#ext-upgrade}

Redefine an installed extension from a new archive with `DEFINE EXTENSION OVERWRITE`. The command compares the new archive with the installed definition, keeps the `PERMISSIONS` and `COMMENT`, and starts from the capabilities granted at install, so that only capabilities the new archive requests beyond the installed one need approval.

<Synopsis>
surreal ext upgrade [OPTIONS] --namespace <NAMESPACE> --database <DATABASE> <NAME> [SOURCE]
</Synopsis>

<OptionsTable
    title="Options"
    options={[
        { "name": "<NAME>", "required": true, "description": "The installed extension's name, as in `ext::<name>`." },
        { "name": "[SOURCE]", "description": "The new source. Defaults to the newest Silo release of the installed package, or the installed bucket file read again." },
        { "name": "--trust-signer", "value": "<SIGNER>", "description": "As for `install`." },
        { "name": "--allow-signer-change", "description": "Accept a signer that differs from the installed one. `--trust-signer` must still name it." },
        { "name": "--allow-downgrade", "description": "Allow moving to a lower version than the installed one." },
        { "name": "--allow-package-change", "description": "Allow moving to another organisation or package." },
        { "name": "--with-capability", "value": "<CAP>", "description": "As for `install`. Without it, a run without a terminal keeps the installed grant and grants nothing new." },
        { "name": "--bind", "value": "<NAME=EXPR>", "description": "As for `install`. A name it leaves out keeps its installed expression." }
    ]}
/>

```bash
surreal ext upgrade colour 'f"extensions:/acme-colour-1.1.0.surli"' \
    -e ws://localhost:8000 -u root -p secret --ns app --db main \
    --trust-signer SHA256:WAbQymSgov5xQFo9qtOeZGglO/HWeqqovf6ztZ0HM7U
```

Each binding keeps its installed expression unless `--bind` gives a new one, and a name that the new archive asks for and the installed definition does not have is asked for as in `install`. A binding that the new archive no longer declares is dropped. An upgrade that changes only a binding redefines the extension from the same archive.

Upload each release under its own file name, as above. When a new archive replaces the installed file under the same name, the installed archive can no longer be read, so the command cannot check for a downgrade or a change of package, and in a script it then needs both `--allow-downgrade` and `--allow-package-change`.

## Command help

```bash
surreal ext --help
```

```text title="Output"
Develop, build, inspect and run SurrealDB WASM extensions

Usage: surreal-ext [OPTIONS] <COMMAND>

Commands:
  init     Initialize a new SurrealDB extension project
  run      Run a function with arguments
  sig      Show the function signature
  info     Show the extension's information
  build    Build a WASM extension
  sign     Sign a .surli archive: Sigstore keyless from CI, an SSH key, or an imported bundle
  config   Read and change the project's package.toml
  install  Install an extension into a database: inspect, approve, define
  upgrade  Upgrade an installed extension: compare signer and capabilities, redefine
  help     Print this message or the help of the given subcommand(s)

Options:
  -v, --version  Print version
  -j, --json     Emit machine-readable JSON on stdout
  -h, --help     Print help
```

## Further reading

- [Extension overview](/docs/learn/extensions/plugins/overview.md): the end-to-end workflow
- [`DEFINE EXTENSION`](/docs/reference/query-language/statements/define/extension.md): `DIGEST`, `SIGNER`, `UNSIGNED`, `CAPABILITIES` and `BINDINGS`
- [Creating custom extensions](/docs/learn/extensions/guides/creating-custom-extensions.md): attributes, `package.toml` and bundled filesystems

---

Source: https://surrealdb.com/docs/reference/cli/formatter/overview

# SurrealQL formatter

The surqlfmt command automatically formats SurrealQL files for consistent style and readability.

The `surqlfmt` tool reformats `.surql` files to follow a consistent style. It adjusts whitespace, indentation, and keyword casing so that SurrealQL code is easy to read and review.

`surqlfmt` is a separate command-line tool alongside the [`surreal` CLI](/docs/reference/cli.md). It is shipped as an npm package rather than as part of the `surreal` binary, it never connects to a database, and it only reads and writes files.

## Installation

The tool can be installed through a single [npm install command](https://www.npmjs.com/package/@surrealdb/surql-fmt):

```bash
npm install -g @surrealdb/surql-fmt
```

## Usage

<Synopsis>
surqlfmt [OPTIONS] [FILES]...
</Synopsis>

<OptionsTable
    title="Arguments"
    options={[
        {
            "name": "[FILES]...",
            "description": "Files to format, given as paths or glob patterns. Omit them when reading from stdin."
        }
    ]}
/>

<OptionsTable
    title="Options"
    options={[
        {
            "name": "--write",
            "short": "-w",
            "description": "Reformat each file in place instead of printing the result."
        },
        {
            "name": "--check",
            "short": "-c",
            "description": "Report each file that is not already formatted, without changing it, and exit with code 1 if any is not. Useful in CI."
        },
        {
            "name": "--stdin",
            "short": "-s",
            "description": "Read SurrealQL from standard input and write the formatted result to standard output."
        },
        {
            "name": "--output",
            "short": "-o",
            "value": "<FILE>",
            "description": "Write the result to a file instead of standard output."
        },
        {
            "name": "--quiet",
            "short": "-q",
            "description": "Print nothing to standard output."
        },
        {
            "name": "--indent",
            "value": "<WIDTH>",
            "default": 2,
            "description": "Number of indent characters per level."
        },
        {
            "name": "--indent-char",
            "value": "<CHAR>",
            "default": "space",
            "description": "Character used for indentation: `space` or `tab`."
        },
        {
            "name": "--max-line-length",
            "value": "<LENGTH>",
            "default": 80,
            "description": "Line length the formatter tries to stay within, wrapping a statement that would go past it."
        },
        {
            "name": "--version",
            "short": "-v",
            "description": "Print the installed version."
        }
    ]}
/>

The tool prints the reformatted file by default, and reformats a `.surql` file in place when `--write` is passed.

```bash
# Format a single file
surqlfmt ./query.surql

# Check if files are formatted
surqlfmt --check ./src/**/*.surql

# Format from stdin
cat query.surql | surqlfmt --stdin

# Configure indentation and line length
surqlfmt --indent 1 --indent-char tab --max-line-length 120 *.surql

# Write files in-place
surqlfmt --write ./src/**/*.surql
```

A long statement is split over several lines, one clause and one condition per line:

```bash
echo "SELECT name, age FROM person WHERE age > 18 AND email CONTAINS '@' ORDER BY age;" | surqlfmt --stdin
```

```surql title="Output"
SELECT
  name,
  age
FROM person
WHERE
  age > 18
  AND email CONTAINS '@'
ORDER BY age;
```

## Input the formatter cannot parse

The formatter refuses a file that contains syntax it does not understand, rather than reformatting it, because reformatting a statement it cannot read could drop or reorder parts of it. The file is left unchanged, and `surqlfmt` reports the position of the first problem and exits with code 1:

```text title="Error output"
error: query.surql: Unable to parse SurrealQL at position 28
```

The formatter can lag behind the newest SurrealQL syntax, so a query that runs on SurrealDB can still be refused here. A file with no statements, such as one holding only comments, is accepted and left as it is.

## Use it from JavaScript

The same package exports the formatter as a library:

```bash
npm install @surrealdb/surql-fmt
```

```ts
import { format, formatRange, FormatSyntaxError } from "@surrealdb/surql-fmt";

// Format a whole query with four spaces per level
const formatted = format(query, { indent: 4, maxLineLength: 100 });

// Format only the statements that overlap characters 0 to 100
const partly = formatRange(query, 0, 100);

try {
    format("SELECT * FROM person WHERE (");
} catch (error) {
    if (error instanceof FormatSyntaxError) {
        console.log(`Syntax error at ${error.position}`);
    }
}
```

`format` and `formatRange` throw a `FormatSyntaxError`, carrying the position of the first syntax error, for the same input the command line refuses.

For the options of the version you have installed, run `surqlfmt --help`.

## When to use the formatter

- **Before committing** - run `surqlfmt` on any `.surql` migration or seed files to keep diffs clean.
- **In CI** - add a `surqlfmt --check` step to catch inconsistencies early.
- **During development** - pipe ad-hoc queries through the formatter for readability.

For the other command-line tools, see the [CLI tools overview](/docs/reference/cli.md).

---

Source: https://surrealdb.com/docs/reference/cli/guides

# SurrealDB CLI

The surreal command installs once, then installs, versions and runs components: the database (surreal db), SurrealDB Cloud (surreal cloud) and SurrealDB extensions (surreal ext). A first session, how components work, and where each workflow is documented.

`surreal` is the SurrealDB command line. You install it once, and it installs, updates and runs the rest: the database, SurrealDB Cloud management, and module tooling. Each of these is a **component** with its own commands and its own version, so a new `surreal cloud` release does not wait for a database release, and the reverse.

This page covers what the command does and gets you through a first session. For the full option lists, see the [CLI reference](/docs/reference/cli.md).

## Components

A component is a separate program that the `surreal` launcher finds, fetches when needed, and starts for you. You type `surreal <component> <command>`, and everything after the component name goes to that component unchanged.

| Component | Command | What it does | Guide |
| --- | --- | --- | --- |
| Database | `surreal db` | Start a server, open a SurrealQL shell, import and export data, validate query files | [Using the database](/docs/reference/cli/guides/database.md) |
| Cloud | `surreal cloud` | Organisations, instances, backups, members and tokens on SurrealDB Cloud | [Managing SurrealDB Cloud](/docs/reference/cli/guides/cloud.md) |
| Extensions | `surreal ext` | Build, sign and install SurrealDB extensions | [Working with extensions](/docs/reference/cli/guides/extensions.md) |

The launcher itself has five commands of its own, and they are the only commands that install or change versions: `surreal install`, `surreal upgrade`, `surreal use`, `surreal uninstall` and `surreal list`. [Managing components](/docs/reference/cli/guides/components.md) explains each of them, how to pin a version, and how to run another version once with `+VERSION`.

## Install

The install script installs `surreal` and, by default, the database as a pinned component.

```bash title="macOS and Linux"
curl -sSf https://install.surrealdb.com | sh
```

```powershell title="Windows (PowerShell)"
irm https://windows.surrealdb.com | iex
```

Add the Cloud component at the same time with `--with cloud` (`-With cloud` on Windows), or install it later with `surreal install cloud`. [Install the SurrealDB CLI](/docs/reference/cli/guides/install.md) covers the options, Homebrew and other package managers, and installing without the database.

## First session

Run the database locally, then talk to it.

```bash title="Run a local database"
surreal db start --user root --pass secret
```

In a second terminal, open a SurrealQL shell against it.

```bash title="Open a shell"
surreal db sql --username root --password secret --pretty
```

To work with SurrealDB Cloud, install the Cloud component, sign in, and create an instance.

```bash title="Manage SurrealDB Cloud"
surreal install cloud
surreal cloud auth login
surreal cloud org use acme
surreal cloud instance create api --type shared-1 --region aws-euw1
surreal cloud instance sql api -- --ns app --db main
```

`surreal cloud instance sql` resolves the instance and credentials, then hands off to `surreal db sql` through the launcher, so one command covers both planes. If a command needs a component that is not installed, `surreal` names the download host and asks before it fetches anything.

## Control plane and data plane

The components divide along a clear line.

| Component | Plane | Answers |
| --- | --- | --- |
| `surreal cloud` | Control plane | Which instances exist, what they run, what they cost, who may reach them |
| `surreal db` | Data plane | Queries, imports, exports, and running a server yourself |

A component never installs or upgrades another one. When `surreal cloud` needs the database, it runs `surreal db` through the launcher, which offers to install it if it is missing.

## Output that scripts can read

Every launcher command and every `surreal cloud` command takes `--json`, and sends its data to stdout and everything else, including progress, prompts and warnings, to stderr. A failed command leaves stdout empty.

```bash title="Machine-readable output"
surreal cloud instance list --json | jq -r '.[] | select(.state == "ready") | .name'
```

[Scripting and CI](/docs/reference/cli/guides/cloud/scripting.md) covers exit codes, non-interactive credentials and long-running operations.

## Where to go next

- [Install](/docs/reference/cli/guides/install.md) - The install script, package managers, and installing without the database.

- [Managing components](/docs/reference/cli/guides/components.md) - Install, upgrade, pin, switch and remove components.

- [Using the database](/docs/reference/cli/guides/database.md) - Start a server, query it, and move data in and out.

- [Managing SurrealDB Cloud](/docs/reference/cli/guides/cloud.md) - Sign in, create and scale instances, and manage members.

- [CLI reference](/docs/reference/cli.md) - Every command and flag of the launcher and each component.

---

Source: https://surrealdb.com/docs/reference/cli/guides/cloud

# Managing SurrealDB Cloud

Manage SurrealDB Cloud from the command line with surreal cloud: sign in, create and scale instances, pause and resume them, read logs and metrics, manage members, and script it in CI. Includes the move from surrealctl.

`surreal cloud` is the component of the [`surreal` command](/docs/reference/cli/guides.md) for the SurrealDB Cloud control plane. Use it to sign in, deploy [SurrealDB Earth](/docs/operate/instances/earth.md) and dedicated instances, list them, scale them, pause and resume them, take backups, read logs and metrics, manage organisation members, and mint tokens, from a terminal, a shell script or a CI job.

This page covers what the component is for and gets you through a first session. It is written for operators and developers who already have a SurrealDB Cloud account. For exhaustive flag detail, see the [`surreal cloud` reference](/docs/reference/cli/cloud.md).

## When to use which tool

- **[SurrealDB Studio](https://studio.surrealdb.com)** is the place for sign-up, browsing data, billing pages and anything you do once. The browser is the fastest route for one-off work.
- **`surreal cloud`** is for anything you want to repeat, script, schedule or review in a pull request: provisioning, scaling, pausing an environment overnight, pulling logs into a report, granting a colleague a role.
- **[`surreal db`](/docs/reference/cli/guides/database.md)** is for schema, queries and data, and for a local server during development.

`surreal cloud` and Studio use the same API, so a change made in one shows up in the other.

## Install

Install the component with the launcher. If you do not have `surreal` yet, the [install script](/docs/reference/cli/guides/install.md) installs it, and `--with cloud` adds this component in the same step.

```bash
surreal install cloud
```

Instance commands that open a shell or move data, `instance sql`, `instance import` and `instance export`, run the database through the launcher as `surreal db`, which offers to install it if it is missing. Nothing else in `surreal cloud` needs the database. To upgrade the component, run `surreal upgrade cloud`; see [Managing components](/docs/reference/cli/guides/components.md).

## Sixty-second quickstart

```bash title="First session"
surreal cloud auth login
surreal cloud whoami
surreal cloud org list
surreal cloud org use acme

surreal cloud instance create api --type shared-1 --region aws-euw1
surreal cloud instance sql api -- --ns app --db main
surreal cloud instance pause api
surreal cloud instance delete api --force
```

`auth login` opens a browser and stores the session for later commands. `org use` remembers an organisation so you do not have to name it every time. `instance create` waits until the instance is ready before it returns, so the `sql` command on the next line connects to a running database.

This session deploys a dedicated instance, because it passes a cloud `--region`. Without `--region`, `instance deploy` deploys a serverless SurrealDB Earth instance instead; see [Create an instance](/docs/reference/cli/guides/cloud/instances.md#create-an-instance).

## Output that scripts can read

Every command takes `--json`. Every command sends its data to stdout and everything else, including progress, prompts, warnings and errors, to stderr, so a pipe always receives data and nothing else, and a failed command leaves stdout empty.

```bash title="Machine-readable output"
surreal cloud instance list --json | jq -r '.[] | select(.state == "ready") | .name'
```

## Guides

- [Authenticating surreal cloud](/docs/reference/cli/guides/cloud/authentication.md) - Login sessions, personal access tokens, scopes and CI credentials.

- [Organisations with surreal cloud](/docs/reference/cli/guides/cloud/organisations.md) - Choose an organisation, manage members and invitations, and read usage.

- [Instances with surreal cloud](/docs/reference/cli/guides/cloud/instances.md) - Create, scale, pause, back up, connect to and delete instances.

- [Scripting surreal cloud](/docs/reference/cli/guides/cloud/scripting.md) - Exit codes, waiting, non-interactive credentials and CI recipes.

## Coming from surrealctl

`surrealctl` is now `surreal cloud`, with the same commands and flags. On its first run, `surreal cloud` copies your configuration and stored login from `~/.config/surrealctl` (`%APPDATA%\surrealctl` on Windows) to `~/.surrealdb/cloud`, and says so once. The original stays in place, so an installed `surrealctl` keeps working beside it.

The `SURREALCTL_*` environment variables still work as aliases of `SURREAL_CLOUD_*`, and a run that uses any of them prints one warning naming each replacement. Update scripts to `surreal cloud` and the `SURREAL_CLOUD_` prefix.

---

Source: https://surrealdb.com/docs/reference/cli/guides/cloud/authentication

# Authenticating surreal cloud

Choose between a login session and a personal access token with surreal cloud, create and revoke tokens, scopes, profiles, where credentials are stored, and authenticating an unattended run.

`surreal cloud` accepts two kinds of credential. This page explains what each one is good for, how to create and inspect them, and how to hand one to a CI job. It is for anyone setting up their own machine, and for engineers wiring `surreal cloud` into a pipeline. To install the component first, see [Install](/docs/reference/cli/guides/install.md) and [Components](/docs/reference/cli/guides/components.md). For the mechanism underneath - the sign-in flows, what travels on the wire, and how the credential store behaves - see the [authentication reference](/docs/reference/cli/cloud/authentication.md).

## Two kinds of credential

The two credentials differ in what they can **write**, not in what they can reach.

| Credential | How you get it | Use it for | Cloud writes |
| --- | --- | --- | --- |
| Login session | `surreal cloud auth login` | Everyday work at a terminal | Yes |
| Personal access token | `surreal cloud token create`, or SurrealDB Studio | Scripts, CI jobs, shared runners | No |

A login session is the credential that can do everything. A personal access token reads the control plane and cannot change it, which is what makes it safe to leave in a CI secret store.

## Login sessions

`surreal cloud auth login` signs in through your identity provider and stores a refresh token plus one access token per audience. There are three sign-in flows, chosen with `--flow`: `browser` opens a browser and listens on `127.0.0.1` for the redirect, `device` shows a code to type on another device, and `paste` prints a URL and takes back the address the browser was redirected to. `--no-browser` shows a code or a URL instead of opening a browser, and `--force` signs in again when the profile already has a credential.

Four commands inspect and maintain the session.

```bash
surreal cloud auth status          # which credential is in use, read from disk
surreal cloud auth status --verify # the same, plus one request to check it
surreal cloud auth refresh         # renew now, rather than at the next request (add --all for the account-management token too)
surreal cloud auth logout          # remove this profile's stored credentials
```

`auth status` and `auth scopes` touch no network, so they work on a plane, in a container with no egress, and in a CI job that is about to fail for another reason. `whoami` is the command that asks the API who you are.

`auth status` also warns when this machine's clock is more than five minutes out of step with the API, because a wrong clock produces authentication failures that look like a rejected credential.

`auth logout` revokes the refresh token at the identity provider on a best-effort basis. A failed revocation prints a warning and still removes the credential from this machine. Logging out when nothing is signed in succeeds and still prints a document, so a teardown script does not fail on its second run.

> [!NOTE]
> `auth scopes` returns an empty list for a login session. Identity scopes are not the authorisation model for a session - your role in the organisation is. Run `surreal cloud org permissions` to see what you may do.

## Personal access tokens

A personal access token is a long-lived string beginning `sdbp_`. Create one with a login session in place, then hand it to whatever needs it.

```bash
surreal cloud token scopes
surreal cloud token create "ci-nightly-report" --scope read:cloud --expires-in 90 | tail -1
```

<OptionsTable
    title="token create"
    options={[
        {
            "name": "<LABEL>",
            "required": true,
            "description": "What this token is for. Shown in every listing. 1 to 120 characters."
        },
        {
            "name": "--scope",
            "value": "<SCOPE>",
            "description": "A scope to grant. Repeat the flag to grant several, up to 32."
        },
        {
            "name": "--expires-in",
            "value": "<DAYS>",
            "default": "30",
            "description": "Days until the token expires, from 1 to 365, or `never`."
        },
        {
            "name": "--reveal",
            "description": "Print the secret even when stdout is a terminal."
        }
    ]}
/>

Four things to know about `token create` before you run it:

- **The secret is returned once.** It is the last line on stdout, so `| tail -1` is the whole capture recipe. Nothing can recover it later.
- **It refuses to print a secret to a terminal.** Pipe the output, or pass `--reveal` if you meant to read it. The check happens before the token is minted, so a forgotten flag never costs you a credential nobody can use.
- **It is the one command with no `--json` form.** The secret can neither go inside the document nor share stdout with it, so `--json` is a usage error here.
- **A token with no `--scope` is permitted nothing.** Grant what the job needs and no more.

List and revoke tokens by id or label.

```bash
surreal cloud token list
surreal cloud token delete ci-nightly-report
```

> [!WARNING]
> Revocation is not instant. A revoked token can continue to work for several minutes while the platform's exchange cache expires. Rotate a leaked token and then confirm with `surreal cloud token list`.

## What a personal access token cannot do

**It cannot manage personal access tokens.** All four `token` verbs - `list`, `create`, `delete`, and `scopes` - refuse a personal access token. The refusal is local, costs no requests, and exits `4`. A leaked token must not be able to mint its own replacements, nor revoke the one you would use to clean up after it.

```text
Managing personal access tokens needs an interactive login session, so nothing was sent.

Sign in with:  surreal cloud auth login
```

**It cannot write to the control plane.** The API refuses a personal access token on every mutating route, whatever scopes the token carries. `instance create`, `instance delete`, `org update`, and `team invite` all need a login session. Reads work normally.

**It cannot exceed its scopes.** A missing scope produces a 403 naming the scope, and exits `4`.

Everything else works: `org list`, `instance list`, `instance logs`, `auth status`, `auth scopes`, and `auth logout`.

## Choosing between them

- **At a terminal, sign in.** A login session covers every command and renews itself.
- **In CI, use a token** for anything that only reads: nightly usage reports, drift checks, dashboards, alerting on instance state.
- **For unattended writes, use a login session** on a dedicated machine account, with the credential file mounted into the job. Scope the account's role in the organisation to what the pipeline needs.

## Supplying a token

Two flags supply a token, each with an environment variable, and neither writes the token to disk.

<OptionsTable
    title="Credential options"
    options={[
        {
            "name": "--token",
            "value": "<TOKEN>",
            "env": "SURREAL_CLOUD_TOKEN",
            "description": "Personal access token to authenticate with. Conflicts with `--token-file`."
        },
        {
            "name": "--token-file",
            "value": "<PATH>",
            "env": "SURREAL_CLOUD_TOKEN_FILE",
            "description": "Read the personal access token from a file, or `-` for stdin."
        }
    ]}
/>

`SURREAL_CLOUD_TOKEN` is the usual choice in CI, because the environment is where a secret store puts things.

```bash
export SURREAL_CLOUD_TOKEN="$(cat /run/secrets/surreal-cloud)"
surreal cloud instance list --json
```

`--token` has no short form on purpose: `-t` reads as `--type` on the instance commands, and a credential in `argv` is visible through `ps` and lands in shell history.

A credential supplied this way lasts for the one invocation. The only command that stores a token is `auth login --with-token`, which reads it from stdin and remembers it for the profile.

```bash
surreal cloud auth login --with-token --label laptop < ~/token.txt
```

## Scopes

The scopes include `read:cloud`, `write:cloud-instances`, `write:cloud-organization`, and `write:cloud-billing`. Run `surreal cloud token scopes` for the current list.

Two commands report on them, and they answer different questions.

- `surreal cloud token scopes` - the catalogue of scopes a token can be granted. This one is the menu.
- `surreal cloud auth scopes` - what the credential in your hand carries. This one is the receipt.

## Profiles

A profile bundles a credential, an API base URL, and configuration under one name. Use profiles to keep a work account and a personal account apart, or production and staging.

```bash
surreal cloud context use staging          # switch the active profile
surreal cloud --profile staging auth login # sign that profile in
surreal cloud context list                 # every profile, and which is active
surreal cloud context show                 # what this invocation resolved, and why
```

Each profile stores its own credential, so switching profiles switches identity. `surreal cloud org use` works *within* a profile and remembers an organisation; neither command is expressible as the other.

## Where credentials are stored

Credentials live in `credentials.json`, mode `0600`, beside `config.toml` in the configuration directory, `~/.surrealdb/cloud` (`%USERPROFILE%\.surrealdb\cloud` on Windows). The directory follows `SURREAL_CLI_HOME` when the launcher has another home, and `--config` or `SURREAL_CLOUD_CONFIG_DIR` puts it elsewhere. `config.toml` holds no secrets and is safe to commit; `credentials.json` is not.

Two behaviours matter at a terminal. `surreal cloud` refuses to read a `credentials.json` that group or other can read, and tells you the `chmod` to run. And concurrent invocations serialise on an advisory lock, so if a run reports that another `surreal cloud` is updating credentials, retry in a moment.

On first run, `surreal cloud` copies the configuration and stored login of the former `surrealctl` tool from `~/.config/surrealctl` (`%APPDATA%\surrealctl` on Windows) once, and leaves the original in place. The old `SURREALCTL_*` environment variables still work as deprecated aliases of `SURREAL_CLOUD_*`, with a warning naming each replacement.

The [authentication reference](/docs/reference/cli/cloud/authentication.md#where-credentials-are-stored) covers the rest: the resolution order for the directory, why the store is a file rather than the OS keyring, how the lock and the atomic rename work, and how clock skew is learned.

## Troubleshooting

| Symptom | Cause | Resolution |
| --- | --- | --- |
| Exit `3` on any command | No credential, or one that expired and could not be renewed | `surreal cloud auth login`, or `surreal cloud auth refresh` |
| Exit `4` on a `token` command | A personal access token is in use | Sign in with a login session |
| Exit `4` on a write | Insufficient scope, insufficient role, or a token where a session is needed | Check `surreal cloud org permissions`; use a login session for writes |
| `auth status` warns about clock skew | This machine's clock is more than five minutes out | Fix time synchronisation on the host |
| Exit `30` | An interactive sign-in did not complete | Run `surreal cloud auth login` again; add `--flow device` when there is no browser |
| Exit `11` | The credential store could not be read or written | Check the permissions and free space on the configuration directory |
| A refusal to read `credentials.json` | The file is readable by group or other | `chmod 600` on the path in the message |

To see which requests are being made and which configuration layer won each value, add `--debug`. Credentials are logged as a digest, never in full.

## Next steps

- [Organisations](/docs/reference/cli/guides/cloud/organisations.md) - choose an organisation, manage members, read usage and spend.
- [Instances](/docs/reference/cli/guides/cloud/instances.md) - everyday instance work.
- [Scripting](/docs/reference/cli/guides/cloud/scripting.md) - exit codes, `--json`, and unattended runs.
- [Members and roles](/docs/operate/organisations/members-and-roles.md) - what a role permits in an organisation.

---

Source: https://surrealdb.com/docs/reference/cli/guides/cloud/instances

# Instances with surreal cloud

Deploy SurrealDB Earth and dedicated instances, then find, connect to, scale, pause, back up, set capabilities and network policies on, and delete them with the surreal cloud instance commands.

This page walks through everyday instance work from the command line: deploying a [SurrealDB Earth](/docs/operate/instances/earth.md) or dedicated instance, finding it again, opening a SurrealQL session, resizing it, pausing it, taking backups, and deleting it. It assumes you are signed in and that an organisation resolves; see [Authentication](/docs/reference/cli/guides/cloud/authentication.md) if not. For every flag on every verb, see the [`surreal cloud` reference](/docs/reference/cli/cloud/commands/instance.md).

## Before you start

Instances belong to an organisation, and there is no route that lists them across organisations. Pick one for the profile once, and every `instance` command follows it.

```bash
surreal cloud org use acme
```

`--org` overrides it for a single command, and `SURREAL_CLOUD_ORG` overrides it for a shell. See [Organisations](/docs/reference/cli/guides/cloud/organisations.md#choosing-an-organisation) for the full order of precedence.

The catalogues tell you what you can deploy.

```bash
surreal cloud catalog residencies
surreal cloud catalog regions
surreal cloud catalog instance-types
surreal cloud catalog instance-versions
surreal cloud catalog storage-types
surreal cloud org plans
```

`catalog residencies` lists the areas where Earth places the data of an instance. The other catalogues are for dedicated instances. `catalog` lists what the platform offers in general. `org plans` is narrower and organisation-specific - it is the one to trust before deploying a dedicated instance.

## Create an instance

<Synopsis>
surreal cloud instance deploy [OPTIONS] [NAME]
</Synopsis>

`create` is an alias of `deploy`. `--region` decides what is deployed: with no `--region`, or `--region earth`, you get a SurrealDB Earth instance, and with a cloud region you get a dedicated instance there. At a terminal, `deploy` asks for anything you did not pass as a flag, starting from the same defaults as the deploy page in SurrealDB Studio, and asks you to confirm before it deploys. `--yes`, or a script that cannot prompt, takes every default.

### An Earth instance

```bash
surreal cloud instance deploy edge-api
surreal cloud instance deploy edge-api --residency eu --cells 10 --yes
```

An Earth instance takes Earth's own settings, which are the same as on the deploy page: a data residency, a preferred location, the number of [cells](/docs/operate/instances/earth.md#cells), a network policy and capabilities. It always runs the platform's latest SurrealDB.

`deploy` returns once the instance is ready, so the next command can connect to it:

```bash title="Deploy an Earth instance and open a SurrealQL session"
surreal cloud instance deploy edge-api --yes
surreal cloud instance sql edge-api --namespace app --database main
```

<OptionsTable
    title="Earth options"
    options={[
        {
            "name": "--residency",
            "value": "<RESIDENCY>",
            "default": "world",
            "description": "Where the data may be stored: `world`, `eu` or `us`. Cannot be changed later."
        },
        {
            "name": "--location-hint",
            "value": "<LOCATION>",
            "description": "Where in its residency the instance prefers to run, such as `weur`. Defaults to automatic placement. Cannot be changed later."
        },
        {
            "name": "--cells",
            "value": "<N>",
            "description": "The most cells the instance may run across, from the counts the deploy page offers."
        },
        {
            "name": "--allow-ip, --deny-ip",
            "value": "<CIDRS>",
            "description": "The addresses that may connect, and the ones that may not, as comma-separated IP addresses or CIDR blocks."
        },
        {
            "name": "--allow-guests, --deny-guests",
            "description": "Allow or refuse unauthenticated guest access. The other capability lists take `--allow-*` and `--deny-*` flags as well."
        }
    ]}
/>

### A dedicated instance

```bash
surreal cloud instance estimate --type shared-1 --region aws-euw1
surreal cloud instance deploy production --region aws-euw1 --nodes 1 --type shared-1
```

Price a dedicated instance first if the cost matters, then deploy it. A dedicated instance takes a node count, an instance type for it, a version, storage and an access type.

<OptionsTable
    title="Dedicated options"
    options={[
        {
            "name": "--region",
            "value": "<SLUG>",
            "required": true,
            "description": "The cloud region to deploy into, by slug. See `surreal cloud catalog regions`."
        },
        {
            "name": "--nodes",
            "value": "<N>",
            "description": "1 for a single-node instance on the Start plan, 3 or more for a multi-node instance on the Scale plan."
        },
        {
            "name": "--type",
            "value": "<SLUG>",
            "description": "The instance type, by slug. See `surreal cloud catalog instance-types`."
        },
        {
            "name": "--version",
            "value": "<VERSION>",
            "description": "The SurrealDB version to run. Defaults to the latest."
        },
        {
            "name": "--storage",
            "value": "<GB>",
            "description": "Storage to allocate, in gigabytes."
        },
        {
            "name": "--access-type",
            "value": "<ACCESS>",
            "description": "How the instance may be reached: `public`, `private`, or `dual`."
        },
        {
            "name": "--restore-from",
            "value": "<INSTANCE/SNAPSHOT>",
            "description": "Restore from a snapshot, as `<instance>/<snapshot>`."
        }
    ]}
/>

A flag for the other kind of instance is refused rather than ignored, so `--cells` with a cloud region, or `--nodes` without one, stops the command before anything is deployed.

`deploy` waits until the instance is ready before it returns, so the next line in your script can connect. Pass `--no-wait` to return as soon as the API accepts the request; the output then includes the `surreal cloud instance watch` command to pick the state back up.

> [!WARNING]
> Deploying an instance is not idempotent. A retried `instance deploy` is a second instance and a second bill. `surreal cloud` never replays a deploy automatically for this reason - if a deploy fails without a clear answer, run `surreal cloud instance list` before trying again.

## Naming an instance

Every command that takes an instance accepts four spellings: the id, the slug, the name, or `org/name` when you want to be explicit about which organisation.

```bash
surreal cloud instance get production
surreal cloud instance get acme/production
surreal cloud instance get prod-a1b2c3
```

Omit the name at a terminal and `surreal cloud` offers a picker. Omit it in a script and you get a usage error that lists the available instances, so the failure tells you what you should have typed.

## Find instances

```bash
surreal cloud instance list
surreal cloud instance list --wide
surreal cloud instance list --columns name,state,version --sort name
surreal cloud instance get production
```

`--columns`, `--wide`, `--sort`, `--reverse`, and `--limit` shape the table. The API has no pagination or sort parameter, so all five are applied on your machine after the whole list arrives - and none of them reaches `--json`, where the complete payload is always emitted. A `--limit 1` must not silently truncate a pipeline.

## Connect to an instance

```bash
surreal cloud instance endpoint production
surreal cloud instance sql production --namespace app --database main
```

`instance endpoint` prints the endpoint alone, with no label and no styling, and its output is byte-identical whether you are at a terminal or in a pipe. That makes `$(surreal cloud instance endpoint production)` safe to embed in another command.

`instance sql` resolves the instance, mints a database token, and hands over to `surreal db sql` through the launcher. If the database component is not installed, the launcher offers to install it; see [Components](/docs/reference/cli/guides/components.md). Everything after `--` is passed to `surreal db sql` verbatim, so the full flag surface of the database shell is available. The token travels in the child process's environment, never in `argv`, where `ps` and shell history can both read it.

`instance import` and `instance export` work the same way. All three need a namespace and a database, because `surreal db` requires them. The check happens before a token is minted.

```bash
surreal cloud instance export production --namespace app --database main -- backup.surql
surreal cloud instance import staging --namespace app --database main -- seed.surql
```

To authenticate your own client instead, mint a database token.

```bash
surreal cloud instance token production > token.txt
surreal cloud instance jwks production
```

`instance token` refuses to print to a terminal, where the token would stay in your scrollback. Pipe it, redirect it, or pass `--reveal` if you meant to read it. `instance jwks` fetches the key set that verifies those tokens; under `--json` it emits the whole key set so it can be piped straight into a verifier.

## Scale an instance

```bash
surreal cloud instance update production --compute-units 4
surreal cloud instance update production --storage 100
surreal cloud instance update production --version 3.2.4
```

Pass at least one of `--type`, `--compute-units`, `--storage`, `--version`, or `--access-type`. With no flags at all, `update` is a usage error rather than a silent no-op.

One invocation may be several requests. Each field has its own route, and `surreal cloud` applies them in a fixed order - type, compute units, storage, version, access type - stopping at the first failure. If a later change fails, the earlier ones have already been applied.

An Earth instance has no type, compute units, storage size or version choice, so `update` refuses those flags for one. It takes `--name` instead, which renames an Earth instance without restarting it:

```bash
surreal cloud instance update edge-api --name edge-api-eu
```

The number of cells is changed through the Cloud API with `surreal cloud api`, as [Choose a cell count](/docs/operate/instances/earth.md#choose-a-cell-count) shows.

> [!IMPORTANT]
> Every change in this list restarts the instance. Plan updates the way you would plan a deployment, and expect a reconnect window. Storage can only be changed once every few hours; `surreal cloud` reports the cool-off and when the last change happened rather than sending a request that would be refused. A type change starts the cool-off as well, so change `--type` and `--storage` in separate invocations.

## Pause and resume

```bash
surreal cloud instance pause staging
surreal cloud instance resume staging
```

Pausing stops compute charges and keeps storage and configuration. Pausing an instance that is already paused prints a note, still emits the same document, and exits `0`, so a script that pauses an environment every evening is safe to run twice.

## Watch an operation

`instance watch` follows an operation that was started elsewhere - by a colleague, by Studio, or by an earlier `--no-wait` command.

```bash
surreal cloud instance watch production
surreal cloud instance watch production --until paused
surreal cloud instance watch production --json
```

`--until` takes `ready`, `paused`, or `deleted`. Under `--json`, `watch` writes one compact object per line to stdout as the state changes, because the transitions are the answer rather than a progress report.

## Waiting semantics

`deploy`, `update`, `delete`, `pause`, and `resume` wait for the instance to settle before they return.

<OptionsTable
    title="Wait options"
    options={[
        {
            "name": "--wait",
            "default": "on",
            "description": "Wait for the operation to finish. On by default in every output mode."
        },
        {
            "name": "--no-wait",
            "description": "Return as soon as the API accepts the request."
        },
        {
            "name": "--wait-timeout",
            "value": "<DURATION>",
            "default": "15m",
            "description": "How long to wait before giving up, such as `90s` or `20m`."
        }
    ]}
/>

Waiting is on in rich, plain, CI, and `--json` output alike. A default that changed with the terminal would mean `CI` changed behaviour rather than presentation, and would break the obvious script: create, then connect.

Polling backs off - two seconds for the first thirty, then five, then ten - with jitter so parallel waiters do not all poll at the same moment. Being rate limited extends the deadline rather than consuming it, up to a couple of minutes of credit, so a busy account does not get spurious timeouts.

If the wait gives up, `surreal cloud` exits `10` and says so. That is a distinct outcome from a failure: **the operation is still running server-side.** Poll again with `instance get` or `instance watch` rather than rolling back.

Interrupting a wait does not stop the operation either. It carries on, and `surreal cloud instance watch <name>` picks the state back up.

## Read state, logs, and metrics

```bash
surreal cloud instance status production
surreal cloud instance logs production --level error --limit 100
surreal cloud instance logs production --follow
surreal cloud instance metrics production --metric cpu --from 2026-08-11T10:00:00Z
surreal cloud instance usage production
```

`instance status` reports the deployment phase and the snapshots the instance can be restored from, as one document.

`--level` is a display filter applied on your machine - the API has no level parameter - so `--json` still carries every line the API sent, and a note tells you how many lines were hidden. `--follow` polls every five seconds and, under `--json`, writes one compact object per new line.

`--metric` is free-form, because the set of metrics is not published anywhere `surreal cloud` can read. `cpu`, `memory`, and `disk` are the usual ones. `--from` and `--to` take RFC 3339 timestamps and are forwarded byte for byte.

Earth instances have no metrics or logs, so `metrics` and `logs` refuse one. `instance usage` reports an Earth instance's request units, active time, requests, records read and written, and storage for the billing period so far; see [What is measured](/docs/operate/instances/earth.md#what-is-measured).

For the equivalent views in the browser, see [Monitoring](/docs/operate/instances/monitoring.md).

## Backups

```bash
surreal cloud instance backup list production
surreal cloud instance backup create production
surreal cloud instance backup policy get production
surreal cloud instance backup policy set production --daily 14 --weekly 8
```

The three retention flags - `--daily`, `--weekly`, `--monthly` - take a number of periods to keep, or the literal `default` to restore your organisation's own value for that tier. `--frequency-hours` sets how often a snapshot is taken, in whole hours up to 24; the plan decides which values are allowed.

Only a **reduction** asks for confirmation. Lengthening a retention cannot lose a snapshot, so it is applied without a prompt.

Which tiers you may change depends on the organisation's plan. `backup policy get` shows which are editable.

`instance backup create` returns as soon as the platform accepts the request. It has no `--wait`, and a new snapshot takes a while to appear in the list, so do not expect to restore from one you took a moment ago.

Restoring means creating a new instance from a snapshot, which leaves the original untouched.

```bash
snapshot=$(surreal cloud instance backup list production --json \
  | jq -r 'sort_by(.started_at) | last | .snapshot_id')

surreal cloud instance create recovery \
  --type shared-1 --region aws-euw1 \
  --restore-from "production/${snapshot}"
```

See [Backups and recovery](/docs/operate/instances/backups.md) for retention behaviour and what a snapshot contains. Earth instances have no backups or snapshots, so the `backup` commands refuse one.

## Capabilities

Capabilities decide what SurrealQL running on the instance may do: scripting, guest access, outbound network access, which functions and RPC methods are permitted.

```bash
surreal cloud instance capabilities get production
surreal cloud instance capabilities set production --deny-scripting --allow-net api.example.com
```

The endpoint is a full replacement, so `capabilities set` reads the current configuration, applies your flags, prints what would change, and asks before writing. Two consequences matter:

- **A list flag replaces that list.** `--allow-net a.example.com,b.example.com` sets the whole list. A later run naming only `a.example.com` removes `b.example.com`.
- **Anything you do not name is left exactly as it is**, including capabilities this version of `surreal cloud` does not know about.

Flags that would change nothing print a note and write nothing. `--force` skips the confirmation.

For what each capability means, see [Configure an instance](/docs/operate/instances/configure.md) and [Network access](/docs/operate/instances/network-access.md).

## Network policy

A network policy lists the client addresses that may connect to an Earth instance, as IP addresses or CIDR blocks. A dedicated instance has none; its access is set with `update --access-type`.

```bash
surreal cloud instance network get edge-api
surreal cloud instance network set edge-api --allow-ip 203.0.113.0/24
surreal cloud instance network set edge-api --open
```

`network set` works like `capabilities set`: it replaces only the lists you name, shows what would change, and asks before writing. A denied address stays denied even when the allow list matches it, and `--open` clears both lists to admit every address again. See [Limit the addresses that can connect](/docs/operate/instances/earth.md#limit-the-addresses-that-can-connect).

## Delete an instance

```bash
surreal cloud instance delete staging
surreal cloud instance delete staging --force
```

The confirmation names the instance, its slug, and its region. Declining changes nothing and exits `0`. `--force` skips the prompt; in an unattended session with neither `--force` nor `--yes`, `delete` exits `2` having sent no request.

Deletion removes the instance and everything in it. Take an export or confirm a snapshot first.

## Worked examples

### Stand up a review environment

```bash title="review-env.sh"
#!/usr/bin/env bash
set -euo pipefail

name="review-${1}"

surreal cloud instance create "$name" --type shared-1 --region aws-euw1
surreal cloud instance import "$name" --namespace app --database main -- fixtures/seed.surql
surreal cloud instance endpoint "$name"
```

`create` returns only once the instance is ready, so the `import` on the next line has something to talk to. The final line prints the endpoint for whatever consumes this script.

### Pause every non-production instance overnight

```bash title="pause-overnight.sh"
#!/usr/bin/env bash
set -euo pipefail

surreal cloud instance list --json \
  | jq -r '.[] | select(.state == "ready" and .name != "production") | .name' \
  | while read -r name; do
        surreal cloud instance pause "$name" --wait-timeout 5m
    done
```

### Clone production from its latest snapshot

```bash title="clone-production.sh"
#!/usr/bin/env bash
set -euo pipefail

snapshot=$(surreal cloud instance backup list production --json \
  | jq -r 'sort_by(.started_at) | last | .snapshot_id')

surreal cloud instance create scratch \
  --type shared-1 --region aws-euw1 \
  --restore-from "production/${snapshot}"

surreal cloud instance endpoint scratch
```

## Next steps

- [Organisations](/docs/reference/cli/guides/cloud/organisations.md) - members, roles, invitations, usage, and spend.
- [Scripting](/docs/reference/cli/guides/cloud/scripting.md) - exit codes and the `--json` contract in full.
- [`surreal cloud` reference](/docs/reference/cli/cloud/commands/instance.md) - every instance flag and default.

---

Source: https://surrealdb.com/docs/reference/cli/guides/cloud/organisations

# Organisations with surreal cloud

Select an organisation, manage members and invitations, check roles, and read usage, spend and plans from the command line with surreal cloud.

An organisation owns instances, members, and billing. This page covers how `surreal cloud` decides which organisation you mean, how to manage the people in it, and how to read what it has used and what it has cost. It is for anyone who administers a team's SurrealDB Cloud account.

## Choosing an organisation

Almost every command needs an organisation. `surreal cloud` works down a fixed order and stops at the first answer.

1. `--org` on the command line
2. `SURREAL_CLOUD_ORG` in the environment
3. `org` in this profile's section of `config.toml`
4. The organisation remembered by `surreal cloud org use`
5. Your account's default organisation
6. The only candidate, when you belong to exactly one
7. An interactive picker, at a terminal
8. An error naming the flag

```bash
surreal cloud org list
surreal cloud org use acme          # remember it for this profile
surreal cloud --org acme instance list
surreal cloud org use --clear       # forget it again
```

`surreal cloud context show` reports which organisation resolved and which layer decided it. Add `--debug` to any command to see the winning layer for every value.

In CI, set `SURREAL_CLOUD_ORG` to the organisation **id** rather than its name. An id is used as it stands; a name costs a lookup on every command.

> [!NOTE]
> `SURREAL_CLOUD_ORG` outranks the value `org use` remembered. If a remembered organisation seems to be ignored, check whether the variable is exported. `org use` warns you about it at the time.

## Manage organisations

```bash
surreal cloud org list
surreal cloud org list --all                 # include archived organisations
surreal cloud org get acme
surreal cloud org create acme-labs --use
surreal cloud org update acme --name "Acme Ltd"
surreal cloud org archive acme
```

An organisation name is 1 to 30 characters. `--use` on `create` remembers the new organisation immediately, so the commands after it need no `--org`. `org archive` asks for confirmation unless you pass `--force`.

`org get` shows the plan, the state, your role, the member count, the instance allowances, and the billing configuration.

## Members

Members are addressed by username or user id.

```bash
surreal cloud team list
surreal cloud team get ada
surreal cloud team update ada --role admin
surreal cloud team remove ada
```

`team remove` ends someone's membership of the organisation. Their account is untouched, which is why the verb is `remove` and not `delete`.

`team list` deliberately does not fold in pending invitations. Someone who has been invited is not yet a member; `invite list` is where they appear.

## Invitations

Roles are defined per organisation, so read the list before you send an invitation.

```bash
surreal cloud org roles
surreal cloud team invite ada@example.com --role member
surreal cloud invite list
surreal cloud invite delete ada@example.com
```

<OptionsTable
    title="team invite"
    options={[
        {
            "name": "<EMAIL>",
            "required": true,
            "description": "The email address to invite."
        },
        {
            "name": "--role",
            "value": "<ROLE>",
            "required": true,
            "description": "The role to grant. Run `surreal cloud org roles` for the ones this organisation defines."
        }
    ]}
/>

`surreal cloud team invite` and `surreal cloud invite create` are the same command under two names - use whichever reads better where you are. If the API rejects the role, the error points you back at `org roles`.

`invite delete` withdraws an invitation, by the email address it was sent to or by its code. The confirmation names the address.

## Roles and permissions

```bash
surreal cloud org roles        # the roles this organisation can assign
surreal cloud org permissions  # what you are permitted to do here
```

`org permissions` answers "what may I do in this organisation" for the credential in hand. It is the question `auth scopes` cannot answer for a login session, where the authorisation model is your role rather than a scope list.

For what Owner, Admin, and Member each permit, see [Members and roles](/docs/operate/organisations/members-and-roles.md).

## Personal access tokens

Tokens belong to your account rather than to an organisation, but they are how a pipeline reads an organisation's data.

```bash
surreal cloud token scopes
surreal cloud token create "ci-read-only" --scope read:cloud | tail -1
surreal cloud token list
surreal cloud token delete ci-read-only
```

All four verbs need a login session, so a token cannot mint its own replacement. See [Authentication](/docs/reference/cli/guides/cloud/authentication.md#personal-access-tokens) for scopes, expiry, and how to capture the secret.

## Usage and spend

```bash
surreal cloud org usage                  # consumption across every instance
surreal cloud instance usage production  # one instance
surreal cloud org spend                  # the current billing period
surreal cloud org spend --period 03-2026 # a specific month
surreal cloud org plans                  # the plans available to this organisation
```

`--period` is written month first, as `MM-YYYY`. If you write it the other way round, `surreal cloud` says so and shows the correction rather than sending the request.

In text output, `org spend` prints a total on stderr. The total is computed before `--limit` is applied, so it is always the whole bill even when the table is trimmed.

> [!IMPORTANT]
> Under `--json`, money stays in integer minor units - cents, or millicents where the API uses them. Do not treat `amount` as a decimal. Divide before you display.

```bash title="Total spend for a month, in whole currency units"
surreal cloud org spend --period 03-2026 --json | jq '[.[].amount] | add / 100'
```

```bash title="Line items as TSV"
surreal cloud org spend --json \
  | jq -r '.[] | [.effective_at, .resource, .description, .amount] | @tsv'
```

For invoices, payment methods, and how the platform bills, see [Billing](/docs/operate/organisations/billing.md).

## Open the dashboard

```bash
surreal cloud open org acme
surreal cloud open billing acme
surreal cloud open instance production
surreal cloud open terms
```

The URL is always printed; a browser is only opened when somebody is present to look at it, so this is safe in a script that logs its output. `surreal cloud` links to the terms and never accepts them on your behalf.

## Worked examples

### Onboard a new engineer

```bash title="onboard.sh"
#!/usr/bin/env bash
set -euo pipefail

email="$1"

surreal cloud team invite "$email" --role member
surreal cloud invite list --columns email,role,status
```

### Report which instances cost the most

```bash title="top-spend.sh"
#!/usr/bin/env bash
set -euo pipefail

surreal cloud org spend --json \
  | jq -r 'group_by(.instance_id)
           | map({instance: .[0].instance_id, cents: ([.[].amount] | add)})
           | sort_by(-.cents)
           | .[] | [.instance, .cents] | @tsv'
```

### Audit who is in every organisation you belong to

```bash title="audit-members.sh"
#!/usr/bin/env bash
set -euo pipefail

surreal cloud org list --json | jq -r '.[].id' | while read -r org; do
    echo "== ${org}"
    surreal cloud --org "$org" team list --json | jq -r '.[] | [.username, .role] | @tsv'
done
```

## Next steps

- [Scripting](/docs/reference/cli/guides/cloud/scripting.md) - exit codes, `--json`, and unattended runs.
- [Instances](/docs/reference/cli/guides/cloud/instances.md) - the instance lifecycle from the command line.
- [Organisations](/docs/operate/organisations.md) - the same concepts in SurrealDB Studio.
- [Reference](/docs/reference/cli/cloud/commands/org.md) - every `org` flag, with [`team`](/docs/reference/cli/cloud/commands/team.md) and [`invite`](/docs/reference/cli/cloud/commands/invite.md) alongside.

---

Source: https://surrealdb.com/docs/reference/cli/guides/cloud/scripting

# Scripting surreal cloud

Drive surreal cloud from CI and shell scripts: the JSON contract, exit codes for control flow, unattended runs, waiting semantics, and installing the component in a pipeline.

This page covers running `surreal cloud` where nobody is watching: in CI, in cron, and in shell scripts. It explains the output contract, how to branch on exit codes, how to keep a run from blocking on a prompt, and where to put a credential. It is for engineers automating control-plane work.

## The two streams

`surreal cloud` splits its output by purpose, and the split is absolute.

- **stdout** carries the command's data payload and nothing else.
- **stderr** carries progress, prompts, warnings, hints, errors, and debug output.

So `| jq` always works, `--json > out.json` can still ask you a question, and a failed command leaves stdout empty rather than half a document. A broken downstream pipe is not an error: `surreal cloud instance list | head -3` exits `0` silently.

## Reading successful output

`--json` prints the bare wire payload on stdout, with no envelope. There is no `.data[]` to unwrap, because the stream split and the exit code already answer "did it work".

```bash
surreal cloud instance list --json | jq -r '.[] | select(.state == "ready") | .name'
surreal cloud instance get production --json | jq -r '.version'
surreal cloud org list --json | jq -r '.[] | [.id, .name] | @tsv'
```

Every invocation emits exactly one document. Two commands stream instead, and say so in their own help: `instance watch` and `instance logs --follow` emit newline-delimited JSON, one object per line. Two more are not documents at all: `completion` writes a shell script, and `token create` writes a secret, so it has no `--json` form.

A field the API adds appears in `--json` without a new release of `surreal cloud`, so treat the payload as open: read the keys you need and ignore the rest.

`--limit`, `--sort`, `--columns`, `--wide`, and `--reverse` are presentation only. They shape a table and never reach `--json`, so `--limit 1` cannot silently truncate a pipeline.

## Reading failures

On failure, `--json` writes one enveloped object to **stderr** and leaves stdout empty.

```json title="Error envelope"
{
  "kind": "conflict",
  "message": "could not pause `api`: Instance is not in a valid state",
  "status": 409,
  "code": null,
  "request_id": "01J8XYZ7QK9M3P5R7T9V1W3Y5Z",
  "hint": "The instance is busy with another change.",
  "command": "surreal cloud instance get --wait",
  "docs": null,
  "retry_after_secs": null,
  "exit_code": 6
}
```

Every key is always present, with an explicit `null` rather than being omitted, so a consumer can index without checking first.

| Key | Type | Contents |
| --- | --- | --- |
| `kind` | string | The error class. Never `null` |
| `message` | string | The whole failure chain, including which command failed |
| `status` | integer or `null` | The HTTP status, when there was one |
| `code` | string or `null` | The API's own error code, when it sent a non-empty one |
| `request_id` | string or `null` | The request identifier to quote in a support report |
| `hint` | string or `null` | What to do about it |
| `command` | string or `null` | A command to run next |
| `docs` | string or `null` | A documentation link, for the classes that have a useful one |
| `retry_after_secs` | integer or `null` | How long to wait, from the response |
| `exit_code` | integer | The process exit code, so the document and the shell agree |

One further key appears conditionally: `candidates`, an array of suggested names, when a reference failed to resolve and `surreal cloud` had near matches to offer.

`kind` is a closed vocabulary of eleven values, so it is safe to match on: `auth`, `forbidden`, `not_found`, `conflict`, `invalid`, `rate_limited`, `upstream`, `network`, `not_available`, `wait_timeout`, `unknown`.

```bash
if ! surreal cloud instance pause api --json > /dev/null 2> error.json; then
    jq -r '"\(.kind): \(.message)"' < error.json >&2
fi
```

`not_available` means a feature is not enabled for this deployment. It does not indicate a fault.

## Exit codes

The exit codes below are a stable contract; error text is not.

| Code | Meaning |
| --- | --- |
| `0` | Success, including an empty list |
| `1` | An unclassified failure |
| `2` | Bad invocation, or a destructive command that could not confirm |
| `3` | Not authenticated, or the credential expired and could not be renewed |
| `4` | Authenticated but not allowed: scope, role, or credential kind |
| `5` | The named resource does not exist |
| `6` | The resource is not in a state that allows this, or a precondition failed |
| `7` | The API rejected the request as invalid |
| `8` | Rate limited, after the retry budget was spent |
| `9` | The API or its upstream is unreachable, or the feature is not available |
| `10` | A wait gave up. **The operation is still running** |
| `11` | The credential store could not be read or written |
| `12` | A component the command needs, such as the database for `instance sql`, is not installed and was not fetched. The message names the command that installs it |
| `30` | An interactive sign-in did not complete |
| `130` | Interrupted |

`0`, `1`, and `2` keep their conventional meanings, so `if ! surreal cloud …` and usage errors behave exactly as they do with the `surreal db` CLI. Everything above `2` is additive.

`10` has its own code because "still running" is a genuinely different answer from "failed". A pipeline may reasonably poll again rather than roll back.

### Branching on the code

Capture the status rather than testing it inside an `if`, so `set -e` does not end the script and `$?` still means what you think it does.

```bash title="create-if-missing.sh"
#!/usr/bin/env bash
set -euo pipefail

status=0
surreal cloud instance get api --json > instance.json 2> error.json || status=$?

case "$status" in
    0)  ;;
    5)  surreal cloud instance create api --type shared-1 --region aws-euw1 --json > instance.json ;;
    3)  echo "credential expired; re-authenticate the runner" >&2; exit 1 ;;
    8)  exit 75 ;;  # tell the scheduler to requeue
    *)  jq -r '.message' < error.json >&2; exit "$status" ;;
esac
```

## Unattended runs

<OptionsTable
    title="Options that matter in automation"
    options={[
        {
            "name": "--json",
            "short": "-j",
            "env": "SURREAL_CLOUD_JSON",
            "description": "Emit machine-readable JSON on stdout."
        },
        {
            "name": "--no-input",
            "env": "SURREAL_CLOUD_NO_INPUT",
            "description": "Never prompt for input; fail instead. Also spelled `--non-interactive`."
        },
        {
            "name": "--yes",
            "short": "-y",
            "env": "SURREAL_CLOUD_YES",
            "description": "Assume yes for every confirmation."
        },
        {
            "name": "--quiet",
            "short": "-q",
            "description": "Suppress progress and informational output."
        },
        {
            "name": "--plain",
            "env": "SURREAL_CLOUD_PLAIN",
            "description": "Disable tables, spinners, and relative times."
        },
        {
            "name": "--org",
            "value": "<ORG>",
            "env": "SURREAL_CLOUD_ORG",
            "description": "The organisation to operate on, by id or name."
        },
        {
            "name": "--token",
            "value": "<TOKEN>",
            "env": "SURREAL_CLOUD_TOKEN",
            "description": "Personal access token to authenticate with."
        },
        {
            "name": "--timeout",
            "value": "<DURATION>",
            "default": "30s",
            "env": "SURREAL_CLOUD_TIMEOUT",
            "description": "Maximum time to wait for a single API request."
        },
        {
            "name": "--retries",
            "value": "<N>",
            "default": "3",
            "env": "SURREAL_CLOUD_RETRIES",
            "description": "How many times to retry a failed request."
        },
        {
            "name": "--debug",
            "env": "SURREAL_CLOUD_DEBUG",
            "description": "Log every API request and response to stderr."
        }
    ]}
/>

Every one of these has an environment variable, so a pipeline can set them once for the whole job rather than repeating flags on each step.

Two rules govern prompts.

**A destructive command refuses rather than proceeds when it cannot ask.** With no `--yes` and no command-specific `--force`, `instance delete` in a non-interactive session exits `2` having sent nothing. A command that quietly went ahead because there was no terminal would be the worst possible default.

**`--no-input` makes any session behave as an unattended one**, even at a terminal. Use it to test a pipeline locally: if the script works with `--no-input`, it will work in CI.

**Bash**

```bash
export SURREAL_CLOUD_NO_INPUT=1
surreal cloud instance delete staging --force
```

**PowerShell**

```powershell
$env:SURREAL_CLOUD_NO_INPUT = "1"
surreal cloud instance delete staging --force
```

## CI detection and output modes

`surreal cloud` detects a CI environment and switches to plain output on its own: no spinners, no borders, no relative times. `CI=false`, `CI=0`, and an empty `CI` all mean *not* CI, so a system that sets the variable deliberately is not trapped in plain output.

What CI changes is structure, interactivity, and how much progress is reported. What it must not change, and does not: colour, `--json` bytes, exit codes, which requests are made, timeouts, poll intervals, `--wait` defaults, and confirmation semantics.

`--json` output is byte-identical whatever the terminal, the width, or the colour settings. Plain output does not depend on terminal width either, so it is stable to diff between runs. For parsing, still prefer `--json`.

## The token in the environment

Put a personal access token in the environment and leave it out of `argv`, where `ps` and shell history can both read it. See [Authentication](/docs/reference/cli/guides/cloud/authentication.md#personal-access-tokens) for how to create one.

```bash
export SURREAL_CLOUD_TOKEN="$(cat /run/secrets/surreal-cloud)"
export SURREAL_CLOUD_ORG=67upifj5dt6p87ch3nh5t3a8
surreal cloud instance list --json
```

Set `SURREAL_CLOUD_ORG` to the organisation **id**. An id is used as it stands; a name costs a lookup on every command.

A missing component is never downloaded silently in an unattended run: the launcher exits `12` with the install command, and `SURREAL_CLI_OFFLINE=1` forbids all network use. Install what the job needs in an earlier step, as below. See [Install](/docs/reference/cli/guides/install.md) and [Components](/docs/reference/cli/guides/components.md).

```yaml title=".github/workflows/instance-report.yml"
name: instance-report

on:
  schedule:
    - cron: "0 6 * * *"

jobs:
  report:
    runs-on: ubuntu-latest
    env:
      SURREAL_CLOUD_TOKEN: ${{ secrets.SURREAL_CLOUD_TOKEN }}
      SURREAL_CLOUD_ORG: ${{ vars.SURREAL_CLOUD_ORG_ID }}
      SURREAL_CLOUD_NO_INPUT: "1"
    steps:
      - run: curl -sSf https://install.surrealdb.com | sh -s -- --no-db --with cloud
      - run: surreal cloud status
      - run: surreal cloud instance list --json > instances.json
      - uses: actions/upload-artifact@v4
        with:
          name: instances
          path: instances.json
```

Run `surreal cloud status` early in a job. It takes about one second, and it names which credential is in use, whether the API answers, and which organisation resolved, all before a later step fails for one of those reasons.

> [!IMPORTANT]
> A personal access token reads the control plane and cannot write to it. A job that creates, updates, or deletes needs a login session on a dedicated machine account. See [What a personal access token cannot do](/docs/reference/cli/guides/cloud/authentication.md#what-a-personal-access-token-cannot-do).

## Waiting in a pipeline

`instance create`, `update`, `delete`, `pause`, and `resume` wait for the operation to finish, in every output mode including `--json`. You have three choices.

| Choice | Behaviour | Use it when |
| --- | --- | --- |
| Default | Wait up to 15 minutes | The next step needs the instance ready |
| `--wait-timeout <DURATION>` | Wait that long, then exit `10` if it has not settled | The job has its own time budget |
| `--no-wait` | Return as soon as the request is accepted | Something else will follow up |

Under `--json`, a waiting command streams progress as newline-delimited JSON on **stderr** and puts one final document on stdout. That split is what keeps "exactly one document on stdout" true for a command that reports progress.

```json title="Progress events, on stderr"
{"event":"started","resource":"instance","goal":"ready","state":"pending"}
{"event":"transition","resource":"instance","from":"pending","to":"ready","elapsed_secs":86}
{"event":"finished","resource":"instance","outcome":"succeeded","state":"ready","elapsed_secs":86,"succeeded":true}
```

Six event types appear: `started`, `transition`, `heartbeat`, `poll_failed`, `throttled`, and `finished`. `instance watch --json` inverts the stream and writes these to stdout instead, because for a watch the transitions *are* the answer.

Treat exit `10` as "poll again", not "failed".

```bash title="fail-fast-then-follow.sh"
#!/usr/bin/env bash
set -euo pipefail

status=0
surreal cloud instance create api \
    --type shared-1 --region aws-euw1 \
    --wait-timeout 2m --json > instance.json || status=$?

if [ "$status" -eq 10 ]; then
    echo "still provisioning after two minutes; following the state" >&2
    surreal cloud instance watch api
elif [ "$status" -ne 0 ]; then
    exit "$status"
fi
```

Interrupting a wait does not stop the operation. It continues server-side, and `surreal cloud instance watch <name>` picks the state back up.

## Retries, timeouts, and repeated runs

`--timeout` bounds a single request and `--retries` bounds how many times one is retried. Retry behaviour depends on what the request would change: a read is retried on a connection failure or a 5xx, and a create is never retried after a 5xx, because the instance may exist and a replay would bill for two. Rate limits honour the server's `Retry-After`.

Your script needs to know what each command does when it runs again:

| Command | Repeating it |
| --- | --- |
| `instance create` | Creates a second instance. Check with `instance get` first |
| `instance backup create` | Takes a second snapshot |
| `instance pause`, `instance resume` | Safe. Already-paused prints a note, emits the same document, exits `0` |
| `instance delete` | Safe. A missing instance while waiting counts as done |
| `auth logout` | Safe. Signed out already still exits `0` with a document |
| `instance capabilities set` | Safe. No change means no write |

## Calling the API directly

When a route has no verb yet, `surreal cloud api` sends the request with the credential, headers, and retry policy already handled.

```bash
surreal cloud api get /api/cloud/v0/organizations
surreal cloud api get /api/cloud/v0/organizations --include
surreal cloud api post /api/cloud/v0/organizations -d @body.json --force
```

The path is a path, not a URL - the host comes from `--api`. Any write method asks for confirmation unless you pass `--force`. `--query key=value` and `--header name:value` are repeatable. Authentication headers cannot be overridden here; change the credential instead. `--include` prints the status and headers to stderr, and `--raw` prints the body exactly as it arrived.

## Configuration on the machine

Values a script should not have to repeat can live in the profile instead.

```bash
surreal cloud config list
surreal cloud config set json true
surreal cloud config set org acme
surreal cloud config path
```

An environment variable outranks the configured value, and `config set` warns you when the matching variable is exported. `config get` prints the value alone, and nothing at all when there is none, so `[ -z "$(surreal cloud config get org)" ]` behaves.

## Checklist before shipping a pipeline

- Set `SURREAL_CLOUD_NO_INPUT=1` so nothing can block on a prompt.
- Set `SURREAL_CLOUD_ORG` to an organisation id.
- Pass `--json` and parse with `jq`. Never grep stderr.
- Branch on exit codes, not on messages.
- Treat `10` as "poll again", and `8` as "requeue".
- Pass `--yes` or a command's `--force` deliberately, on the steps that need it.
- Give a read-only job a personal access token, and nothing more.
- Run `surreal cloud status` first, so a misconfigured job says so in one line.

## Next steps

- [Authentication](/docs/reference/cli/guides/cloud/authentication.md) - credentials, scopes, and profiles.
- [Instances](/docs/reference/cli/guides/cloud/instances.md) - the workflows these scripts drive.
- [`surreal cloud` reference](/docs/reference/cli/cloud.md) - every command, flag, default, and environment variable.
- [Output and exit codes](/docs/reference/cli/cloud/output-and-exit-codes.md) - the full contract.

---

Source: https://surrealdb.com/docs/reference/cli/guides/components

# Managing components

How surreal installs, upgrades, pins, switches and removes components, how version names work (3.3.2, 2, beta, nightly), running another version once with +VERSION, and offline or unattended use.

`surreal` runs components, and it is the only thing that installs, upgrades or removes them. Five launcher commands cover the whole life of a component: `surreal install`, `surreal upgrade`, `surreal use`, `surreal uninstall` and `surreal list`. A component never installs or upgrades another one, and `surreal <component> ...` always belongs to the component itself.

This page explains how components are stored, how to name a version, and how to install, upgrade, pin, switch and remove them. The reference for each command is [Launcher commands](/docs/reference/cli/launcher.md).

## How components are stored

Every component version is a separate executable under the SurrealDB home, `~/.surrealdb` unless `SURREAL_CLI_HOME` says otherwise.

```text
~/.surrealdb/components/<name>/<version>/surreal-<name>   the executable
~/.surrealdb/components/<name>/pin                        the version that runs by default
```

Several versions of one component can sit side by side. The **pin** names the one that runs when you type `surreal db ...`, and nothing else decides it. The first install of a component pins it, a later install leaves the pin alone, and only `surreal use`, `surreal upgrade` and `surreal uninstall` move it. That is why installing a second database version cannot quietly change which database `surreal db start` runs.

When you run a component, `surreal` looks for its executable in this order:

1. The version named with `+VERSION`, from the store.
2. A `surreal-<name>` beside the `surreal` executable, which is how a package that ships several binaries together provides them. It runs ahead of the store, and the launcher does not upgrade or remove it.
3. The pinned version, from the store.
4. A `surreal-<name>` on your `PATH`.

A name that is not a component, such as `surreal foo`, runs a `surreal-foo` from your `PATH` if one exists, and reports an unknown component otherwise.

## Naming a version

Commands that take `COMPONENT[@VERSION]` accept these forms.

| Form | Meaning |
| --- | --- |
| `db` | The newest stable release. While a component has no stable release, its newest beta, then its newest alpha |
| `db@3.3.2` | That exact release (`db@v3.3.2` also works) |
| `db@2` | The newest stable release on major line 2 |
| `db@latest` | The newest stable release |
| `db@beta`, `db@alpha` | The newest release on that prerelease channel |
| `db@nightly` | The latest nightly build. Only the database publishes nightlies |

## See what is installed

```bash
surreal list
```

The table shows each component, the version that runs, where that version comes from, every installed version, and the path it runs from. In the `SOURCE` column, `pinned` is a version the launcher installed and pinned, `external` is a copy beside `surreal`, and `path` is a copy found on `PATH`. `surreal list --json` prints the same information as one JSON document. `surreal --version` prints only the launcher's own version.

## Install a component

```bash
surreal install cloud
surreal install db@3.3.2 cloud@0.1.0
```

`surreal install` downloads each release, checks it against its published SHA-256, runs it once to confirm it starts, and only then puts it in place. The first install of a component becomes its default. Installing another version of a component you already have installs it beside the pinned one and leaves the pin where it was.

To make what you install the default, add `--pin`. A version you name exactly becomes the default whatever it was before. A channel's release, such as `db@2` or `db@beta`, becomes the default unless the current default is a later release.

```bash
surreal install db@2 --pin
```

## Upgrade

```bash
surreal upgrade
```

With no arguments, `surreal upgrade` upgrades the launcher and every installed component that has a default version. Each follows the channel its default is on: a stable release stays on its major line, so a database on 2.x upgrades to the newest 2.x, and a prerelease follows its own channel. The `--dry-run` flag says what would change without changing it.

```bash
surreal upgrade --dry-run
```

To upgrade only some things, or to move to a particular version, name them.

```bash
surreal upgrade cloud
surreal upgrade db@3.3.2
surreal upgrade db@3
surreal upgrade cli
```

`cli` is the launcher itself. Naming a version moves the default to it, installing it first if needed.

The database also takes its familiar release flags, which are shorthand for naming the channel or version.

| Flag | Same as |
| --- | --- |
| `surreal upgrade --nightly` | `surreal upgrade db@nightly` |
| `surreal upgrade --beta` | `surreal upgrade db@beta` |
| `surreal upgrade --alpha` | `surreal upgrade db@alpha` |
| `surreal upgrade --version <VERSION>` | `surreal upgrade db@<VERSION>` |

> [!NOTE]
> The database no longer upgrades itself. `surreal db upgrade` is not run and points you to `surreal upgrade db`.

## Pin or switch a version

`surreal use` makes an installed version the default. It never downloads.

```bash
surreal use db@3.3.2
surreal use db@2
```

A major line or channel, such as `db@2`, selects the newest installed release on it. To pin a version that is not installed yet, use `surreal install db@<VERSION> --pin` or `surreal upgrade db@<VERSION>`.

## Run another version once

`+VERSION` as the first argument runs one version of whatever follows, for that command only. The pin does not change. If that version is not installed, `surreal` offers to install it first, under the rules in [Offline and unattended use](#offline-and-unattended-use).

```bash
surreal +2.6.5 db start --user root --pass secret
surreal +2 db export --endpoint http://localhost:8000 backup.surql
```

The version takes the same forms as in `COMPONENT@VERSION`: a release, a major line, or `latest`, `beta`, `alpha` or `nightly`. This is how you run an older database against data that has not been migrated yet, or compare two releases.

## Remove a component

```bash
surreal uninstall db@2.7.0
surreal uninstall cloud
```

`surreal uninstall <component>@<version>` removes that version. Naming a component alone removes every version of it and its default. The default version is removed by name only when nothing else is installed, so move the pin with `surreal use` first.

## Offline and unattended use

A component is never fetched behind your back.

- **At a terminal**, `surreal` names the download host and asks before it installs a missing component. `surreal db start` on a machine without the database offers to install it.
- **Unattended** (a CI runner, an agent, `--no-input`, a pipe on standard input, or a dumb terminal), `surreal` makes no request, and exits with code 12 and the command that would install the component. The `SURREAL_CLI_YES` variable does not count as consent to a download in the middle of another command; to install without a prompt, run `surreal install` explicitly, with `--yes` if you wish.
- **With `SURREAL_CLI_OFFLINE=1`**, the network is never touched, and a missing component fails at once.

In a pipeline, install what you need in an early step.

```bash title="CI step"
surreal install db cloud --no-input
```

## Environment variables

| Variable | Effect |
| --- | --- |
| `SURREAL_CLI_HOME` | Where the SurrealDB home is. Defaults to `~/.surrealdb` |
| `SURREAL_CLI_OFFLINE` | `1` forbids every network request |
| `SURREAL_CLI_DOWNLOAD_ROOT` | Replaces the download host, for a mirror |
| `SURREAL_CLI_NO_BANNER` | Hides the banner above `surreal help` |
| `SURREAL_CLI_JSON`, `SURREAL_CLI_PLAIN` | Same as `--json` and `--plain` on the launcher's commands |

These are the launcher's variables. Variables that start with `SURREAL_` and not `SURREAL_CLI_` belong to the database, and the launcher never reads them. Cloud's variables start with `SURREAL_CLOUD_`. See [Launcher commands](/docs/reference/cli/launcher.md) for exit codes and the full list.

## Package managers and shared machines

Where a package manager such as Homebrew or Nix owns `surreal`, the launcher refuses to install or replace anything in its place, and the package manager upgrades it. Components that the package provides beside `surreal` run before any pinned copy in the store, so a package upgrade is not shadowed by an older pinned version.

---

Source: https://surrealdb.com/docs/reference/cli/guides/database

# Using the database

Run the SurrealDB database through the surreal launcher: surreal db start, sql, import, export, is-ready, validate, fix and mcp. Workflows for local development, moving data, and checking a server, plus the deprecated surreal start forms.

`surreal db` is the database component. It starts a server, opens an interactive SurrealQL shell, moves data in and out, and checks that a server is ready. Everything after `db` is forwarded to the database unchanged, so every database flag and environment variable works the way its [reference page](/docs/reference/cli/db.md) describes.

The database is installed by the [install script](/docs/reference/cli/guides/install.md) by default. If it is not installed, `surreal db <command>` offers to install it the first time you run it.

## Commands

| Command | Use it to |
| --- | --- |
| [`surreal db start`](/docs/reference/cli/db/commands/start.md) | Run a server, in memory or on disk |
| [`surreal db sql`](/docs/reference/cli/db/commands/sql.md) | Open a SurrealQL shell, or pipe queries into a server |
| [`surreal db import`](/docs/reference/cli/db/commands/import.md) | Load a SurrealQL file into a database |
| [`surreal db export`](/docs/reference/cli/db/commands/export.md) | Write a database out as a SurrealQL file |
| [`surreal db is-ready`](/docs/reference/cli/db/commands/isready.md) | Check that a server accepts connections |
| [`surreal db validate`](/docs/reference/cli/db/commands/validate.md) | Check that SurrealQL files parse |
| [`surreal db fix`](/docs/reference/cli/db/commands/fix.md) | Repair storage issues |
| [`surreal db mcp`](/docs/reference/cli/db/commands/mcp.md) | Run the Model Context Protocol server over stdio |
| [`surreal db version`](/docs/reference/cli/db/commands/version.md) | Print the database version, or a server's |

Upgrading the database is not a database command. Use [`surreal upgrade db`](/docs/reference/cli/guides/components.md#upgrade).

## Run a database for development

Start an in-memory server with a root user. It listens on `127.0.0.1:8000`.

```bash
surreal db start --user root --pass secret
```

Add a storage path to keep the data between runs.

```bash
surreal db start --user root --pass secret surrealkv:mydata
```

A relative path is resolved from the folder you run the command in. See [`surreal db start`](/docs/reference/cli/db/commands/start.md) for the storage engines, binding, TLS and capabilities.

In a second terminal, open a shell against it.

```bash
surreal db sql --username root --password secret --pretty
```

The shell connects to `ws://localhost:8000` and the `main` namespace and database. Name others with `--namespace` and `--database`. To run queries from a script instead, pipe them in.

```bash
echo "SELECT * FROM person;" | surreal db sql --username root --password secret --hide-welcome
```

## Check that a server is ready

`surreal db is-ready` exits successfully once a server accepts connections, which suits a health check or a wait loop in a script.

```bash
surreal db start --user root --pass secret &
until surreal db is-ready --endpoint http://localhost:8000; do sleep 1; done
```

## Move data in and out

Export a database to a SurrealQL file, and import it into another.

```bash
surreal db export --endpoint http://localhost:8000 --username root --password secret --namespace app --database main backup.surql
surreal db import --endpoint http://localhost:8000 --username root --password secret --namespace app --database main backup.surql
```

Both commands need a namespace and a database. `surreal db export` writes to standard output when you give it no file, or `-` as the file, so it composes with other tools.

To import into or export from a SurrealDB Cloud instance, use [`surreal cloud instance import` and `surreal cloud instance export`](/docs/reference/cli/guides/cloud/instances.md#connect-to-an-instance), which resolve the endpoint and credentials and then run these commands for you.

## Validate query files

`surreal db validate` parses SurrealQL files without running them. With no argument it checks every `**/*.surql` file under the current folder, so it fits a pre-commit hook or a CI step.

```bash
surreal db validate
surreal db validate "schema/**/*.surql"
```

## Run a different database version

The launcher keeps several database versions side by side. Run one command against another version with `+VERSION`, or change the default with `surreal use`.

```bash
surreal +2.6.5 db export --endpoint http://localhost:8000 --namespace app --database main
surreal use db@2
```

See [Managing components](/docs/reference/cli/guides/components.md) for installing, pinning and upgrading versions.

## The deprecated top-level commands

The database's commands also run without `db`, and print a warning that names the replacement.

```bash
surreal start
```

```text title="Output"
warning: `surreal start` is deprecated; use `surreal db start`.
```

The set of commands that still run this way is closed: `start`, `sql`, `import`, `export`, `isready`, `is-ready`, `validate`, `fix`, `ml`, `module` and `mcp`, and database options placed before a command, as in `surreal --log debug start`. The warning goes to stderr and names only the command, never an argument, so it is safe in CI logs. A command the database adds later runs only as `surreal db <command>`. Change scripts and service definitions to the `surreal db` form.

> [!NOTE]
> Docker and other container images run the database directly. Inside an image, the command is `surreal start` and not `surreal db start`, and the examples in [Running with Docker](/docs/running/docker.md) use that form.

## Environment variables

`surreal db` reads the same `SURREAL_*` variables as before. `SURREAL_USER`, `SURREAL_PASS`, `SURREAL_NAMESPACE`, `SURREAL_DATABASE` and the rest are listed on the [database environment variables](/docs/reference/cli/db/environment-variables.md) page. The launcher's own variables start with `SURREAL_CLI_`, and it never reads `SURREAL_*` itself, so the two sets stay apart.

---

Source: https://surrealdb.com/docs/reference/cli/guides/extensions

# Working with extensions

Scaffold, build, inspect, run, sign and install SurrealDB WebAssembly extensions from the command line with surreal ext, the extension component of the Surreal CLI.

Extensions are WebAssembly packages that add functions to the database. This page shows the command-line workflow for an [extension](/docs/learn/extensions/plugins/overview.md) extension: scaffold a project, build it, inspect the result, run a function, then sign and install it. Extensions were called modules before SurrealDB 4.0, when the commands below were `surreal db module` commands, part of the database.

The commands belong to `ext`, the extension component of the Surreal CLI, run as `surreal ext`. Its first release is not published yet, so `surreal install ext` does not work today.

## Create a project

```bash
surreal ext init my-extension
```

`init` scaffolds a Rust project with a `package.toml` and a starter `src/lib.rs`. It asks for the organisation and extension name interactively. In a script, add `--headless` with `--org`, and `--name` when the extension should not take the folder's name.

```bash
surreal ext init my-extension --headless --org acme --name my-extension
```

## Build the extension

Run `build` from the project folder, or name the source folder. The archive is named after the organisation, name and version in `package.toml` unless `--out` names it.

```bash
surreal ext build
surreal ext build ./my-extension --out my-extension.surli
```

A build is a release build. Add `--debug` for a debug build.

## Inspect and run it

`info` lists the functions the archive exports, and `sig` shows the signature of one of them.

```bash
surreal ext info my-extension.surli
surreal ext sig --fnc greet my-extension.surli
```

`run` calls a function with arguments, without a database. Repeat `--arg` for each argument, written as a SurrealQL value.

```bash
surreal ext run --fnc greet --arg '"World"' my-extension.surli
```

## Sign and install it

To let others check where an archive came from, name a signer in `package.toml`, build again, and sign the archive:

```bash
surreal ext config signer ssh ~/.ssh/release.pub
surreal ext build --out my-extension.surli
surreal ext sign --key ~/.ssh/release my-extension.surli
```

Place the archive in a [bucket](/docs/reference/query-language/statements/define/bucket.md) of the database, then install it. `install` shows the signer, the digest and the capabilities the extension requests, asks which to accept, and defines it:

```bash
surreal ext install 'f"extensions:/my-extension.surli"' --as greeting \
    -e ws://localhost:8000 -u root -p secret --ns app --db main
```

The extension's functions are then called from SurrealQL as `ext::greeting::greet('World')`. [`DEFINE EXTENSION`](/docs/reference/query-language/statements/define/extension.md) defines an extension directly, and the [extension guides](/docs/learn/extensions/plugins/overview.md) cover writing the functions and the attribute reference.

## Reference

The command reference is [`surreal ext`](/docs/reference/cli/ext.md).

---

Source: https://surrealdb.com/docs/reference/cli/guides/install

# Install the SurrealDB CLI

Install the surreal command with the install script on macOS, Linux and Windows. Options for the database switch (--db, --no-db, SURREAL_CLI_INSTALL_DB), choosing a release, adding components, mirrors, package managers and Docker.

This page installs the `surreal` command and, optionally, the components it runs. Pick one installation method; everything after it applies whichever you chose.

The install script puts the `surreal` launcher on your machine, then uses it to install the database as a component and pin it, so `surreal db start` works from then on with no network connection. The script checks every download against the SHA-256 published beside it, and installs nothing if a check fails.

## Install on macOS and Linux

```bash
curl -sSf https://install.surrealdb.com | sh
```

The script installs `surreal` into `/usr/local/bin`. If that folder is not writable it falls back to `~/.surrealdb`, or asks where to install when you pass `--interactive`, and then prints the `PATH` line to add. It never edits your shell profile. The script is served as plain text, so you can open the same URL in a browser and read it before you run it.

Pass options after `-s --`, which is how `sh` forwards arguments to a script it reads from a pipe.

```bash
curl -sSf https://install.surrealdb.com | sh -s -- --no-db --with cloud
```

<OptionsTable
	title="Options"
	options={[
		{ "name": "--db", "description": "Install the database and pin it. This is the default." },
		{ "name": "--no-db", "description": "Install `surreal` without the database. The database installs on first use instead." },
		{ "name": "--minimal", "description": "The same as `--no-db`." },
		{ "name": "--version", "short": "-v", "value": "<VERSION>", "description": "The database release to install and pin." },
		{ "name": "--nightly", "short": "-n", "description": "Install the latest nightly database." },
		{ "name": "--beta", "short": "-b", "description": "Install the latest beta database." },
		{ "name": "--alpha", "short": "-a", "description": "Install the latest alpha database." },
		{ "name": "--with", "value": "<A,B>", "description": "Further components to install, comma-separated. For example `--with cloud`." },
		{ "name": "--interactive", "short": "-i", "description": "Ask where to install when the default folder is not writable." },
		{ "name": "<DIR>", "description": "Where to put `surreal`, instead of `/usr/local/bin`." },
		{ "name": "--help", "short": "-h", "description": "Print the options and exit." }
	]}
/>

`--version`, `--nightly`, `--beta` and `--alpha` choose the database release, so they apply only when the database is installed. The script refuses them together with `--no-db`.

## Install on Windows

Run the PowerShell script from a normal or an elevated shell.

```powershell
irm https://windows.surrealdb.com | iex
```

The script installs `surreal.exe` into `C:\Program Files\SurrealDB` from an elevated shell, and into `%LOCALAPPDATA%\SurrealDB` otherwise, and adds that folder to your user `PATH`. A folder you name yourself is not added to `PATH`.

`irm | iex` cannot pass options. To pass them, run the script as a script block.

```powershell
& ([scriptblock]::Create((irm https://windows.surrealdb.com))) -NoDb -With cloud
```

<OptionsTable
	title="Parameters"
	options={[
		{ "name": "-Db", "description": "Install the database and pin it. This is the default." },
		{ "name": "-NoDb", "description": "Install `surreal` without the database." },
		{ "name": "-Minimal", "description": "Another name for `-NoDb`." },
		{ "name": "-Version", "short": "-v", "value": "<VERSION>", "description": "The database release to install and pin." },
		{ "name": "-Nightly", "short": "-n", "description": "Install the latest nightly database." },
		{ "name": "-Beta", "short": "-b", "description": "Install the latest beta database." },
		{ "name": "-Alpha", "short": "-a", "description": "Install the latest alpha database." },
		{ "name": "-With", "value": "<A,B>", "description": "Further components to install. For example `-With cloud`." },
		{ "name": "-Interactive", "short": "-i", "description": "Ask where to install when the install folder is not writable." },
		{ "name": "<InstallDir>", "description": "Where to put `surreal.exe`." }
	]}
/>

## Choose whether to install the database

The database is installed by default. Choose explicitly with `--db` or `--no-db` (`-Db` or `-NoDb` on Windows), or with the `SURREAL_CLI_INSTALL_DB` environment variable for callers that cannot pass options, such as `curl ... | sh` in a Dockerfile or a CI step.

| Setting | Effect |
| --- | --- |
| `SURREAL_CLI_INSTALL_DB=1` | Install the database, as `--db` does |
| `SURREAL_CLI_INSTALL_DB=0` | Install `surreal` alone, as `--no-db` does |

```bash title="Install surreal alone from a pipe"
curl -sSf https://install.surrealdb.com | SURREAL_CLI_INSTALL_DB=0 sh
```

A flag wins over the variable, and the last of `--db`, `--no-db` and `--minimal` wins over the others. Because the default may change, a script that needs one outcome should say so with a flag or the variable.

Without the database, `surreal db <command>` offers to install it the first time you run it, and `surreal install db` installs it at any time. Components installed this way follow the rules in [Managing components](/docs/reference/cli/guides/components.md).

## Install more components

`--with` installs further components in the same step, through the launcher.

```bash
curl -sSf https://install.surrealdb.com | sh -s -- --with cloud
```

With `surreal` already installed, `surreal install cloud` does the same. [Managing components](/docs/reference/cli/guides/components.md) covers versions, upgrading and pinning.

## Confirm the installation

`surreal list` lists each component, the version that runs, and where it runs from.

```bash
surreal list
```

```text title="Example output"
COMPONENT  VERSION  SOURCE  INSTALLED  PATH
cli        1.0.0    cli                /usr/local/bin/surreal
db         4.0.0    pinned  4.0.0      /home/you/.surrealdb/components/db/4.0.0/surreal-db
ext
cloud      1.0.0    pinned  1.0.0      /home/you/.surrealdb/components/cloud/1.0.0/surreal-cloud
lsp
memory
```

`surreal list --json` prints the same information as one JSON document, and `surreal --version` prints only the launcher's own version.

## Where files go

The launcher keeps everything it installs in one folder, the SurrealDB home. It is `~/.surrealdb` (`%USERPROFILE%\.surrealdb` on Windows) unless `SURREAL_CLI_HOME` names another folder. Each component version is a separate file under `components/<name>/<version>/`, which is what lets several versions sit side by side.

## Other ways to install

### Package managers

Homebrew (`surrealdb/tap/surreal`), Chocolatey (`surreal`) and Scoop (`surrealdb`) install the launcher, without the database. Install the database with `surreal install db`, or let it install the first time a `surreal db` command runs. From then on the launcher manages components as it does after the install script, and the package manager updates only the launcher. See the installation pages for [macOS](/docs/running/installation/macos.md) and [Windows](/docs/running/installation/windows.md).

The `surrealdb/tap/surreal-db` Homebrew formula installs the database alone, as `surreal-db`, which `surreal db` runs when the launcher has no database component of its own.

The install script leaves a `surreal` that a package manager owns alone; remove the package first, or install into another folder.

### Docker

The Docker image runs the database directly, so Docker examples use `surreal start` rather than `surreal db start`, and nothing inside the image installs or upgrades components. See [Running with Docker](/docs/running/docker.md).

### A mirror

`SURREAL_CLI_DOWNLOAD_ROOT` replaces the download host, for an internal mirror. The mirror must publish the launcher under `cli/launcher/`, each component in its own folder beneath `cli/`, and the database at its root, in the same layout as `https://download.surrealdb.com`. The value is an `http` or `https` address with no user name, password, query or fragment.

### Offline machines

`SURREAL_CLI_OFFLINE=1` forbids every network request. A component that is already installed runs normally, and a missing one fails at once with the command that would install it. See [Managing components](/docs/reference/cli/guides/components.md#offline-and-unattended-use).

## Troubleshooting

### A different `surreal` runs

A `surreal` earlier on your `PATH`, such as an older standalone database, runs instead of the launcher. The install script warns when it finds one. Remove the older executable, or put the launcher's folder first on `PATH`. `surreal list` shows the path each component runs from.

---

Source: https://surrealdb.com/docs/reference/cli/launcher

# surreal launcher commands

Reference for the surreal launcher: install, upgrade, use, uninstall, list, --version, +VERSION, help, version names, SURREAL_CLI_* environment variables, and exit codes.

The `surreal` launcher is the command you install once. It owns every operation that installs or changes versions, and it hands everything else to a [component](/docs/reference/cli/guides/components.md). Its own commands are `install`, `upgrade`, `use`, `uninstall` and `list`.

<Synopsis>
surreal [+VERSION] [COMPONENT] <COMMAND> [ARGS]...
surreal install [OPTIONS] <COMPONENT[@VERSION]>...
surreal upgrade [OPTIONS] [COMPONENT[@VERSION] | cli]...
surreal use [OPTIONS] <COMPONENT@VERSION>
surreal uninstall [OPTIONS] <COMPONENT[@VERSION]>...
surreal list [OPTIONS]
</Synopsis>

A component name as the first argument runs that component with everything after it, unchanged: `surreal db ...`, `surreal cloud ...`, `surreal ext ...`. The launcher never interprets those arguments. The guide to [managing components](/docs/reference/cli/guides/components.md) explains how components are stored and chosen.

## Components

| Component | Runs as | Reference |
| --- | --- | --- |
| `db` | `surreal db <command>` | [Database commands](/docs/reference/cli/db.md) |
| `cloud` | `surreal cloud <command>` | [Cloud commands](/docs/reference/cli/cloud.md) |
| `ext` | `surreal ext <command>` | [Extensions](/docs/reference/cli/ext.md) |

## Version names

Commands that take `COMPONENT[@VERSION]`, and `+VERSION`, accept the following.

| Form | Meaning |
| --- | --- |
| `3.3.2` or `v3.3.2` | That exact release |
| `2` | The newest stable release on major line 2 |
| `latest` | The newest stable release. Without a version, a component installs this, or its newest beta then alpha while it has no stable release |
| `beta`, `alpha` | The newest release on that channel |
| `nightly` | The latest nightly build. Only the database publishes one |

## surreal install

Install components, or another version of one beside those installed. The first install of a component becomes its default; later installs leave the default alone unless `--pin` is given.

<Synopsis>
surreal install [OPTIONS] <COMPONENT[@VERSION]>...
</Synopsis>

```bash
surreal install cloud
surreal install db@3.3.2 db@2 --pin
```

<OptionsTable
	title="Options"
	options={[
		{ "name": "--pin", "description": "Make each installed version the default. A version named exactly becomes the default whatever it was; a channel's release, such as `db@2`, becomes the default unless the current default is later." },
		{ "name": "--json", "description": "Print one JSON document on stdout." },
		{ "name": "--plain", "description": "Plain text: no tables, no colour, no animation." },
		{ "name": "--color", "value": "<WHEN>", "description": "When to use colour: `auto` (default), `always` or `never`." },
		{ "name": "--quiet", "short": "-q", "description": "Print only results and errors." },
		{ "name": "--yes", "short": "-y", "description": "Answer yes to every question." },
		{ "name": "--no-input", "description": "Never prompt. Fail where a question would be asked." }
	]}
/>

Every download is checked against its published SHA-256 and run once before it is put in place.

## surreal upgrade

Upgrade the launcher and every installed component, or only the ones named. Each follows the channel its default is on: a stable release stays on its major line, and a prerelease follows its own channel. Naming a version moves the default to that version, installing it first if needed. `cli` is the launcher itself.

<Synopsis>
surreal upgrade [OPTIONS] [COMPONENT[@VERSION] | cli]...
</Synopsis>

```bash
surreal upgrade
surreal upgrade db@3.3.2
surreal upgrade cli --dry-run
```

<OptionsTable
	title="Options"
	options={[
		{ "name": "--nightly", "description": "Upgrade the database to the latest nightly build. The same as `db@nightly`." },
		{ "name": "--alpha", "description": "Upgrade the database to the latest alpha release. The same as `db@alpha`." },
		{ "name": "--beta", "description": "Upgrade the database to the latest beta release. The same as `db@beta`." },
		{ "name": "--version", "value": "<VERSION>", "description": "Upgrade the database to this version. The same as `db@<VERSION>`." },
		{ "name": "--dry-run", "description": "Say what would change without changing it." },
		{ "name": "--json", "description": "Print one JSON document on stdout." },
		{ "name": "--plain", "description": "Plain text: no tables, no colour, no animation." },
		{ "name": "--color", "value": "<WHEN>", "description": "When to use colour: `auto` (default), `always` or `never`." },
		{ "name": "--quiet", "short": "-q", "description": "Print only results and errors." },
		{ "name": "--yes", "short": "-y", "description": "Answer yes to every question." },
		{ "name": "--no-input", "description": "Never prompt. Fail where a question would be asked." }
	]}
/>

`surreal db upgrade` is not run. It reports that the launcher manages the database's versions and points to `surreal upgrade db`.

## surreal use

Make an installed version of a component the default. It never downloads.

<Synopsis>
surreal use [OPTIONS] <COMPONENT@VERSION>
</Synopsis>

```bash
surreal use db@2.7.0
surreal use db@2
```

A major line or channel selects the newest installed release on it. The output options are the same as for `surreal install`.

## surreal uninstall

Remove installed versions of components.

<Synopsis>
surreal uninstall [OPTIONS] <COMPONENT[@VERSION]>...
</Synopsis>

```bash
surreal uninstall db@2.7.0
surreal uninstall cloud
```

`db@2.7.0` removes that version, and `db` alone removes every version of the component and its default. A channel such as `db@2` is refused, because it does not name a release. The default is removed by name only once nothing else is installed, so choose another with `surreal use` first. The output options are the same as for `surreal install`.

## surreal list

Show each component, the version that runs, and where it runs from.

<Synopsis>
surreal list [OPTIONS]
</Synopsis>

```text title="Example output"
COMPONENT  VERSION  SOURCE  INSTALLED  PATH
cli        1.0.0    cli                /usr/local/bin/surreal
db         4.0.0    pinned  4.0.0      /home/you/.surrealdb/components/db/4.0.0/surreal-db
ext
cloud      1.0.0    pinned  1.0.0      /home/you/.surrealdb/components/cloud/1.0.0/surreal-cloud
lsp
memory
```

The `SOURCE` column is `pinned` for a version in the launcher's store, `external` for an executable beside `surreal`, `path` for one found on `PATH`, and `missing` or `unpinned` where nothing is selected. With `--json`, the command prints one document with the launcher, the home folder, whether offline mode is on, and each component's `name`, `version`, `source`, `installed` versions and `path`. The output options are the same as for `surreal install`.

`surreal ls` is an alias. `surreal --version` (`-V`) prints only the launcher's own version, such as `1.0.0 for macos on aarch64`. To print a database server's version, use [`surreal db version`](/docs/reference/cli/db/commands/version.md).

## +VERSION

Run one version of a component for a single command, without changing the default.

<Synopsis>
surreal +VERSION COMPONENT [ARGS]...
</Synopsis>

```bash
surreal +2.6.5 db start --user root --pass secret
```

If the version is not installed, the launcher offers to install it, under the rules in [Offline and unattended use](/docs/reference/cli/guides/components.md#offline-and-unattended-use).

## surreal help

`surreal help` and `surreal --help` print the launcher's help, with the banner. `--no-banner` or `SURREAL_CLI_NO_BANNER` prints it without. `surreal <COMPONENT> help` prints a component's own help.

## Deprecated forms

The database's commands still run without `db`, and print a deprecation warning that names the replacement: `surreal start` is `surreal db start`. The set is closed: `start`, `sql`, `import`, `export`, `isready`, `is-ready`, `validate`, `fix`, `ml`, `module`, `mcp` and `version`, and database options placed before a command. `surreal module` points to `surreal ext`. See [Using the database](/docs/reference/cli/guides/database.md#the-deprecated-top-level-commands).

## Environment variables

| Variable | Effect |
| --- | --- |
| `SURREAL_CLI_HOME` | The SurrealDB home, where components are stored. Defaults to `~/.surrealdb` |
| `SURREAL_CLI_OFFLINE` | `1` forbids every network request. A missing component fails at once with exit code 12 |
| `SURREAL_CLI_DOWNLOAD_ROOT` | Replaces the download host, for a mirror. An `http` or `https` address with no credentials, query or fragment |
| `SURREAL_CLI_NO_BANNER` | Hides the banner above `surreal help` |
| `SURREAL_CLI_JSON` | The same as `--json` |
| `SURREAL_CLI_PLAIN` | The same as `--plain` |
| `SURREAL_CLI_INSTALL_DB` | Read by the install script: `1` installs the database, `0` does not. See [Install the SurrealDB CLI](/docs/reference/cli/guides/install.md) |

The launcher reads only `SURREAL_CLI_*`. Variables that start with `SURREAL_` and not `SURREAL_CLI_` belong to the database, and [`SURREAL_CLOUD_*`](/docs/reference/cli/cloud/global-flags.md) belong to Cloud. Every component the launcher runs receives `SURREAL_INVOKED_AS`, the way it was typed, so its help reads `surreal cloud instance list`, and `SURREAL_CLI_LAUNCHER`, the launcher's absolute path, which a component uses to run another one.

## Exit codes

A component's exit code is the launcher's. The launcher's own commands use the same codes as `surreal cloud`.

| Code | Meaning |
| --- | --- |
| `0` | The command did what was asked |
| `1` | A failure that fits no other code |
| `2` | A bad invocation, such as an unknown component or an invalid version name |
| `12` | A component the command needs is not installed and was not fetched: offline, nobody there to agree, or the offer declined. The message names the command that installs it |

The full list is in [output and exit codes](/docs/reference/cli/cloud/output-and-exit-codes.md).

---

Source: https://surrealdb.com/docs/reference/studio

# Introduction

SurrealDB Studio is the official visual interface for SurrealDB.

SurrealDB Studio is the official visual interface for managing and querying SurrealDB. It connects to any SurrealDB instance, letting you run SurrealQL, explore records, and manage schema from the web or desktop.

[Visit studio.surrealdb.com](https://studio.surrealdb.com)

SurrealDB Studio succeeds Surrealist, the earlier SurrealDB interface. It is the version to use with SurrealDB 4.

## Web or desktop

Studio comes as a web app and a desktop app. Both query and manage a database, and the desktop app can also start a local database for you:

| | Web app | Desktop app |
| --- | --- | --- |
| Where | [studio.surrealdb.com](https://studio.surrealdb.com) | Download from [surrealdb.com/studio](https://surrealdb.com/studio) for macOS, Windows and Linux, on Intel and ARM |
| Account | Sign in with a SurrealDB Cloud account | Optional: choose to continue without an account, and Studio keeps your connections on that computer |
| Databases it can reach | Any database served over TLS (`wss://` or `https://`), and one on the same computer | Any database, including one served over plain `ws://` or `http://` on another machine |

The difference in what each can reach comes from the browser. A page served over HTTPS, such as the web app, may only open an unencrypted connection to the computer it runs on. To connect to a database on another machine that has no TLS certificate, such as a server on your local network, use the desktop app or put the database behind TLS.

## In this section

- [SurrealQL editors](/docs/reference/studio/surrealql-editors.md) - write and run queries against a connection
- [Search and shortcuts](/docs/reference/studio/search-and-shortcuts.md) - move around Studio from the keyboard

---

Source: https://surrealdb.com/docs/reference/studio/search-and-shortcuts

# Search and shortcuts

The SurrealDB Studio command palette and its keyboard shortcuts.

SurrealDB Studio offers a range of shortcuts to help you navigate the interface more efficiently. You can find a list of all available shortcuts by pressing `Ctrl + K` or `Cmd + K` on your keyboard.

In the search modal, you can access all available shortcuts for open sessions, the views, all available tables in your connected database and the settings dialog.

<img src="~/assets/img/image/surrealist/search-and-hot-key.png" alt="Search and Shortcuts" />

<br/>

<br/>

<table>
    <thead>
        <tr>
            <th scope="col">Options</th>
            <th scope="col">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td scope="row" data-label="Type">
                <code>Connections</code>
            </td>
            <td scope="row" data-label="Description">
                Open a list of all available connections and create a new connection type.
            </td>
        </tr>
        <tr>
            <td scope="row" data-label="Type">
                <code>Views</code>
            </td>
            <td scope="row" data-label="Description">
                Open all available views in the current session. This can be the Cloud view, GraphQL view, Query view, Designer view or the Authentication view.
            </td>
        </tr>
        <tr>
            <td scope="row" data-label="Type">
                <code>Tables</code>
            </td>
            <td scope="row" data-label="Description">
                Shows all available tables in the connected database. If you have no tables in the connection, load the Surreal Deal Store dataset, you can see the tables in the dataset.
            </td>
        </tr>
        <tr>
            <td scope="row" data-label="Type">
                <code>Query</code>
            </td>
            <td scope="row" data-label="Description">
                See all saved queries, view the query history and create a new query. Comment out a line in the query editor using `Cmd + /` or `Ctrl + /`.
            </td>
        </tr>
        <tr>
            <td scope="row" data-label="Type">
                <code>Explorer</code>
            </td>
            <td scope="row" data-label="Description">
                Import and export your database schema in a `.surql` file format.
            </td>
        </tr>
        <tr>
            <td scope="row" data-label="Type">
                <code>Authentication</code>
            </td>
            <td scope="row" data-label="Description">
                Create user permissions and roles for your connected database.
            </td>
        </tr>
        <tr>
            <td scope="row" data-label="Type">
                <code>API Docs</code>
            </td>
            <td scope="row" data-label="Description">
                Access the SurrealDB API documentation and access snippets for your queries in different SDK languages.
            </td>
        </tr>
        <tr>
            <td scope="row" data-label="Type">
                <code>Settings</code>
            </td>
            <td scope="row" data-label="Description">
                Access the Settings dialog to customise the appearance and behaviour of SurrealDB Studio.
                Increase the view size of your editor with `cmd + Option + +` or reduce with `cmd + Option + -`.
            </td>
        </tr>
        <tr>
            <td scope="row" data-label="Type">
                <code>Navigator</code>
            </td>
            <td scope="row" data-label="Description">
                Reload the navigator to see all available shortcuts and open the search modal.
            </td>
        </tr>
        <tr>
            <td scope="row" data-label="Type">
                <code>Developer</code>
            </td>
            <td scope="row" data-label="Description">
                Open a new connection and reset tour settings.
            </td>
        </tr>
    </tbody>
</table>

---

Source: https://surrealdb.com/docs/reference/studio/surrealql-editors

# SurrealQL editors

SurrealQL editor shortcuts in SurrealDB Studio. Indentation, comments, multi-cursor edits, running queries, record inspection, and JSON formatting.

Throughout SurrealDB Studio you will encounter various SurrealQL editors. These editors support intelligent SurrealQL highlighting and provide a range of features to help you write queries and edit records.

## Shortcuts

Editors support an array of useful shortcuts to help you navigate and edit more efficiently.

<table>
    <thead>
        <tr>
            <th scope="col">Shortcuts</th>
            <th scope="col">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td scope="row" data-label="Shortcuts">
                <code>tab</code>
            </td>
            <td scope="row" data-label="Description">
                Indent the current line by 4 spaces.
            </td>
        </tr>
		<tr>
            <td scope="row" data-label="Shortcuts">
                <code>shift + tab</code>
            </td>
            <td scope="row" data-label="Description">
                Unindent the current line by 4 spaces.
            </td>
        </tr>
		<tr>
            <td scope="row" data-label="Shortcuts">
                <code>ctrl/cmd + f</code>
            </td>
            <td scope="row" data-label="Description">
                Open the search and replace panel
            </td>
        </tr>
		<tr>
            <td scope="row" data-label="Shortcuts">
                <code>ctrl/cmd + /</code>
            </td>
            <td scope="row" data-label="Description">
                Toggles comments on the selected or active line(s)
            </td>
        </tr>
		<tr>
            <td scope="row" data-label="Shortcuts">
                <code>ctrl/cmd + left click</code>
            </td>
            <td scope="row" data-label="Description">
                Place multiple cursors at the clicked locations
            </td>
        </tr>
		<tr>
            <td scope="row" data-label="Shortcuts">
                <code>ctrl/cmd + shift + L</code>
            </td>
            <td scope="row" data-label="Description">
                Selects all occurrences of the currently selected text
            </td>
        </tr>
		<tr>
            <td scope="row" data-label="Shortcuts">
                <code>ctrl/cmd + d</code>
            </td>
            <td scope="row" data-label="Description">
                Selects next occurrence of the currently selected text
            </td>
        </tr>
		<tr>
            <td scope="row" data-label="Shortcuts">
                <code>ctrl/cmd + enter</code>
            </td>
            <td scope="row" data-label="Description">
                Execute the query query (only applied to the query editor)
            </td>
        </tr>
	</tbody>
</table>

## Record inspection

Some editors support record inspection, which allows you to open a record in the Record inspector drawer by holding `ctrl/cmd` and left-clicking on a record id.

## JSON

Some editors, such as the record editor and query responses, support falling back to a JSON representation. This can be configured in the Settings dialog under `Appearance > Value formatting mode`.
