Thanks to visit codestin.com
Credit goes to deepwiki.com

Menu

Integration Patterns

Relevant source files

Purpose and Scope

This page documents common integration patterns used when building tasks with Trigger.dev, as demonstrated throughout the documentation examples and use case guides. These patterns represent proven approaches for orchestrating workflows across external services, processing pipelines, and system integrations.

For information about the SDK's task definition and triggering APIs, see Task Definition API and Task Triggering and Scheduling. For build-time integrations and runtime customizations, see Build Extensions. For production examples and detailed implementations, see Example Projects and Tasks.


Common Workflow Orchestration Patterns

Integration patterns in Trigger.dev leverage core SDK features to coordinate work across multiple systems. These patterns appear repeatedly across different use cases with similar structural characteristics.

Router Pattern

The Router pattern analyzes input or intermediate state to determine which specialized processing path to follow. A parent task examines the payload and conditionally triggers different child tasks based on classification logic.

Key characteristics:

  • Single entry point task that classifies or routes work
  • Conditional logic determines which downstream task(s) to trigger
  • Each branch handles a specific type of processing
  • Often combined with task.trigger() or task.triggerAndWait() for orchestration

Diagram: Router Pattern Structure

Sources: docs/guides/use-cases/media-processing.mdx69-98 docs/guides/use-cases/media-generation.mdx100-141 docs/guides/use-cases/marketing.mdx76-100

Coordinator Pattern

The Coordinator pattern manages parallel execution of multiple child tasks and aggregates their results. The parent task uses batchTriggerAndWait() to fan out work to child tasks, waits for all to complete, then processes the combined output.

Key characteristics:

  • Parent task coordinates multiple parallel child tasks
  • Uses task.batchTriggerAndWait() for concurrent execution
  • Configurable concurrency limits via queue settings
  • Results aggregated after all children complete

Diagram: Coordinator Pattern with Batch Triggering

Example implementation from Hacker News scraper:

Sources: docs/guides/examples/scrape-hacker-news.mdx129-136 docs/guides/use-cases/data-processing-etl.mdx83-105 docs/guides/use-cases/media-generation.mdx100-122

Supervisor Pattern with Approval Gate

The Supervisor pattern implements human-in-the-loop workflows by pausing execution with wait.forToken() to enable manual review and approval before proceeding.

Key characteristics:

  • Task execution pauses at approval checkpoint
  • Uses wait.forToken() to create waitpoint token
  • External approval process completes the token
  • Conditional logic handles approval vs. rejection paths
  • May loop back to regenerate on rejection

Diagram: Supervisor Pattern with Human Review

Sources: docs/guides/use-cases/media-generation.mdx67-84 docs/guides/use-cases/marketing.mdx102-119 docs/guides/use-cases/media-processing.mdx157-188

Sequential Pipeline Pattern

The Sequential Pipeline pattern chains multiple processing stages where each stage's output becomes the next stage's input. Common in ETL and media processing workflows.

Key characteristics:

  • Linear sequence of transformations
  • Each step depends on previous step's output
  • May include wait.for() delays between stages
  • Output progressively transformed through pipeline

Diagram: Sequential Pipeline

Sources: docs/guides/use-cases/data-processing-etl.mdx69-80 docs/guides/use-cases/media-generation.mdx126-140


Integration Pattern Categories

The documentation examples demonstrate integration patterns organized by use case domains. Each category leverages the core orchestration patterns while integrating with domain-specific external services.

AI Agent Integration Patterns

AI agent integrations coordinate LLM calls, tool execution, and multi-agent workflows. These patterns handle unpredictable API latencies and complex orchestration requirements.

Documented examples:

ExamplePatternDescriptionDocumentation Reference
OpenAI Agents SDK PlaygroundRouter + CoordinatorMultiple agent types with tool calling and handoffsdocs/guides/example-projects/openai-agents-sdk-typescript-playground.mdx
OpenAI Agents SDK GuardrailsSupervisorInput/output guardrails with exception handlingdocs/guides/example-projects/openai-agent-sdk-guardrails.mdx
Content ModerationCoordinatorParallel content checks while respondingdocs/guides/introduction.mdx26
Route QuestionsRouterComplexity-based model routingdocs/guides/introduction.mdx29
Translation RefinementSequential + SupervisorIterative translation with feedbackdocs/guides/introduction.mdx30

Common SDK features used:

  • task.trigger() for agent invocation
  • task.batchTriggerAndWait() for parallel agent processing
  • logger.info() for agent state tracking
  • wait.forToken() for human verification
  • Error handling with retry configuration

Diagram: Multi-Agent Coordinator Pattern

Sources: docs/guides/example-projects/openai-agents-sdk-typescript-playground.mdx40-48 docs/guides/introduction.mdx24-42

Media Processing Integration Patterns

Media processing integrations handle video transcoding, image optimization, audio transformation, and document conversion. These patterns process large files and long-running operations.

Documented examples:

