Live queries
Live queries allow your application to receive real-time notifications whenever records in a table are created, updated, or deleted. The Go SDK delivers notifications through Go channels, making it easy to integrate with goroutines and concurrent patterns.
Live queries require a WebSocket connection (ws:// or wss://). They are available on *DB and *Session but not on *Transaction.
API References
Starting a live query
Use the Live function to subscribe to changes on a table. It returns a UUID that identifies the live query.
liveID, err := surrealdb.Live(ctx, db, models.Table("persons"), false)
if err != nil {
log.Fatal(err)
}
The diff parameter controls notification format. When false, notifications contain the full record. When true, they contain JSON Patch diffs instead.
Receiving notifications
After starting a live query, call .LiveNotifications() on the *DB or *Session to get a channel that receives Notification values.
ch, err := db.LiveNotifications(liveID.String())
if err != nil {
log.Fatal(err)
}
for notification := range ch {
fmt.Printf("Action: %s, Result: %v\n", notification.Action, notification.Result)
}
Each notification includes:
| Field | Type | Description |
|---|
ID | *models.UUID | The live query UUID |
Action | Action | One of CREATE, UPDATE, or DELETE |
Result | interface{} | The record data or JSON Patch diff |
Processing notifications in a goroutine
A common pattern is to process live query notifications in a separate goroutine while the main goroutine continues other work.
liveID, err := surrealdb.Live(ctx, db, models.Table("persons"), false)
if err != nil {
log.Fatal(err)
}
ch, err := db.LiveNotifications(liveID.String())
if err != nil {
log.Fatal(err)
}
go func() {
for n := range ch {
switch n.Action {
case "CREATE":
fmt.Println("New record:", n.Result)
case "UPDATE":
fmt.Println("Updated record:", n.Result)
case "DELETE":
fmt.Println("Deleted record:", n.Result)
}
}
}()
Stopping a live query
Use the Kill function to terminate a live query on the server and close its notification channel.
if err := surrealdb.Kill(ctx, db, liveID.String()); err != nil {
log.Fatal(err)
}
Kill both sends the kill RPC to the server and closes the local notification channel. If you only want to close the channel without killing the server-side query, use .CloseLiveNotifications() instead.
Learn more