Vercel: 504 timeout on serverless functions [2026 fix]

Serverless function exceeds 10s timeout or hits memory limit. Optimize code, reduce dependencies, or increase function timeout in vercel.json.

Vercel: 504 timeout on serverless functions [2026 fix]

TL;DR

Cause: Your serverless function runs longer than the 10-second timeout limit (Pro plan) or hits memory constraints. Fix: Add "maxDuration": 60 to your vercel.json function config and optimize heavy operations with streaming or background jobs.

---

Exact Error Messages from Console Output

Here are real 504 errors you'll see in Vercel logs:

``` Error: Function execution time exceeded 10 seconds At timestamp: 2026-01-15T02:34:22.456Z FunctionName: api/generate Duration: 10003ms ```

``` HTTP/1.1 504 Gateway Timeout Content-Type: application/json {"error": "504: GATEWAY_TIMEOUT", "message": "Serverless Function timed out after 10.00 seconds"} X-Vercel-ID: sfo1::abc123-def456 ```

``` ERROR [api/process]: Task exceeded time limit Stack: at Runtime.invokeAsync (/var/task/node_modules/...) Memory Used: 1024 MB / 1024 MB (at capacity) ```

``` WARNING: Function cold start detected Initialization Duration: 2847ms Execution Duration: 7234ms Total: 10081ms (TIMEOUT) ```

``` RequestID: req_ZxY9wK8vL StatusCode: 504 ErrorCode: ERR_FUNCTION_TIMEOUT Message: Gateway timeout - function did not respond within timeout window ```

---

Broken Code vs. Fixed Code

❌ BROKEN: Default 10-second timeout with heavy processing

```javascript // api/generate.js (TIMES OUT AT 2AM) export default async function handler(req, res) { try { // Processing 50,000 database records without streaming const results = await db.query('SELECT * FROM large_table'); const processed = results.map(item => { // Complex calculations return expensiveOperation(item); }); // Generating 5MB PDF in memory const pdf = await generatePDF(processed); res.status(200).json({ data: processed, size: pdf.length }); } catch (error) { res.status(500).json({ error: error.message }); } } ```

✅ FIXED: Extended timeout + streaming + optimized queries

Step 1: Update vercel.json ```json { "functions": { "api/generate.js": { "maxDuration": 60, "memory": 3008 } } } ```

Step 2: Optimize the function ```javascript // api/generate.js (NOW HANDLES LONG OPERATIONS) export default async function handler(req, res) { try { // Stream response for large datasets res.setHeader('Content-Type', 'application/json'); res.write('['); // Batch process records instead of loading all at once const batchSize = 100; let isFirst = true; let offset = 0; while (true) { const batch = await db.query( 'SELECT * FROM large_table LIMIT ? OFFSET ?', [batchSize, offset] ); if (batch.length === 0) break; const processed = batch.map(item => expensiveOperation(item)); if (!isFirst) res.write(','); res.write(JSON.stringify(processed)); isFirst = false; offset += batchSize; } res.write(']'); res.end(); } catch (error) { res.status(500).json({ error: error.message }); } }

export const config = { maxDuration: 60 }; ```

---

Why This Happens

Free/Hobby tier: 10-second hard limit (non-configurable). Pro tier: 10-second default, configurable up to 60 seconds. Enterprise: Up to 900 seconds.

Common culprits at 2am (high traffic):

  • Database queries without pagination
  • Processing large files in memory
  • External API calls without timeouts
  • Cold starts (first invocation after deployment)
  • Dependency initialization overhead
  • ---

    Still Broken? Check These Too

    1. Cold Start Delays → [Optimize Node.js cold starts](/?guide=vercel-cold-start-fix) by reducing bundle size, removing unused dependencies, and using native modules.

    2. Database Connection Pooling → Functions create new connections per invocation. Use PgBouncer or connection pooling middleware to reuse connections and cut initialization time by 2-3 seconds.

    3. Memory Exhaustion → Set "memory": 3008 (max) in vercel.json if hitting limits. Monitor with CloudWatch or Vercel Analytics to spot memory leaks in loops or recursive functions.

    ---

    Additional Checks

  • Verify your plan tier: Free accounts can't extend beyond 10s. Upgrade to Pro.
  • Check regional latency: Your database might be in a different region. Use Vercel edge functions in the same region.
  • Review function logs: Go to Vercel dashboard → Deployments → Function Logs. Filter for duration to see actual runtimes.
  • Test locally: Run vercel dev and monitor execution time before deployment.
  • Reduce payload size: Compress responses, paginate results, and avoid sending unnecessary data.
  • ---

    Official Resources

  • [Vercel Serverless Functions Documentation](https://vercel.com/docs/functions/serverless-functions)
  • [Function Configuration & Limits](https://vercel.com/docs/functions/serverless-functions/api-specification#max-duration)
  • [Pricing & Plan Limits](https://vercel.com/pricing)
  • ---

    Quick Checklist Before Redeploying

  • [ ] Added maxDuration: 60 to vercel.json
  • [ ] Upgraded to Pro plan (if Free tier)
  • [ ] Implemented pagination or streaming
  • [ ] Removed synchronous heavy operations
  • [ ] Set database query timeout (5s recommended)
  • [ ] Tested with vercel dev locally
  • [ ] Monitored function logs in Vercel dashboard
  • 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