ExamplePatternExternal ServicesDocumentation Reference
FFmpeg Video ProcessingSequentialFFmpeg, Cloudflare R2docs/guides/examples/ffmpeg-video-processing.mdx
Product Image GeneratorRouter + CoordinatorReplicatedocs/guides/example-projects/product-image-generator.mdx
LibreOffice PDF ConversionSequentialLibreOfficedocs/guides/examples/libreoffice-pdf-conversion.mdx
Sharp Image ProcessingSequentialSharp, Cloudflare R2docs/guides/examples/sharp-image-processing.mdx
PDF to ImageSequentialMuPDF, Cloudflare R2docs/guides/examples/pdf-to-image.mdx

Build extensions commonly used:

Diagram: Adaptive Video Processing with Router Pattern

Sources: docs/guides/use-cases/media-processing.mdx44-98 docs/introduction.mdx92-107

AI Media Generation Integration Patterns

AI media generation integrations coordinate image generation, video synthesis, and audio creation through AI model APIs. These patterns handle unpredictable generation times and implement quality gates.

Documented examples:

ExamplePatternAI ServiceDocumentation Reference
Fal.ai Image Generation (Realtime)SequentialFal.aidocs/guides/examples/fal-ai-realtime.mdx
Fal.ai Image to CartoonSequentialFal.aidocs/guides/examples/fal-ai-image-to-cartoon.mdx
DALL·E 3 Image GenerationSequentialOpenAIdocs/guides/examples/dall-e3-generate-image.mdx
Replicate Image GenerationSequentialReplicatedocs/guides/examples/replicate-image-generation.mdx
Meme GeneratorSupervisorOpenAI DALL·E 3docs/guides/example-projects/meme-generator-human-in-the-loop.mdx
Vercel AI SDK Image GeneratorSequentialVercel AI SDKdocs/guides/example-projects/vercel-ai-sdk-image-generator.mdx

Fal.ai integration example:

Diagram: AI Generation with Approval Gate

Sources: docs/guides/examples/fal-ai-realtime.mdx42-78 docs/guides/examples/fal-ai-image-to-cartoon.mdx59-101 docs/guides/use-cases/media-generation.mdx64-143

Data Pipeline Integration Patterns

Data pipeline integrations implement ETL workflows, web scraping, database synchronization, and batch enrichment operations. These patterns process large datasets without timeout constraints.

Documented examples:

ExamplePatternData Source/SinkDocumentation Reference
Realtime CSV ImporterSequentialCSV filesdocs/guides/example-projects/realtime-csv-importer.mdx
Hacker News ScraperCoordinatorBrowserBase, Puppeteerdocs/guides/examples/scrape-hacker-news.mdx
Supabase Database WebhooksSequentialSupabasedocs/guides/frameworks/supabase-edge-functions-database-webhooks.mdx
Sequin Database TriggersSequentialSequin, PostgreSQLdocs/guides/frameworks/sequin.mdx
Python Web CrawlerCoordinatorCrawl4AI, Playwrightdocs/guides/python/python-crawl4ai.mdx

Scraping pattern with proxy (required for compliance):

The Hacker News scraper demonstrates the Coordinator pattern with BrowserBase proxy integration (required by terms of service):

Diagram: Parallel Web Scraping with Coordinator

Sources: docs/guides/examples/scrape-hacker-news.mdx80-210 docs/guides/use-cases/data-processing-etl.mdx64-156 docs/snippets/web-scraping-warning.mdx1-3

Marketing Automation Integration Patterns

Marketing automation integrations implement drip campaigns, behavioral triggers, personalization engines, and multi-channel orchestration. These patterns use delays and conditional branching extensively.

Documented examples:

ExamplePatternServicesDocumentation Reference
Resend Email SequenceSequential with DelaysResenddocs/guides/examples/resend-email-sequence.mdx
React EmailSequentialReact Emaildocs/guides/examples/react-email.mdx
Stripe WebhooksRouterStripe, webhooksdocs/guides/examples/stripe-webhook.mdx

Key features for marketing workflows:

  • wait.for({ days: 7 }) for drip campaign delays over 5 seconds (automatically checkpointed)
  • schedules.task() for recurring campaigns
  • idempotencyKey to prevent duplicate sends
  • task.triggerAndWait() for conditional follow-up logic

Diagram: Multi-Channel Drip Campaign with Router

Sources: docs/guides/use-cases/marketing.mdx56-145 docs/guides/introduction.mdx86

Webhook Integration Patterns

Webhook integrations receive external events and trigger task execution. These patterns validate incoming payloads, implement idempotency, and route to appropriate handlers.

Documented examples:

ExampleFrameworkWebhook SourceDocumentation Reference
Stripe WebhooksMultipleStripedocs/guides/examples/stripe-webhook.mdx
Next.js WebhooksNext.jsGenericdocs/guides/frameworks/nextjs-webhooks.mdx
Remix WebhooksRemixGenericdocs/guides/frameworks/remix-webhooks.mdx
Supabase Database WebhooksSupabase Edge FunctionsSupabasedocs/guides/frameworks/supabase-edge-functions-database-webhooks.mdx

