惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
CXSECURITY Database RSS Feed - CXSecurity.com
WordPress大学
WordPress大学
美团技术团队
Last Week in AI
Last Week in AI
Microsoft Azure Blog
Microsoft Azure Blog
D
DataBreaches.Net
Hugging Face - Blog
Hugging Face - Blog
腾讯CDC
B
Blog RSS Feed
J
Java Code Geeks
The GitHub Blog
The GitHub Blog
人人都是产品经理
人人都是产品经理
Recorded Future
Recorded Future
The Register - Security
The Register - Security
博客园 - 三生石上(FineUI控件)
Recent Announcements
Recent Announcements
Recent Commits to openclaw:main
Recent Commits to openclaw:main
V
Vulnerabilities – Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
T
The Exploit Database - CXSecurity.com
博客园 - 【当耐特】
C
Check Point Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Simon Willison's Weblog
Simon Willison's Weblog
T
Troy Hunt's Blog
P
Privacy International News Feed
S
Security Affairs
The Cloudflare Blog
P
Proofpoint News Feed
G
GRAHAM CLULEY
Engineering at Meta
Engineering at Meta
A
Arctic Wolf
博客园_首页
Blog — PlanetScale
Blog — PlanetScale
D
Docker
S
SegmentFault 最新的问题
N
News | PayPal Newsroom
Cyberwarzone
Cyberwarzone
H
Help Net Security
T
Threatpost
A
About on SuperTechFans
L
LINUX DO - 热门话题
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
N
News and Events Feed by Topic
Attack and Defense Labs
Attack and Defense Labs
M
MIT News - Artificial intelligence
Schneier on Security
Schneier on Security
月光博客
月光博客
F
Fortinet All Blogs
L
Lohrmann on Cybersecurity

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Python Background Tasks — Asyncio Traps, FastAPI & Celery (2026)
Kaushikcoder · 2026-05-05 · via DEV Community

Decoupling Workloads: Strategies for Non-Blocking API Responses in Python

Modern web applications demand instant feedback. Users expect immediate responses, and frustrating delays can quickly lead to abandonment. When an API endpoint performs computationally intensive or time-consuming operations directly within the request-response cycle, it creates a bottleneck that can cripple your backend system.

Consider a scenario where a user triggers a complex AI inference or a large data processing job through a web interface. If this task runs synchronously, the user's browser waits, the HTTP connection remains open, and the server's worker process is tied up. This can quickly lead to:

  • User Frustration: Long loading spinners are a poor user experience.
  • Gateway Timeouts: Reverse proxies like NGINX have strict timeout limits. If your API doesn't respond fast enough, the proxy will sever the connection, returning a 504 Gateway Timeout error.
  • Resource Exhaustion: Multiple concurrent slow requests can quickly consume all available server resources (CPU, RAM, worker processes), leading to cascading failures as the system struggles to keep up.
  • System Instability: In containerized environments, unresponsive services are often deemed unhealthy and restarted, potentially losing in-flight work and exacerbating the problem.

The solution is to offload these heavy operations to background tasks. This "fire and forget" pattern allows your API to acknowledge the request immediately with an HTTP 202 Accepted status, then delegate the actual work to a separate process or system. Think of uploading a large video to a platform: the upload completes instantly, and the platform processes it in the background, notifying you when it's ready.

Let's explore various methods for implementing background tasks in Python, from simple in-process solutions to robust distributed systems.

In-Process Asynchronous Execution with Asyncio

For applications already leveraging Python's asyncio event loop, the quickest way to schedule a non-blocking task is with asyncio.create_task(). This function schedules a coroutine to run on the event loop without awaiting its completion, allowing the current function to proceed immediately.

import asyncio

async def send_notification_email(recipient: str):
    # Simulate a network call or I/O operation
    await asyncio.sleep(2) 
    print(f"Email sent to {recipient}")

async def handle_user_signup():
    print("1. Persisting user data to database...")

    # DANGER: Task created, but not awaited or referenced.
    # Python's Garbage Collector might terminate it prematurely.
    asyncio.create_task(send_notification_email("new.user@example.com"))

    print("2. Responding to client immediately.")
    return {"status": "user registered"}

Enter fullscreen mode Exit fullscreen mode

