Vercel: 504 timeout on serverless functions [2026 fix]

Serverless function exceeds 10s timeout or cold start memory—increase function timeout and optimize initialization code.

TL;DR

Cause: Your serverless function is exceeding Vercel's 10-second default timeout or hitting memory limits during cold starts.

Fix: Increase function timeout in vercel.json, optimize initialization code, and reduce bundle size.

---

Real Console Error Messages

Here are exact error patterns you'll see:

``` Error: FUNCTION_INVOCATION_TIMEOUT The function execution took too long to complete (duration: 12000ms). Please check your function code for performance issues. ```

``` ERR_FUNCTION_TIMEOUT: Serverless Function timed out after 10.00s Request from 203.0.113.45 did not complete before deadline ```

``` 504 Gateway Timeout The request took too long to process and timed out. Vercel logs: Function invocation: 11234ms (limit: 10000ms) ```

``` Error: Task timed out after 10.00 seconds. Exceeded memory during initialization. Heap snapshot: 487MB of 512MB used before handler execution ```

``` DEADLINE_EXCEEDED rpc error: code = DeadlineExceeded desc = context deadline exceeded Serverless function runtime: nodejs18.x ```

---

Code: Broken vs Fixed

❌ Broken Code

```javascript // api/process-data.js - Default timeout (10s) import fs from 'fs/promises'; import { processLargeDataset } from './heavy-lib';

// Slow initialization at module level const DATABASE = require('./db-connection'); const ML_MODEL = require('./ml-model-500mb');

export default async function handler(req, res) { // Function starts execution here, but initialization ate 3 seconds already const data = await processLargeDataset(req.body); const result = await DATABASE.query(data); res.json(result); } ```

No timeout configuration. Library loads synchronously every cold start. Database connection blocking.

✅ Fixed Code

Step 1: Update vercel.json

```json { "functions": { "api/process-data.js": { "maxDuration": 30, "memory": 3008 } } } ```

Step 2: Optimize handler code

```javascript // api/process-data.js - With lazy loading and timeout handling import fs from 'fs/promises';

// Lazy load heavy dependencies let database = null; let mlModel = null;

async function getDatabase() { if (!database) { database = await import('./db-connection-async.js'); } return database; }

async function getMLModel() { if (!mlModel) { mlModel = await import('./ml-model-500mb.js'); } return mlModel; }

export default async function handler(req, res) { // Add explicit timeout wrapper const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error('Function timeout')), 25000) );

try { const db = await getDatabase(); const { processLargeDataset } = await import('./heavy-lib.js'); const data = await Promise.race([ processLargeDataset(req.body), timeoutPromise ]); const result = await db.query(data); res.status(200).json(result); } catch (error) { console.error('Function error:', error.message); res.status(504).json({ error: 'Processing timeout' }); } } ```

Key changes:

  • maxDuration: 30 extends timeout to 30 seconds (Pro plan required)
  • Lazy loading defers heavy imports until first use
  • Explicit timeout race condition ensures graceful failure
  • Memory bumped to 3008MB for faster execution
  • ---

    Configuration Details

    Timeout Limits by Plan:

  • Hobby (Free): 10 seconds max
  • Pro: 60 seconds max
  • Enterprise: Custom (contact sales)
  • Memory Limits:

  • Default: 1024MB
  • Maximum: 3008MB (increases CPU allocation proportionally)
  • To confirm your current settings:

    ```bash vercel env list vercel inspect api/process-data.js ```

    ---

    Still broken? Check these too

    1. Cold Start Performance: Load testing doesn't reveal cold starts. Use vercel logs to check actual invocation times. Add X-Vercel-Trace-ID header inspection to distinguish cold vs warm starts. See [Monitoring function performance](/?guide=vercel-logs).

    2. Database Connection Pooling: Each function invocation creates new connection. Add connection reuse via global variable wrapping or use serverless-compatible pools (PgBouncer, Redis connection manager). Unoptimized queries can add 3-5 seconds silently.

    3. External API Calls: Timeouts on third-party APIs (payment gateways, ML services) kill your function. Implement request timeouts and circuit breakers. Retry logic with exponential backoff prevents retry loops. See [External service timeouts](/?guide=external-api-timeout).

    ---

    Verification

    After applying fixes:

    ```bash

    Deploy and tail logs in real-time

    vercel deploy --prod vercel logs --follow ```

    Monitor function duration in Vercel dashboard: Settings > Functions > Logs > Duration.

    ---

    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/max-duration)
  • [Node.js Runtime Best Practices](https://vercel.com/docs/runtimes/nodejs)
  • ---

    Found a different variation? Drop it in the comments—include your error message and what fixed it for your stack.

    🔥 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