为什么 async def 里的阻塞调用会拖慢全部请求?——从脏发票校验到异步限流

用 Pydantic 拦截脏发票数据,并用 httpx.AsyncClient 与信号量限流消除事件循环阻塞。

系列教程:生产级 AI 应用开发(1 / 22)

平时处理发票或者调用外部第三方接口,如果只是写个单机脚本,拿列表循环一张张处理,一般不会觉得有什么问题。

但把逻辑接进 Web 后端(比如 FastAPI),只要稍微遇到外部接口延迟,或者员工一次性上传了几十张发票,接口就会变得奇慢无比。为了提速,很多人的第一反应是在函数前面加个 async def,再用 asyncio.gather 并发跑。

结果一测耗时,发现时间根本没有缩短,甚至同一个服务里的其他接口也跟着卡死。

底层的问题出在:虽然声明了异步,但如果代码内部依然包含同步阻塞调用,Python 的主事件循环就会被活活占死。


先用 Pydantic 把脏发票拦在门外

在把数据送去外部 OCR 校验之前,必须先在业务入口把明显的脏数据拦截下来。

真实场景里的发票数据往往有很多缺陷:金额可能被录入成负数、缺少必要的消费明细、或者明细加起来跟总金额对不上。如果把这些残缺数据直接打给外部接口,不仅浪费网络调用,还会污染下游数据库。

这里使用 Pydantic V2 来做强类型校验。新建 invoice_models.py:

# invoice_models.py
from decimal import Decimal
from pydantic import BaseModel, Field, model_validator


class InvoiceItem(BaseModel):
    name: str = Field(min_length=1, description="消费明细名称")
    amount: Decimal = Field(gt=Decimal("0"), description="单项金额,必须大于 0")


class RawInvoiceInput(BaseModel):
    invoice_id: str = Field(min_length=1, description="发票唯一编号")
    currency: str = Field(default="CNY", description="币种标识")
    total_amount: Decimal = Field(gt=Decimal("0"), description="发票总金额,必须大于 0")
    items: list[InvoiceItem] = Field(min_length=1, description="消费条目列表,至少包含一项")

    @model_validator(mode="after")
    def verify_total_matches_items(self) -> "RawInvoiceInput":
        # 逐项累加明细金额,验证是否等于总金额
        computed_sum = sum(item.amount for item in self.items)
        if computed_sum != self.total_amount:
            raise ValueError(
                f"发票 {self.invoice_id} 明细合计金额 ({computed_sum}) 与总金额 ({self.total_amount}) 不一致"
            )
        return self

这段代码有三个务实的工程考虑:

一是涉及资金计算时,统一使用 Python 内置的 Decimal 而非浮点数 float,避免二进制浮点运算产生类似 0.1 + 0.2 = 0.30000000000000004 的精度差。

二是通过 model_validator(mode="after") 在对象构造完成之后做跨字段校验。如果明细总和与总金额不一致,直接抛出 ValueError。

三是在下游业务代码中,只要拿到了 RawInvoiceInput 的实例,就可以完全信任它的基础字段是合法的,不需要在后续写单据、落数据库时反复加 if total <= 0 的防御判断。


顺手加上 async 之后,速度为什么没有变快?

有了合法模型后,我们需要把发票提交给外部 OCR 接口做票面真实性比对。

我们先写一个最简单的同步批量处理函数。代码保存在 invoice_batch.py:

# invoice_batch.py
import time
from typing import Any
from pydantic import ValidationError
from course.lesson_01.invoice_models import RawInvoiceInput


def mock_sync_ocr_verify(invoice_id: str, delay_seconds: float = 0.1) -> dict[str, Any]:
    # 模拟外部 OCR 接口的网络往返等待
    time.sleep(delay_seconds)
    return {"invoice_id": invoice_id, "ocr_status": "VERIFIED"}


