In our Shopify Dec 8 allowed_sources & Jan 1, 2027 expiring offline token guide, a sharp question came up in the comments right away:

How does pg_advisory_xact_lock actually behave behind **PgBouncer in transaction pooling mode, and when should you use **Redis SET NX PX + Lua* instead?*

When Shopify's 60-minute expiring offline tokens roll over during a merchant flash sale (10–50 concurrent orders/create and inventory_levels/update webhooks hitting your app at the same millisecond), picking the wrong locking primitive either causes 401 OAuth token rotation storms or exhausts your Postgres connection pool.

Here is the exact breakdown of all three patterns in production.

1. NEVER Use Session-Level pg_advisory_lock Behind PgBouncer transaction Pooling

In PgBouncer pool_mode = transaction, your backend PostgreSQL connection is returned to the pool the instant a transaction ends.

  • Calling session-level SELECT pg_advisory_lock(...) acquires a lock on whichever backend PG process served that statement.
  • Your subsequent pg_advisory_unlock(...) often runs on a different backend PG connection — silently failing to release the original lock and wedging that shop permanently until the backend disconnects.

2. When pg_advisory_xact_lock Works (and Its Hidden Pool-Starvation Trap)

Transaction-scoped pg_advisory_xact_lock(hashtextextended($1, 0)) is safe with PgBouncer transaction pooling because PostgreSQL releases the lock automatically on COMMIT or ROLLBACK on the exact same backend connection.

The catch: Because Shopify's OAuth token exchange (POST https://{shop}/admin/oauth/access_token) is an external network call taking 250ms–2,000ms, holding an open DB transaction across that HTTP call pins 1 Postgres backend connection per waiting webhook.

  • Low-to-medium concurrency (<15 concurrent webhooks/shop, modest merchant count): pg_advisory_xact_lock with strict lock_timeout is zero extra infrastructure and rock-solid:
-- Inside a single explicit transaction (PgBouncer transaction-pool safe) BEGIN; SET LOCAL lock_timeout = '5000ms'; SET LOCAL statement_timeout = '8000ms'; -- 64-bit collision-resistant hash of the shop domain SELECT pg_advisory_xact_lock(hashtextextended('shopify:refresh:' || $1, 0)); -- Double-check session freshness AFTER acquiring the lock! SELECT access_token, refresh_token, expires_at FROM "Session" WHERE shop = $1 AND is_online = false FOR UPDATE; -- Only if expires_at <= now() + interval '60 seconds', exchange token & UPDATE row, then COMMIT. COMMIT; 
  • High concurrency / serverless (Vercel, Netlify, Lambda, >20 simultaneous webhooks): Holding 30 open Postgres transactions waiting on an upstream Shopify HTTP timeout will saturate PgBouncer's default_pool_size and cascade into 503s across unrelated shops.

3. Production Pattern for Serverless & High Burst: Redis SET NX PX + Atomic Lua Release

Moving the single-flight mutex to Redis (Upstash, Redis Cloud, or self-hosted Redis) keeps zero PostgreSQL connections pinned during Shopify's HTTP OAuth round-trip.

Two rules make a Redis mutex actually race-proof:

  1. Unique ownerToken per caller (crypto.randomUUID()), released ONLY via an atomic Lua compare-and-delete script — so if Worker A stalls past ttlMs and Worker B acquires the lock, Worker A's late finally block can NEVER delete Worker B's lock.
  2. Short jittered poll + DB re-read for waiters (45–90ms), immediately returning the freshly written token the moment the winner commits to Postgres.
import crypto from "node:crypto"; const RELEASE_IF_OWNER_LUA = ` if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("DEL", KEYS[1]) else return 0 end `; export interface ShopSession { accessToken: string; refreshToken: string; expiresAtMs: number; } export async function refreshShopifyTokenRedisSingleFlight( shop: string, deps: { redisSetNxPx(key: string, val: string, ttlMs: number): Promise<boolean>; redisEvalRelease(lua: string, key: string, ownerToken: string): Promise<number>; loadSession(shop: string): Promise<ShopSession>; saveSession(shop: string, next: ShopSession): Promise<void>; callShopifyOAuthRefresh(shop: string, refreshToken: string): Promise<ShopSession>; }, opts = { skewMs: 60_000, lockTtlMs: 12_000, maxWaitMs: 8_000 } ): Promise<string> { const isFresh = (s: ShopSession) => s.expiresAtMs - Date.now() > opts.skewMs; const initial = await deps.loadSession(shop); if (isFresh(initial)) return initial.accessToken; const lockKey = `shopify:refresh:lock:${shop}`; const owner = crypto.randomUUID(); const deadline = Date.now() + opts.maxWaitMs; while (Date.now() < deadline) { const acquired = await deps.redisSetNxPx(lockKey, owner, opts.lockTtlMs); if (acquired) { try { const latest = await deps.loadSession(shop); if (isFresh(latest)) return latest.accessToken; const refreshed = await deps.callShopifyOAuthRefresh(shop, latest.refreshToken); await deps.saveSession(shop, refreshed); return refreshed.accessToken; } finally { await deps.redisEvalRelease(RELEASE_IF_OWNER_LUA, lockKey, owner); } } await new Promise((r) => setTimeout(r, 45 + Math.floor(Math.random() * 45))); const polled = await deps.loadSession(shop); if (isFresh(polled)) return polled.accessToken; } throw new Error(`Timed out waiting for single-flight Shopify token refresh for ${shop}`); } 

Decision Matrix

Architecture Recommended Lock Why
Monolith / single VPS, <15 concurrent webhooks/shop Postgres pg_advisory_xact_lock + lock_timeout Zero extra infra; PgBouncer transaction-pool safe
Serverless (Vercel/Netlify/Lambda) or busy Plus merchants Redis SET NX PX + Lua compare-and-delete Zero Postgres connections held during Shopify's HTTP call
Anything behind PgBouncer transaction mode Never session pg_advisory_lock Leaks locks across pooled backend connections

Audit Your Shopify App Before Dec 8 & Jan 1 (Zero Upload — CLI, Browser & Official MCP Server)

(Disclosure: the CLI, MCP server, browser auditor, and 401 simulator are completely free/MIT. Our optional $49/$99 Shopify Compliance Survival Kit ZIP bundles both tested Redis Lua and Postgres advisory-lock implementations, a checkpointed batch migrateToExpiringToken() runner with HTTP 429 backoff, and drop-in Prisma/Drizzle/SQL migrations.)