Use a background job whenever work is slow, unreliable, or not needed for the user’s immediate response. The web request saves what must be saved, drops a small message describing the remaining work onto a queue, and returns quickly. A separate worker process picks the message up and does the slow part, such as sending an email.
This guide is for backend interns and beginners. It gives you a decision table for choosing between synchronous and background work, a concept map, a simple email example, a 14-day practice plan, and a short quiz to check your understanding.
Why a web request should not do slow work
A web server handles requests with a limited number of workers. If one request spends four seconds talking to an email provider, that worker is busy for four seconds. Multiply that by a few hundred users and your site feels frozen, even though nothing is broken.
Slow work also fails in ways the user cannot fix. The email provider may time out, the network may drop, or a third-party API may return an error. If the user’s signup request depends on all of that succeeding, a problem in the email system becomes a problem with signing up.
Background processing separates two questions:
- Did we record what the user asked for? This must happen inside the request.
- Did we finish every side effect? This can happen a moment later, with retries if needed.
Concept map: the moving parts of a task queue
Read this map from top to bottom. Each line is one component and what it hands to the next.
User (browser / app)
| HTTP request: "register me"
v
Web app (Flask / Django / FastAPI)
| 1. saves user to database
| 2. enqueues task: send_welcome_email(user_id=42)
| 3. returns "201 Created" immediately
v
Broker / queue (Redis, RabbitMQ, or a database table)
| holds messages until a worker is free
v
Worker process (Celery, RQ, Dramatiq, or a custom loop)
| pulls message, runs the function
v
External service (SMTP server / email API)
|
v
Result / status (success, failed, retry scheduled)
-> optionally stored in a result backend or log
Key vocabulary in plain words:
- Producer: the code that creates a task, usually your web view.
- Broker: the storage and delivery system for messages between producer and worker.
- Worker: a long-running process that executes tasks. It is separate from the web server.
- Task: a named function plus its arguments.
- Retry: running a failed task again, usually with a growing delay.
- Idempotent: safe to run twice with the same result. This matters because queues often deliver a message more than once.
Free 2-Week CareerSwami Internship
Online, 14 days, with a free offer letter and a free completion certificate once you finish the work. Check with your college that it fits your requirement before you enrol.
Decision table: should this work run in the background?
Use this table as a quick checklist when you are unsure. The examples are illustrative.
| Situation | Run in request? | Use background job? | Reason |
|---|---|---|---|
| Validate a signup form | Yes | No | The user needs the answer now. |
| Save the new user row | Yes | No | It is the core action and is fast. |
| Send a welcome email | No | Yes | Depends on an external service; user does not need to wait. |
| Resize an uploaded profile photo | No | Yes | CPU-heavy and variable in duration. |
| Generate a monthly PDF report | No | Yes | Can take many seconds; show “report is being prepared”. |
| Call a payment gateway to confirm a charge | Usually yes | Sometimes | The user may need the result, so design the screen to show a pending state. |
| Look up a product price | Yes | No | Fast read; a queue adds complexity for nothing. |
| Nightly cleanup of expired sessions | No | Yes (scheduled) | Not triggered by a user at all. |
| Import a 50,000-row CSV | No | Yes | Long-running; report progress separately. |
Three questions that settle most cases
- Does the user need the result to see the next screen? If yes, keep it in the request or show a pending state.
- Could this take longer than about a second, or depend on something outside our control? If yes, lean towards a background job.
- If it fails, should we retry automatically? If yes, a queue gives you that nearly for free.
A simple email-sending example, before and after
The code below is illustrative. It shows the shape of the solution and has not been run as part of this article. Names like send_mail stand in for whatever email library or provider you use.
Before: the slow, fragile version
@app.post("/register")
def register():
user = create_user(request.json) # fast, database write
send_mail(user.email, "Welcome!") # slow, may fail
return {"id": user.id}, 201
If send_mail hangs, the user waits. If it raises an error, the user may see a 500 even though their account was created.
After: the request hands off the email
# tasks.py
@task(retries=3, retry_delay=60)
def send_welcome_email(user_id):
user = get_user(user_id) # re-read fresh data
if user.welcome_sent: # idempotency guard
return
send_mail(user.email, "Welcome!")
user.welcome_sent = True
user.save()
# views.py
@app.post("/register")
def register():
user = create_user(request.json)
send_welcome_email.enqueue(user.id) # pass an ID, not the whole object
return {"id": user.id}, 201
Notice four deliberate choices:
- Pass an ID, not an object. Messages should be small and serialisable. The worker loads current data itself.
- Guard against duplicates. The
welcome_sentflag means a repeated delivery does not send two emails. - Limit retries. Three attempts with a delay avoids hammering a failing service forever.
- Return fast. The user sees success once the account exists.
One gotcha: enqueue after the database commit
If you enqueue inside a database transaction, the worker might run before the transaction commits and fail to find the user. Enqueue after the commit, or use your framework’s “on commit” hook if it has one. This is one of the most common beginner bugs in this pattern.
Choosing a queue tool as a beginner
| Option | Good for | Trade-off |
|---|---|---|
Python’s built-in threads or BackgroundTasks-style helpers in your framework |
Tiny jobs, learning, prototypes | Tasks vanish if the server restarts; no retries or visibility. |
| Celery with Redis or RabbitMQ | Widely used, many features, scheduling | More configuration and more concepts to learn. |
| RQ (Redis Queue) | Simple, readable, good for first projects | Redis only; fewer advanced features. |
| Database-backed queue table | Small apps where you want no extra service | Does not scale as far; you build more yourself. |
For a first exercise, pick the tool your team or mentor already uses. Learning the concepts transfers between tools; the syntax differs only in details.
What can go wrong: failure modes to design for
- Duplicate delivery. Make tasks idempotent with a flag, a unique key, or a check before acting.
- Lost tasks. If the broker restarts without persistence, messages disappear. Know whether your broker persists data.
- Poison messages. A task that always fails will retry until the limit. Cap retries and log the final failure so someone sees it.
- Worker not running. The web app happily enqueues while nothing consumes. Monitor queue length and alert if it grows.
- Stale arguments. If you pass old data in the message, the worker may act on outdated information. Pass IDs and reload.
- Silent failure. Without logging, a failed email is invisible. Log task start, success and failure with the task ID.
Noble University students: using background tasks in internship and project work
Noble University describes itself on its official homepage as a private university in Junagadh, Gujarat. That page is marketing wording, so it does not tell you the statutory category or how academic rules are set. The same homepage mentions a Provost and a Registrar at a Vice-Chancellors’ conference, which hints at a central administration, but it does not say whether internship or project rules apply university-wide or differ by faculty.
This matters for your backend learning in a practical way. If you plan to turn an email-queue exercise into a project report or mention it in an internship record, you need to know what your own department expects. The university site refers to separate faculties such as Engineering and Polytechnic, so a rule for one programme may not match another. No internship, industrial-training or project-work rule has been verified for this article, so do not assume duration, credit treatment, documentation or whether an online internship is accepted.
The same applies to claims about outcomes. A university page makes promotional placement statements, but that page gives no cell structure or data. Treat your own portfolio as the evidence employers will see: a small project with a worker, retry logic and a short README explaining your choices is more useful than a claim on a website.
If you want a free way to practise, the free two-week online internship from CareerSwami offers 26 tracks, a free offer letter and a free completion certificate after successful completion. It does not promise stipend, academic credit or placement.
Verification steps for Noble University students
- Ask your department office or internship coordinator, in writing, whether an online two-week internship is accepted for your programme and semester.
- Ask for the current scheme or regulation document that covers internships, industrial training or project work for your course, and note its version or year.
- Ask whether those rules are set by the university or by your own faculty or college.
- Ask what evidence is required: certificate, report, mentor letter, or viva, and in what format.
- Check the semester calendar with your department so you can schedule the 14 days without clashing with exams.
- Keep the reply as an email or notice you can show later.
A 14-day practice plan for learning background jobs
This plan fits a two-week internship or a self-study fortnight. Aim for roughly one to two hours a day, more if you can.
| Days | Focus | Output |
|---|---|---|
| 1-2 | Build a tiny web app with a signup endpoint and a database | Working /register route |
| 3 | Add synchronous email sending using a console or test backend | Baseline you can time |
| 4-5 | Install a broker and queue library; run a worker with a hello-world task | Worker log showing a task ran |
| 6-7 | Move the email into a task; pass the user ID | Request returns before the email step |
| 8 | Add retries and a fixed delay | Simulated failure that retries |
| 9 | Make the task idempotent | Duplicate delivery sends one email |
| 10 | Fix commit ordering | Task never runs before data exists |
| 11 | Add logging with task IDs | Readable success and failure lines |
| 12 | Add one scheduled job, such as cleaning old records | Periodic task configured |
| 13 | Write tests for the task function and the enqueue call | Passing test run on your machine |
| 14 | Write a README and draw your own concept map | Portfolio-ready repository |
Worked decision: a feedback form with three side effects
This scenario is illustrative. A student portal has a feedback form. When submitted, the app must (a) save the feedback, (b) email a confirmation to the student, (c) notify an admin channel, and (d) update a daily summary count.
- Save the feedback: inside the request. It is the core action and fast.
- Confirmation email: background. External service, user does not need to wait.
- Admin notification: background. Also external. Make it a separate task so a failure here does not block the email.
- Daily summary count: do not enqueue per submission. Run one scheduled job each night that counts rows. It is simpler and avoids many tiny tasks.
Result: one fast database write, two small tasks with their own retries, and one scheduled job. The user sees “Thanks” almost instantly, and a failure in any side effect is isolated and retryable.
Short quiz: check your understanding of background tasks
- Why should a signup request not call the email provider directly?
- What is the role of the broker?
- Why pass a user ID to a task rather than the whole user object?
- What does idempotent mean, and why do queues make it important?
- What bug can happen if you enqueue before a database transaction commits?
- Name one situation where a background job is the wrong choice.
Answer key
- The provider is slow and can fail, so the user would wait or see an error even though their account was created.
- It stores messages and delivers them to workers when they are free.
- Messages stay small and serialisable, and the worker reads fresh data instead of stale data.
- Running the task twice gives the same result as running it once. Queues may deliver a message more than once, so duplicates must be harmless.
- The worker may start before the data is visible and fail to find it.
- Any case where the user needs the result immediately, such as a fast price lookup or form validation.
Frequently Asked Questions
Is a background task the same as a thread?
No. A thread runs inside your web process and disappears if that process restarts. A queue-based task is stored in a broker and run by a separate worker, so it survives restarts and can be retried.
Do I always need Redis or RabbitMQ?
Not for learning. A database table can act as a simple queue for small projects. Redis or RabbitMQ become useful when you need speed, many workers or richer features.
What happens if the worker is down when I enqueue a task?
The message waits in the broker, assuming it persists data. When a worker starts, it processes the backlog. Monitor queue length so you notice the problem early.
How many retries should I configure?
A small number, such as three to five, with increasing delays, is a common starting point. The right value depends on the task. Retrying forever can hide a real bug and overload a failing service.
Should the user be told that an email was sent?
Be honest in the wording. Say “we are sending a confirmation” rather than “sent”, because the task may not have run yet or may be retrying.
Can I count this exercise toward my university internship requirement?
That depends on your department’s rules, which are not verified here. Ask your internship coordinator in writing whether an online internship or self-built project is accepted and what documents are needed.
How do I test a background task?
Test the task function directly as ordinary code, and separately test that the view enqueues it with the right arguments. Many libraries offer an eager mode that runs tasks immediately during tests; check your library’s documentation.
What should I put in my portfolio from this topic?
A small repository with a web endpoint, a worker, a retrying idempotent email task, logging, tests and a README that explains why each piece exists. Include your concept map as an image or text diagram.
Related Python & Backend Engineering guides
- Sushant University Students: Writing the Final Backend Internship Report Without Padding
- The Glocal University Students: Handling Feedback and Rework in a Backend Internship
- Apex Professional University Students: Finding Backend Internships From Arunachal Pradesh Without Relocating
- All Python & Backend Engineering internship guides
Ready to put this into practice?
Join the free two-week CareerSwami online internship in Python & Backend Engineering. The internship, the offer letter and the completion certificate are free.




















