การประมวลผลแบบอะซิงโครนัส

การ Deploy AI สู่ Production ด้วย FastAPI

Matt Eckerle

Software and Data Engineering Leader

การประมวลผลแบบอะซิงโครนัสคืออะไร

บุคคลกำลังเสิร์ฟเครื่องดื่มให้ลูกค้าที่นั่งอยู่ที่โต๊ะ

 

รองรับการจัดการคำขอหลายรายการพร้อมกัน

การ Deploy AI สู่ Production ด้วย FastAPI

คำขอแบบซิงโครนัส vs อะซิงโครนัส

กราฟแสดงความแตกต่างของเวลาประมวลผลระหว่างคำขอแบบซิงโครนัสและอะซิงโครนัส

การ Deploy AI สู่ Production ด้วย FastAPI

แปลง endpoint แบบซิงโครนัสเป็นอะซิงโครนัส

 

@app.post("/analyze")
def analyze_sync(comment: Comment):
    result = sentiment_model(comment.text)
    return {"sentiment": result}

 

import asyncio

@app.post("/analyze")
async def analyze_async(comment: Comment):
    result = await asyncio.to_thread(
        sentiment_model, comment.text
    )
    return {"sentiment": result}
การ Deploy AI สู่ Production ด้วย FastAPI

การใช้งาน background tasks

from fastapi import BackgroundTasks
from typing import List
@app.post("/analyze_batch")
async def analyze_batch(
    comments: Comments,
    background_tasks: BackgroundTasks
):
    async def process_comments(texts: List[str]):
        for text in texts:
            result = await asyncio.to_thread(
              sentiment_model, text)
    background_tasks.add_task(process_comments, 
                              comments.texts)
    return {"message": "Processing started"}
  • BackgroundTasks จัดการคิวการประมวลผลคอมเมนต์

 

  • background_tasks ดูแลการประมวลผลหลังส่ง response

 

  • add_task กำหนดเวลาให้ process_comments ทำงานแบบอะซิงโครนัส
การ Deploy AI สู่ Production ด้วย FastAPI

การเพิ่ม error handling

@app.post("/analyze_comment")
async def analyze_comment(comment: Comment):
    try:
        sentiment_model = SentimentAnalyzer()
        result = await asyncio.wait_for(
            sentiment_model(comment.text),
            timeout=5.0
        )
        return {"sentiment": result["label"]}
การ Deploy AI สู่ Production ด้วย FastAPI

การเพิ่ม error handling

    except asyncio.TimeoutError:
        raise HTTPException(
            status_code=408,
            detail="Analysis timed out"
        )
    except Exception:
        raise HTTPException(
            status_code=500,
            detail="Analysis failed"
        )
การ Deploy AI สู่ Production ด้วย FastAPI

มาฝึกกันเถอะ!

การ Deploy AI สู่ Production ด้วย FastAPI

Preparing Video For Download...