Vercel: 504 timeout on serverless functions [2026 fix]
Serverless function exceeds 10s timeout or cold start memory fails. Reduce function complexity, increase memory allocation, or implement request queuing.
Vercel: 504 timeout on serverless functions [2026 fix]
TL;DR
Cause: Your serverless function exceeded Vercel's 10-second execution timeout (or 900 seconds for Pro plans) due to slow database queries, missing indexes, or insufficient memory allocation. Fix: Increase function memory to 3008 MB, implement response caching, offload heavy work to background jobs, or add database query timeouts.---
Real Console Error Messages
Error #1: Standard timeout
``` FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory 504 Service Unavailable A Function took too long to execute, please check your Function logs in the Vercel dashboard. ```Error #2: Cold start + slow import
``` [WARN] Unhandled error during request: TypeError: Cannot read properties of undefined (reading 'query') Error: connect ETIMEDOUT 10.0.0.1:5432 504 Gateway Timeout ```Error #3: Database connection pool exhaustion
``` Error: too many connections at Connection.query (/var/task/node_modules/pg/lib/connection.js:219:14) 504 Service Unavailable - Vercel Function execution timeout ```Error #4: Streaming response timeout
``` Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client 504 GATEWAY_TIMEOUT Function was terminated after 10.0 seconds ```Error #5: Module loading delay
``` Task timed out after 10.00 seconds ERROR in /var/task: node_modules size 487MB exceeds recommendations 504 ```---
Code: Broken vs Fixed
❌ BROKEN: Unoptimized database query
```javascript // api/users.js - causes 504 export default async function handler(req, res) { const { Pool } = require('pg'); const pool = new Pool({ connectionString: process.env.DATABASE_URL, }); // NO TIMEOUT, NO INDEX, FETCHES ALL ROWS const result = await pool.query( 'SELECT * FROM users WHERE status = $1', ['active'] ); res.status(200).json(result.rows); } ```✅ FIXED: Optimized with timeout + connection pooling
```javascript // api/users.js - works reliably import { Pool } from 'pg';const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 2, // Vercel limit idleTimeoutMillis: 10000, connectionTimeoutMillis: 5000, });
export default async function handler(req, res) { const client = await pool.connect(); try { // QUERY TIMEOUT: 8 seconds (under 10s limit) const result = await Promise.race([ client.query( 'SELECT id, name FROM users WHERE status = $1 LIMIT 100', ['active'] ), new Promise((_, reject) => setTimeout(() => reject(new Error('Query timeout')), 8000) ) ]); // ADD CACHE HEADERS res.setHeader('Cache-Control', 'public, s-maxage=60, stale-while-revalidate=120'); res.status(200).json(result.rows); } catch (error) { console.error('Database error:', error); res.status(503).json({ error: 'Service temporarily unavailable' }); } finally { client.release(); } } ```
---
Configuration Fix: Increase Memory
Create or update vercel.json:
```json { "functions": { "api/**/*.js": { "memory": 3008, "maxDuration": 60 } } } ```
Note: Memory allocation up to 3008 MB is available on Pro/Enterprise plans. Free tier limited to 1024 MB.
---
Still broken? Check these too
1. N+1 Query Problem — Your function loops and queries the database inside loops. Use JOIN clauses or batch queries instead. [See related database optimization guide](/?guide=n-plus-one-queries).
2. Missing Database Indexes — Run CREATE INDEX idx_status ON users(status); on your production database. Unindexed queries on large tables consistently timeout.
3. Synchronous File Operations — Using fs.readFileSync() or large JSON parsing blocks the event loop. Switch to async: fs.readFile() or fs.promises.readFile(). [See file handling guide](/?guide=async-file-operations).
4. Oversized Node Modules — Install size >50MB triggers slow cold starts. Check: npm ls --depth=0. Remove unused dependencies with npm prune --production.
5. Unhandled Promise Rejections — If a promise never resolves, Vercel kills the function at 10 seconds. Always add .catch() or use async/await try-catch.
---
Version-Specific Notes
We're documenting behavior current as of January 2026. We are uncertain whether Vercel will extend the default 10-second timeout on free tier in future releases—check [official status page](https://status.vercel.com) before assuming limits. Pro plan's 900-second timeout is documented as stable.
---
Official Documentation
---
Prevention Checklist
maxDuration to actual needsnpm size)---
Found a different variation? Drop it in the comments — if you hit 504s with a unique stack trace or scenario, share details and we'll add it to this guide.