Skip to main content

Data Flow

This document describes how data moves through the UniPulse platform, covering both synchronous request handling and asynchronous job processing.


Synchronous Request Flow

Step-by-Step Breakdown

StepComponentPurpose
1React SPAMakes API call via TanStack Query to /api/v1/*
2Express RouterRoutes request to the correct handler
3auth.tsValidates JWT from Authorization: Bearer <token> header
4requireWorkspace.tsAttaches workspace context, enforces RBAC role check
5requireFeature.tsChecks if the feature is enabled for the workspace's plan
6requireQuota.tsEnsures workspace hasn't exceeded usage quotas
7validate.tsValidates request body/params against Zod schema from @unipulse/shared
8rateLimiter.tsEnforces per-IP rate limits (separate limits for auth and AI routes)
9Service LayerExecutes business logic
10Prisma ORMRuns database queries (always scoped by workspaceId)
11ResponseReturns JSON payload to client
Middleware Order Matters

The middleware chain runs in strict order. Authentication runs first so that unauthorized requests are rejected before any business logic executes. Validation runs after auth so that validation errors include the user context for logging.


Asynchronous Processing Flow

Heavy operations are offloaded to BullMQ queues backed by Redis. This keeps API response times fast while processing happens in the background.

Queue Job Lifecycle

StateDescription
waitingJob is in the queue, waiting for a worker
activeWorker has picked up the job and is processing it
completedJob finished successfully
failedJob failed (will retry based on backoff config)
delayedJob is scheduled for future execution

All 27 Queue Flows

Queue NameTriggerProcessingOutput
publishUser publishes postPosts to Facebook/Instagram/TikTok APIsPostPublication records
scheduleCron or scheduled timeTriggers publish queue at scheduled timeMoves post to publish queue
analytics-syncPeriodic / manualFetches metrics from platform APIsPostMetric records
ai-suggestionsBackground generationCalls Gemini API for content suggestionsAiSuggestion records
workflow-engineWorkflow trigger eventEvaluates conditions, executes actionsWorkflowRun records
prediction-evalAfter analytics syncRuns engagement/revenue prediction modelsEngagementPrediction records
competitor-scanPeriodic scheduleScrapes competitor social profilesCompetitorSnapshot records
ecommerce-syncWebhook / periodicSyncs products and orders from storesEcommerceProduct/CommerceOrder records
calendar-generateUser requestGenerates AI content calendarCalendarEntry records
trend-scanPeriodic scheduleDetects trending topics via GeminiTrend data
ad-syncPeriodic scheduleSyncs ad performance from Meta/TikTokAdCampaign metrics
ab-test-evalTest duration elapsedEvaluates A/B test resultsABTest results
audience-syncAfter interactionUpdates audience graph and scoresAudienceNode records
benchmark-computePeriodic scheduleComputes industry benchmarksIndustryBenchmark records
ice-processIncoming messageRuns 3-step LLM pipeline (classify, context, respond)ConversationMessage reply
ice-escalationEscalation rule matchRoutes thread to human agentEscalation records
ice-experiment-evalExperiment duration elapsedEvaluates reply experimentsReplyExperiment results
order-syncWebhook / periodicSyncs orders for revenue attributionCommerceOrder records
payment-webhookPayment provider webhookProcesses subscription changesSubscription/Transaction records
post-classifyAfter post creationClassifies post content type and topicPostClassification records
revenue-attributionAfter order syncMatches orders to posts via UTM paramsRevenueAttribution records
segment-evalAfter audience updateRe-evaluates audience segmentsAudienceSegment membership
token-refreshBefore token expiryRefreshes social platform OAuth tokensUpdated SocialAccount tokens
webhook-processExternal webhook receivedProcesses incoming webhook payloadsVarious
workspace-classifyPeriodicClassifies workspace industry/nicheWorkspace metadata
Queue Failure Handling

All queues are configured with exponential backoff retry. Default: 3 attempts with 5-second base delay. Failed jobs after all retries are retained in Redis for debugging and are visible in the admin dashboard.


End-to-End Data Flow Examples

Post Publishing Flow

Conversation Engine Flow

Revenue Attribution Flow


Cross-Reference