Skip to content

Features

Multi-model. Documents, graphs, vectors, time-series and relations in one engine.
AI-native. Vector, full-text and graph retrieval, built in.
Built in. Auth, permissions, live queries and functions, native to the engine.

Architecture and storage

Data storage

In-memory

SurrealDB can run in-memory, enabling high performance with the same transactional and multi-model features. This is suitable for caching data or testing locally.

Embedded

Run SurrealDB embedded within your application, executing directly inside Python and JavaScript runtimes, with WebAssembly, on mobile devices, at the edge, or within the browser.

Single node

SurrealDB supports single-node deployments with persistent on-disk storage, making it suitable for development, edge, or smaller production workloads.

Distributed

Run on a distributed storage architecture. Separation of compute and storage enables horizontally scaling compute nodes for read and write concurrency, and storage nodes for multi-TB datasets and high availability.

Scalability

Horizontal scalability

Scale horizontally by adding more nodes to handle increased load and data volume.

Storage-compute separation

Independently scale storage and compute for optimal performance and cost.

Automatic data sharding

Automatic sharding distributes data across nodes for balanced load.

Partition-free tables

Scale tables without manual partitioning with automatic data distribution.

Read replicas

Separate read-only nodes for scaling read-heavy workloads with low-latency queries.

Multi-region replication

Replicate data across geographic regions for low-latency global reads and disaster recovery.

Database engine

ACID compliant

Ensures data integrity with atomicity, consistency, isolation, and durability guarantees.

Multi-tenancy data separation

Split data into namespaces and databases. There is no limit to the number of databases under each namespace, with the ability to switch between databases inside queries and transactions.

Schemafull or schemaless

Store unstructured nested data with any columns, or limit data stored to only specific columns or fields. Get started quickly without having to define every column, and move to schemafull when your data model is defined.

Multi-table, multi-row transactions

As a fully ACID compliant database, SurrealDB allows you to run transactions across multiple rows, and across multiple different tables. There is no limit to the length of time a transaction can run.

Experimental

Versioned temporal tables

Versioned temporal tables enable the option to 'go back in time' when querying your data. See how data looked before changes were made, or restore to a particular point-in-time.

Table fields

When a table is defined as schemafull, only data allowed by defined fields will be stored. Table fields can be nested, and can be limited to a certain data type. VALUE clauses can be used to ensure a default value is always specified if no data is entered.

Table events

Table events can be triggered after any change or modification to the data in a record. Each trigger is able to see the $before and $after value of the record, enabling advanced custom logic with each trigger.

Asynchronous events

Events can be processed asynchronously in the background, enabling non-blocking workflows, webhook triggers, and integration with external services without impacting query performance.

-- Specify a field on the user table
DEFINE FIELD email ON TABLE user TYPE string ASSERT string::is_email($value);

-- Add a unique index on the email field to prevent duplicate values
DEFINE INDEX email ON TABLE user COLUMNS email UNIQUE;

-- Create a new event whenever a user changes their email address
DEFINE EVENT email ON TABLE user WHEN $before.email != $after.email THEN (
CREATE event SET user = $this, time = time::now(), value = $after.email, action = 'email_changed'
);

Relational data model

Traditional relational capabilities with tables, relationships, and SQL queries.

Document data model

Flexible document storage with nested objects, arrays, and JSON-native structures.

Graph data model

Native graph functionality with nodes, edges, and complex relationship traversal.

Time-series data modelling

Temporal data modelling with automatic table sharding and indexing.

Table constraints

Each defined table field supports an ASSERT clause which acts as a constraint on the data. This clause enables advanced SurrealQL statements which can ensure that the $value entered is within certain parameters. Each clause is also able to see the $before and $after value of the record, enabling advanced custom logic with each trigger.

-- Specify a field on the user table
DEFINE FIELD countrycode ON TABLE user TYPE string
-- Enforce country code format to comply with ISO-3166
ASSERT $input = /[A-Z]{3}/
-- Set a default value
DEFAULT 'GBR';

Live queries and record changes

Live SQL queries allow for advanced filtering of the changes to specific documents, documents which match a particular filter, or all documents in a specific table. Live SQL queries can send the fully-updated document, or only the document changesets.

-- Subscribe to all matching document changes
LIVE SELECT * FROM document
WHERE
account = $auth.account
OR public = true
;

-- Subscribe to all changes to a single record
LIVE SELECT * FROM post:c569rth77ad48tc6s3ig;

-- Stop receiving change notifications
KILL "1986cc4e-340a-467d-9290-de81583267a2";

One-directional links

Create direct references between records with automatic referential integrity.

Bi-directional relationships

Establish two-way relationships between records with bi-directional graph traversal.

Recursive graph traversal

Traverse relationships to any depth with infinite recursive graph queries.

-- Create a record link from one record to another
UPDATE person:tobie SET company = company:surrealdb;

-- Traverse from a person to their company
SELECT company.name FROM person:tobie;

-- Traverse the graph to find companies founded by a person
SELECT ->founded->company.name FROM person:tobie;

-- Destructure fields from a record link
SELECT company.{ name, address } FROM person:tobie;