This approach, however, harbors a critical pitfall: Python's garbage collector. If no "strong reference" is held to the Task object returned by asyncio.create_task(), the garbage collector might reclaim the task's memory, silently terminating it mid-execution. Your email might never send, with no error logs to indicate why.

To prevent this, you need to maintain a reference to the task, typically in a global set, and remove it only after it completes.

import asyncio

# Global set to hold strong references to running tasks
active_async_tasks = set()

def safe_fire_and_forget(coro):
    """Schedules a coroutine as a background task, ensuring it's not garbage collected."""
    task = asyncio.create_task(coro)
    active_async_tasks.add(task)
    # Remove the task from the set once it's done (successfully or with error)
    task.add_done_callback(active_async_tasks.discard)
    return task

async def send_notification_email(recipient: str):
    await asyncio.sleep(2) 
    print(f"Email sent to {recipient}")

async def handle_user_signup_safe():
    print("1. Persisting user data to database...")
    safe_fire_and_forget(send_notification_email("new.user@example.com"))
    print("2. Responding to client immediately.")
    return {"status": "user registered"}

Enter fullscreen mode Exit fullscreen mode

Even with this safeguard, asyncio.create_task tasks are entirely in-memory. If your server process restarts for any reason (e.g., deployment, crash, scaling event), any uncompleted background tasks will be lost. This method is suitable only for non-critical operations where occasional loss is acceptable, such as sending telemetry data.

FastAPI's Integrated Background Tasks

FastAPI provides a more robust and convenient way to handle in-process background tasks using its BackgroundTasks dependency. This abstraction manages the task lifecycle cleanly, ensuring the HTTP response is sent to the client before the background task begins execution within the same process.

from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

def process_uploaded_document(document_id: int):
    # Simulate heavy processing like vector database updates or OCR
    print(f"Starting heavy processing for document {document_id}...")
    # ... perform CPU-bound or I/O-bound work ...
    print(f"Finished processing for document {document_id}.")

@app.post("/documents/{document_id}/upload")
async def upload_document(document_id: int, background_tasks: BackgroundTasks):
    # Add the function and its arguments to be run in the background.
    # Do NOT call the function directly here.
    background_tasks.add_task(process_uploaded_document, document_id)

    return {"message": f"Document {document_id} accepted. Processing initiated."}

Enter fullscreen mode Exit fullscreen mode

FastAPI's BackgroundTasks are excellent for quick, post-response operations like updating audit logs, sending simple emails, or invalidating caches. However, like raw asyncio tasks, they are tied to the lifespan of the FastAPI process. If the server crashes or restarts, any uncompleted BackgroundTasks are lost.

Scaling Beyond the Web Server Process

For tasks that are CPU-intensive, blocking, or require guaranteed execution even if the web server fails, you need to move beyond in-process background tasks.

Threads for Blocking I/O

If your application isn't fully asyncio and you have blocking I/O operations (e.g., interacting with a legacy library or a synchronous database driver), threading.Thread can offload this work. Using daemon=True ensures the thread is terminated if the main program exits, preventing zombie threads.

import threading
import time

def generate_complex_report(user_id: int):
    print(f"Thread: Starting report generation for user {user_id}...")
    time.sleep(10) # Simulate a long, blocking I/O or computation
    print(f"Thread: Report for user {user_id} completed.")

def initiate_report(user_id: int):
    # Create a new thread for the blocking task
    thread = threading.Thread(target=generate_complex_report, args=(user_id,), daemon=True)
    thread.start()
    print(f"Main: Report generation for user {user_id} initiated in background.")
    return {"message": "Report generation started."}

# Example usage (not in an API context, just to show thread behavior)
# initiate_report(123)
# time.sleep(1) # Allow main thread to continue
# print("Main: Application still responsive.")

Enter fullscreen mode Exit fullscreen mode

While threading can help with blocking I/O, Python's Global Interpreter Lock (GIL) means that only one thread can execute Python bytecode at a time. This limits its effectiveness for truly parallel CPU-bound tasks.

Multiprocessing for CPU-Bound Work

To bypass the GIL and fully utilize multiple CPU cores for heavy computation, multiprocessing.Process is the go-to solution. This creates entirely new operating system processes, each with its own Python interpreter and memory space.

