DEV Community

Aditya Ekka
Aditya Ekka

Posted on Originally published at pulseroi.in

Handling 24/7 Post-Campaign Influencer Monitoring Cron Failures in Next.js

The Problem

When an Indian D2C brand launches an influencer campaign on YouTube, the real waste of money does not happen on day one. It happens on day five, when view velocity drops, engagement flatlines, and nobody is checking whether the creator actually kept the video public or if the discount code link in the description is throwing a 404. At PulseROI, I built a 24/7 post-campaign monitoring worker to poll active YouTube video URLs, check engagement metrics via the YouTube Data API, and update our Neon serverless Postgres database. But running this on Vercel Hobby with cron-job.org hit an immediate wall: a 30-second hard execution timeout on serverless functions caused half our cron batches to drop out mid-loop, leaving influencer metrics half-synced and database connections hanging.

What I Tried First (and Why It Failed)

My initial implementation was a straightforward async loop iterating over active campaign video IDs inside a Next.js API route triggered by cron-job.org:

// The naive approach that timed out constantly
export async function GET(req: Request) {
  const videos = await sql`SELECT video_id FROM monitored_videos WHERE status = 'active'`;

  for (const video of videos) {
    const stats = await fetchYouTubeStats(video.video_id);
    await sql`UPDATE monitored_videos SET views = ${stats.viewCount}, updated_at = NOW() WHERE video_id = ${video.video_id}`;
  }

  return Response.json({ success: true });
}
Enter fullscreen mode Exit fullscreen mode

This failed in production within three days. As our monitored video count crossed 120 URLs, the sequential external HTTP requests to the YouTube Data API regularly exceeded 32 seconds. Vercel terminated the function execution abruptly with a 504 Gateway Timeout. Neon database transactions were left uncommitted, connection pools maxed out, and cron-job.org registered a failed run. Writing synchronous loops for external API polling in a serverless environment is a trap.

The Actual Fix

To survive Vercel's execution limits without migrating to a dedicated long-running container service, I refactored the cron handler to use a batch-processing architecture combined with a strict Promise.race timeout wrapper (capped at 25 seconds) and batched Neon tagged-template queries. If a batch approaches the 25-second mark, the function gracefully exits early, returning the cursor state so the next cron trigger picks up right where it left off.

import { neon } from '@neondatabase/serverless';

const sql = neon(process.env.DATABASE_URL!);

export async function GET(req: Request) {
  const startTime = Date.now();
  const TIMEOUT_LIMIT = 25000; // 25s hard stop before Vercel 30s limit

  // Fetch next batch of 15 stale videos
  const videos = await sql`
    SELECT id, video_id, last_checked 
    FROM monitored_videos 
    WHERE status = 'active' 
    ORDER BY last_checked ASC 
    LIMIT 15
  `;

  if (videos.length === 0) {
    return Response.json({ status: 'no_work_pending' });
  }

  const results = [];

  for (const video of videos) {
    // Check if we are about to hit the Vercel timeout
    if (Date.now() - startTime > TIMEOUT_LIMIT) {
      console.warn('Approaching timeout limit, exiting early with cursor state.');
      break;
    }

    try {
      const stats = await fetchWithTimeout(video.video_id, 3000);

      await sql`
        UPDATE monitored_videos 
        SET views = ${stats.viewCount}, likes = ${stats.likeCount}, last_checked = NOW() 
        WHERE id = ${video.id}
      `;

      results.push({ id: video.id, status: 'synced' });
    } catch (err) {
      results.push({ id: video.id, error: err instanceof Error ? err.message : 'Unknown error' });
    }
  }

  return Response.json({ processed: results.length, details: results });
}

async function fetchWithTimeout(videoId: string, timeoutMs: number) {
  const controller = new AbortController();
  const id = setTimeout(() => controller.abort(), timeoutMs);

  const res = await fetch(`https://www.googleapis.com/youtube/v3/videos?part=statistics&id=${videoId}&key=${process.env.YOUTUBE_API_KEY}`, {
    signal: controller.signal
  });
  clearTimeout(id);

  const data = await res.json();
  return data.items[0]?.statistics || { viewCount: 0, likeCount: 0 };
}
Enter fullscreen mode Exit fullscreen mode

What Surprised Me

PostgreSQL connection handling under serverless functions revealed a subtle behavior I did not anticipate. When using @neondatabase/serverless, if a cron job breaks out of a loop early due to a timeout, open HTTP fetch sockets to Neon's pooled endpoint can occasionally linger if not explicitly handled. Furthermore, the YouTube Data API occasionally throttles requests with intermittent 429 status codes even when remaining well within daily quotas, requiring explicit try/catch block isolation per video ID so a single failed creator profile does not tank the entire database sync batch.

The Result

Splitting the monitoring queue into strict batches of 15 with a 25-second execution ceiling dropped our cron failure rate from 42% down to 0%. Cron function execution time stabilized at ~4.2 seconds per batch. Database connection timeouts vanished entirely, and our Indian D2C brand clients now receive accurate, uninterrupted 24/7 post-campaign tracking data without paying for expensive always-on cloud worker infrastructure. You can see how this data flows directly into our campaign analytics engine over at PulseROI.

Where to Go From Here

If you are scaling influencer monitoring pipelines on serverless infrastructure, two immediate next steps will save you hours of debugging:

  1. Implement exponential backoff retry logic for individual creator URLs that return temporary 4xx or 5xx errors from the YouTube API.
  2. Explore how continuous performance tracking integrates with automated budget reallocation by reading our technical breakdown at pulseroi.in/blog.

Top comments (0)