Vercel: 504 timeout on serverless functions [2026 fix]

Serverless functions exceed 10s default timeout or hit memory limits. Increase function timeout in vercel.json and optimize cold starts.

Vercel: 504 timeout on serverless functions [2026 fix]

TL;DR

Cause: Your serverless function is taking longer than Vercel's 10-second default timeout (or hitting memory/CPU limits during cold starts). Fix: Add "functionTimeout": 60 to vercel.json and optimize your function's initialization code.

---

Common Error Messages from Console Output

Here are EXACT error messages you'll see in Vercel logs:

``` ERROR: Serverless Function timed out after 10.00s status: 504 message: Gateway Timeout ```

``` ERROR at /api/endpoint: Function execution took 12043ms, exceeding timeout of 10000ms Error: Task timed out after 10.00 seconds ```

``` WARN: Cold start detected - initialization took 8234ms ERROR: Subsequent execution timeout (total runtime: 11567ms) ```

``` Vercel/Timeout Code: ERR_FUNCTION_TIMEOUT Message: Your serverless function failed to complete within the maximum allowed time ```

``` ERROR DETAILS: Lambda runtime exited with error code 504 Cause: Process exceeded maximum runtime duration ```

---

The Problem & Solution: Side by Side

❌ BROKEN CODE

vercel.json (missing timeout config): ```json { "buildCommand": "npm run build", "env": { "DATABASE_URL": "@database_url" } } ```

api/slow-endpoint.js (database query takes 15 seconds): ```javascript export default async function handler(req, res) { // Heavy database query without timeout const users = await db.query(` SELECT * FROM users WHERE status = 'active' AND created_at > NOW() - INTERVAL '30 days' ORDER BY engagement DESC `); // Processing takes 8+ seconds const enriched = await Promise.all( users.map(u => enrichUserData(u)) ); res.status(200).json(enriched); } ```

✅ FIXED CODE

vercel.json (with timeout configuration): ```json { "buildCommand": "npm run build", "functions": { "api/**/*.js": { "maxDuration": 60 } }, "env": { "DATABASE_URL": "@database_url" } } ```

api/slow-endpoint.js (with optimizations): ```javascript export default async function handler(req, res) { // Set response timeout header res.setHeader('X-Accel-Buffering', 'no'); // Query with limit to reduce processing time const users = await db.query(` SELECT id, name, engagement FROM users WHERE status = 'active' AND created_at > NOW() - INTERVAL '30 days' ORDER BY engagement DESC LIMIT 100 `, { timeout: 5000 }); // Batch processing in parallel with concurrency limit const enriched = await Promise.allSettled( users.slice(0, 50).map(u => enrichUserData(u)) ); // Return early if possible const results = enriched .filter(r => r.status === 'fulfilled') .map(r => r.value); res.status(200).json(results); } ```

---

Key Changes Explained

1. Timeout Configuration: Vercel's Pro plan allows maxDuration up to 60 seconds (Hobby plan capped at 10s). We're setting it to 60 for safety.

2. Database Query Optimization:

  • Added LIMIT 100 to prevent fetching massive datasets
  • Reduced SELECT columns to only needed fields
  • Added query timeout of 5 seconds
  • 3. Concurrency Control: Reduced from users.map() (unlimited parallel) to users.slice(0, 50) to prevent memory exhaustion.

    4. Error Handling: Used Promise.allSettled() instead of Promise.all() so one slow enrichment doesn't fail everything.

    ---

    Version-Specific Notes

    ⚠️ Important disclaimer: The maxDuration syntax varies by Vercel CLI version. If you're on Vercel CLI v28.x or earlier, use "functionTimeout" instead. Test in a staging deployment first.

    Current approach (v29+): ```json "functions": { "api/**/*.js": { "maxDuration": 60 } } ```

    Legacy approach (v28 and earlier): ```json "functionTimeout": 60 ```

    Check your version with vercel --version.

    ---

    Still broken? Check these too

    1. Cold Start Overhead – [How to eliminate Vercel cold starts](/?guide=vercel-cold-start). If initialization takes 7+ seconds, you're timeout before user requests even run.

    2. Memory Exhaustion – Increase function memory in vercel.json: "memory": 3008 (max Pro value). Memory pressure causes CPU throttling → timeouts.

    3. External API Delays – Your function calls a slow third-party API. Add request timeout: fetch(url, { timeout: 3000 }) and implement retry logic with exponential backoff. [See timeout patterns](/?guide=fetch-timeout-patterns).

    4. Database Connection Pooling – Each cold start creates new DB connection. Use connection pooling library like pgBouncer or managed services like Prisma Data Proxy.

    5. Vercel Analytics Disabled – Enable Web Analytics to see actual function duration, not just timeout notices.

    ---

    Official Resources

  • [Vercel Serverless Functions Documentation](https://vercel.com/docs/concepts/functions/serverless-functions)
  • [Vercel maxDuration Configuration](https://vercel.com/docs/concepts/functions/serverless-functions/api-reference#maxduration)
  • [AWS Lambda Timeout Limits](https://docs.aws.amazon.com/lambda/latest/dg/limits.html) (Vercel runs on Lambda)
  • ---

    What You Should Do Right Now

    1. Deploy with increased maxDuration: 60 2. Monitor function duration in Vercel Analytics dashboard 3. If still timing out, add database query limits 4. Consider splitting into multiple smaller functions 5. Set up alerts when function duration exceeds 8 seconds

    Found a different variation? Drop it in the comments – this guide covers the most common scenario, but edge cases exist (Turbopack builds, monorepos, regional deployment issues). Share your specific error and fix so we can keep this updated.

    🔥 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