| | |

Netlify 13 ๐ŸŒ Background & Scheduled Functions โ€” Handling long-running tasks and cron-based schedules

โฑ๏ธ Estimated read: 8 min | |

Standard Netlify functions have a strict execution timeout, typically 10 seconds. This is sufficient for most API requests, but inadequate for heavy lifting like image processing, bulk database operations, or sending large email batches. To solve this, Netlify provides specialized function patterns: Background Functions and Scheduled Functions. Background functions enable long-running execution (up to 15 minutes) for tasks triggered by the client, while Scheduled Functions provide a robust cron-based system for executing tasks at predefined intervals, independent of user activity.

These two patterns effectively separate the “request-response” lifecycle from “processing” lifecycles. By offloading work to these patterns, you keep your main UI responsive and your user-facing API routes fast. This chapter explores the implementation of both patterns, how to configure them using file naming conventions and the Netlify scheduler, and how to manage state between these asynchronous processes.

Key point: Background functions allow asynchronous execution for up to 15 minutes by bypassing the standard request-response timeout, while Scheduled functions use a cron-like schedule to trigger execution automatically without needing an external HTTP request.


The 10-second request timeout problem.
Most standard serverless environments enforce strict timeouts to keep functions cheap and fast. If your logic needs to process a CSV file, resize 50 images, or update thousands of rows in a database, a 10-second limit will cause your function to crash. Background functions exist to extend this window up to 15 minutes, allowing for I/O-intensive work.

The fire-and-forget problem.
Users should not have to wait for your server to finish background processing. If a user triggers an action that involves sending an email, generating a PDF, and syncing with a CRM, forcing them to wait for these to complete results in a poor user experience. Background functions allow you to acknowledge the request immediately while the work continues in the background.

The periodic maintenance problem.
Many applications require routine tasks: cleaning up expired database sessions, aggregating analytics, or fetching fresh data from third-party APIs. Without Scheduled functions, you would have to build or pay for an external cron service (like GitHub Actions or a dedicated server) to ping your API endpoints. Scheduled functions bring this capability natively into the Netlify platform.

The resource contention problem.
Running heavy background tasks on the same compute resource as your user-facing API can degrade performance for active users. Because background and scheduled functions are decoupled from the main request flow, they can be scaled and managed separately, ensuring that a spike in background processing doesn’t crash your main website.

The reliability and retry problem.
Complex tasks often fail due to transient network errors. By isolating these tasks into their own execution environments, you can implement better error handling and retry logic specific to that task, without impacting the state of your main application’s request handlers.


a. Background Functions

A Background function is a specific variant of a standard Netlify function designed for long-running execution. You create one by adding the .background suffix to your file name (e.g., process-video.background.js). When a client triggers this function, Netlify returns a 202 Accepted status code immediately, and the function continues to run in the background for up to 15 minutes.

// netlify/functions/process-data.background.ts
import type { Handler } from "@netlify/functions";

export const handler: Handler = async (event, context) => {
  // Heavy task here
  await performHeavyTask();

  // No need to worry about the 10s timeout
  return { statusCode: 200 };
};

Because the client receives a 202 response immediately, they do not wait for the code inside the function to finish. This is ideal for tasks that don’t need to return data to the user, such as notifying an external service or performing database cleanup.

b. Scheduled Functions

Scheduled functions are triggered based on a cron expression defined in your netlify.toml file. They don’t require an HTTP request to execute. Netlify invokes them on your specified schedule. This is perfect for recurring tasks. You define the schedule and link it to your function handler, which receives a payload containing the next run time and the previous run time.

// netlify/functions/daily-cleanup.ts
import { schedule } from "@netlify/functions";

export const handler = schedule("@daily", async (event) => {
  // Logic runs automatically every 24 hours
  await cleanupExpiredSessions();

  return { statusCode: 200 };
});

The schedule wrapper provides a built-in way to handle cron strings. You can use standard cron syntax (e.g., * * * * * for every minute) or descriptive strings like @daily, @weekly, or @hourly. The function runs as a standard Netlify function but is invoked by the platform’s scheduler.

c. The Async Architecture

The power of these patterns lies in decoupling. Instead of one monolithic function doing everything, you break your logic down. Your API handler receives the request, stores the intent in a database or queue, and then potentially triggers a background function or simply sets the state for a scheduled function to pick up later.

// Using a function to trigger a process
export const handler = async (event) => {
  // 1. Save data to DB
  await saveRequest(event.body);

  // 2. We don't perform heavy work here
  // The background function is called as an endpoint
  await fetch("/.netlify/functions/process-data.background");

  return { statusCode: 202 }; // Accepted
};

This ensures your application remains fast. If the background task fails, you can log it, retry it, or notify the user via a status dashboard. You are no longer chaining promises in a way that risks blocking the user’s browser or hitting HTTP timeouts.


Complete Example Session

// ============================================
// PART 1: BACKGROUND FUNCTION (15m Limit)
// ============================================
// netlify/functions/sync-db.background.ts
export const handler = async () => {
  console.log("Starting sync...");
  await expensiveDatabaseOperation(); // Can take > 10s
  return { statusCode: 200 };
};

// ============================================
// PART 2: SCHEDULED FUNCTION (CRON)
// ============================================
// netlify/functions/cleanup.ts
import { schedule } from "@netlify/functions";

