Vercel: 504 timeout on serverless functions [2026 fix]

Serverless function exceeds 10s timeout or memory limit. Reduce cold starts, optimize queries, increase function timeout in vercel.json.

TL;DR

Cause: Your serverless function is executing longer than Vercel's 10-second default timeout (Pro: 60s, Enterprise: 900s) or hitting memory constraints during cold starts. Fix: Add "functionTimeout": 60 to vercel.json and optimize database queries to reduce execution time.

---

Exact Error Messages You'll See

``` 504 GATEWAY_TIMEOUT Error: Task timed out after 10.00 seconds ```

``` FunctionTooLarge: Your serverless function "api/endpoint" exceeds the 50MB uncompressed limit ERROR: Serverless Function returned statusCode: undefined ```

``` Error: connect ECONNREFUSED 127.0.0.1:5432 function completed after 11234ms (timeout at 10000ms) ```

``` WARNING: Cold start took 8234ms + 3000ms execution = 11234ms total Gateway timeout - function did not respond within timeout window ```

``` ERROR: FATAL: remaining connection slots are reserved for non-replication superuser connections at Database.query (db.js:45:23) at async handler (api/route.ts:12:8) ```

---

Code: Broken vs. Fixed

Problem #1: Missing Timeout Configuration

BROKEN: ```javascript // vercel.json - using defaults { "buildCommand": "npm run build", "outputDirectory": "dist" } ```

FIXED: ```javascript // vercel.json - explicit timeout for Pro plan { "buildCommand": "npm run build", "outputDirectory": "dist", "functions": { "api/**/*.ts": { "memory": 1024, "maxDuration": 60 } } } ```

---

Problem #2: Unoptimized Database Queries

BROKEN: ```typescript // api/users.ts - N+1 query problem export default async function handler(req: NextApiRequest, res: NextApiResponse) { const users = await db.query('SELECT * FROM users'); for (const user of users) { user.posts = await db.query('SELECT * FROM posts WHERE user_id = $1', [user.id]); } res.json(users); } // Takes 8-15 seconds depending on user count ```

FIXED: ```typescript // api/users.ts - single JOIN query export default async function handler(req: NextApiRequest, res: NextApiResponse) { const users = await db.query(` SELECT u.*, json_agg(p.*) as posts FROM users u LEFT JOIN posts p ON p.user_id = u.id GROUP BY u.id `); res.json(users); } // Executes in 200-400ms ```

---

Problem #3: Large Dependencies Causing Cold Starts

BROKEN: ```typescript // api/process.ts - 15MB bundle import * as tf from '@tensorflow/tfjs'; import * as cv from 'opencv4nodejs'; import * as sharp from 'sharp';

export default async function handler(req, res) { // Cold start: 8s just for imports + 4s execution = 504 const result = await tf.loadLayersModel('...'); res.json(result); } ```

FIXED: ```typescript // api/process.ts - lazy load or externalize import { createCanvas } from 'canvas'; // lightweight alternative

export default async function handler(req, res) { // Lazy load only when needed const sharp = (await import('sharp')).default; const result = await sharp(req.body.image).resize(200, 200).toBuffer(); res.json({ success: true }); }

// OR move heavy processing to Vercel Background Functions or external service ```

---

Still Broken? Check These Too

1. Database Connection Pool Exhaustion If you have multiple serverless instances hammering a single database connection pool, you'll hit FATAL: remaining connection slots reserved errors. Solution: Use PgBouncer, increase pool size, or switch to [serverless database connections](/?guide=prisma-serverless). Verify with: SELECT count(*) FROM pg_stat_activity;

2. Uncompressed Bundle Size Over 250MB Even if your function timeout is 60s, Vercel can't execute functions over 250MB uncompressed. Check with: npm run build && du -sh .vercel/output. Remove dev dependencies from production, tree-shake unused code, consider AWS Lambda or custom containers instead.

3. Cold Start + Warm Instance Race Condition Sometimes Vercel spins up a new instance while old one is shutting down, causing traffic to get routed to the cold instance during boot. This is infrastructure-level; your only recourse is [increasing memory allocation](/?guide=vercel-memory-optimization) (which also improves CPU) or using Regional Caching with Vercel's Edge Network.

---

Key Differences by Vercel Plan

| Plan | Default Timeout | Max Timeout | Max Memory | |------|-----------------|-------------|------------| | Hobby | 10s | 10s | 512MB | | Pro | 10s | 60s | 3008MB | | Enterprise | 10s | 900s | 12GB |

Important caveat: These timeout values are current as of 2026, but Vercel has historically adjusted them. Always cross-reference the [official Vercel Function Limits documentation](https://vercel.com/docs/functions/serverless-functions#limits).

---

Quick Wins

  • Add "maxDuration": 60 to vercel.json (assumes Pro plan)
  • Replace N+1 queries with JOINs or batch queries
  • Use npx @vercel/cli@latest build locally to test timeout behavior
  • Stream responses if possible: res.setHeader('Transfer-Encoding', 'chunked')
  • Enable Vercel's request caching with res.setHeader('Cache-Control', 'public, s-maxage=300')
  • ---

    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