The short answer: Serverless functions are built to answer requests, not to run long work in the background, so match the tool to the job. For a few seconds of follow-up work after a response (logging, analytics, cache warming), use
after()in Next.js 15.1 and later, orwaitUntilon Vercel. For work on a schedule, use cron jobs that call a protected route. For anything that must not be lost, takes a long time, or needs retries (emails, imports, AI processing), put it on a durable queue or a hosted job service, make every job idempotent, and track its status so users and operators can see what happened.
Sooner or later, every web app needs to do something that shouldn't happen while the user waits. Send a welcome email. Resize an uploaded image. Generate a report. Summarise a document with an LLM. Sync data from a third-party API every night. On a traditional server, you'd start a worker process and push jobs to it. On a serverless platform, there's no long-running process to push to, and that's where teams get stuck.
The usual first attempt is to start the work and return the response without waiting for it. On serverless, that often fails silently: once the response is sent, the platform is free to freeze or stop the function, and the unfinished work disappears. Sometimes it works locally and in testing, and only fails under real traffic, which makes it especially confusing.
This guide walks through the options for background work on serverless platforms, with Next.js and Vercel as the running example: what each is good for, its limits, and the reliability practices (idempotency, retries, status tracking) that apply to all of them.
The serverless constraint
A serverless function handles a request and is allowed to run until it sends its response, up to a maximum duration set by the platform and your plan. After the response, the platform may keep the instance warm for the next request, but it makes no promise to keep running code you left behind. Promises you didn't await are not guaranteed to finish.
That leaves three questions to ask about any piece of background work:
- How long does it take? Milliseconds, seconds, minutes or longer?
- What happens if it's lost? A missing analytics event is tolerable; a missing order confirmation email is not.
- What triggers it? A user request, a schedule, or another system's event?
The answers point to the right tool.
Option 1: after() and waitUntil for short follow-up work
For small tasks that should run after the response, both Next.js and Vercel give you a supported way to extend the function's life. Next.js provides after(), imported from next/server and stable since Next.js 15.1. It schedules a callback to run after the response (or prerender) finishes, without blocking it, and works in Server Components, Server Functions, route handlers and middleware.
// app/api/signup/route.ts
import { after } from "next/server";
export async function POST(req: Request) {
const input = await req.json();
const user = await createUser(input);
after(async () => {
// Runs after the response is sent; the user doesn't wait for it.
await analytics.track("signup", { userId: user.id });
await warmRecommendationsCache(user.id);
});
return Response.json({ id: user.id }, { status: 201 });
}
On Vercel, the underlying primitive is waitUntil from the @vercel/functions package, which tells the platform to keep the function alive until a given promise settles. Vercel's documentation recommends after() for Next.js 15.1 and later; waitUntil is useful in other frameworks or plain functions.
Know the limits. Work scheduled this way still counts against the function's maximum duration, it runs in the same instance, and if it throws or the function hits its time limit, nothing retries it. That makes it right for best-effort, short work: logging, analytics, cache warming, updating a "last seen" timestamp. It's the wrong tool for anything that must happen, such as sending a receipt or charging a card.
Option 2: cron jobs for scheduled work
Work that runs on a schedule (nightly cleanups, daily digests, hourly syncs, publishing scheduled content) fits cron jobs. On Vercel, you define cron jobs in your project configuration; at each scheduled time, the platform sends a request to a route in your app, which does the work like any other request.
{
"crons": [
{ "path": "/api/cron/daily-digest", "schedule": "0 7 * * *" }
]
}
A few rules keep cron routes safe and reliable:
- Protect the route. A cron endpoint is a public URL. Vercel can send a secret in an authorisation header when you set a
CRON_SECRETenvironment variable; check it and reject anything else, so strangers can't trigger your jobs. - Remember time zones. Cron schedules are usually evaluated in UTC. A job meant to run at 7am for users in India or California needs its schedule adjusted accordingly.
- Make runs idempotent. A run might be retried, delayed or occasionally duplicated. Design each run so that running it twice is harmless, for example by processing "all unpublished posts due before now" rather than "the posts for this minute."
- Fan out big work. If a nightly job has to process thousands of items, the cron run should enqueue them rather than process them all within one function's time limit.
Option 3: queues and job services for work that must happen
For work that must not be lost, takes longer than a request should, or needs retries, you want a durable queue: the request records the job somewhere persistent and returns immediately, and a separate worker processes the job, retrying if it fails.
On serverless platforms, this usually takes one of three forms:
- Hosted job and workflow services built for serverless apps. You send an event or enqueue a job from your request handler, and the service calls a route in your app to run it, handling retries, delays, concurrency limits and scheduling. Many also support multi-step workflows, where each step is retried independently and the overall job can run far longer than any single function. Inngest, Trigger.dev and Upstash QStash are examples of this category; compare their pricing, limits and data handling for your needs.
- Cloud provider queues such as Amazon SQS or Google Cloud Tasks, with a function or container as the consumer. Powerful and well understood, with more setup.
- A database-backed queue. A jobs table in Postgres, with workers claiming jobs using
SELECT … FOR UPDATE SKIP LOCKED. This is simple and transactional (the job is created in the same transaction as the data it relates to), but it needs something to run the workers regularly, such as a cron job or a small always-on process.
Whichever you choose, the request handler's job becomes simple: validate the input, record the job, and return a response that says the work has been accepted.
// app/api/reports/route.ts
export async function POST(req: Request) {
const session = await requireSession();
const { range } = await req.json();
const report = await db.reports.create({
data: { userId: session.userId, range, status: "queued" },
});
await jobs.enqueue("generate-report", { reportId: report.id }); // durable
return Response.json({ reportId: report.id, status: "queued" }, { status: 202 });
}
The transactional outbox
One subtle failure: you save a record to your database, then try to enqueue a job, and the enqueue fails. Now the record exists without its job. The reverse can happen too. The outbox pattern fixes this: write the job to an "outbox" table in the same database transaction as the record, and have a separate process (a cron run or worker) move outbox rows to the queue. Because both writes share one transaction, you never get one without the other. A database-backed queue gets this property for free.
Reliability rules for every job
Whatever runs your jobs, the same practices separate reliable systems from flaky ones.
Make jobs idempotent
Most queues deliver messages at least once. A worker can crash after doing the work but before acknowledging it, and the job runs again. So every job must be safe to run twice. Common techniques: key each job by a business identifier, record completion and check it at the start, use unique constraints so duplicate inserts fail harmlessly, and pass idempotency keys to external APIs such as payment and email providers.
Retry with backoff, and stop eventually
Transient failures (a timeout, a rate limit, a brief outage) should be retried with exponential backoff and jitter. Permanent failures (invalid data, a deleted record) should not be retried. After a set number of attempts, move the job to a dead-letter queue or mark it failed, alert someone, and keep its input so it can be inspected and replayed. The guide on handling rate limits, retries and fallbacks covers backoff in detail; it applies to jobs just as much as to API calls.
Track status where users can see it
When work moves to the background, the user loses the natural feedback of waiting for a response. Give it back: store each job's status (queued, running, completed, failed) with the record it relates to, show it in the UI, and notify the user when it's done, by email, an in-app notification or a live update. "Your report is being generated" with a progress indicator beats a button that seems to do nothing.
Respect limits and concurrency
Background jobs often call rate-limited services. A thousand jobs released at once will hit those limits immediately. Set concurrency limits on workers, or use your job service's throttling, so jobs proceed at a sustainable pace.
Make jobs observable
Log each job's start, finish, duration, attempts and outcome with its ID, and connect it to the request that created it with a shared trace or correlation ID. Alert on failure rates and queue depth, not individual failures. When a user says "my import never finished," you should be able to find their job in seconds.
Long-running and AI workloads
AI features are a common reason to need background jobs: summarising long documents, generating embeddings for a large upload, running an agent that takes many steps, or processing a batch with an LLM. These are often slow, depend on rate-limited APIs and can fail midway.
- Split long work into steps. Chunk the document, embed each chunk as its own step or job, then combine. A failure retries one step, not the whole thing.
- Checkpoint progress. Store intermediate results, so a retry resumes rather than starts over and pays for the same tokens twice.
- Use provider batch APIs for large, non-urgent volumes; they're often cheaper and handle throughput for you, as described in the guide to cutting LLM API costs.
- Stream progress to the user if they're waiting, by updating job status as steps complete.
For interactive AI responses where the user is waiting and watching text appear, a background job is usually the wrong shape; streaming the response directly, covered in the guide to streaming LLM responses in Next.js, is better. Background jobs suit work that can finish while the user does something else.
Choosing between the options
| Work | Example | Use |
|---|---|---|
| Short, best-effort, after a response | Analytics, logging, cache warming | after() or waitUntil |
| On a schedule | Nightly cleanup, daily digest, scheduled publishing | Cron job calling a protected route |
| Must happen, needs retries | Receipts, webhooks to other systems, imports | Durable queue or job service |
| Long or multi-step | Document processing, AI pipelines, large exports | Workflow service with steps, or queue plus checkpoints |
| Heavy compute or very long running | Video encoding, large model inference | A dedicated worker service or container outside the request runtime |
It's fine to use several. A typical app might use after() for analytics, a cron job for nightly maintenance, and a job service for emails and document processing.
A worked example: processing an uploaded document
Here's how the pieces combine for a common feature: a user uploads a PDF, and the app extracts its text, splits it into chunks, embeds them for search and generates a summary.
- The upload request stores the file in object storage, creates a
documentsrow with statusqueued, enqueues aprocess-documentjob with the document ID, and returns 202 immediately. The UI shows the document with a "processing" badge. - Step one: extract text. The job loads the file, extracts text and saves it. If extraction fails because the file is corrupt, that's a permanent failure: mark the document failed with a clear message and don't retry.
- Step two: chunk and embed. Each batch of chunks is embedded as a separate step, with embeddings saved as they complete. A rate-limit error retries just that batch, with backoff.
- Step three: summarise. An LLM call generates a summary from the extracted text, saved to the document row.
- Finish. The document's status becomes
ready, and the user gets a notification. If any step exhausts its retries, the status becomesfailed, an alert fires, and the job's input is kept for replay.
Every step is idempotent: re-running extraction overwrites the same text, chunks are keyed by document and position, and the summary is saved against the document ID. So a retry at any point produces the same final result, and the user sees accurate status throughout.
Testing background work
Background code is easy to under-test, because it's out of sight. A few habits help:
- Keep job logic in plain functions that take an input and return a result, separate from the queue wiring, so you can unit-test them directly.
- Test idempotency explicitly by running each job twice with the same input and asserting a single side effect.
- Test failure paths: a transient error retries, a permanent error marks the job failed, and the dead-letter path preserves the input.
- Run jobs synchronously in integration tests, using your job service's local development mode or a test adapter, so tests can assert on the end state.
- Exercise cron routes by calling them with and without the secret, and by running them twice in a row.
Common mistakes
- Unawaited promises after the response, which may never finish on serverless. Use
after(),waitUntilor a queue. - Using
after()for work that must happen. It has no retries. Use a durable queue. - Unprotected cron routes that anyone can trigger.
- Non-idempotent jobs that send duplicate emails or charges when a delivery repeats.
- Enqueueing outside the database transaction, leaving records without jobs or jobs without records. Use an outbox.
- Processing everything in one cron run, which times out as data grows. Fan out to a queue.
- Invisible failures, with no status in the UI, no alerts and no way to replay a failed job.
Building a small database-backed queue
If you already run Postgres and want to avoid another service, a jobs table can serve as a perfectly good queue for modest volumes. The key ingredient is FOR UPDATE SKIP LOCKED, which lets several workers claim jobs at the same time without picking the same one or waiting on each other's locks.
CREATE TABLE jobs (
id bigserial PRIMARY KEY,
kind text NOT NULL,
payload jsonb NOT NULL,
status text NOT NULL DEFAULT 'queued', -- queued | running | done | failed
attempts int NOT NULL DEFAULT 0,
run_after timestamptz NOT NULL DEFAULT now(),
last_error text,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX jobs_ready ON jobs (run_after) WHERE status = 'queued';
-- Claim up to 10 ready jobs atomically.
UPDATE jobs SET status = 'running', attempts = attempts + 1
WHERE id IN (
SELECT id FROM jobs
WHERE status = 'queued' AND run_after <= now()
ORDER BY run_after
LIMIT 10
FOR UPDATE SKIP LOCKED
)
RETURNING id, kind, payload, attempts;
A worker (a cron-triggered route, for example, running every minute) claims a batch, processes each job, and marks it done. On failure, it sets the status back to queued with a later run_after for backoff, or to failed once attempts reach the limit. Because jobs are rows, you can create them in the same transaction as the data they relate to, which gives you the outbox guarantee automatically.
Two extra details make it dependable. First, recover stuck jobs: a worker that crashes mid-job leaves a row in running, so record when each job was claimed and return jobs that have been running far longer than expected to the queue. Second, keep the table small by deleting or archiving completed jobs regularly, so the claim query stays fast.
This approach works well up to a fair volume of jobs and keeps everything in one database you already back up and monitor. When you need high throughput, complex workflows, or fine-grained scheduling across many job types, a dedicated job service starts to pay for itself.
Local development and preview deployments
Background work is often the hardest part of an app to run locally. Cron jobs don't fire on your laptop, and queue services need somewhere to call back to. Most hosted job services provide a local development server that receives events and calls your app on localhost, which is worth setting up early. For cron routes, a simple script or an npm command that calls the route with the secret lets you trigger runs on demand. Be careful with preview deployments: decide whether they should run scheduled jobs and process real queues at all, and point them at separate queues or test data so a preview build can't send real emails to customers or process production jobs with untested code.
Frequently asked questions
How do I run background jobs on Vercel?
Use after() in Next.js 15.1 and later, or waitUntil from @vercel/functions, for short best-effort work after a response. Use Vercel Cron Jobs to call a protected route on a schedule. For work that must not be lost or takes a long time, enqueue it to a durable queue or a hosted job service that calls your app to process it, with retries.
What does after() do in Next.js?
after(), imported from next/server, schedules work to run after a response or prerender has finished, so the user doesn't wait for it. It works in Server Components, Server Functions, route handlers and middleware, and is suited to short tasks such as logging and analytics. It doesn't retry failed work.
Why does my background task stop on serverless?
Serverless platforms only guarantee that a function runs until it sends its response. Work started without being awaited may be frozen or stopped once the response is sent. Use after() or waitUntil to extend the function's lifetime for short work, or move longer or critical work to a queue.
Do I need a queue for background jobs?
You need one for work that must not be lost, needs retries, takes longer than a request should, or must be rate-limited. For short, best-effort tasks, after() or waitUntil is enough, and scheduled work can use cron jobs, which can enqueue larger workloads.
How do I make background jobs reliable?
Make every job idempotent so repeated deliveries are harmless, retry transient failures with exponential backoff and a maximum number of attempts, send exhausted jobs to a dead-letter queue with alerts, record jobs in the same transaction as their data using an outbox, and track job status so users and operators can see progress and failures.
The takeaway
Serverless platforms are excellent at answering requests and deliberately bad at running leftover work. Match the tool to the job: after() for small follow-ups, cron for schedules, and a durable queue or job service for anything that matters or takes time. Then apply the same discipline everywhere: idempotent jobs, sensible retries, visible status and alerts on failure. Your users get fast responses, and the work behind them still gets done.
Author at LuminaryEra
The LuminaryEra editorial desk publishes long-form, hands-on guides on AI-assisted development, large language models, developer tools and web engineering. Articles are researched and drafted with the help of AI tools, link to their sources, and are corrected when readers report errors.
View all articles





