비동기 처리

FastAPI로 AI 프로덕션 배포하기

Matt Eckerle

Software and Data Engineering Leader

비동기 처리란

테이블에 앉은 손님에게 음료를 서빙하는 사람

 

여러 요청을 동시에 처리할 수 있습니다

FastAPI로 AI 프로덕션 배포하기

동기 vs 비동기 요청

동기 및 비동기 요청의 처리 시간 차이를 보여주는 차트

FastAPI로 AI 프로덕션 배포하기

동기 엔드포인트를 비동기로 전환

 

@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}
FastAPI로 AI 프로덕션 배포하기

백그라운드 태스크 구현

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는 응답 후 처리를 담당합니다.

 

  • add_task는 process_comments를 비동기로 예약합니다.
FastAPI로 AI 프로덕션 배포하기

오류 처리 추가

@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"]}
FastAPI로 AI 프로덕션 배포하기

오류 처리 추가

    except asyncio.TimeoutError:
        raise HTTPException(
            status_code=408,
            detail="Analysis timed out"
        )
    except Exception:
        raise HTTPException(
            status_code=500,
            detail="Analysis failed"
        )
FastAPI로 AI 프로덕션 배포하기

연습해 봅시다!

FastAPI로 AI 프로덕션 배포하기

Preparing Video For Download...