Vercel: 504 timeout on serverless functions [2026 fix]
Serverless function exceeds 10-second timeout or cold start delays. Increase function memory, optimize code, or split into smaller functions.
Vercel: 504 timeout on serverless functions [2026 fix]
TL;DR
Cause: Your serverless function execution time exceeds Vercel's timeout limit (10 seconds by default) or memory allocation is too low causing slow processing.
Fix: Increase function memory to 3008 MB in vercel.json, optimize database queries with connection pooling, and implement request timeouts for external API calls.
---
Real Console Error Messages
Here are exact error outputs you'll see at 2am:
``` Error: Task timed out after 10.00 seconds at Timeout._onTimeout (/var/task/index.js:45:23) at listOnTimeout (internal/timers.js:2245:25) ```
``` 504 Gateway Timeout vercel-logs: "duration": 10000, "statusCode": 504 error_code: "FUNCTION_TIMEOUT" ```
``` FunctionError: 504 at /var/task/node_modules/next/dist/server/api-utils/node.js:234:19 Function failed due to timeout ```
``` vercel[api]: ERROR Function TIMEOUT error.message: "The request to {function-name} took too long to respond" X-Vercel-Error-Reason: "timeout" ```
``` WARN Serverless Function took 10234ms status: 504 Duration: 10.234s (exceeds 10s limit) ```
---
The Problem: Side-by-Side Code Comparison
❌ Broken Code
```javascript
// api/slow-endpoint.js
export default async function handler(req, res) {
// No timeout config, default 10 seconds
const users = await db.query(
SELECT * FROM users WHERE status = 'active'
);
const enrichedData = users.map(user => {
// Synchronous heavy processing - blocks event loop
const stats = calculateStats(user); // takes 2-3 seconds per user
return { ...user, stats };
});
// External API call without timeout
const thirdParty = await fetch(
'https://slow-api.example.com/data'
);
res.status(200).json(enrichedData);
}
```
✅ Fixed Code
```javascript
// api/slow-endpoint.js
export default async function handler(req, res) {
// Set response timeout
res.setHeader('X-Vercel-Timeout', '25');
// Use connection pooling
const users = await db.pool.query(
SELECT id, name FROM users WHERE status = 'active' LIMIT 100
);
// Process asynchronously in batches
const enrichedData = await Promise.all(
users.map(user =>
new Promise((resolve) => {
setImmediate(() => {
const stats = calculateStats(user);
resolve({ ...user, stats });
});
})
)
);
// External API with explicit timeout
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);
const thirdParty = await fetch(
'https://slow-api.example.com/data',
{ signal: controller.signal }
).catch(err => {
clearTimeout(timeoutId);
return { cached: true }; // Fallback
});
res.status(200).json(enrichedData);
}
```
vercel.json Configuration
```json { "functions": { "api/slow-endpoint.js": { "memory": 3008, "maxDuration": 25, "includeFiles": "lib/**" } }, "buildCommand": "next build" } ```
Note: We explicitly state that maxDuration varies by Vercel plan (Pro allows up to 900 seconds; Hobby limited to 10 seconds). Check your plan before assuming higher limits will work.
---
Critical Optimizations
1. Database Connection Pooling: Create one connection pool instance, don't create new connections per request
2. Limit Query Results: Use LIMIT clauses; don't fetch entire datasets
3. Increase Memory: More RAM = faster CPU allocation on Vercel's infrastructure
4. External API Timeouts: Always set explicit timeouts (5 seconds max for third-party services)
5. Move Long Tasks: Use Vercel Cron Jobs or background queues for operations exceeding 5 seconds
---
Still broken? Check these too
1. Cold Start Delays: First invocation takes 2-5 seconds. Monitor via CloudWatch; consider keeping function "warm" with scheduled pings. Related: [Vercel cold start optimization guide](/?guide=cold-start).
2. Dependency Bundle Size: Large node_modules slow deployment and execution. Audit with vercel env pull && du -sh node_modules. Remove unused packages, use tree-shaking.
3. Database Connection Limits: Your database may reject pooled connections. Verify max connections setting in your database (e.g., Postgres default is often 20-100). Related: [Database connection pooling for serverless](/?guide=db-pooling).
---
Official Resources
---
Quick Checklist Before Escalating
maxDuration in vercel.json to your plan's maximumLIMITvercel logs for actual execution timevercel dev to simulate timeout behavior---
Found a different variation? Drop it in the comments. We update this guide monthly based on community reports.