Trigger Trigger.dev tasks from database changes
How to use Sequin to trigger Trigger.dev tasks from database changes.
Trigger.dev makes it easy to write and run long-running tasks. You write and test tasks locally in your project, and then deploy them to Trigger.dev where they reliably invoke the tasks. Trigger.dev handles the infrastructure, observability, and execution.
Often, you want to trigger a task when a record in your database is created, updated, or deleted. For instance, you might want to use a Trigger.dev task to generate an embedding for each new post in your database:
In this guide, you’ll learn how to use Sequin to trigger Trigger.dev tasks from database changes.
Prerequisites
You are about to create a regular Trigger.dev task that you will execute when ever a post is inserted or updated in your database. Sequin will detect all the changes on the posts
table and then send the payload of the post to an API endpoint that will call tasks.trigger()
to create the embedding and update the database.
As long as you create an HTTP endpoint that Sequin can deliver webhooks to, you can use any web framework or edge function (e.g. Supabase Edge Functions, Vercel Functions, Cloudflare Workers, etc.) to invoke your Trigger.dev task. In this guide, we’ll show you how to setup Trigger.dev tasks using Next.js API Routes.
You’ll need the following to follow this guide:
- A Next.js project with Trigger.dev installed
If you don’t have one already, follow Trigger.dev’s Next.js setup guide to setup your project. You can return to this guide when you’re ready to write your first Trigger.dev task.
- A Sequin account
- A Postgres database (Sequin works with any Postgres database version 12 and up) with a
posts
table.
Create a Trigger.dev task
Start by creating a new Trigger.dev task that takes in a Sequin change event as a payload, creates an embedding, and then inserts the embedding into the database:
Create a `create-embedding-for-post` task
In your src/trigger/tasks
directory, create a new file called create-embedding-for-post.ts
and add the following code:
This task takes in a Sequin record event, creates an embedding, and then uppserts the embedding into a post_embeddings
table.
Add the task to your Trigger.dev project
Register the create-embedding-for-post
task to your Trigger.dev cloud project by running the following command:
npx trigger.dev@latest dev
In the Trigger.dev dashboard, you should now see the create-embedding-for-post
task:
You’ve successfully created a Trigger.dev task that will create an embedding for each post in your database. In the next step, you’ll create an API endpoint that Sequin can deliver records to.
Setup API route
You’ll now create an API endpoint that will receive posts from Sequin and then trigger the create-embedding-for-post
task.
This guide covers how to setup an API endpoint using the Next.js App Router. You can find examples for Next.js Server Actions and Pages Router in the Trigger.dev documentation.
Create a route handler
Add a route handler by creating a new route.ts
file in a /app/api/create-embedding-for-post
directory:
import type { createEmbeddingForPost } from "@/trigger/create-embedding-for-post";
import { tasks } from "@trigger.dev/sdk/v3";
import { NextResponse } from "next/server";
export async function POST(req: Request) {
const authHeader = req.headers.get('authorization');
if (!authHeader || authHeader !== `Bearer ${process.env.SEQUIN_WEBHOOK_SECRET}`) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const payload = await req.json();
const handle = await tasks.trigger<typeof createEmbeddingForPost>(
"create-embedding-for-post",
payload
);
return NextResponse.json(handle);
}
This route handler will receive records from Sequin, parse them, and then trigger the create-embedding-for-post
task.
Set secret keys
You’ll need to set four secret keys in a .env.local
file:
SEQUIN_WEBHOOK_SECRET=your-secret-key
TRIGGER_SECRET_KEY=secret-from-trigger-dev
OPENAI_API_KEY=sk-proj-asdfasdfasdf
DATABASE_URL=postgresql://
The SEQUIN_WEBHOOK_SECRET
ensures that only Sequin can access your APIendpoint.
The TRIGGER_SECRET_KEY
is used to authenticate requests to Trigger.dev and can be found in the API keys tab of the Trigger.dev dashboard.
The OPENAI_API_KEY
and DATABASE_URL
are used to create an embedding using OpenAI and connect to your database. Be sure to add these as environment variables in Trigger.dev as well.
You’ve successfully created an API endpoint that can receive record payloads from Sequin and trigger a Trigger.dev task. In the next step, you’ll setup Sequin to trigger the endpoint.
Create Sequin consumer
You’ll now configure Sequin to send every row in your posts
table to your Trigger.dev task.
Connect Sequin to your database
- Login to your Sequin account and click the Add New Database button.
- Enter the connection details for your Postgres database.
If you need to connect to a local dev database, flip the use localhost switch and follow the instructions to create a tunnel using the Sequin CLI.
- Follow the instructions to create a publication and a replication slot by running two SQL commands in your database:
create publication sequin_pub for all tables;
select pg_create_logical_replication_slot('sequin_slot', 'pgoutput');
- Name your database and click the Connect Database button.
Sequin will connect to your database and ensure that it’s configured properly.
If you need step-by-step connection instructions to connect Sequin to your database, check out our quickstart guide.
Tunnel to your local endpoint
Now, create a tunnel to your local endpoint so Sequin can deliver change payloads to your local API:
- In the Sequin console, open the HTTP Endpoint tab and click the Create HTTP Endpoint button.
- Enter a name for your endpoint (i.e.
local_endpoint
) and flip the Use localhost switch. Follow the instructions in the Sequin console to install the Sequin CLI, then run:
sequin tunnel --ports=3001:local_endpoint
- Now, click Add encryption header and set the key to
Authorization
and the value toBearer SEQUIN_WEBHOOK_SECRET
. - Click Create HTTP Endpoint.
Create a Push Consumer
Create a push consumer that will capture posts from your database and deliver them to your local endpoint:
- Navigate to the Consumers tab and click the Create Consumer button.
- Select your
posts
table (i.epublic.posts
). - You want to ensure that every post receives an embedding - and that embeddings are updated as posts are updated. To do this, select to process Rows and click Continue.
You can also use changes for this particular use case, but rows comes with some nice replay and backfill features.
- You’ll now set the sort and filter for the consumer. For this guide, we’ll sort by
updated_at
and start at the beginning of the table. We won’t apply any filters:
- On the next screen, select Push to have Sequin send the events to your webhook URL. Click Continue.
- Now, give your consumer a name (i.e.
posts_push_consumer
) and in the HTTP Endpoint section select thelocal_endpoint
you created above. Add the exact API route you created in the previous step (i.e./api/create-embedding-for-post
):
- Click the Create Consumer button.
Your Sequin consumer is now created and ready to send events to your API endpoint.
Test end-to-end
Spin up you dev environment
- The Next.js app is running:
npm run dev
- The Trigger.dev dev server is running
npx trigger.dev@latest dev
- The Sequin tunnel is running:
sequin tunnel --ports=3001:local_endpoint
Create a new post in your database
insert into
posts (title, body, author)
values
(
'The Future of AI',
'An insightful look into how artificial intelligence is shaping the future of technology and society.',
'Alice H Johnson'
);
Trace the change in the Sequin dashboard
In the Sequin console, navigate to the Trace tab and confirm that Sequin delivered the event to your local endpoint:
Confirm the event was received by your endpoint
In your local terminal, you should see a 200
response in your Next.js app:
POST /api/create-embedding-for-post 200 in 262ms
Observe the task run in the Trigger.dev dashboard
Finally, in the Trigger.dev dashboard, navigate to the Runs tab and confirm that the task run completed successfully:
Every time a post is created or updated, Sequin will deliver the row payload to your API endpoint and Trigger.dev will run the create-embedding-for-post
task.
Next steps
With Sequin and Trigger.dev, every post in your database will now have an embedding. This is a simple example of how you can trigger long-running tasks on database changes.
From here, add error handling and deploy to production:
- Add retries to your Trigger.dev task to ensure that any errors are captured and logged.
- Deploy to production and update your Sequin consumer to point to your production database and endpoint.
Was this page helpful?