Solving the "Arrived-Before-Wait" 2FA Race Condition for Headless Browser Agents
Why naive webhook polling and sleep loops fail when OTPs arrive 150ms before page.click() resolves—and how Upstash Redis ZSET lookbacks, atomic Lua claiming, and <8ms deterministic sanitization eliminate race conditions.
Why Naive 2FA Webhooks and IMAP Pollers Fail in Production
Most headless browser teams start handling 2FA the same way: click "Send Code", sleep 5 seconds, query an IMAP inbox or wait on a Pub/Sub subscriber, and regex the newest message for 6 digits.
In production across Stagehand, Browserbase, Playwright, and Browser Use fleets, that pattern develops three catastrophic failure modes as soon as concurrency climbs above a single serial script:
- The "Arrived-Before-Wait" Race Condition: Modern transactional mailers and SMS shortcodes often deliver an OTP in 350ms—before Playwright finishes awaiting page.click("button[type=submit]") and transitions to the 2FA route. If your worker opens a pure Pub/Sub stream after the click resolves, the event already fired into the void and your agent hangs until timeout.
- Parallel Worker Token Collision: When two parallel browser sessions log into the same SaaS portal or share a client inbox, a naive "get latest email" poller returns the exact same 6-digit OTP to both workers. Worker B submits an already-invalidated token and locks out the account.
- LLM Extraction Latency & Prompt Injection: Piping raw HTML emails into an LLM to extract a verification code adds 1.5–4 seconds of latency, burns tokens on every login, and exposes your agent context to hidden preheader prompt injection traps.
Inside the Race-Free Bus: Lookback Timeline ZSET + Atomic Lua Claiming
Sentry Relay eliminates both timing races and parallel collisions at the Redis layer by pairing a per-Identity Sorted Set timeline (identity:{id}:timeline scored by arrival millisecond) with an atomic Lua claim script (CLAIM_AUTH_EVENT_LUA) and an Upstash Pub/Sub channel.
When your agent calls GET /api/v1/identities/{id}/wait (with a default 15,000ms lookback window), the server executes CLAIM_AUTH_EVENT_LUA immediately before subscribing to Pub/Sub:
-- Executed atomically on Upstash Redis inside /wait and /latest
local eventIds = redis.call('ZREVRANGEBYSCORE', KEYS[1], '+inf', ARGV[1])
for _, eventId in ipairs(eventIds) do
local eventKey = ARGV[7] .. eventId
local raw = redis.call('GET', eventKey)
if raw then
local evt = cjson.decode(raw)
local isUnconsumed = (evt.consumed == false)
local isAuthOrAllowed = (evt.classification ~= 'non_auth' or ARGV[8] == '1')
local channelOk = (ARGV[2] == '' or evt.channel == ARGV[2])
local senderOk = (ARGV[3] == '' or string.find(string.lower(evt.sender or ''), ARGV[3], 1, true) ~= nil)
local subjectOk = (ARGV[4] == '' or string.find(string.lower(evt.subject or ''), ARGV[4], 1, true) ~= nil)
if isUnconsumed and isAuthOrAllowed and channelOk and senderOk and subjectOk then
if ARGV[5] == '1' then
if ARGV[6] == '1' then
redis.call('DEL', eventKey)
redis.call('ZREM', KEYS[1], eventId)
else
evt.consumed = true
evt.consumedAtMs = tonumber(redis.call('TIME')[1]) * 1000
local ttl = redis.call('TTL', eventKey)
if ttl > 0 then
redis.call('SETEX', eventKey, ttl, cjson.encode(evt))
end
end
end
return cjson.encode(evt)
end
end
end
return nilBecause Redis executes Lua scripts atomically in a single thread, two workers polling the same Identity simultaneously can never claim the same event. If burnAfterRead is enabled (ARGV[6] == "1"), the raw payload is purged from Redis RAM inside the exact same atomic transaction.
If no unconsumed matching event exists inside the lookback window yet, /wait subscribes to channel:identity:{id} and re-runs CLAIM_AUTH_EVENT_LUA the millisecond an inbound Cloudflare Email Worker or Telnyx SMS webhook fires—delivering <200ms p95 wake-up latency.
Zero-LLM <8ms Deterministic Extraction & Forwarding Header Unwrapping
Before an inbound email or SMS ever touches Redis, @sentryrelay/extractor runs a 5-stage deterministic pipeline in under 8ms with zero LLM inference cost:
- 01Stage 1: Size Guard & Unicode Normalization
Enforces a 256 KB payload cap, decodes HTML entities, and strips zero-width characters and Unicode homoglyphs commonly inserted by obfuscated transactional templates.
- 02Stage 2: Forwarded-Email Header Unwrapping
Detects Gmail ("---------- Forwarded message ---------"), Outlook, and Apple Mail forwarding wrappers to recover the true originalSender and originalSubject—so 60-second auto-forward rules still match sender="stripe.com".
- 03Stage 3: HTML DOM Sanitizer & Click-Tracker Unwrapper
Strips hidden preheader traps, extracts structural emphasis blocks (<h1>, <code>), removes footer unsubscribe noise, and unwraps SendGrid, Mailgun, and Postmark click-tracking redirects.
- 04Stage 4: Priority Custom Rules & 16 Curated Vendor Templates
Evaluates per-Identity custom regex rules first, then applies curated vendor rules (GitHub, Google G-code stripping, Stripe 123-456 collapsing, Slack A4B-9K2 codes, Clerk __clerk_ticket, AWS, Okta, etc.) while disqualifying invoices, PR alerts, and receipts.
- 05Stage 5: Proximity-Scored Heuristics
For arbitrary banking, insurance carrier, healthcare EHR, or custom ERP portals, scores candidate tokens and verification links by proximity to authentication keywords and classifies non-auth messages cleanly for Human Fallback.
Eliminating the Silent 10% TOTP Rollover Failure Rate
Even static RFC 6238 TOTP has a hidden timing race in LLM-driven browser agents. If your script fetches a TOTP code with 2.1 seconds remaining in the 30-second window, Stagehand or Browser Use takes 2–3 seconds to locate the input and click Submit—by which time the server rejects the expired code.
Both @sentryrelay/sdk and sentryrelay-sdk solve this by checking remainingSeconds: when <=4 seconds remain, the client transparently pauses until the next 30-second period activates, guaranteeing a fresh 26–30 second token in one call:
import { SentryRelay } from '@sentryrelay/sdk';
const relay = new SentryRelay({ apiKey: process.env.SENTRY_RELAY_API_KEY! });
// Wait for Email/SMS OTP with 15s lookback + <200ms Redis Pub/Sub push
const auth = await relay.wait('checkout-bot', {
sender: 'stripe.com',
timeout: 30,
});
// Or generate a Cloud KMS TOTP code guaranteed valid for 26-30 seconds
const totp = await relay.totp.get('checkout-bot', 'aws_root', {
autoWaitFreshWindow: true,
});