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:
fs.readFileSync() blocks the event loopNote 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:
---
Quick Checklist
maxDuration in vercel.json to match your needs (up to 60s on Pro)connectToDatabase() calls with connection poolingfs.readFileSync() — use async alternativesnode_modules, use ES modules---
Found a different variation? Drop it in the comments — Include your exact error message, vercel.json config, and what fixed it for you.