Skip to content
TheChatArchiveThe Chat Archive
Qwenqwen3-235b-a22b-no-thinking· Alibaba (Qwen)Hugging Face LMArena Human Preference 140K

write a backend with a background tasks and a server sent events endpoint that gives…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Hunyuanhunyuan-turbos-20250416’s answer.
  1. User

    write a backend with a background tasks and a server sent events endpoint that gives updates about the tasks status

  2. Qwen Assistant

    Here's a complete example of a backend using FastAPI (Python) that includes:

    • A background task system using asyncio
    • Server-Sent Events (SSE) to stream updates to clients
    • Task status tracking and broadcasting

    🧠 Overview

    • /start-task — Starts a long-running background task.
    • /events — An SSE endpoint where clients can listen for real-time task status updates.

    ✅ Requirements

    Install FastAPI and Uvicorn:

    pip install fastapi uvicorn
    

    You can run the server with:

    uvicorn main:app --reload
    

    📁 File: main.py

    from fastapi import FastAPI, BackgroundTasks
    import asyncio
    import uuid
    from typing import List
    from fastapi.responses import StreamingResponse
    from fastapi.middleware.cors import CORSMiddleware
    
    app = FastAPI()
    
    # Allow CORS for local development
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_methods=["*"],
        allow_headers=["*"],
    )
    
    # Store task statuses
    class Task:
        def __init__(self, task_id: str):
            self.task_id = task_id
            self.status = "pending"
            self.progress = 0
    
    tasks = {}  # {task_id: Task}
    listeners = {}  # {task_id: [asyncio.Queue]}
    
    def get_task_or_404(task_id: str):
        task = tasks.get(task_id)
        if not task:
            raise HTTPException(status_code=404, detail="Task not found")
        return task
    
    @app.on_event("startup")
    async def startup_event():
        """Initialize background task manager."""
        asyncio.create_task(background_task_manager())
    
    async def background_task_manager():
        while True:
            await asyncio.sleep(1)
    
    # Helper to send message to all listeners of a task
    async def event_generator(task_id: str):
        queue = asyncio.Queue()
        listeners.setdefault(task_id, []).append(queue)
        try:
            while True:
                message = await queue.get()
                yield message
        except asyncio.CancelledError:
            # Remove the listener when client disconnects
            listeners[task_id].remove(queue)
            if not listeners[task_id]:
                del listeners[task_id]
            raise
    
    @app.post("/start-task")
    async def start_task(background_tasks: BackgroundTasks):
        task_id = str(uuid.uuid4())
        task_obj = Task(task_id)
        tasks[task_id] = task_obj
    
        async def run_background():
            for i in range(1, 101):
                await asyncio.sleep(0.2)  # Simulate work
                task_obj.progress = i
                if i == 100:
                    task_obj.status = "completed"
                else:
                    task_obj.status = "running"
                # Notify all listeners
                message = f"data: {{\"task_id\": \"{task_id}\", \"status\": \"{task_obj.status}\", \"progress\": {task_obj.progress}}}\n\n"
                for q in listeners.get(task_id, []):
                    await q.put(message)
            # Clean up task after completion
            tasks.pop(task_id, None)
    
        background_tasks.add_task(run_background)
        return {"task_id": task_id}
    
    @app.get("/events")
    async def events(task_id: str):
        if task_id not in tasks:
            return {"error": "Task not found"}, 404
    
        return StreamingResponse(event_generator(task_id), media_type="text/event-stream")
    

    🧪 Test It Out

    1. Start a Task

    Make a POST request:

    curl -X POST http://localhost:8000/start-task
    

    Response:

    {"task_id": "abc123..."}
    

    2. Listen for Updates (Server-Sent Events)

    Open your browser or use curl:

    curl "http://localhost:8000/events?task_id=abc123..."
    

    You'll see updates like:

    data: {"task_id": "abc123...", "status": "running", "progress": 5}
    data: {"task_id": "abc123...", "status": "running", "progress": 10}
    ...
    data: {"task_id": "abc123...", "status": "completed", "progress": 100}
    

    🧱 How It Works

    • Each task is uniquely identified by a UUID.
    • When a task starts, it runs in the background using BackgroundTasks.
    • The progress updates are sent via asyncio.Queue to connected SSE clients.
    • Clients can connect to /events?task_id=... to get live updates.

    ✅ Optional Enhancements

    • Add task cancellation support
    • Persist tasks in a database
    • Limit number of concurrent tasks
    • Add authentication to endpoints

    Let me know if you want any of these added!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.