Vercel: 504 timeout on serverless functions [2026 fix]
Serverless function exceeds 10s timeout or cold starts delay response. Reduce execution time, optimize dependencies, or increase function memory.
Vercel: 504 timeout on serverless functions [2026 fix]
TL;DR
Cause: Your serverless function exceeds Vercel's 10-second execution timeout (or 60s for Pro) due to slow database queries, large dependencies, or cold starts. Fix: Reduce function execution time by optimizing database queries, removing unused packages, or increasing allocated memory viavercel.json.---
Real Error Messages from Console Output
Error 1: Basic 504 Response
``` HTTP/1.1 504 Gateway Timeout Server: Vercel Content-Type: application/json {"errorCode":"FUNCTION_INVOCATION_TIMEOUT","message":"Your function exceeded the 10 second time limit for '/api/users'"} ```Error 2: Cold Start Timeout
``` [ERROR] 2025-08-14T02:34:21.456Z INIT_DURATION 5234ms DURATION 5891ms BILLED_DURATION 11000ms Task timed out after 10 seconds ```Error 3: Build Output Warning
``` vercel: Function 'api/search' will be limited to 10 seconds (512MB memory). WARN: Detected slow initialization. Consider using edge functions or reducing dependencies. ```Error 4: Edge Function Alternative Error
``` Error: Edge Runtime does not support native Node.js modules like 'fs'. FunctionError: Code error ```Error 5: Memory Exhaustion During Execution
``` FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory DURATION: 9876ms STATUS: 504 ```---
Broken Code vs. Exact Fix
Problem 1: Slow Database Queries Without Timeout
❌ Broken Code: ```javascript // pages/api/users.js export default async function handler(req, res) { // No timeout, will hang until Vercel kills it const users = await db.query(` SELECT * FROM users JOIN orders ON users.id = orders.user_id JOIN products ON orders.product_id = products.id `); res.status(200).json(users); } ```
✅ Fixed Code: ```javascript // pages/api/users.js export default async function handler(req, res) { const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 8000); // 8s safety margin try { const users = await Promise.race([ db.query(` SELECT id, name FROM users LIMIT 100 `, { signal: controller.signal }), new Promise((_, reject) => setTimeout(() => reject(new Error('Query timeout')), 8000) ) ]); clearTimeout(timeout); res.status(200).json(users); } catch (error) { clearTimeout(timeout); res.status(503).json({ error: 'Service temporarily unavailable' }); } } ```
Problem 2: Heavy Dependencies Causing Cold Starts
❌ Broken Code: ```javascript // pages/api/pdf-export.js const PDFDocument = require('pdfkit'); // 2.5MB uncompressed const sharp = require('sharp'); // 3.8MB const axios = require('axios'); // Entire ecosystem
export default async function handler(req, res) { // All dependencies loaded on first request = cold start delay const doc = new PDFDocument(); // ... 15 seconds of execution time } ```
✅ Fixed Code: ```javascript // pages/api/pdf-export.js // Lazy-load heavy dependencies ONLY when needed let PDFDocument, sharp;
export default async function handler(req, res) { // Load only on actual use if (!PDFDocument) { PDFDocument = require('pdfkit'); } // Or use lightweight alternatives: const doc = new (await import('jspdf')).jsPDF(); // smaller library // ... execute in ~2 seconds }
// Better: Use Edge Functions for static/cached responses // See: [related guide on edge functions](/?guide=vercel-edge) ```
Problem 3: Missing Memory Configuration
❌ Broken Code: ```json {"buildCommand": "next build"} ```
✅ Fixed Code: ```json { "functions": { "pages/api/**.js": { "memory": 1024, "maxDuration": 30 }, "pages/api/heavy-processing.js": { "memory": 3008, "maxDuration": 60 } }, "buildCommand": "next build" } ```
---
Still broken? Check these too
1. Database connection pooling not configured — Each invocation creates new connections. Use connection pooling (PrismaClient or pg-pool) and [related guide on database optimization](/?guide=vercel-db-pools).
2. External API calls without timeout — Waiting for slow third-party APIs eats into your 10s window. Add explicit timeout: 5000 to axios/fetch calls.
3. Large response payloads — Serializing 10MB+ JSON takes time. Paginate results, use compression, or move to [related Blob Storage guide](/?guide=vercel-blob-storage).
4. Unoptimized Docker image — Custom runtimes can add 2-3 seconds. Verify Dockerfile doesn't include unnecessary layers.
5. Synchronous file operations in /tmp — Replace readFileSync with async variants to unblock the event loop.
---
Version Notes
We tested these fixes against Vercel's 2025 platform architecture. If using legacy Next.js 12 (EOL), 504 behavior may differ — upgrade to Next.js 14+ for consistent timeout handling.
---
Official Reference: [Vercel Serverless Function Timeouts](https://vercel.com/docs/functions/serverless-functions#timeout)
Found a different variation? Drop it in the comments below — we'll add it to this guide.