def process_invoices_sync(
    raw_records: list[dict[str, Any]],
    delay_per_item: float = 0.1
) -> dict[str, list[Any]]:
    succeeded = []
    failed = []

    for raw in raw_records:
        try:
            # 步骤 1:本地模型校验
            validated = RawInvoiceInput.model_validate(raw)
            # 步骤 2:同步调用外部接口(线程在此阻塞挂起)
            ocr_res = mock_sync_ocr_verify(validated.invoice_id, delay_per_item)
            succeeded.append({
                "invoice_id": validated.invoice_id,
                "amount": validated.total_amount,
                "ocr_status": ocr_res["ocr_status"],
            })
        except ValidationError as err:
            failed.append({
                "raw_id": raw.get("invoice_id", "UNKNOWN"),
                "error_type": "VALIDATION_ERROR",
                "detail": err.errors()[0]["msg"],
            })

    return {"succeeded": succeeded, "failed": failed}

如果输入 4 张合法发票,每张外部 OCR 调用需要 0.1 秒,由于是 for 循环串行执行,总耗时大约是 4 × 0.1s = 0.4s。

为了缩短处理时间,一种很容易出现的写法是:直接在函数前加上 async def,并在外部套上 asyncio.gather:

# invoice_batch.py(存在阻塞隐患的实现)
import asyncio


async def mock_blocked_async_ocr(invoice_id: str, delay_seconds: float = 0.1) -> dict[str, Any]:
    # 表面是 async 函数,内部却调用了同步阻塞的 time.sleep()
    time.sleep(delay_seconds)
    return {"invoice_id": invoice_id, "ocr_status": "VERIFIED"}


async def process_invoices_broken_async(
    raw_records: list[dict[str, Any]],
    delay_per_item: float = 0.1
) -> dict[str, list[Any]]:
    async def _handle_one(raw: dict[str, Any]) -> tuple[bool, dict[str, Any]]:
        try:
            validated = RawInvoiceInput.model_validate(raw)
            # 这里虽然写了 await,但底层调用的方法并不会交出执行权
            ocr_res = await mock_blocked_async_ocr(validated.invoice_id, delay_per_item)
            return True, {
                "invoice_id": validated.invoice_id,
                "amount": validated.total_amount,
                "ocr_status": ocr_res["ocr_status"],
            }
        except ValidationError as err:
            return False, {
                "raw_id": raw.get("invoice_id", "UNKNOWN"),
                "error_type": "VALIDATION_ERROR",
                "detail": err.errors()[0]["msg"],
            }

    tasks = [_handle_one(raw) for raw in raw_records]
    results = await asyncio.gather(*tasks)

    succeeded = [item for is_ok, item in results if is_ok]
    failed = [item for is_ok, item in results if not is_ok]
    return {"succeeded": succeeded, "failed": failed}

运行这段代码处理同样的 4 张发票,实测耗时依然是 0.4 秒左右。而且在执行这 0.4 秒期间,当前 Python 进程的主线程被占满,FastAPI 无法响应同一进程内的其他请求,所有并发用户的请求都会跟着卡住。


单线程的事件循环是怎么被卡住的

为什么加了 async def 还是串行?

Python 的 asyncio 并不是多线程,它本质上是一个单线程的事件循环(Event Loop)。协程之所以能并发,依赖的是“主动让渡控制权”:

  1. 协程 A 发出真正的异步网络请求后,发现数据还没从网卡回来,于是通过 await 主动告诉事件循环:“我先歇着,你先去跑别的任务”;
  2. 事件循环立即把 CPU 切给协程 B,协程 B 同样发出请求并挂起;
  3. 当某个请求的数据返回时,事件循环再切回去唤醒对应的协程继续往下执行。

Python 主线程事件循环阻塞与非阻塞并发对比

但当代码里调用了 time.sleep()、同步数据库驱动或同步 HTTP 客户端时,底层执行的是操作系统级别的线程阻塞。

它不会向事件循环交出控制权,而是直接占死了整个 CPU 执行时间。事件循环根本没有机会去调度下一个协程,所有原本打算并发的任务,只能排在这一条被堵死的单行道后面。


