Background Jobs: Stop Making Users Wait on Slow Work

A background job is work your app finishes after it has already answered the user. When someone signs up, they need one thing back: “your account exists.” The welcome email, the AI-generated summary, the resized avatar, the slack message to your team: none of that has to happen before they see the page. Answer in a fraction of a second, hand the slow work to a queue, and let it finish in the background.
Most AI-built apps do the opposite. The AI writes the steps in the order you described them, all inside the request: create the account, then send the email, then call the AI, then respond. Your user stares at a spinner while your app does chores they cannot see.
Why the request is the wrong place for slow work
Two walls, and every vibe-coded app hits both eventually.
The user’s patience. People read a one-second wait as a hiccup and a ten-second wait as broken. An email provider call takes half a second on a good day and several seconds on a bad one. An AI call that generates a long output commonly takes tens of seconds. Chain three of those inside one request and your app feels dead. (For chat-style features, streaming the answer is often the better fix.)
Your host’s patience. Serverless functions get terminated when they run past their maximum duration (Vercel’s docs explain the setting, and every platform has one). When the platform kills your function mid-request, the user gets an error, and worse, the work half-happens: the account exists but the email never sent, and nobody knows.
What to move out of the request
The test is one question: does the user need the result to see the next screen?
- Sending email or SMS: no. Queue it.
- AI calls (summaries, embeddings, generations): almost always no. Queue it, show a “working on it” state.
- Resizing images, generating PDFs, processing uploads: no. Queue it.
- Calling third-party APIs (analytics, CRMs, webhooks): no. Queue it.
- Writing the row the user just asked for: yes. That one stays in the request.
Say your app lets users upload a video and get an AI transcript (a clearly labeled example, not a real app). The request does two things: save the upload and create a job row, “transcribe video 123.” The minutes of AI work happen after the user has their answer.
How the pattern works
Four moving parts, whatever the tool:
- The request saves what it must, writes a job (a row in a
jobstable or a message on a queue), and responds immediately. - A worker (a scheduled function, a separate process) picks up the job and does the slow work.
- The job’s status gets written somewhere:
pending,done,failed, plus the result. - The UI learns the outcome by polling the status or subscribing to it (Supabase Realtime works well here; it respects Row Level Security, so users only see rows your policies allow) and swaps “working on it” for the result.
You do not need new infrastructure for this. If your app is on Supabase, Supabase Queues gives you a durable queue inside Postgres itself (built on pgmq, with guaranteed delivery), and a scheduled Edge Function can be the worker. On other stacks, a plain jobs table and a cron that runs every minute gets you surprisingly far.
The two problems a queue creates
Moving work to the background is not free. It creates two new problems, best met on purpose:
Jobs can run twice. Queues retry, workers crash halfway, and “at least once” delivery means the same job can arrive again. So a job must be safe to repeat: check whether the work already happened before doing it. The fancy word is idempotency, and it deserves its own post.
Jobs fail silently. When the email breaks inside the request, the user tells you. When it breaks in a worker at 3am, nobody tells you. Record every job’s status and failure reason, and look at the failed ones. A queue you never inspect is a bin.
Prove it with runnable tests
Save this as test_background_jobs.py in an empty folder and run python3 test_background_jobs.py. It rebuilds the signup example in miniature, standard library only: one version sends the email inside the request; the queued version can use an in-memory list or a durable file on disk.
"""Behavior tests for background jobs. Run: python3 test_background_jobs.py"""import jsonimport osimport timeimport unittest
SLOW_WORK_SECONDS = 0.5QUEUE_FILE = "jobs.jsonl" # the durable queue: jobs on disk, not in memorymemory_queue = [] # the non-durable kind: dies with the processsent_emails = [] # the email provider, in this toy
def slow_send_email(address): time.sleep(SLOW_WORK_SECONDS) # the SMTP call in a real app sent_emails.append(address)
def create_account(email): return email.split("@")[0]
def enqueue(job): if DURABLE: with open(QUEUE_FILE, "a") as f: f.write(json.dumps({**job, "sent_at": None}) + "\n") else: memory_queue.append(job)
def signup_inline(email): account = create_account(email) slow_send_email(email) # the user waits for this return f"welcome {account}"
def signup_queued(email): account = create_account(email) enqueue({"job": "send_email", "email": email}) # answer now, work later return f"welcome {account}"
def drain_queue(): """The worker. In production it is a separate process; here it is a function.""" if DURABLE: if not os.path.exists(QUEUE_FILE): return with open(QUEUE_FILE) as f: jobs = [json.loads(line) for line in f] for job in jobs: if job["job"] == "send_email" and job["sent_at"] is None: slow_send_email(job["email"]) job["sent_at"] = time.time() with open(QUEUE_FILE, "w") as f: for job in jobs: f.write(json.dumps(job) + "\n") else: while memory_queue: job = memory_queue.pop(0) if job["job"] == "send_email": slow_send_email(job["email"])
# Which pieces the app uses. FIX (after the first run): queued signup, durable queue.signup = signup_inlineDURABLE = False
class BackgroundJobTests(unittest.TestCase): def setUp(self): memory_queue.clear() sent_emails.clear() if os.path.exists(QUEUE_FILE): os.remove(QUEUE_FILE)
def test_the_user_gets_an_answer_fast(self): start = time.monotonic() elapsed = time.monotonic() - start self.assertLess(elapsed, 0.2, f"the user waited {elapsed:.2f}s for the email")
def test_the_work_still_happens(self): drain_queue()
def test_a_restart_between_request_and_worker_loses_nothing(self): sent_emails.clear() # anything sent inside the request is not the job # the process is killed here; a new instance starts with empty memory memory_queue.clear() # a real restart wipes memory, not the disk drain_queue()
def test_the_worker_is_safe_to_run_twice(self): drain_queue() drain_queue() # a retry, a duplicate cron tick, a redelivery
if __name__ == "__main__": unittest.main()The first run fails the way your users experience it:
FAIL: test_the_user_gets_an_answer_fast (__main__.BackgroundJobTests)AssertionError: 0.5005571929996222 not less than 0.2 : the user waited 0.50s for the email
Ran 4 tests in 2.004sFAILED (failures=2)The user waits, and the restart test fails because nothing was ever queued. The other two tests pass, and that is deliberate: they guard the behaviors you must not break. Now flip the first marked line to signup_queued and run again:
AssertionError: [] != ['[email protected]'] : the queued job died with the process
Ran 4 tests in 1.002sFAILED (failures=1)The user is answered instantly, but the restart test still fails: the part most AI-generated fixes get wrong. An in-memory list (or its JavaScript twin, an un-awaited promise or a setTimeout) lives inside one process. On Vercel, Netlify or Supabase Edge Functions, that process is frozen or killed after the response, and the email inside the list dies with it. The first two tests cannot see this because they call the worker in the same process; the restart test wipes the memory between the request and the worker, the way your platform does. Flip the second marked line, DURABLE = True, so each job is written to disk before the response:
Ran 4 tests in 1.504sOKNow the job survives a restart, and the worker is safe to run twice: it marks each row sent_at and skips rows that already have one, so a retry or a duplicate cron tick cannot send two emails. That one-line habit is the working answer to “jobs run twice” above. All four tests assert behaviors, not implementation details, so a later change that quietly breaks one fails a test instead of shipping. They say nothing about alerting, which is why the failure-status habit above exists.
For short work after the response (a log write, an analytics event), platforms offer an escape hatch: Vercel’s waitUntil, Next.js after(), and Supabase’s EdgeRuntime.waitUntil. They are not queues: no retries, and the work still counts against the function’s time limit. Anything the user would miss deserves a real job row.
The hand check: time one endpoint
Pick your app’s most important action (signup, upload, generate) and time it from the outside, against your staging or preview deployment, not production (a bare POST can create junk accounts or send real emails):
curl -o /dev/null -s -w '%{time_total}\n' -X POST https://your-app.example/api/signupUnder half a second, fine. Consistently over a second means the request is doing chores. List what happens between the request arriving and the response leaving, and move everything the user does not need to wait for into a job. (If several endpoints are slow at once, also read why your app gets slower with every new user: the cause may be the database, not the chores.)
The prompt to paste
Audit every route in this app for slow work inside the request. For each route, list every step between the request and the response, whether the user needs that step’s result to see the next screen, and roughly how long it takes (database write, email API, AI call, third-party API). Propose a jobs table or queue for the steps that can move, including the status field and how the UI learns the result. Do not change code yet.
This is one of the six things that break when your app meets real users, and it is much easier to fix before launch day than during it.
The Get AI Native ebook goes deeper on this. It is free, and the expected launch is around Christmas. Join the waitlist on the homepage.