我們的產品是多租戶架構,同一套後台服務好幾個客戶,每個客戶有自己的資料庫。

二月修了一個蠻嚴重的 bug:在特定時機下,A 客戶的管理後台可能讀到 B 客戶的資料庫。原因是「目前的租戶」存在模組層級的全域變數裡。

問題

簡化過的程式:

# db.py
current_db = None   # ⚠️ 全域

def set_tenant(tenant):
    global current_db
    current_db = mongo[tenant.db_name]

def get_collection(name):
    return current_db[name]
# middleware
@app.middleware("http")
async def tenant_middleware(request, call_next):
    set_tenant(resolve_tenant(request))
    return await call_next(request)

如果一次只處理一個請求,這樣寫沒事。但 FastAPI 是 async 的:

請求 A:set_tenant(A) → await 查詢中(讓出控制權)
請求 B:set_tenant(B)
請求 A:恢復執行 → get_collection() → 拿到 B 的資料庫 💥

中間只要有一個 await,全域變數就可能被別的請求改掉。

改用 ContextVar

contextvars 從 Python 3.7 開始就有,每個 asyncio Task 有自己的一份 context,彼此不會互相覆蓋。

from contextvars import ContextVar

_current_db: ContextVar = ContextVar("current_db")

def set_tenant(tenant):
    _current_db.set(mongo[tenant.db_name])

def get_collection(name):
    db = _current_db.get(None)
    if db is None:
        raise RuntimeError("tenant not set for this request")
    return db[name]

Starlette 和 FastAPI 的每個請求都在獨立的 context 裡跑,middleware 裡 set 的值只有這個請求看得到。

幾個細節

用 .get(default)。沒有預設值又沒 set 過的話,ContextVar.get() 會丟 LookupError。背景任務、排程、CLI 腳本這些不經過 HTTP 的路徑最容易遇到。

拿不到租戶就報錯,不要退回某個預設資料庫。退回預設看起來比較友善,但跨租戶的問題就被藏起來了。

限制能放的東西。我們把 request-scoped 的屬性做成白名單,只允許 db、collections、tenant 這幾個 key。不然大家什麼都往裡面塞,最後又變成另一種全域變數。

單元測試沒有 middleware,記得在 setup 裡自己 set。

怎麼測

這種 race condition 一般的單元測試抓不到。我寫了一個故意讓出控制權的測試:

async def test_no_cross_tenant_leak():
    async def call(tenant):
        set_tenant(tenant)
        await asyncio.sleep(0)          # 故意讓出控制權
        return get_collection("users").database.name

    results = await asyncio.gather(*(call(t) for t in tenants))
    assert results == [t.db_name for t in tenants]

舊的全域變數版本跑這個測試會失敗,換成 ContextVar 之後就過了。之後只要是每個請求都不一樣的值,像租戶、使用者、trace id,我都直接放 ContextVar。