Vercel: 504 timeout on serverless functions [2026 fix]

Serverless functions exceed 10s timeout or cold start delays. Reduce function execution time or increase timeout in vercel.json config.

Vercel: 504 timeout on serverless functions [2026 fix]

TL;DR

Cause: Your serverless function exceeded Vercel's 10-second default timeout (or cold start exceeded limits).

Fix: Add "maxDuration": 60 to your function's vercel.json config and optimize payload processing.

---

Real Console Error Messages

Here are exact error signatures you'll see in Vercel logs:

``` 504: DEADLINE_EXCEEDED Deadline exceeded before the function completed execution ```

``` FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory at processRequest (file:///var/task/index.js:1:1) ```

``` Error: connect ETIMEDOUT 10.0.0.1:5432 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:10) at Function.Module._load (internal/modules/commonRequires:js:485:15) ```

``` {"errorCode":"FUNCTION_INVOCATION_TIMEOUT","duration":10042} ```

``` WARNING in /var/task/node_modules: Critical dependency warning [Function] Duration: 10000.45 ms, Billed Duration: 10001 ms, Memory Size: 1024 MB ```

---

The Problem: Before & After Code

❌ BROKEN CODE

api/slow-endpoint.js ```javascript export default async function handler(req, res) { // Database query without connection pooling const db = await connectToPostgres(); const users = await db.query('SELECT * FROM users WHERE ...'); // Synchronous file operations (blocks execution) const fileData = fs.readFileSync('/mnt/data/large-file.json'); const processed = JSON.parse(fileData); // Long processing loop for (let i = 0; i < 1000000; i++) { processed[i] = expensive_calculation(processed[i]); } res.json(processed); } ```

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

✅ FIXED CODE

api/slow-endpoint.js ```javascript import { Pool } from 'pg';

// Connection pool (reused across invocations) const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 2 });

export default async function handler(req, res) { try { // Use connection pooling + timeout const client = await pool.connect(); const result = await Promise.race([ client.query('SELECT * FROM users LIMIT 100'), new Promise((_, reject) => setTimeout(() => reject(new Error('Query timeout')), 5000) ) ]); client.release(); // Stream large files instead of loading entire file const processedData = await streamProcessFile('/mnt/data/large-file.json'); res.status(200).json(processedData); } catch (error) { console.error('Function error:', error); res.status(500).json({ error: error.message }); } }

async function streamProcessFile(filePath) { const stream = fs.createReadStream(filePath, { encoding: 'utf-8' }); // Process in chunks rather than all at once return new Promise((resolve) => { let data = ''; stream.on('data', chunk => { data += chunk.substring(0, 1000); // Limit processing }); stream.on('end', () => resolve(JSON.parse(data))); }); } ```

vercel.json (with proper timeout + config) ```json { "buildCommand": "npm run build", "outputDirectory": ".next", "functions": { "api/**/*.js": { "maxDuration": 60, "memory": 3008 } }, "env": { "DATABASE_POOL_SIZE": "2" } } ```

---

Why This Matters

Vercel's default serverless timeout is 10 seconds on hobby plans and 60 seconds maximum on Pro plans. Common culprits:

  • Cold starts: First invocation loads dependencies (1-3s overhead)
  • Database queries: Unoptimized or missing connection pooling
  • Synchronous I/O: fs.readFileSync() blocks the event loop
  • Unbounded loops: Processing large datasets without chunking
  • Missing error handling: Failed requests retry, consuming the timeout window
  • Note on version behavior: As of 2026, Vercel's timeout behavior hasn't changed significantly since v3, but Pro plan limits may vary. Check your deployment plan in [Vercel Dashboard](https://vercel.com/dashboard).

    ---

    Still broken? Check these too

    1. [Cold start optimization](/?guide=cold-starts) — Reduce bundle size and dependency count. Minify and tree-shake unused code. Enable [Prerender](https://vercel.com/docs/functions/supported-languages) for static routes.

    2. Memory exhaustion — Increase "memory" in vercel.json (up to 3008 MB). Check for memory leaks in loops or cached objects that aren't freed.

    3. [Environment variables loading slowly](/?guide=env-secrets) — Verify DATABASE_URL and secrets are properly configured in project settings. Large .env files can add startup delay.

    ---

    External Resources

    📖 Official Vercel Documentation:

  • [Vercel Serverless Function Limits](https://vercel.com/docs/functions/limitations)
  • [Vercel Functions Configuration](https://vercel.com/docs/functions/configuring-functions)
  • [Debugging 504 Errors](https://vercel.com/support/articles/how-do-i-debug-504-errors)
  • ---

    Quick Checklist

  • [ ] Set maxDuration in vercel.json to match your needs (up to 60s on Pro)
  • [ ] Replace connectToDatabase() calls with connection pooling
  • [ ] Remove all fs.readFileSync() — use async alternatives
  • [ ] Add error handling with try/catch to fail fast
  • [ ] Reduce cold start: minimize node_modules, use ES modules
  • [ ] Monitor real function duration in Vercel Analytics
  • ---

    Found a different variation? Drop it in the comments — Include your exact error message, vercel.json config, and what fixed it for you.

    🔥 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