换成真正的非阻塞调用与并发限流

要解决这个问题,需要做三处改造:

  1. 替换为异步客户端:使用支持真正异步非阻塞网络通信的 httpx.AsyncClient;
  2. 连接池复用与逐请求超时:统一通过参数传递或依赖注入复用已有的客户端连接池,同时为单次请求设置 timeout,防止慢请求无限期卡死;
  3. 信号量(Semaphore)限流:当下游 OCR 接口有限流要求时,不能一股脑发起几百个并发请求,必须通过 asyncio.Semaphore 限制在途并发数量。

在 invoice_batch.py 中增加修复后的生产级实现:

# invoice_batch.py(修复后的非阻塞实现)
import asyncio
import httpx


async def mock_network_ocr_call(
    client: httpx.AsyncClient,
    invoice_id: str,
    delay_seconds: float = 0.05
) -> dict[str, Any]:
    # 模拟真正的异步网络 IO 等待
    # 在真实工程中,这里对应 await client.post("https://api.ocr-vendor.com/verify", json=...)
    await asyncio.sleep(delay_seconds)
    return {"invoice_id": invoice_id, "ocr_status": "VERIFIED"}


async def process_invoices_async(
    raw_records: list[dict[str, Any]],
    client: httpx.AsyncClient | None = None,
    max_concurrency: int = 2,
    request_timeout: float = 1.0,
    delay_per_item: float = 0.05,
) -> dict[str, list[Any]]:
    # 限制同时发往外部接口的最大请求数,保护下游不被冲垮
    semaphore = asyncio.Semaphore(max_concurrency)

    async def _handle_single(
        target_client: httpx.AsyncClient,
        raw: dict[str, Any]
    ) -> tuple[bool, dict[str, Any]]:
        # 步骤 1:本地数据合规校验,不合规的数据绝不发往网络
        try:
            validated = RawInvoiceInput.model_validate(raw)
        except ValidationError as err:
            return False, {
                "raw_id": raw.get("invoice_id", "UNKNOWN"),
                "error_type": "VALIDATION_ERROR",
                "detail": err.errors()[0]["msg"],
            }

        # 步骤 2:进入受控并发窗口
        async with semaphore:
            try:
                # 给单次外部请求设置明确超时,防止异常网络链路无限挂起
                ocr_resp = await asyncio.wait_for(
                    mock_network_ocr_call(target_client, validated.invoice_id, delay_per_item),
                    timeout=request_timeout
                )
                return True, {
                    "invoice_id": validated.invoice_id,
                    "amount": validated.total_amount,
                    "ocr_status": ocr_resp["ocr_status"],
                }
            except asyncio.TimeoutError:
                return False, {
                    "raw_id": validated.invoice_id,
                    "error_type": "OCR_TIMEOUT",
                    "detail": f"外部调用超过时限 ({request_timeout}s)",
                }
            except Exception as exc:
                return False, {
                    "raw_id": validated.invoice_id,
                    "error_type": "OCR_ERROR",
                    "detail": str(exc),
                }

    async def _execute_with_client(active_client: httpx.AsyncClient) -> dict[str, list[Any]]:
        tasks = [_handle_single(active_client, record) for record in raw_records]
        results = await asyncio.gather(*tasks)
        succeeded = [res for is_ok, res in results if is_ok]
        failed = [res for is_ok, res in results if not is_ok]
        return {"succeeded": succeeded, "failed": failed}

    # 步骤 3:支持从外部传入已有的连接池;若未传入则新建并自动管理其生命周期
    if client is not None:
        return await _execute_with_client(client)

    async with httpx.AsyncClient(timeout=httpx.Timeout(request_timeout)) as managed_client:
        return await _execute_with_client(managed_client)

这段实现中有三个关键细节:

首先,async with semaphore: 是实现受控并发的屏障。即使传入 100 张发票,只要 max_concurrency=2,同一时刻发往外部 OCR 的在途请求就不会超过 2 个。一旦某个请求结束并释放槽位,下一个协程才会补位进入。

