• Start

Multi-tenancy

Namespace & database architecture

Layering namespaces and databases for isolation, security, and strict mode.

SurrealDB scopes data in two levels: a namespace holds one or more databases, and each database holds your tables and other resources. There is no fixed cap on how many namespaces or databases you create. Design is driven by who should be isolated from whom (tenants, environments, product lines) and who is allowed to administer each layer.

In fact, there are some social media platforms that even run by creating an entire database per user.

A more common SaaS pattern is one namespace per tenant so credentials and data never cross tenant boundaries; another pattern is one namespace per environment (dev, staging, prod) with multiple databases inside.

Namespaces are created by root users. Databases live inside a namespace and are created by root or namespace owners/editors once you execute a USE statement to move to that namespace.

Reference pages: DEFINE NAMESPACE, DEFINE DATABASE.

For convenience, a new running instance will create a new namespace and database that each have the name main. This can be disabled by passing in a flag or setting an environment variable when using the surreal start command.

Below shows how you can create a namespace using the DEFINE NAMESPACE statement.

DEFINE NAMESPACE platform_ltd;

A database is where your application schema actually lives. Options such as STRICT change whether undefined resources may be created implicitly to allow CRUD operations to perform.

Below shows how you can create a database using the DEFINE DATABASE statement.

-- Specify the namespace for the database
USE NS platform_ltd;

-- Define database
DEFINE DATABASE app_vitalsense;

A strict database is one that does not allow a resource to be used unless it has already been defined. The default behaviour in SurrealDB works otherwise, by allowing statements like CREATE, INSERT, and UPSERT to work.

CREATE some_new_table;
INFO FOR DATABASE.tables;

The output of the INFO statement shows that a table called some_new_table has been created with a few default clauses.

{
some_new_table: 'DEFINE TABLE some_new_table TYPE ANY SCHEMALESS PERMISSIONS NONE'
}

Such an operation within a strict database is simply not allowed.

DEFINE DATABASE new_db STRICT;
USE DATABASE new_db;
CREATE some_new_table;

Output

"The table 'some_new_table' does not exist"

Was this page helpful?