-- Destructure fields with infinite depth graph traversal
SELECT
name,
->(founded WHERE time.founded > d'2020-01-01')
..->company.{ name, address }
FROM person:tobie;

Global parameters

Global parameters can be used to store values across the database, which are then accessible to all queries.

-- Define a global parameter which will be accessible to all queries.
DEFINE PARAM $STRIPE VALUE "https://api.stripe.com/payments/new";

-- Use the defined global parameter in all queries on the database.
DEFINE EVENT payment ON TABLE order WHEN $event = 'CREATE' THEN http::post($STRIPE, $value);

Unique indexes

Enforce uniqueness constraints on one or more fields. Unique indexes prevent duplicate values while improving query performance.

Compound indexes

Define indexes across multiple fields for efficient multi-column queries. Compound indexes support all nested fields including arrays and objects.

Flattened array indexes

Index individual values within array fields using compound flattened indexes, enabling efficient queries on nested array content.

Non-blocking indexing

Indexes are built and maintained without blocking reads or writes. Tables remain fully queryable and writable while indexes are created, rebuilt, or updated.

Concurrent background processing

Index construction runs concurrently in the background across distributed cluster nodes, enabling efficient processing of massive datasets with minimal impact on query performance.

Full-text indexing and filtering

Define full-text indexes with configurable analysers, tokenizers, and filters. Supports BM25 ranking, relevance scoring, and highlighting with offset extraction.

-- Define a text analyzer
DEFINE ANALYZER en TOKENIZERS camel,class FILTERS snowball(English);

-- Define a search index for a field on the book table
DEFINE INDEX search_title ON book FIELDS title FULLTEXT ANALYZER en BM25 HIGHLIGHTS;

-- Select all books who match given keywords
SELECT search::score(1) AS score, search::highlight('<b>', '</b>', 1) AS title
FROM book WHERE title @1@ 'rust web' ORDER BY score DESC;

Vector embedding indexing

HNSW vector indexing for approximate nearest neighbour search, with support for euclidean, cosine, and manhattan distance metrics. Configurable storage types including F64, F32, F16, I64, I32, I16, I8 and U8 let you balance precision against memory usage.

-- Add vector embedding data to record content
CREATE article:1 SET embedding = [0.1, 0.2, 0.3, 0.4];
CREATE article:2 SET embedding = [0.2, 0.1, 0.4, 0.3];
CREATE article:3 SET embedding = [0.4, 0.3, 0.2, 0.1];
-- Define an HNSW vector index with cosine distance
DEFINE INDEX hnsw_idx ON article FIELDS embedding HNSW DIMENSION 4 DIST COSINE;
-- Find the 2 nearest neighbours to a query vector
LET $query = [0.15, 0.25, 0.35, 0.45];
SELECT id, vector::distance::knn() AS dist
FROM article WHERE embedding <|2|> $query ORDER BY dist;

DiskANN vector indexing

DiskANN vector indexing: disk-based approximate nearest neighbour index for indexes larger than memory, with F32, F16, I8 and U8 element types.

Hybrid search

Combine full-text search and vector similarity in a single query using reciprocal rank fusion. Hybrid search merges lexical and semantic results for more accurate retrieval across structured and unstructured data.

-- Define a full-text index with a custom analyser
DEFINE ANALYZER simple TOKENIZERS class, punct FILTERS lowercase, ascii;
DEFINE INDEX idx_text ON article FIELDS text FULLTEXT ANALYZER simple BM25;
-- Define an HNSW vector index on the same table
DEFINE INDEX idx_embed ON article FIELDS embedding HNSW DIMENSION 3 DIST COSINE;
-- Combine full-text and vector search with reciprocal rank fusion
LET $qvec = [0.12, 0.18, 0.27];
LET $vs = SELECT id FROM article WHERE embedding <|2,100|> $qvec;
LET $ft = SELECT id, search::score(1) AS score
FROM article WHERE text @1@ 'graph database'
ORDER BY score DESC LIMIT 2;
search::rrf([$vs, $ft], 2, 60);

Aggregate indexed views

Aggregate views let you pre-compute analytics queries as data is written to SurrealDB. Similarly to an index, a table view lets you select, aggregate, group, and order data, with support for moving averages, time-based windowing, and attribute-based counting.

-- Drop all writes to the reading table. We don't need every reading.
DEFINE TABLE reading DROP;

-- Define a table as a view which aggregates data from the reading table
DEFINE TABLE temperatures_by_month AS
SELECT
count() AS total,
time::month(recorded_at) AS month,
math::mean(temperature) AS average_temp
FROM reading
GROUP BY city
;

-- Add a new temperature reading with some basic attributes
CREATE reading SET
temperature = 27.4,
recorded_at = time::now(),
city = 'London',
location = (-0.118092, 51.509865)
;

Count indexes

Maintain a pre-computed record count for instant count() queries using GROUP ALL, avoiding full table scans on large datasets.

Future

Partial indexes

Index only a subset of records matching a condition, reducing index size and improving write performance for filtered queries.

Future