export const handler = schedule("@daily", async () => {
  console.log("Daily cleanup started");
  await deleteOldFiles();
  return { statusCode: 200 };
});

// ============================================
// PART 3: NETLIFY.toml CONFIG
// ============================================
[functions]
  # Optional: Configure default runtime
  node_bundler = "esbuild"

// ============================================
// PART 4: CLIENT-SIDE TRIGGER
// ============================================
async function triggerBackground() {
  // Calling the background function is just a fetch
  await fetch("/.netlify/functions/sync-db.background");
  alert("Sync started in background!");
}

The parts above cover creating a background function with the suffix, implementing a scheduled function with cron syntax, the configuration file, and how a client triggers the background process.


Quick Reference

Function Types

TypeTriggerMax Duration
BackgroundHTTP Request15 minutes
ScheduledCron Time10 seconds (standard)
StandardHTTP Request10 seconds

Cron Syntax Examples

ScheduleSyntax
Daily@daily
Hourly@hourly
Every 5 mins*/5 * * * *
Midnight0 0 * * *

Naming Conventions

FeatureNaming Requirement
Backgroundfilename.background.js
ScheduledAny name (uses schedule wrapper)

Best Practices

โœ… Do This:

// Return 202 for background tasks
return { statusCode: 202 };                                   // โœ…

// Log frequently for observability
console.log("Task started");                                  // โœ…

// Handle idempotency (if cron runs twice)
if (isAlreadyProcessed()) return;                             // โœ…

// Use environment variables for secrets
const apiKey = process.env.API_KEY;                           // โœ…

โŒ Don’t Do This:

// Wait for background tasks to finish
await performHeavyWork(); // Don't do this in main API       // โŒ

// Rely on memory state
let data = []; // Memory clears between invocations          // โŒ

// Hardcode cron times
// (Use env variables or config)                              // โŒ

// Use background functions for short tasks
// (Adds unnecessary overhead)                                // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Timeout errorTask takes > 10s in standardUse .background
Cron failureInvalid cron syntaxCheck crontab.guru
Race conditionsMultiple instances runImplement database locks
Logic errorsNo logsUse console.log heavily
HTTP dependencyBackground tasks ignore responseUse async queues/DB

Real-World Examples

1. Newsletter sending

export const handler = schedule("@weekly", async () => { ... });

2. DB Cleanup

export const handler = schedule("0 0 * * *", async () => { ... });

3. Image processing

// process-image.background.ts

4. Clearing cache

await purgeCache();

5. Triggering by ID

fetch("/.netlify/functions/task.background?id=123");

6. Database backup

export const handler = schedule("@daily", async () => { ... });

7. Checking run time

const { next_run } = event;

8. Retrying failed logic

try { await task(); } catch { await retry(); }

9. Logging to external service

await logger.send(data);

10. Skipping logic

if (!shouldRun) return { statusCode: 200 };

Visual

Standard Request vs Background

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  USER โ”€โ”€โ–บ API โ”€โ”€โ–บ WAIT โ”€โ”€โ–บ RESPONSE          โ”‚
โ”‚                                              โ”‚
โ”‚  USER โ”€โ”€โ–บ BACKGROUND โ”€โ”€โ–บ 202 ACCEPTED        โ”‚
โ”‚                โ”‚                             โ”‚
โ”‚                โ””โ”€โ–บ PROCESSING (15 min)       โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Cron Trigger Flow

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  NETLIFY SCHEDULER                           โ”‚
โ”‚       โ”‚                                      โ”‚
โ”‚       โ–ผ (Tick)                               โ”‚
โ”‚  SCHEDULED FUNCTION                          โ”‚
โ”‚       โ”‚                                      โ”‚
โ”‚       โ””โ”€โ–บ RUNS TASK                          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Lifecycle Difference

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  STANDARD (10s)    BACKGROUND (15m)          โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”     โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”‚
โ”‚  โ”‚ Execution โ”‚     โ”‚      Execution       โ”‚  โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜     โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Decoupled Architecture

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  MAIN APP โ”€โ”€โ–บ DB/QUEUE โ—„โ”€โ”€ BACKGROUND FUNC   โ”‚
โ”‚                                              โ”‚
โ”‚  Ensures API remains fast and responsive     โ”‚
โ”‚  while tasks process out-of-band.            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Background limit15 minutes
Scheduled limit10 seconds
Background triggerHTTP Request
Scheduled triggerTime (Cron)
Standard limit10 seconds
Background extension.background suffix

Key takeaways:

  • Use Background functions for I/O. They are perfect for tasks that take longer than 10 seconds, such as processing large files or bulk data operations, by extending execution time to 15 minutes.
  • Use Scheduled functions for automation. They replace external cron jobs and run on a schedule defined by cron syntax, ideal for maintenance and cleanup tasks.
  • Decouple your architecture. Always separate long-running logic from user-facing API routes to keep your UI responsive and avoid timeout errors.
  • Idempotency is crucial. Because scheduled functions and retries may cause tasks to run more than once, ensure your logic is safe to repeat.
  • Naming matters. The .background suffix is a functional requirement for Netlify to recognize the long-running execution mode.

Remember: The primary goal of both Background and Scheduled functions is to remove the “wait” from your user’s experience and the “timeout” from your server’s constraints. By moving heavy, non-blocking work into these specialized execution environments, you build more robust, scalable, and responsive applications that handle heavy workloads gracefully.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!