Events let the database react to record changes: write an audit log, normalise related records, or enqueue follow-up work. They run after the record change but inside the same transaction (unless you opt into async), and they see $before and $after snapshots of the record.
Events are a side effect of normal writes. They are not fired during a bulk import.
Key ideas
$event:"CREATE","UPDATE", or"DELETE".$before/$after: state immediately before and after the change.$value: the record as seen by the event (after create/update, before delete).WHEN: optional filter so the body runs only when something meaningful changed.THEN: the SurrealQL block to execute.
You need the usual database privileges and USE scope. Full syntax and async options are in DEFINE EVENT; Reactive patterns covers ASYNC, RETRY, and MAXDEPTH.
Example usage
The examples on this page add events to a small shop, with customers, products and orders. Each example runs on its own.
The first event keeps an audit trail of a customer's email address. In this example:
The
WHENclause checks if the email has changed. When a record is created,$beforeisNONE, and when it is deleted,$afterisNONE, so the email changes in both cases.The
THENclause records this change in anaudittable.
DEFINE EVENT email_audit ON TABLE customer
WHEN $before.email != $after.email THEN {
CREATE audit CONTENT {
customer: $value.id,
event: $event,
old_email: $before.email,
new_email: $after.email,
at: time::now()
};
};
CREATE customer:ana SET email = "ana@example.com";
-- The email does not change, so no audit record is written
UPDATE customer:ana SET name = "Ana Silva";
UPDATE customer:ana SET email = "ana.silva@example.com";
DELETE customer:ana;
SELECT event, old_email, new_email FROM audit ORDER BY at;[
{ event: 'CREATE', new_email: 'ana@example.com', old_email: NONE },
{ event: 'UPDATE', new_email: 'ana.silva@example.com', old_email: 'ana@example.com' },
{ event: 'DELETE', new_email: NONE, old_email: 'ana.silva@example.com' }
]More complex logic
An event body can hold several statements. When an order is placed, the following event links the customer to the product in the graph, takes the quantity out of stock, and writes an audit record.
DEFINE EVENT order_placed ON TABLE order
WHEN $event = "CREATE"
THEN {
RELATE ($after.customer)->bought->($after.product)
SET quantity = $after.quantity;
UPDATE $after.product SET stock -= $after.quantity;
CREATE audit SET
action = "order_placed",
order = $after.id,
at = time::now();
};
CREATE customer:ana;
CREATE product:mug SET stock = 10;
CREATE order:1 SET customer = customer:ana, product = product:mug, quantity = 2;
product:mug.stock;
//- 8
customer:ana->bought->product;
//- [product:mug]Specific events
You can trigger events based on specific events. You can use the variable $event to detect what type of event is triggered on the table. The shop sends a notification when the price of a product changes or when a product is removed, and audits every change. An event without a WHEN clause, such as product_audit below, runs on every create, update and delete.
-- Only an UPDATE that changes the price
DEFINE EVENT price_changed ON TABLE product
WHEN $event = "UPDATE" AND $before.price != $after.price
THEN {
CREATE notification SET
message = $after.name + " now costs " + <string>$after.price;
};
-- Only a DELETE, which has the record in `$before`
DEFINE EVENT product_removed ON TABLE product
WHEN $event = "DELETE"
THEN {
CREATE notification SET message = $before.name + " was removed";
};
-- Every CREATE, UPDATE and DELETE
DEFINE EVENT product_audit ON TABLE product THEN {
CREATE audit SET event = $event, at = time::now();
};
CREATE product:mug SET name = "Travel mug", price = 12;
UPDATE product:mug SET price = 10;
UPDATE product:mug SET name = "Travel mug 350 ml";
DELETE product:mug;
SELECT VALUE message FROM notification ORDER BY message;
//- ['Travel mug 350 ml was removed', 'Travel mug now costs 10']
SELECT VALUE event FROM audit ORDER BY at;
//- ['CREATE', 'UPDATE', 'UPDATE', 'DELETE']An event can also change other records. This one marks every order in a new shipment as shipped, and leaves the other orders as they are.
DEFINE FIELD status ON order TYPE "paid" | "shipped" DEFAULT "paid";
DEFINE EVENT ship_orders ON TABLE shipment
WHEN $event = "CREATE"
THEN {
UPDATE $after.orders SET status = "shipped";
};
CREATE order:1, order:2, order:3;
CREATE shipment SET orders = [order:1, order:3];
SELECT id, status FROM order;[
{ id: order:1, status: 'shipped' },
{ id: order:2, status: 'paid' },
{ id: order:3, status: 'shipped' }
]Events and permissions
Queries inside the event always execute without any permission checks, even when triggered by changes made by the currently authenticated user.
Consider a CREATE query sent by a customer signed in as a record user, who has CREATE access to the review table only:
CREATE review SET
product = product:mug,
rating = 5,
author = $auth.id;Logic can be added to the event itself to modify the behaviour depending on a user's permissions or any other condition. The event below reads the product table and the customer's purchases, which the customer has no access to, and sets a verified field that record users have no permission to set themselves.
DEFINE EVENT review_created ON TABLE review
WHEN $event = "CREATE"
THEN {
-- Refuse reviews of a product that does not accept them
IF $after.product.reviews_closed {
THROW "Reviews are closed for this product";
};
-- A review is verified when its author bought the product
UPDATE $after.id SET
verified = $after.product IN $after.author->bought->product;
};
-- Ana bought the mug, and the lamp does not accept reviews
CREATE customer:ana, customer:ben;
CREATE product:mug;
CREATE product:lamp SET reviews_closed = true;
RELATE customer:ana->bought->product:mug;
CREATE review:1 SET product = product:mug, author = customer:ana, rating = 5;
CREATE review:2 SET product = product:mug, author = customer:ben, rating = 2;
CREATE review:3 SET product = product:lamp, author = customer:ana, rating = 4;
//- 'Error while processing event review_created: An error occurred: Reviews are closed for this product'
SELECT id, verified FROM review;
//- [{ id: review:1, verified: true }, { id: review:2, verified: false }] Accessing $input in events
The behaviour of events can be further refined via the $input parameter, which holds the data that the statement supplied: the fields set by a SET clause or a CONTENT object, rather than the whole record. Here orders are sent for a manual check when the statement that writes them sets flagged to true.
DEFINE EVENT needs_review ON order WHEN $input.flagged = true THEN {
CREATE review_queue SET order = $after.id, input = $input;
};
-- `flagged` is false, so the event does not run
CREATE order:1 SET total = 20, flagged = false;
CREATE order:2 SET total = 950, flagged = true;
-- `$input` only holds the field that this statement sets
UPDATE order:1 SET flagged = true;
SELECT order, input FROM review_queue ORDER BY order;[
{ input: { flagged: true }, order: order:1 },
{ input: { flagged: true, total: 950 }, order: order:2 }
]Async events
Events in SurrealDB are executed synchronously within the same transaction that triggers them. While this ensures consistency, it can lead to increased latency for write operations if the event logic is complex or resource intensive.
To allow events to execute independently of the transaction that triggers them, the ASYNC clause can be used.
How async events are processed
Async events are processed in an interval dependent on the environment variable SURREAL_ASYNC_EVENT_PROCESSING_INTERVAL (or --async-event-interval when starting the server) which is set to 5 seconds as the default. Lowering this will reduce the latency between a document change and its events, while leading to more frequent polls by the background worker.
Some more notes on the characteristics of async events:
Atomicity: The event is enqueued within the same transaction as the document change. If the transaction fails, the event is never queued.
Consistency: Asynchronous events run in a separate transaction from the original change. They see the database state at the time they are executed.
Ordering: Events are generally processed in the order they were created, though parallel processing may occur within a single batch.
Delivery: An event runs at least once, and can run more than once. If the event's transaction fails to commit because of a write conflict with another event, it runs again in a new transaction. From SurrealDB 3.3.1 these conflict retries do not count against the
RETRYclause. The database changes of a failed attempt are rolled back, but side effects outside the database, such as anhttp::post()call, are not, so make those safe to repeat.
The easiest way to demonstrate that async events do not occur in the same transaction is by causing one to throw an error. As an error inside any part of a transaction will cause the transaction to fail and roll back, the following event, which sends an order confirmation and fails about 50% of the time, would cause the CREATE statement that follows to fail if it were not async. As an async event, however, the events that follow the statement are each run in their own transaction, and all 50 orders are created.
DEFINE TABLE email_sent;
DEFINE EVENT send_confirmation ON order ASYNC THEN {
IF rand::bool() {
THROW "The mail server did not respond";
} ELSE {
CREATE email_sent SET order = $after.id;
}
};
CREATE |order:50|;
count(SELECT * FROM order);
//- 50 The MAXDEPTH clause
The MAXDEPTH clause is used to set the maximum number of times that an async event can be triggered. The number following this can range from 0 to 16.
The default for MAXDEPTH is 3, as events defined on other events that lead to record creation can quickly spiral out of control at greater levels.
Take the following contrived referral scheme, in which every new referral creates nine more:
DEFINE EVENT spread ON referral ASYNC MAXDEPTH 4 THEN {
CREATE |referral:9|;
};
CREATE referral;Each event creates nine new records, so every level holds nine times as many as the one before. While the MAXDEPTH in this case is only one greater than the default, once the events have run, count(SELECT * FROM referral) is 7381, compared to 820 if the default is used:


This is somewhat similar to recursive queries which can also quickly add up. Five products that each list the other four as related products give 1024 results after five levels of depth:
CREATE |product:1..=5|;
-- Each product lists the four others as related
UPDATE product SET related = (
SELECT VALUE id FROM product WHERE id != $parent.id
);
count(product:1.{..5}.related);
//- 1024 The RETRY clause
The RETRY clause is suitable for events that may fail but can succeed on successive attempts, such as a call to another service.
The example below shows an event that asks a courier to collect an order. It has a 50% chance of failure and zero retries.
DEFINE EVENT notify_courier ON order ASYNC RETRY 0 THEN {
IF rand::bool() {
THROW "The courier service timed out";
} ELSE {
CREATE courier_request:[$after.id] SET at = time::now();
}
};
CREATE order:1;Once the event has run, a SELECT * FROM courier_request returns the request half of the time:
[
{
at: d'2026-11-16T04:15:02.120Z',
id: courier_request:[order:1]
}
]The other half of the time, the event fails once and is not run again, and the query returns the error "The table 'courier_request' does not exist". A higher RETRY gives the event more attempts before it is dropped.