Expression indexes

Index the result of an expression or function rather than a raw field value, enabling efficient lookups on computed values.

Future

Graph indexes

Dedicated indexing for graph traversals, optimising performance for multi-hop queries across relationships and edges.

Future

Geospatial indexes

Spatial indexing for geometry and geography data types, enabling efficient containment, intersection, and proximity queries.

Future

Record link indexes

Indexes on record link fields for faster graph-adjacent lookups and relationship traversals without requiring full graph indexes.

Data model

Basic types

Support for booleans, strings, bytes, integers, floats, decimal numbers, and empty values is built in by default.

Arrays

SurrealDB has native support for arrays, with no limit to the depth of nesting within arrays. Arrays can contain any other data value.

Objects

Embedded object types are an integral feature of SurrealDB, with no limit to the depth of nesting for objects.

Datetimes

Dates and datetimes in ISO-8601 format are supported. All dates are converted and stored in the UTC timezone.

Durations

Any duration from nanoseconds to weeks can be stored and used for calculations. Durations can be added to datetimes, and to other durations.

UUIDs

Native support for UUID values with built-in generation functions for v4 and v7 formats.

Geometry types

SurrealDB makes working with GeoJSON easy, with support for Point, Line, Polygon, MultiPoint, MultiLine, MultiPolygon, and Collection values. SurrealQL automatically detects GeoJSON objects, converting them into a single data type.

UPDATE city:london SET
centre = (-0.118092, 51.509865),
boundary = {
type: "Polygon",
coordinates: [[
[-0.38314819, 51.37692386],
[0.1785278, 51.37692386],
[0.1785278, 51.61460570],
[-0.38314819, 51.61460570],
[-0.38314819, 51.37692386]
]]
}
;

Strict typing

With a strict typing system, SurrealQL ensures that document structures are easier to understand, and any data conforms to the defined record schema. Advanced types for arrays and record links ensure that related data works in the same way as basic types. Values can be explicitly cast between types using operators including bool, int, float, string, number, decimal, datetime, and duration.

// Ensure that a record field must be a number.
DEFINE FIELD age ON person TYPE number;

// Allow the field to be optional or a number.
DEFINE FIELD age ON person TYPE option<number>;

// Ensure that a record link is specified and of a specific type.
DEFINE FIELD author ON book TYPE record<person>;

// Allow a field to be optional and of a selection of types.
DEFINE FIELD pet ON user TYPE option<record<cat | dog>>;

// Allow a field to be one of multiple types.
DEFINE FIELD rating ON film TYPE float | decimal;

// Ensure that a field is an a array of unique values of a certain length.
DEFINE FIELD tags ON person TYPE set<string, 5>;

Query language

SELECT, CREATE, UPDATE, DELETE statements

Manipulation and querying of data in SurrealQL is done using the SELECT, CREATE, UPDATE, and DELETE methods. These enable selecting or modifying individual records, or whole tables. Each statement supports multiple different tables or record types at once.

-- Create a new article record with a specific id
CREATE article:surreal SET name = "SurrealDB: The next generation database";

-- Update the article record, and add a new field
UPDATE article:surreal SET time.created = time::now();

-- Select all matching articles
SELECT * FROM article, post WHERE name CONTAINS 'SurrealDB';

-- Delete the article
DELETE article:surreal;

RELATE statements

The RELATE statement adds graph edges between records in SurrealDB. It follows the convention of vertex -> edge -> vertex or noun -> verb -> noun, enabling the addition of metadata to the edge record.

-- Add a graph edge between user:tobie and article:surreal
RELATE user:tobie->write->article:surreal
SET time.written = time::now()
;

-- Add a graph edge between specific users and developers
LET $from = (SELECT users FROM company:surrealdb);
LET $devs = (SELECT * FROM user WHERE tags CONTAINS 'developer');
RELATE $from->like->$devs UNIQUE
SET time.connected = time::now()
;

INSERT statements

The INSERT statement resembles the traditional SQL statement, enabling users to get started quickly. It supports the creation of records using a VALUES clause, or by specifying the record data as an object.

INSERT INTO company {
name: 'SurrealDB',
founded: "2021-09-10",
founders: [person:tobie, person:jaime],
tags: ['big data', 'database']
};

INSERT IGNORE INTO company (name, founded)
VALUES ('SurrealDB', '2021-09-10')
ON DUPLICATE KEY UPDATE tags += 'developer tools'
;

FOR statements

FOR statements enable simplified iteration over data, or for advanced logic when dealing with nested arrays or recursive functions, within code blocks or custom functions.

THROW statements

Return custom errors which allow for complex programming and business logic right within the database and authentication engine.

Parameters

Parameters can be used to store values or result sets, and can be used as stored parameters in client code.

Subqueries

Recursive subqueries are useful for advanced querying or modification of values, whilst simplifying the overall query.

Nested field queries

In SurrealQL any nested array or object value can be accessed and manipulated using traditional dot notation, or array notation.

Set operators

Set operators enable working with sets of distinct values.

Geo operators

Geospatial operators enable geospatial containment and intersection operators on geospatial types.

