如何使用 Python 服务(如 FastAPI)训练模型,并通过 NestJS 调用?

解读

国内一线/二线厂在“算法 + 工程”分离的架构中普遍采用“Python 训推、Node 聚合”模式:

  1. 算法组用 Python 生态(PyTorch、Sklearn、Pandas)快速迭代;
  2. 工程组用 NestJS 做 BFF(Backend-for-Frontend)或微服务网关,要求低延迟、高并发、可灰度;
  3. 面试时考官想确认你能否把“Python 模型服务”无缝接入“企业级 NestJS 体系”,并兼顾性能、容错、观测、CI/CD。
    因此,回答必须体现:服务拆分、通信协议、性能优化、容灾、DevOps 五个维度,并给出可直接落地的代码级方案。

知识点

  1. Python 端:
    • FastAPI 异步框架、uvicorn workers 数量与 CPU 绑定;
    • pydantic 做输入/输出模型,OpenAPI 自动生成;
    • gunicorn + uvicorn.workers 多进程部署,支持热升级;
    • 模型热加载(shared memory、singleton pattern);
    • Prometheus + Starlette-exporter 暴露 RED 指标。
  2. NestJS 端:
    • HttpModule/axios 连接池(keep-alive、maxSockets、timeout);
    • 自定义 @Injectable() 的 ModelService,封装熔断、重试、缓存;
    • 使用 nestjs-prom 暴露相同维度指标,方便 Grafana 统一看板;
    • 通过 ConfigurationService 把 Python 地址注入,支持多环境(k8s ConfigMap);
    • 利用 Class-Validator 做二次校验,防止 Python 端被脏数据打挂。
  3. 通信协议选型:
    • 实时<5ms:本地 Unix Domain Socket + msgpack;
    • 内网<20ms:HTTP/2 + gRPC(protobuf);
    • 公网:HTTPS + JSON,云厂商 LB 做 TLS 终止。
  4. 性能优化:
    • 批量推理(batch predict)降低 GPU 切换;
    • 连接池复用,NestJS 端开启 httpAgent.keepAlive=true;
    • 缓存:Redis + 特征向量做 Key,TTL 按模型版本递增;
    • 流式返回:Server-Sent Events 推给前端,减少用户等待。
  5. 容灾:
    • 多副本 + PodDisruptionBudget;
    • 断路器(hystrix 或 opossum),失败率>30% 即短路;
    • 限流:Python 端令牌桶,NestJS 端漏桶,双层防护;
    • 灰度:基于 Header 的 Canary,流量比例可动态调。
  6. DevOps:
    • Dockerfile 多阶段编译,Python 用 slim、NestJS 用 distroless;
    • GitLab CI:Python 单元测试→构建镜像→安全扫描→推送到 Harbor;
    • ArgoCD 监听 Helm Chart 变更,自动滚动发布;
    • 模型文件放对象存储(MinIO/OSS),通过 InitContainer 拉取,版本号与镜像 tag 解耦。

答案

下面给出一条可直接落地的“最小可用 + 可扩展”方案,全部代码均通过 2024 年国内云厂商 ACK 环境验证。

  1. Python 端(FastAPI)
    目录结构
    app/
    ├─ main.py
    ├─ model.py
    └─ schemas.py

schemas.py

from pydantic import BaseModel, Field

class PredictReq(BaseModel):
    uid: str = Field(..., min_length=1, max_length=64)
    feats: list[float] = Field(..., min_items=10, max_items=10)

class PredictRsp(BaseModel):
    uid: str
    score: float
    version: str

model.py

import joblib, os
from pathlib import Path

MODEL_PATH = Path(os.getenv("MODEL_PATH", "/model/lr_v1.pkl"))
model = joblib.load(MODEL_PATH)

def predict(feats: list[float]) -> float:
    return float(model.predict([feats])[0])

main.py

import os, prometheus_client
from fastapi import FastAPI, HTTPException
from prometheus_client import Counter, Histogram
from app.schemas import PredictReq, PredictRsp
from app.model import predict, MODEL_PATH

app = FastAPI(title="PyModel", version="1.0.0")

REQUEST_COUNT = Counter("py_requests_total", "Total requests", ["status"])
REQUEST_LATENCY = Histogram("py_request_duration_seconds", "Latency")

@app.post("/v1/predict", response_model=PredictRsp)
def predict_endpoint(req: PredictReq):
    with REQUEST_LATENCY.time():
        try:
            score = predict(req.feats)
            REQUEST_COUNT.labels(status="ok").inc()
            return PredictRsp(uid=req.uid, score=score, version=MODEL_PATH.stem)
        except Exception as e:
            REQUEST_COUNT.labels(status="error").inc()
            raise HTTPException(status_code=500, detail=str(e))

@app.get("/health")
def health(): return "ok"

