Collection Triggers

Event-driven automation that creates background jobs when documents change.

Overview

Triggers allow you to automatically execute Lua scripts when documents are inserted, updated, or deleted in a collection. Instead of executing synchronously, triggers create background jobs in the _jobs collection, which are then processed by SoliDB's distributed queue workers.

How It Works

1 Document Operation
2 Check Triggers
3 Create Job
4 Execute Script

Key features include:

  • Asynchronous Execution: Triggers don't block document operations - they create jobs for later processing.
  • Event Types: React to insert, update, and delete events.
  • Full Context: Scripts receive the document data, old data (for updates/deletes), and event metadata.
  • Reliable Processing: Jobs support priority, retries, and are processed by distributed workers.
  • Dashboard Management: Create, edit, and monitor triggers through the web dashboard.

Trigger Schema

Triggers are stored in the _triggers collection within each database.

Field Type Description
_key string Unique identifier (UUID)
name string Human-readable trigger name
collection string Collection to watch for changes
events array Events to trigger on: "insert", "update", "delete"
script_path string Path to the Lua script in _scripts collection
queue string Queue name for job execution (default: "default")
priority integer Job priority (higher = more important, default: 0)
max_retries integer Maximum retry attempts on failure (default: 5)
enabled boolean Whether the trigger is active

Example Trigger Document

{
  "_key": "550e8400-e29b-41d4-a716-446655440000",
  "name": "send_welcome_email",
  "collection": "users",
  "events": ["insert"],
  "script_path": "triggers/welcome_email.lua",
  "queue": "emails",
  "priority": 10,
  "max_retries": 3,
  "enabled": true,
  "created_at": 1705312800,
  "updated_at": 1705312800
}

Job Parameters

When a trigger fires, it creates a job with the following parameters passed to your Lua script:

Parameter Type Description
trigger_name string Name of the trigger that fired
event string Event type: "insert", "update", or "delete"
collection string Collection where the change occurred
key string Document key
data object|null New document data (for insert/update)
old_data object|null Previous document data (for update/delete)

Example Job Params

{
  "trigger_name": "send_welcome_email",
  "event": "insert",
  "collection": "users",
  "key": "user_123",
  "data": {
    "_key": "user_123",
    "email": "[email protected]",
    "name": "Jane Doe"
  },
  "old_data": null
}

Trigger Script Example

Here's an example Lua script that handles a trigger event:

-- triggers/welcome_email.lua
-- This script runs when a new user is inserted

-- params contains all the trigger context
local trigger_name = params.trigger_name
local event = params.event
local collection = params.collection
local key = params.key
local data = params.data
local old_data = params.old_data

Log(kLogInfo, "Trigger fired: " .. trigger_name .. " on " .. event)

if event == "insert" and data then
  -- Send welcome email to new user
  local email = data.email
  local name = data.name or "User"

  if email then
    -- Use your email service
    local result = Fetch("https://api.emailservice.com/send", {
      method = "POST",
      headers = {
        ["Content-Type"] = "application/json",
        ["Authorization"] = "Bearer " .. GetEnv("EMAIL_API_KEY")
      },
      body = EncodeJson({
        to = email,
        subject = "Welcome to Our App!",
        body = "Hello " .. name .. ", welcome aboard!"
      })
    })

    Log(kLogInfo, "Welcome email sent to: " .. email)
  end

elseif event == "update" and data and old_data then
  -- Check if email changed
  if data.email ~= old_data.email then
    Log(kLogInfo, "User email changed from " .. (old_data.email or "nil") .. " to " .. (data.email or "nil"))
    -- Send email change notification
  end

elseif event == "delete" and old_data then
  -- Handle user deletion
  Log(kLogInfo, "User deleted: " .. (old_data.email or key))
  -- Cleanup or send goodbye email
end

return { success = true }
Important: Trigger scripts are stored in the _scripts collection. Create your script first, then reference its path when creating the trigger.

Common Use Cases

Notifications

Send emails, SMS, or push notifications when documents change.

Data Sync

Sync changes to external systems, APIs, or other databases.

Audit Logging

Track all changes to sensitive documents for compliance.

Denormalization

Update derived data or materialized views when source data changes.

Cleanup Tasks

Delete related data or resources when documents are removed.

Workflow Automation

Trigger multi-step business processes based on data changes.

Dashboard Management

Manage your triggers through the modern, intuitive **Triggers** dashboard:

  • Visual Monitoring: View all triggers with clear status indicators (Active/Paused) and event badges.
  • Quick Actions: Toggle triggers, edit configuration, or delete them directly from the table view.
  • Refined Creation: Use the enhanced creation modal with visual event selectors and advanced configuration options (queue, priority, retries).
  • Status Tracking: Instantly see which collections and scripts are linked to each automation.
Creation

The new creation flow features a multi-column layout and improved field validation.

Control

One-click toggling allows you to pause automations without deleting their configuration.

Tip: Monitor triggered jobs in the Queues section. Jobs created by triggers show the trigger name in their parameters.

API Reference

GET /_api/database/:db/triggers

List all triggers in the database.

POST /_api/database/:db/triggers

Create a new trigger.

{
  "name": "send_welcome_email",
  "collection": "users",
  "events": ["insert"],
  "script_path": "triggers/welcome_email.lua",
  "queue": "emails",
  "priority": 10,
  "max_retries": 3,
  "enabled": true
}
GET /_api/database/:db/triggers/:id

Get a specific trigger by ID.

PUT /_api/database/:db/triggers/:id

Update an existing trigger.

DELETE /_api/database/:db/triggers/:id

Delete a trigger.

POST /_api/database/:db/triggers/:id/toggle

Toggle a trigger's enabled/disabled state.

GET /_api/database/:db/collections/:coll/triggers

List triggers for a specific collection.