Vercel: 504 timeout on serverless functions [2026 fix]

Serverless functions exceed 10s timeout or memory limits. Increase function timeout, optimize code, or split into async workers.

TL;DR

Cause: Your Vercel serverless function exceeded the 10-second timeout limit or hit memory constraints during execution.

Fix: Increase function timeout in vercel.json, optimize database queries, or offload long tasks to background jobs.

---

Real Console Error Messages

``` 504 Gateway Timeout Failed to get a response from the function within the timeout period. ```

``` ERROR: Task timed out after 10.00 seconds Function execution took 12843ms to complete ```

``` FaaSError: Function crashed or timed out Status: 504 Gateway Timeout - Vercel Functions ```

``` Node.js process exited with code 137 Out of memory: Kill process (memory usage: 1024MB) ```

``` WARNING: Execution timeout will occur at 10000ms Function still running after 9800ms ```

---

The Problem: Broken Code Example

❌ Broken: Unoptimized Database Query

```javascript // api/users.js - Vercel Serverless Function export default async function handler(req, res) { const db = require('pg'); const client = new db.Client({ connectionString: process.env.DATABASE_URL, }); await client.connect(); // Fetching ALL users without pagination - causes 504 const result = await client.query('SELECT * FROM users;'); // Additional slow operations const enriched = result.rows.map(user => { // Synchronous processing blocks execution return complexCalculation(user); }); await client.end(); res.status(200).json(enriched); } ```

✅ Fixed: Optimized with Timeout & Pagination

```javascript // api/users.js - Production Ready import { Pool } from 'pg';

const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 5, // Connection pooling idleTimeoutMillis: 30000, });

export default async function handler(req, res) { const page = parseInt(req.query.page || '1'); const limit = 20; const offset = (page - 1) * limit; try { // Paginated query with specific columns const result = await Promise.race([ pool.query( 'SELECT id, name, email FROM users LIMIT $1 OFFSET $2;', [limit, offset] ), new Promise((_, reject) => setTimeout(() => reject(new Error('DB query timeout')), 8000) ) ]); res.status(200).json({ data: result.rows, page, limit, }); } catch (error) { console.error('Database error:', error); res.status(503).json({ error: 'Service temporarily unavailable' }); } } ```

---

Solution 1: Increase Function Timeout

Create or update vercel.json at your project root:

```json { "functions": { "api/heavy-computation.js": { "maxDuration": 30 } } } ```

Important Note: Maximum timeout varies by Vercel plan. We're uncertain if this still applies to 2026 Pro tier pricing—check the official docs link below for your current plan limits.

---

Solution 2: Offload to Background Jobs

Instead of waiting for long operations:

```javascript // api/process-batch.js import { sendToQueue } from '@vercel/functions';

export default async function handler(req, res) { try { // Queue job instead of processing inline await sendToQueue({ name: 'process-large-dataset', payload: req.body, delay: 0, }); res.status(202).json({ message: 'Processing queued' }); } catch (error) { res.status(500).json({ error: error.message }); } } ```

---

Solution 3: Optimize Memory Usage

  • Use connection pooling (shown above)
  • Stream large file responses instead of buffering
  • Split data processing into chunks
  • Avoid loading entire datasets into memory
  • ---

    Still broken? Check these too

    1. [Cold Start Issues](/guide=vercel-cold-start-performance) – Functions timeout after inactivity due to initialization delays. Solution: Use Vercel's Warm Invocations or implement keep-alive pings.

    2. Environment Variable Loading – Missing DATABASE_URL or API credentials cause silent hangs. Verify all env vars are set: vercel env list and check .env.local.

    3. [External API Timeouts](/guide=external-api-failures) – Your function calls a slow third-party service. Add request timeouts and implement retry logic with exponential backoff.

    4. Memory Leaks – Global variables accumulating data across invocations. Initialize variables inside handlers, not at module level.

    5. Large Dependency Bundles – Dependencies bloat function size, increasing cold start time. Run vercel analytics to audit bundle size.

    ---

    Debugging Checklist

  • Check Vercel logs: vercel logs command
  • Monitor function duration in Vercel Dashboard → Analytics
  • Use console.time() to profile slow sections
  • Test locally with vercel dev before deploying
  • Check network tab for slow external requests
  • ---

    Official Documentation

    📖 [Vercel Functions Documentation](https://vercel.com/docs/functions/serverless-functions) 📖 [Vercel Timeout Configuration](https://vercel.com/docs/functions/serverless-functions/max-duration)

    ---

    Found a different variation? Drop it in the comments below. Share your 504 error scenario and solution to help future developers at 2am.

    🔥 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