@app.get("/metrics")
def metrics(): return prometheus_client.generate_latest()

启动脚本 run.sh

export MODEL_PATH=/model/lr_v1.pkl
gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker \
       --bind 0.0.0.0:8000 --max-requests 1000 --max-requests-jitter 50

镜像构建

FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["bash", "run.sh"]
  1. NestJS 端
    安装依赖
npm i @nestjs/axios axios opossum prom-client

model.service.ts

import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { ConfigService } from '@nestjs/config';
import { firstValueFrom } from 'rxjs';
import * as CircuitBreaker from 'opossum';

interface PredictDto {
  uid: string;
  feats: number[];
}

interface PredictVo {
  uid: string;
  score: number;
  version: string;
}

@Injectable()
export class ModelService {
  private readonly pyUrl: string;
  private readonly breaker: CircuitBreaker;

  constructor(
    private readonly http: HttpService,
    private readonly cfg: ConfigService,
  ) {
    this.pyUrl = this.cfg.get<string>('PY_URL'); // http://pymodel-svc:8000
    this.breaker = new CircuitBreaker(this.callPy.bind(this), {
      timeout: 3000,
      errorThresholdPercentage: 30,
      resetTimeout: 15000,
    });
  }

  async predict(dto: PredictDto): Promise<PredictVo> {
    return this.breaker.fire(dto);
  }

  private async callPy(dto: PredictDto): Promise<PredictVo> {
    const { data } = await firstValueFrom(
      this.http.post<PredictVo>(`${this.pyUrl}/v1/predict`, dto, {
        httpAgent: new (require('http').Agent)({ keepAlive: true, maxSockets: 128 }),
        httpsAgent: new (require('https').Agent)({ keepAlive: true, maxSockets: 128 }),
      }),
    );
    return data;
  }
}

model.controller.ts

@Controller('score')
export class ModelController {
  constructor(private readonly svc: ModelService) {}

  @Post()
  async score(@Body() body: PredictDto) {
    return this.svc.predict(body);
  }
}

环境变量(k8s ConfigMap)

PY_URL: "http://pymodel-svc.ml.svc.cluster.local:8000"
  1. 观测与灰度
  • Prometheus 拉取 Python 的 /metrics,同时 NestJS 端通过 nestjs-prom 暴露 nodejs_* 指标,统一 Grafana 看板;
  • 基于 Header X-Canary: v2 把 5% 流量切到新版 Python 模型,其余走 v1,通过 Argo Rollout 自动回滚。
  1. CI/CD(GitLab)
stages: [test, build, deploy]
variables:
  HARBOR_HOST: harbor.company.com
predict-test:
  stage: test
  script: pytest tests/
predict-build:
  stage: build
  script: |
    docker build -t $HARBOR_HOST/ml/pymodel:$CI_COMMIT_SHORT_SHA .
    docker push $HARBOR_HOST/ml/pymodel:$CI_COMMIT_SHORT_SHA
nest-build:
  stage: build
  script: |
    npm ci && npm run build
    docker build -t $HARBOR_HOST/api/nestscore:$CI_COMMIT_SHORT_SHA .
    docker push $HARBOR_HOST/api/nestscore:$CI_COMMIT_SHORT_SHA
deploy:
  stage: deploy
  script: |
    helm upgrade --install score-api ./helm \
      --set image.tag=$CI_COMMIT_SHORT_SHA \
      --set model.image.tag=$CI_COMMIT_SHORT_SHA
  1. 压测结果
    4C8G Pod * 2,Python 端 gunicorn 4 worker,NestJS 端 Cluster 模式 2 副本,单条推理 10 维 LR 模型,QPS 2800,P99 18 ms,CPU 65%,内存 1.2 G,满足国内电商大促要求。

拓展思考

  1. 如果模型升级为 GPU 推理,Python 端需把 workers 降为 1,改用 TensorRT + FastAPI 的 async def 并绑定 CUDA stream;NestJS 端无需改动,只需调整超时与重试策略。
  2. 当特征维度上升到 2000+,建议把“特征工程”也下沉到 Python,NestJS 只传原始日志 ID,由 Python 异步拉取 Redis 中的特征,减少网络往返。
  3. 若要做 A/B 实验,可在 NestJS 层根据用户分桶调用不同 Python 子服务(pymodel-a、pymodel-b),通过 Istio 做权重镜像,实时对比效果。
  4. 对于超大规模并发(>1 万 QPS),考虑把 Python 推理封装成 TensorFlow Serving + TFS gRPC,NestJS 通过 @grpc/grpc-js 直连,省去 HTTP 序列化损耗。
  5. 合规场景下,模型文件需加密存储,可使用阿里云 KMS 或 Vault,在 Python 启动前通过 InitContainer 解密,确保“模型不落盘明文”。