其次,AsyncClient 支持从外部传入(如 FastAPI 挂载的应用级连接池),避免每次批处理都重复执行系统 SSL 证书加载与 TCP 握手。

最后,错误处理按照业务原因(VALIDATION_ERROR)、网络超时(OCR_TIMEOUT)与其他外部错误(OCR_ERROR)进行了清晰归类。当上游接口出现大面积超时时,调用方能立刻定位,而不是面对一堆笼统的 500 Internal Server Error。


怎么用自动化测试验证它

写好了逻辑,需要用自动化测试守住两条底线:脏数据在本地就能拦下,以及异步限流确实在控制并发上限的同时压低了总耗时。

完整测试放在 test_0_1.py,核心断言如下:

# test_0_1.py(节选)
async with httpx.AsyncClient() as client:
    t0 = time.perf_counter()
    # 单项延迟 0.05s,并发度为 2,4 个任务分两批完成,总耗时显著低于串行的 0.20s
    res = await process_invoices_async(
        records, client=client, max_concurrency=2, delay_per_item=0.05
    )
    elapsed = time.perf_counter() - t0

assert len(res["succeeded"]) == 4
assert elapsed < 0.18, f"受控异步并发超时,耗时: {elapsed}s"

文件里共包含 5 项离线确定性测试:

  1. 负数金额拦截:直接由 Pydantic 在本地抛出校验错误,不进入批处理。
  2. 明细合计不一致拦截:明细总和与 total_amount 不等时抛出 ValueError。
  3. 同步阻塞复现:4 条 0.05s 任务串行耗时达到 0.19s 以上。
  4. 受控并发验证:Semaphore=2 下 4 条任务分两批重叠完成,总耗时控制在 0.18s 以内。
  5. 超时分类验证:单请求超时设成 0.02s(模拟延迟 0.08s),任务被准确标为 OCR_TIMEOUT 而不拖垮整批。

运行测试:

python -m pytest course/lesson_01/test_0_1.py -v

测试通过后,既能锁定脏数据拦截的确定性,也能用实际耗时证明阻塞已经消除。


它的边界在哪里

写到这里,这套批处理机制已经能够平稳支撑常规业务。但在引入实际服务前,还需要清楚它的适用边界:

第一,它只能解决网络与 IO 等待,不能解决 CPU 密集型计算。如果后续发票需要在本地做高分辨率图像锐化、重度降噪计算,这些操作主要消耗 CPU 算力。由于 Python GIL 的存在,单纯把计算写进 async def 依然会霸占事件循环,必须用 loop.run_in_executor 把它丢进独立的进程池。

第二,内存中的 Semaphore 无法跨进程生效。如果生产环境通过 Gunicorn 或 Uvicorn 启动了 4 个工作进程,每个进程内部各有一个信号量,此时打往下游的实际最大并发数就会变成 2 × 4 = 8。如果下游服务对总并发有极其严苛的上限,后续就需要换成基于 Redis 的分布式限流。

第三,内存批处理不具备断电恢复能力。如果单次处理的发票数量很大(比如月末导入上千张),或者外部服务陷入持续数十分钟的故障,纯内存中的协程任务一旦遇上服务器重启就会全部丢失。这种场景需要把单次请求拆解为异步持久化任务,交给后续章节将要引入的任务队列去消化。


结论

在 async def 里混入同步阻塞,会直接夺走事件循环的调度能力,让并发调用退化成完全串行。工程上需要使用 httpx.AsyncClient 进行真正的非阻塞调用,并搭配 asyncio.Semaphore 与逐请求超时控制,在保护下游服务的同时缩短等待耗时。对于确定性的金额核算与脏数据拦截,则应始终在网络调用发生之前由本地强类型模型挡在门外。

半開

十年互联网经验,做过软件测试、Python 开发和产品工作,现在做个人产品,也写开发过程。

关于我订阅 RSS

回到文章列表