Maths operators

Maths operators can be used to perform complex mathematical calculations.

Maths constants

Built-in constants can be used for advanced mathematical expressions and calculations, including math::E, math::PI, math::TAU, and more.

-- Use mathematical operators to calculate value
SELECT * FROM temperature WHERE (celsius * 1.8) + 32 > 86.0;

-- Use geospatial operator to detect polygon containment
SELECT * FROM restaurant WHERE location INSIDE {
type: "Polygon",
coordinates: [[
[-0.38314819, 51.37692386],
[0.1785278, 51.37692386],
[0.1785278, 51.61460570],
[-0.38314819, 51.61460570],
[-0.38314819, 51.37692386]
]]
};

-- Select all people whose tags contain "tag1" OR "tag2"
SELECT * FROM person WHERE tags CONTAINSANY ["tag1", "tag2"];

-- Select all people who have any email address ending in 'gmail.com'
SELECT * FROM person WHERE emails.*.value ?= /gmail.com$/;

Expressions

SurrealQL supports fetching data using dot notation, array notation, and graph semantics. SurrealQL enables records to link to other records and traverses all embedded links or graph connections as desired. When traversing and fetching remote records SurrealQL enables advanced filtering using traditional WHERE clauses.

-- Select a nested array, and filter based on an attribute
SELECT emails[WHERE active = true] FROM person;

-- Select all 1st, 2nd, and 3rd level people who this specific person record knows, or likes, as separate outputs
SELECT ->knows->(? AS f1)->knows->(? AS f2)->(knows, likes WHERE influencer = true AS e3)->(? AS f3) FROM person:tobie;

-- Select all person records (and their recipients), who have sent more than 5 emails
SELECT *, ->sent->email->to->person FROM person WHERE count(->sent->email) > 5;

-- Select other products purchased by people who purchased this laptop
SELECT <-purchased<-person->purchased->product FROM product:laptop;

-- Select products purchased by people in the last 3 weeks who have purchased the same products that we purchased
SELECT ->purchased->product<-purchased<-person->(purchased WHERE created_at > time::now() - 3w)->product FROM person:tobie;

Complex record IDs

SurrealDB supports the ability to define complex record IDs using arrays. These values sort correctly, and can be used to store values or recordings in a time-series context.

// Set a new parameter
LET $now = time::now();
// Create a record with a complex ID using an array
CREATE temperature:['London', $now] SET
location = 'London',
date = time::round($now, 1h),
temperature = 23.7
;

Record ID ranges

SurrealDB supports the ability to query a range of records using the record ID. The record ID ranges retrieve records using the natural sorting order of the record IDs. These range queries can be used to query a range of records in a time-series context.

-- Select all person records with IDs between the given range
SELECT * FROM person:1..1000;
-- Select all records for a particular location, inclusive
SELECT * FROM temperature:['London', NONE]..=['London', time::now()];
-- Select all temperature records with IDs less than a maximum value
SELECT * FROM temperature:..['London', '2022-08-29T08:09:31'];
-- Select all temperature records with IDs greater than a minimum value
SELECT * FROM temperature:['London', '2022-08-29T08:03:39']..;
-- Select all temperature records with IDs between the specified range
SELECT * FROM temperature:['London', '2022-08-29T08:03:39']..['London', '2022-08-29T08:09:31'];

Machine learning

Custom machine learning models

Use SurrealML to train custom machine learning models in Python, using PyTorch, Tensorflow, or Sklearn. The models are stored in a custom .surml data-format, enabling the model to be run consistently and safely in Python, Rust, or SurrealDB.

Import models into SurrealDB

SurrealDB allows developers the choice of storing SurrealML models on local storage, or remote storage including Amazon S3, Google Cloud Storage, or Azure Storage.

PyTorch

PyTorch models are supported natively with SurrealML when running in Python, or within SurrealDB.

Tensorflow

Tensorflow models are supported natively with SurrealML when running in Python, or within SurrealDB.

Sklearn

Sklearn models are supported natively with SurrealML when running in Python, or within SurrealDB.

Export models from SurrealDB

SurrealDB allows developers to store multiple versions of each SurrealML model, and to export each model from the database as a binary file.

Model inference in Python

Inference on .surml model files in Python allows for consistent and reproducible model computation in development, continuous integration, testing, or production environments.

Model inference in SurrealDB

Model inference within SurrealDB is powered by a Rust-native runtime, backed by ONNX, with support for PyTorch, Tensorflow, and Sklearn models. This secure and performant runtime allows for CPU and GPU model inference right alongside the data within the database.

-- Perform raw computation against the imported model
RETURN ml::house::price::prediction<0.3.0>(
[1.0, 2.0], [1, 2]
);
-- Perform named buffered computation against the imported model
SELECT
*,
ml::house::price::prediction<0.3.0>({
squarefoot: squarefoot_col,
num_floors: num_floors_col
}) AS price_prediction
FROM property_listing
WHERE price_prediction > 177206.21875
;

File storage

Buckets

Define storage buckets with DEFINE BUCKET to manage files directly from SurrealQL. Buckets support in-memory, file-backed, and global backends with fine-grained permission controls.

