Vercel: 504 timeout on serverless functions [2026 fix]

Serverless functions exceed 10s timeout limit or hit memory/cold start issues. Increase function timeout, optimize code path, or split into smaller functions.

Vercel: 504 timeout on serverless functions [2026 fix]

TL;DR

Cause: Your serverless function exceeded Vercel's 10-second default timeout or hit cold start/memory limits. Fix: Increase maxDuration in vercel.json, optimize slow database queries, or split heavy processing into background jobs.

---

Real Console Error Messages

``` [504] Gateway Timeout A request to a function on Vercel timed out after 10s ```

``` Error: Task timed out after 10.00 seconds at Timeout._onTimeout (internal/timers.js:10:39) ```

``` FETCH_ERROR: request to https://yourapi.vercel.app/api/process failed, reason: socket hang up ```

``` 502 Bad Gateway The function did not respond in time ```

``` AWAIT_TIMEOUT: Serverless Function timed out while executing "default" ```

---

Code Comparison: Broken vs Fixed

❌ BROKEN CODE

api/process.js (no timeout config) ```javascript export default async function handler(req, res) { // Fetching 50k records synchronously const users = await db.query('SELECT * FROM users'); const processed = users.map(u => complexCalculation(u)); // Loop through related data without batching for (let user of processed) { const orders = await db.query(SELECT * FROM orders WHERE user_id = ${user.id}); user.orders = orders; } res.status(200).json(processed); } ```

vercel.json (missing timeout) ```json { "buildCommand": "npm run build", "outputDirectory": ".next" } ```

---

✅ FIXED CODE

api/process.js (optimized with chunking) ```javascript export default async function handler(req, res) { // Paginate instead of fetching all const limit = 100; const offset = req.query.offset || 0; const users = await db.query( 'SELECT * FROM users LIMIT ? OFFSET ?', [limit, offset] ); // Batch load related data with JOIN const enriched = await db.query(` SELECT u.*, json_agg(o.*) as orders FROM users u LEFT JOIN orders o ON u.id = o.user_id LIMIT ? OFFSET ? `, [limit, offset]); res.status(200).json(enriched); } ```

vercel.json (with extended timeout) ```json { "buildCommand": "npm run build", "outputDirectory": ".next", "functions": { "api/process.js": { "maxDuration": 30 } } } ```

---

Why This Happens

1. Default timeout is 10 seconds on Vercel's Pro plan; 60s on Enterprise 2. Cold starts add 2-5 seconds before your code runs (dependency bundling) 3. Synchronous loops over database queries create N+1 problems 4. Large dataset processing (CSV parsing, image transforms) eats time 5. External API calls waiting for slow third-party responses

---

Step-by-Step Fix

Step 1: Increase Timeout (Quick Fix)

Edit vercel.json and set maxDuration up to 30 seconds (Pro) or 300s (Enterprise): ```json { "functions": { "api/**/*.js": {"maxDuration": 30}, "api/heavy-processing.js": {"maxDuration": 60} } } ```

Step 2: Profile Your Function

Add timing logs: ```javascript const start = Date.now(); const data = await slowOperation(); console.log(Query took ${Date.now() - start}ms); ```

Step 3: Optimize the Slow Path

  • Use database JOINs instead of application-level loops
  • Add pagination to avoid loading massive datasets
  • Cache frequently accessed data (Redis, Upstash)
  • Use connection pooling for database connections
  • Step 4: Consider Background Jobs

    For operations >30s, use Vercel Cron or external job queues: ```javascript // api/queue-process.js export default async function handler(req, res) { // Queue for processing, return immediately await queue.add({userId: req.body.userId}); res.status(202).json({queued: true}); }

    // api/crons/process-queue.js export default async function handler(req, res) { // This can run up to 900 seconds await processQueue(); res.status(200).json({processed: true}); } ```

    ---

    Still broken? Check these too

    1. [Check your Node.js version](/?guide=vercel-nodejs-version) — Older versions have slower JSON parsing; update to 18+ in package.json's engines field

    2. [Bundle size bloat](/?guide=vercel-bundle-analysis) — Unused dependencies slow cold starts; run vercel build --analyze to identify culprits

    3. Database connection pooling — Each function invocation opens a new connection; use PgBouncer or native pooling to reuse connections across warm invocations

    ---

    Official Resources

  • [Vercel Serverless Function Timeout Docs](https://vercel.com/docs/concepts/functions/serverless-functions#maximum-duration)
  • [Performance best practices](https://vercel.com/docs/concepts/functions/serverless-functions/fundamentals#cold-starts)
  • ---

    Version Notes

    This guide applies to Vercel Functions 2024-2026. Maximum duration limits and cold start behavior may vary between Pro/Enterprise/Hobby tiers — verify your plan at [vercel.com/account](https://vercel.com/account).

    ---

    Found a different variation? Drop it in the comments.

    🔥 0d
    LIVE
    PlanetScale rage spiking Vercel pricing complaints Railway gaining fast Supabase happiness rising Resend loved by devs PlanetScale rage spiking Vercel pricing complaints Railway gaining fast Supabase happiness rising
    DEVELOPER PAIN RADAR // Loading...

    Developers complain.
    Opportunities appear.

    We track what developers are struggling with today — and what opportunities that creates.

    guides today
    avg happiness
    🔥 Pain
    📖 Guides
    🔭 Explore
    👤 Mine
    🔥 Pain Radar — rage scores today
    ↗ share
    💡 Opportunity Feed — pain = market gap
    📈 Tool Momentum
    all scores →
    📖 Latest Guide
    all guides →
    📖 All Guides
    📊 Tool Scores
    + Submit
    📰 Hacker News
    ➕ Submit a Tool
    ← back