Skip to content

fix(cache): await db query before cache.onMutate to close stale-repopulation race#5951

Open
sanjibani wants to merge 1 commit into
drizzle-team:mainfrom
sanjibani:fix/cache-invalidation-race
Open

fix(cache): await db query before cache.onMutate to close stale-repopulation race#5951
sanjibani wants to merge 1 commit into
drizzle-team:mainfrom
sanjibani:fix/cache-invalidation-race

Conversation

@sanjibani

Copy link
Copy Markdown

Closes #5828.

The cache invalidation in PgPreparedQuery.queryWithCache was firing concurrently with the DB write via Promise.all, contradicting the in-code comment that said the DB write should resolve first.

When onMutate (a single Redis Lua script call) completed before the DB write committed, a concurrent SELECT could read the pre-mutation row and repopulate the cache via cache.put(), serving stale data until TTL expiry. Repro: write-heavy workload with cache.ex larger than the DB RTT.

Change Promise.all([query(), onMutate]) to sequential await. The DB write now commits before any cache keys are cleared, closing the race. Same fix applied to mysql-core, sqlite-core, gel-core, singlestore-core which shared the identical pattern.

Regression test added in pg-common-cache.ts that fails on the old ordering and passes on the new.

…ulation race

The cache invalidation in PgPreparedQuery.queryWithCache was firing
concurrently with the DB write via Promise.all, contradicting the
in-code comment that said the DB write should resolve first.

When onMutate (a single Redis Lua script call) completed before the
DB write committed, a concurrent SELECT could read the pre-mutation
row and repopulate the cache via cache.put(), serving stale data
until TTL expiry. Repro: write-heavy workload with cache ex > DB RTT.

Change Promise.all([query(), onMutate]) to sequential await. The DB
write now commits before any cache keys are cleared, closing the race.
Same fix applied to mysql-core, sqlite-core, gel-core, singlestore-core
which shared the identical pattern.

Regression test added in pg-common-cache.ts that fails on the old
ordering (query:end > onMutate) and passes on the new (query:end < onMutate).

Closes drizzle-team#5828
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Cache invalidation runs concurrently with DB write, causing stale-cache repopulation race

1 participant