-- Define a bucket for file storage
DEFINE BUCKET uploads BACKEND "memory";
-- Store a file in the bucket
f"uploads:/readme.txt".put("Hello, SurrealDB!");
-- Read the file contents
<string>f"uploads:/readme.txt".get();
-- Copy a file to a new location
f"uploads:/readme.txt".copy("readme-backup.txt");

In-memory storage

Ephemeral storage for caching, temporary files, and session data. In-memory buckets are fast and ideal for transient workloads.

File-system storage

Persistent on-disk storage with allowlisted directory paths. Suitable for production workloads requiring durable file storage.

Object storage

S3, Google Cloud Storage, and Azure Blob Storage as bucket backends for scalable cloud-native file storage.

Global buckets

A single shared storage backend across all namespaces and databases, with automatic namespace and database path prefixing.

Bucket permissions

Control who can put, get, delete, copy, rename, and list files using PERMISSIONS clauses with $file, $target, and $action variables.

File operations

A full set of file methods including put, get, head, delete, copy, rename, exists, and list, accessible directly from SurrealQL.

AI agents

Model Context Protocol

Connect AI tools like Cursor, VS Code, and Claude directly to SurrealDB using the Model Context Protocol for context-aware interactions and seamless data access.

Unified agent memory

Store structured data, documents, vectors, and graphs in one place, giving agents a single persistent source of context, state, and history.

RAG and Graph RAG

Combine vector similarity, graph traversal, and document retrieval in a single SurrealQL query for retrieval-augmented generation. Blend connections, facts, and semantics in a single round trip.

-- RAG: Find products similar to a user's last purchase
-- using graph traversal and vector similarity
LET $last_purchase = user:one->purchased.at.last();
LET $last_product = (
user:one->purchased[WHERE at = $last_purchase]->product
)[0];
-- Get the most similar products by vector cosine similarity
(
SELECT
id,
vector::similarity::cosine($last_product.vector, vector) AS similarity
FROM product
ORDER BY similarity DESC
LIMIT 3
)[1..];

-- Graph RAG: Find sibling documents that share a tag
-- and calculate semantic similarity
SELECT VALUE (
SELECT *,
vector::similarity::cosine(embedding, $parent.embedding) AS similarity
FROM array::distinct(->tagged_with->$tag<-tagged_with<-document)
) AS siblings
FROM ONLY $record
FETCH siblings;

Real-time agent reactivity

Live queries and event triggers let agents react instantly to changing data, enabling more adaptive behaviour.

AI model integration

Call LLMs, embedding models, or GPU inference directly from within the database via WebAssembly plugins.

Agent governance

Fine-grained permissions, access control, and audit trails for safe, compliant AI workflows.

Prompt-response session storage

Store conversation history and context for AI apps with automatic session management.

LangChain integration

Seamlessly integrate with LangChain for building AI apps with vector search and LLMs.

JSON-native unstructured data

Store and query unstructured data in its native JSON format without schema constraints.

Hybrid document-graph modelling

Combine document and graph models in a single database for flexible data representation.

Functions and extensibility

Array functions

Functions for manipulation, joining, and diffing of arrays are built into SurrealDB as standard.

HTTP functions

HTTP functions can be used for remote trigger events and webhook functionality.

Math functions

Math functions can be used for complex statistical analysis of numbers and sets of numbers.

Parsing functions

Parsing functions can be used for parsing and extracting individual parts of URLs, emails, and domains.

Rand functions

Random generation functions can be used to generate random values, numbers, strings, UUIDs, and datetimes.

Search functions

Functions related to the full-text search capabilities, such as calculating relevance scores or highlighting content.

String functions

Functions for string manipulation enable modification and processing of strings.

Type functions

Type checking functions can be used to check the type of a value, which is useful in custom function definitions.

Vector functions

A collection of essential vector operations that provide foundational functionality for numerical computation, machine learning, and data analysis.

Geo functions

Geospatial functions can be used for converting between geohash values, and for calculating the distance, bearing, and area of GeoJSON data types.

Time functions

Time functions can be used to manipulate dates and times - with support for rounding, and extracting specific parts of datetimes.

Count functions

SurrealDB supports general count functionality for counting total values, or for aggregate grouping. It's also possible to count only those expressions which result in a truthy value.

Custom functions

Custom functions allow for complicated or repeated user-defined code, to be run seamlessly within any query across the database. Custom functions support typed arguments, and multiple nested queries with custom logic.

-- Define a global function which can be used in any query
DEFINE FUNCTION fn::get::person($first: string, $last: string, $birthday: string) {

LET $person = SELECT * FROM person WHERE [first, last, birthday] = [$first, $last, $birthday];

RETURN IF $person[0].id {
$person[0]
} ELSE {
CREATE person SET first = $first, last = $last, birthday = $birthday
};

};

-- Call the global custom function, receiving the returned result
LET $person = fn::get::person('Tobie', 'Morgan Hitchcock', '2022-09-21');

JavaScript functions

