使用 Vitess 时如何在 FastAPI 中设置 shard key?
解读
国内大厂做微服务拆库时,Vitess 是 MySQL 水平分片的主流方案。面试官问“FastAPI 里怎么设 shard key”,并不是让你改 Vitess 的 vschema,而是考察:
- 你是否理解 shard key 最终由 Vitess 的 VTGate 按 SQL 注释或绑定变量决定;
- 你是否能在 Python 侧把“业务字段 → 注释/变量”这一步做干净,让 FastAPI 的异步 SQL 层可维护、可单测、可灰度。
一句话:FastAPI 本身不碰分片逻辑,但它必须“优雅地把 shard key 递到 Vitess”。
知识点
- Vitess 两种显式指定 shard key 的协议
- 注释法:/vtgate::keyspace_id:xxxx/ 或 /vtgate::shard_key:xxxx/
- 绑定变量法:cursor.execute(sql, {"id": 123, "__vtshardkey": 123})
- SQLAlchemy 1.4+ 异步方言:asyncmy、aiomysql 均支持在编译阶段注入 SQL 注释。
- FastAPI 依赖注入:用
Depends(get_db)拿到带路由上下文(含 shard key)的AsyncSession。 - 上下文变量(contextvars)在协程池内安全传递,避免手动透传参数。
- 国内灰度规范:shard key 必须从请求维度提取(uid、手机号、订单号),禁止在代码里硬编码。
答案
给一套可直接落地的“注释法”实现,兼顾单元测试与灰度开关。
- 定义上下文变量
# app/core/shard.py
import contextvars
shard_key_ctx: contextvars.ContextVar[str] = contextvars.ContextVar("shard_key", default="")
- 自定义 SQLAlchemy 编译器,在发往 VTGate 的 SQL 前自动拼注释
# app/core/vitess_dialect.py
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql import crud
@compiles(crud.Insert)
@compiles(crud.Update)
@compiles(crud.Delete)
def _add_vitess_comment(element, compiler, **kw):
sql = compiler.visit_crud(element, **kw)
key = shard_key_ctx.get()
if key:
sql = f"/*vtgate::keyspace_id:{key}*/ {sql}"
return sql
- FastAPI 依赖:从请求头或 JWT payload 里取 shard key,写进上下文
# app/deps/db.py
from fastapi import Depends, Header
from app.core.shard import shard_key_ctx
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from app.core.config import settings
engine = create_async_engine(settings.VITESS_DSN, pool_pre_ping=True, echo=False)
async def get_session(x_shard_key: str = Header(..., alias="X-Shard-Key")) -> AsyncSession:
token = shard_key_ctx.set(x_shard_key)
async with AsyncSession(engine) as session:
yield session
shard_key_ctx.reset(token)
- 业务路由零侵入
# app/routers/order.py
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from app.deps.db import get_session
from app.models import Order
router = APIRouter()
@router.post("/orders")
async def create_order(order: OrderDTO, session: AsyncSession = Depends(get_session)):
session.add(Order(**order.dict()))
await session.commit()
return {"ok": True}
- 单元测试
# tests/test_order.py
import pytest, asyncio
from httpx import AsyncClient
from app.main import app
@pytest.mark.anyio
async def test_create_order_with_shard(client: AsyncClient):
resp = await client.post(
"/orders",
json={"user_id": 123, "amount": 100},
headers={"X-Shard-Key": "123"}
)
assert resp.status_code == 201
至此,FastAPI 侧完成“设置 shard key”:业务代码无感知,VTGate 收到带注释的 SQL 后按 vschema 路由到对应分片。
拓展思考
- 绑定变量法:若公司 DBA 强制要求用
__vtshardkey,可在 SQLAlchemy 事件before_cursor_execute里把execution_options中的shard_key塞进参数,再改 SQL 为WHERE id=:id AND __vtshardkey=:__vtshardkey,避免注释被代理层洗掉。 - 多 keyspace 灰度:利用 FastAPI 的
APIRouter(prefix="/v2")与不同的get_session_v2依赖,按 header 中的X-Keyspace-Version路由到新 keyspace,实现秒级回滚。 - 性能陷阱:contextvars 在
*sync线程池里会丢失,若必须调同步 SDK(如旧版支付库),用asyncio.to_thread并重新传参。 - 监控:在
after_cursor_execute事件里把真正命中的 shard 打到 Prometheus,防止“看似指定 shard key,实际 VTGate 广播”的慢查询。