import multiprocessing
import time

def perform_image_resize(image_path: str):
    print(f"Process: Resizing image {image_path}...")
    time.sleep(8) # Simulate heavy CPU computation
    print(f"Process: Image {image_path} resized.")

def handle_image_upload(image_path: str):
    # Create a new process for the CPU-intensive task
    process = multiprocessing.Process(target=perform_image_resize, args=(image_path,))
    process.start()
    print(f"Main: Image upload for {image_path} accepted. Resizing in background process.")
    return {"message": "Image processing started."}

# Example usage
# handle_image_upload("my_photo.jpg")
# time.sleep(1)
# print("Main: Application remains responsive while image resizes.")

Enter fullscreen mode Exit fullscreen mode

multiprocessing introduces overhead due to process creation and inter-process communication. It's best reserved for genuinely CPU-intensive, isolated tasks that benefit from parallel execution. Like asyncio tasks and FastAPI BackgroundTasks, these processes are typically tied to the lifespan of the parent web server process, meaning tasks might be lost on server restart.

Distributed Task Queues (Celery)

For mission-critical, long-running, or highly scalable background tasks, a distributed task queue system like Celery is the industry standard. Celery decouples task execution entirely from the web server.

Here's how it works:

  1. Message Broker: A message broker (e.g., Redis, RabbitMQ) acts as a central hub.
  2. Web Server (Producer): When a user triggers a background task, the web server serializes the task details (function name, arguments) into a message and publishes it to the message broker. It then immediately returns an HTTP 202 Accepted response.
  3. Celery Workers (Consumer): Separate, dedicated Celery worker processes continuously monitor the message broker. When a new task message arrives, a worker picks it up, deserializes it, and executes the corresponding function.

This architecture offers:

  • Persistence: Tasks are stored in the message broker. If a web server or worker crashes, the task remains in the queue and can be picked up by another worker or after a restart.
  • Scalability: You can scale web servers and Celery workers independently.
  • Reliability: Celery offers features like retries, error handling, and scheduling.

While powerful, Celery introduces operational complexity. You need to manage and monitor additional infrastructure (the message broker and Celery worker processes).

# Example of how a Celery task is defined and called (simplified)

# tasks.py (in your Celery worker application)
# from celery import Celery
# app = Celery('my_app', broker='redis://localhost:6379/0')

# @app.task
# def generate_financial_report(account_id: int):
#     print(f"Celery Worker: Generating report for account {account_id}...")
#     time.sleep(30) # Simulate a very long, critical task
#     print(f"Celery Worker: Report for account {account_id} completed.")

# web_app.py (in your FastAPI/Flask application)
# from tasks import generate_financial_report

# @app.post("/reports/{account_id}/request")
# async def request_report(account_id: int):
#     # Push the task to the Celery queue
#     generate_financial_report.delay(account_id) 
#     return {"message": "Financial report generation initiated. You will be notified."}

Enter fullscreen mode Exit fullscreen mode

Choosing the Right Tool: A Reliability Spectrum

The choice of background task mechanism depends heavily on the task's criticality, resource requirements, and your tolerance for operational complexity.

  • asyncio.create_task (with strong reference): Use for low-stakes, non-critical operations like basic analytics pings where the occasional loss of a task is acceptable. It's the fastest to implement but offers no persistence.
  • FastAPI BackgroundTasks: Ideal for quick, in-process follow-ups after an HTTP response, such as updating audit logs, sending non-essential emails, or performing minor database updates. It's convenient but also lacks persistence across server restarts.
  • threading.Thread (daemonized): Suitable for offloading blocking I/O operations in a synchronous web server context. Still in-process and not persistent.
  • multiprocessing.Process: Essential for CPU-bound tasks that need to bypass the GIL and utilize multiple cores. It incurs process creation overhead and is typically not persistent across server restarts.
  • Celery (with Redis/RabbitMQ): The enterprise-grade solution for critical, long-running, or highly scalable tasks that require guaranteed execution and persistence. It demands additional infrastructure and operational overhead but ensures your business logic completes reliably.

By strategically offloading heavy processing, you can maintain responsive APIs, prevent system overloads, and deliver a much better user experience.