Common webhook handler pattern:

Diagram: Webhook Router Pattern

Sources: docs/guides/introduction.mdx38-42 docs/docs.json366-377

Database Integration Patterns

Database integrations sync data, trigger tasks from database changes, and implement transaction-safe workflows. These patterns often use build extensions for database clients.

Documented examples:

ExampleDatabaseIntegration TypeDocumentation Reference
PrismaPostgreSQL/MySQLORMdocs/guides/frameworks/prisma.mdx
Supabase OperationsPostgreSQLSupabase Clientdocs/guides/examples/supabase-database-operations.mdx
Sequin Database TriggersPostgreSQLCDC Streamingdocs/guides/frameworks/sequin.mdx
DrizzlePostgreSQL/MySQLORMdocs/guides/frameworks/drizzle.mdx
Turborepo with PrismaPostgreSQLMonorepodocs/guides/example-projects/turborepo-monorepo-prisma.mdx

Build extension for Prisma:

Diagram: Database Change Trigger Pattern

Sources: docs/guides/introduction.mdx32 docs/introduction.mdx94 docs/guides/introduction.mdx37


Pattern Implementation Features

The SDK provides specific features that enable these integration patterns. Understanding how patterns map to SDK capabilities helps implement robust integrations.

Orchestration Features

SDK FeaturePattern EnablementCommon Use Cases
task.trigger()Router, SequentialFire-and-forget task invocation
task.triggerAndWait()Router, SequentialWait for child task completion
task.batchTrigger()CoordinatorParallel tasks without waiting
task.batchTriggerAndWait()CoordinatorFan-out with result aggregation
schedules.task()All patternsRecurring workflow execution
wait.for()SequentialDelays between pipeline stages
wait.forToken()SupervisorHuman-in-the-loop approval

Sources: docs/introduction.mdx39-41 docs/introduction.mdx49-82

Reliability Features

SDK FeaturePurposeImplementation Location
idempotencyKeyPrevent duplicate executionTrigger options parameter
retry configurationAutomatic failure recoveryTask definition options
queue configurationConcurrency controlTask definition options
Checkpoint/resumeLong-running task efficiencyAutomatic for waits > 5s
Heartbeat trackingZombie process detectionAutomatic in task execution

Sources: docs/introduction.mdx66-73 docs/guides/examples/scrape-hacker-news.mdx32

Monitoring Features

SDK FeaturePurposeIntegration Pattern Usage
logger.info()Structured loggingAll patterns for progress tracking
logger.error()Error reportingError boundaries in all patterns
context.run.idRun identificationCorrelation across distributed tasks
context.metadataCustom metadataProgress tracking in UI
Realtime APILive status updatesUser-facing progress indicators

Sources: docs/introduction.mdx57-59 docs/video-walkthrough.mdx22

Build Extensions for Integration

Build extensions enable integration with external tools and services by modifying the runtime environment:

ExtensionIntegration SupportDocumentation
prismaExtensionDatabase ORM integrationdocs/introduction.mdx94
pythonExtensionPython script executiondocs/introduction.mdx95
puppeteerHeadless browser automationdocs/introduction.mdx97
playwrightBrowser testing/scrapingdocs/introduction.mdx96
ffmpegVideo/audio processingdocs/introduction.mdx99
aptGetSystem package installationdocs/introduction.mdx100

Sources: docs/introduction.mdx90-107 docs/guides/examples/scrape-hacker-news.mdx52-64


Pattern Selection Guidelines

Choosing the appropriate integration pattern depends on workflow characteristics:

Use Router Pattern when:

  • Input requires classification before processing
  • Different processing logic needed for different input types
  • Conditional branching based on business rules
  • Example: Route support tickets by priority/category

Use Coordinator Pattern when:

  • Multiple independent operations can run in parallel
  • Results need aggregation after parallel processing
  • Rate limiting or concurrency control required
  • Example: Batch process uploaded files, enrich database records

Use Supervisor Pattern when:

  • Human approval required before proceeding
  • Quality gates for AI-generated content
  • Compliance review needed
  • Example: Content moderation, expense approval

Use Sequential Pipeline when:

  • Each stage depends on previous stage output
  • Linear transformation workflow
  • State must progress through ordered stages
  • Example: ETL pipeline, media transcoding

Combining patterns:

  • Router → Coordinator: Route to different batch processors
  • Coordinator → Sequential: Parallel processing with sequential post-processing
  • Sequential → Supervisor: Process then await approval before publishing
  • All patterns can nest additional child patterns

Sources: docs/guides/use-cases/media-processing.mdx44-189 docs/guides/use-cases/data-processing-etl.mdx64-158 docs/guides/use-cases/media-generation.mdx64-143 docs/guides/use-cases/marketing.mdx56-145