JavaScript functions can be used for more complex functions and triggers. Each JavaScript function iteration runs with its own context isolation - with the current record data passed in as the execution context or this value.

CREATE film SET
ratings = [
{ rating: 6, user: user:bt8e39uh1ouhfm8ko8s0 },
{ rating: 8, user: user:bsilfhu88j04rgs0ga70 },
],
featured = function() {
return this.ratings.filter(r => {
return r.rating >= 7;
}).map(r => {
return { ...r, rating: r.rating * 10 };
});
}
;

WebAssembly extensions

Write custom extensions in Rust, compile them to WebAssembly, and load them into SurrealDB at runtime. WebAssembly plugins run in a sandboxed environment with near-native performance, shared ACID transactions, and fine-grained permission controls.

use fake::faker::name::raw::*;
use fake::{Fake, locales::*};
use rand::random_range;
use surrealdb_types::SurrealValue;
use surrealism::surrealism;

#[derive(Debug, SurrealValue)]
pub struct User {
first_name: String,
last_name: String,
age: i32,
}

#[surrealism]
fn can_drive(age: i64) -> bool {
age >= 18
}

#[surrealism]
pub fn random_user() -> User {
User {
first_name: FirstName(EN).fake(),
last_name: LastName(DE_DE).fake(),
age: random_range(10..=50),
}
}
-- Load a compiled WebAssembly module into SurrealDB
DEFINE BUCKET plugins BACKEND "file:/path/to/plugins";
-- Define a module pointing to the compiled .surli file
DEFINE MODULE mod::demo AS f"plugins:/demo.surli";
-- Call WebAssembly functions directly from SurrealQL
CREATE user CONTENT mod::demo::random_user();
-- Use module functions in queries just like built-in functions
SELECT
first_name + ' ' + last_name AS name,
mod::demo::can_drive(age) AS can_drive
FROM user;

Security and authorisation

Role-based access control

Granular role-based permissions with inheritance and custom role definitions.

Field-level access control

Control access to individual fields for sensitive data protection.

Future

Field-level encryption

Selectively encrypt sensitive fields with client-side key management.

Encryption at rest

Data encryption at rest with industry-standard algorithms and key management.

TLS in transit

End-to-end encryption for all data in transit with configurable TLS.

Multi-tenant isolation

Complete tenant isolation with separate compute and storage resources.

Root access

Root access enables full data access for all data in SurrealDB. Root access can be limited to specific IPv4 or IPv6 IP addresses.

Namespace access

Enable full data access for all databases under a specific namespace, controlled using custom defined usernames and passwords.

Database access

Enable full data access to a specific database under a specific namespace, controlled using custom defined usernames and passwords.

Record access

Record access is the powerful functionality which enables SurrealDB to operate as a web database. Flexible authentication and access rules enable fine-grained access to tables and fields with the highest security, whilst ensuring that performance is affected as little as possible.

Third-party authentication

If authentication with a third-party OAuth provider is desired, specific tokens can be used for authentication with SurrealDB. ES256, ES384, ES512, HS256, HS384, HS512, PS256, PS384, PS512, RS256, RS384, and RS512 algorithms are supported.

-- Enable record access directly in SurrealDB
DEFINE ACCESS account ON DATABASE TYPE RECORD
SIGNUP ( CREATE user SET email = $email, pass = crypto::argon2::generate($pass) )
SIGNIN ( SELECT * FROM user WHERE email = $email AND crypto::argon2::compare(pass, $pass) )
DURATION FOR SESSION 24h
;

Table permissions

Fine-grained table permissions can be used to prevent users from accessing data which they shouldn't see. Independent permissions for selecting, creating, updating, and deleting data are supported, ensuring fine-grained control over all data in SurrealDB.

-- Specify access permissions for the 'post' table
DEFINE TABLE post SCHEMALESS
PERMISSIONS
FOR select
-- Published posts can be selected
WHERE published = true
-- A user can select all their own posts
OR user = $auth.id
FOR create, update
-- A user can create or update their own posts
WHERE user = $auth.id
FOR delete
-- A user can delete their own posts
WHERE user = $auth.id
-- Or an admin can delete any posts
OR $auth.admin = true
;

Database audit logs

Comprehensive audit trails of all database operations for compliance and monitoring.

Future

Cloud audit logs

Detailed access logs and audit trails for cloud deployments with SIEM integration.

Connectivity

REST API

All tables and data can be queried using a traditional Key-Value REST API. In addition, SurrealQL statements can be submitted to the REST API for custom query logic.

HTTP protocol

SurrealQL querying and data modification is supported over HTTP using both text and binary protocols.

WebSocket protocol

SurrealQL querying and data modification is supported over WebSockets using both text and binary protocols, enabling bi-directional communication and real-time updates.

Custom HTTP API endpoints

Define custom REST API endpoints directly in SurrealQL using DEFINE API. Endpoints support GET, POST, and other HTTP methods, dynamic path parameters, custom middleware, and permission controls.

-- Define a custom HTTP API endpoint
DEFINE API "/users/:id" FOR get, post
MIDDLEWARE api::timeout(5s)
THEN {
IF $request.method = "GET" {
RETURN {
status: 200,
body: SELECT * FROM user WHERE id = $request.params.id
};
};
};
-- Test the endpoint from SurrealQL
api::invoke("/users/tobie");

GraphQL schema

Support for automatic generation of GraphQL schema, from database tables, fields, types, and custom functions.

GraphQL querying

Support for querying all data using GraphQL, with embedded and remote record fetching.

GraphQL mutations

Support for modifying and updating any data using GraphQL, depending on permissions.

In development

Postgres wire protocol

Postgres wire protocol compatibility for easy migration from existing applications and integration with existing tools that work with Postgres.

In development

ANSI SQL querying

Query SurrealDB using standard ANSI SQL syntax for integration with existing tools and workflows, with JOINs and window functions.

Tooling

Command-line tool

The command-line tool can be used to export data as SurrealQL, import data as SurrealQL, and start a SurrealDB instance or cluster.

SQL export

Export all data as SurrealQL from a SurrealDB database for backup purposes. This includes authentication scopes, tables, fields, events, indexes, and data.

SQL import

Import SurrealQL into a SurrealDB database in order to restore from a backup. This includes authentication scopes, tables, fields, events, indexes, and data.

Future

Incremental backups

Export all data from SurrealDB as raw binary data. This will also support incremental binary backups for efficient backing up of SurrealDB clusters.

IDE language support

Official SurrealQL language highlighting packages for Visual Studio Code using TextMate grammar definitions.

Future

Language Server Protocol

Support for the Language Server Protocol will help with code and query completion, and error highlighting for SurrealQL.

User interface

Web app

An easy-to-use interface with support for table-based views, SurrealQL querying, embedded object editing, and graph visualisation.

macOS

The interface is available as a desktop application for macOS.

Windows

The interface is available as a desktop application for Windows.

AI pair-programming tool

AI-powered development assistant for writing queries, debugging, and optimisation.

Schema designer

Visual schema designer for creating and editing tables, fields, indexes, and relationships.

Graph visualiser

Interactive graph visualisation for exploring record relationships and traversal paths.

ORMs and query builders

TypeScript ORM

TypeScript ORM

ORM capabilities for type-safe database operations in your preferred language.

Future
Python ORM library

Python ORM library

ORM capabilities for type-safe database operations in your preferred language.

Future
Golang ORM library

Golang ORM library

ORM capabilities for type-safe database operations in Go.

Future

3rd party ORM libraries

Integration with popular ORM libraries like Prisma, SQLAlchemy, and Entity Framework.

Future

BI tooling integrations

Integrate with BI tools like Tableau, Power BI, and Looker for analytics.

Deployment options

SurrealDB Cloud

Fully managed cloud service with automatic scaling, backups, and high reliability.

Self-hosted deployment

Deploy SurrealDB on your own infrastructure with full control over configuration.

Edge deployment

Lightweight embedded deployment for edge computing and IoT applications.

Multi-node deployment

Distributed deployment across multiple nodes for high availability and horizontal scaling.

Multi-region support

Deploy across multiple geographic regions for global performance and disaster recovery.

Compute-storage separation

Separate read and write compute resources for optimised performance and cost management.

Docker container

SurrealDB is packaged as a Docker container for easy setup and configuration, and can be used to start a SurrealDB instance or cluster, or to import and export data.

Kubernetes operator

Native Kubernetes integration with a custom operator for automated deployment.

Helm charts

Pre-configured Helm charts for easy deployment and management in Kubernetes.

Future

Terraform + IaC support

Infrastructure as Code support with Terraform for automated infrastructure management.

Studio interface

Management dashboard

Web-based dashboard for managing cloud deployments, monitoring, and configuration.

Team collaboration

Multi-user access with role-based permissions for team collaboration.

Observability and monitoring

Instance logs and traces

Detailed logging and distributed tracing for monitoring performance and debugging.

Instance metrics

Comprehensive metrics collection including performance, resource usage, and statistics.

Query logs and traces

Individual query logging with execution plans and performance analysis.

In development

Query metrics

Real-time query performance metrics with histograms and percentiles.

File-based log output

Persistent logging to files with automatic rotation and compression.

Automatic log rotation

Automatic log file rotation and archival to manage disk space and maintain history.

JSON log formatting

Structured JSON logging for easy parsing and integration with log aggregation.

OpenTelemetry source

Native OpenTelemetry integration for standardised observability and monitoring.

Future

OpenTelemetry receiver

Receive and ingest OpenTelemetry data from external services directly into SurrealDB.

Instance health checks

Built-in health check endpoints for load balancers and monitoring systems.

Trust and compliance

SOC 2 Certified

SOC 2 Type II certification for security, availability, and confidentiality.

ISO 27001 Certified

ISO 27001 information security management certification for enterprise security.

Future

HIPAA Certified

HIPAA compliance for healthcare applications with privacy and security safeguards.

Cyber Essentials +

Cyber Essentials certification for basic cybersecurity controls and best practices.

GDPR Compliant

Full GDPR compliance with data protection, privacy controls, and user rights.

Access audit logging

Comprehensive audit logging of all access attempts and data operations for compliance.

Data encryption in transit

Industry-standard encryption for all data transmitted between clients and the database.

Data encryption at rest

Encryption of all stored data using strong cryptographic algorithms and key management.

Managed backups

Automated daily managed backups with one-click restore for all data.

SAML / SSO support

SAML-based single sign-on integration for enterprise authentication.

Enterprise SLAs

Enterprise-grade service level agreements with guaranteed uptime and support.

Custom SLAs

Customisable service level agreements tailored to specific business requirements.

SDKs

Server-side SDKs

Python

Python

An SDK for sync or async Python runtimes, with binary communication over WebSocket or HTTP, and support for SurrealDB embedded in-memory and on-disk.

JavaScript

JavaScript

A native SDK for JavaScript with bi-directional, binary communication over WebSockets or HTTP, and support for SurrealDB embedded in-memory and on-disk.

TypeScript

TypeScript

Full support for TypeScript definitions from within the JavaScript SDK, for working with strongly-typed data with embedded and remote databases.

Rust

Rust

A native async-friendly SDK for Rust with bi-directional, binary communication over WebSocket or HTTP, and support for SurrealDB embedded in-memory and on-disk.

Golang

Golang

An SDK for Golang with binary communication over WebSocket or HTTP, and support for SurrealDB embedded in-memory and on-disk.

Java

Java

An SDK for Java with binary communication over WebSocket or HTTP, and support for SurrealDB embedded in-memory and on-disk.

.NET

.NET

A native SDK for .NET with bi-directional communication over WebSockets or HTTP.

PHP

PHP

A native SDK for PHP with bi-directional, binary communication over WebSockets or HTTP.

C

C

An SDK for C with binary communication over WebSocket or HTTP, and support for SurrealDB embedded in-memory and on-disk.

Future
Dart

Dart

An SDK for Dart with binary communication over WebSocket or HTTP, and support for SurrealDB embedded in-memory and on-disk.

Future
Swift

Swift

A native SDK for Swift with bi-directional, binary communication over WebSockets or HTTP.

Future
Ruby

Ruby

A native SDK for Ruby with bi-directional, binary communication over WebSockets or HTTP.

Client-side SDKs

JavaScript

JavaScript

A native SDK for JavaScript with bi-directional, binary communication over WebSockets or HTTP, and support for SurrealDB embedded in-memory and on-disk.

TypeScript

TypeScript

Full support for TypeScript definitions from within the JavaScript SDK, for working with strongly-typed data with embedded and remote databases.

WebAssembly

WebAssembly

A WebAssembly plugin for use with the JavaScript SDK in the browser, enabling support for SurrealDB embedded in-memory or persisted in IndexedDB.

React.js

React.js

Support for React.js using the native JavaScript SDK, within TanStack Query, with support for data caching and syncing, and authentication.

Next.js

Next.js

Support for Next.js using the native JavaScript SDK, within TanStack Query, with support for data caching and syncing, and authentication.

Vue.js

Vue.js

Support for Vue.js using the native JavaScript SDK, within TanStack Query, with support for data caching and syncing, and authentication.

Angular

Angular

Support for Angular using the native JavaScript SDK, within TanStack Query, with support for data caching and syncing, and authentication.

Solid.js

Solid.js

Support for Solid.js using the native JavaScript SDK, within TanStack Query, with support for data caching and syncing, and authentication.

Svelte

Svelte

Support for Svelte using the native JavaScript SDK, within TanStack Query, with support for data caching and syncing, and authentication.

Future
Flutter

Flutter

An SDK for Flutter with bi-directional communication over WebSockets.

Your questions,answered

A multi-model database: documents, graphs and vectors in one engine, with an API layer, real-time queries, row-level security and native ML built in.

THE PLATFORM

Everything an application and its agents know. Five surfaces, one engine.

IN PRODUCTION

Trusted at scale. Samsung, Nvidia, Verizon, Tencent and Walmart run on SurrealDB.

14,000+

Developers building on SurrealDB Cloud

4M+

Developers building on SurrealDB worldwide

FROM THE TEAMS

SurrealDB gives us a foundation where we can unify semantic search, knowledge graphs, and AI-driven decision making without stitching together multiple systems. Collapsing responsibility into SurrealDB has become our default engineering posture.
Justin Foley

VP of Engineering, Later

GET STARTED

Start building with SurrealDB. Try it in the cloud, or start with the documentation.

SurrealDB

The context and memory layer for AI agents

Database. Graphs, vectors, documents and relational data in one engine, in a single ACID transaction.
Agent Memory. Connects and retrieves context wherever your data lives, every fact carrying its source.
Cloud. Fully managed, in the cloud provider and region you choose.

Explore with AI

Copyright © 2026 SurrealDB Ltd. Registered in England and Wales. Company no. 13615201

Registered address: 3rd Floor 1 Ashley Road, Altrincham, Cheshire, WA14 2DT, United Kingdom

Trading address: Huckletree Oxford Circus, 213 Oxford Street, London, W1D 2LG, United Kingdom