Repository navigation
fix(analytics): avoid sending the same JavaScript-mode batch twice - #484
rahul-mixpanel wants to merge 2 commits into
Conversation
In JavaScript mode the event queue is shared per token, but every Mixpanel instance runs its own flush timer, and processQueue does not wait for the request it starts. Two instances for the same token (for example one created inside a component), a flush() during a timer flush, or a request slower than the flush interval all sent the same batch again before it was removed from the queue. JavaScript mode adds no $insert_id, so the duplicates were ingested. Allow one flush per token and endpoint at a time, like the native SDKs, which flush on a single worker. Related to #283 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
[Medium impact] The change affects JavaScript-mode queue sending across timer and manual flushes. Do not merge until replacing an old lock can no longer resend a batch whose request is still active. FindingsFix with agent prompt### Issue 1
javascript/mixpanel-core.js:113-124
If a request takes longer than two minutes, a later timer flush replaces its lock and sends the same queued batch again. `sendRequest` has no timeout or cancellation, and its 62 seconds of backoff excludes time spent in `fetch` and `response.json()`. The old request can therefore still deliver or retry the batch, causing duplicate events or profile updates.
The `ownsLock()` check only stops the old request from removing records. Keep the lock until the request settles, or stop the old request and its retries before replacing it.
### Issue 2
__tests__/core.test.js:139-146
Both queue mocks ignore the endpoint, and each request overwrites `finishRequest`. The first `flush()` starts all three endpoints, so `finishRequest()` completes `/groups/` and empties their shared fake queue. The test passes with `/track/` still pending, so it cannot catch a missing lock release after event delivery. Return data only for `MixpanelType.EVENTS`, resolve that request, and check that a later flush can send another event.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
|
| MixpanelQueueManager.getQueue.mockImplementation(() => [...queue]); | ||
| MixpanelQueueManager.spliceQueue.mockImplementation(async (t, ty, start, count) => { | ||
| queue.splice(start, count); | ||
| }); | ||
| let finishRequest; | ||
| MixpanelNetwork.sendRequest.mockImplementation( | ||
| () => new Promise((resolve) => (finishRequest = resolve)) | ||
| ); |
There was a problem hiding this comment.
Test completes the wrong request
Both queue mocks ignore the endpoint, and each request overwrites finishRequest. The first flush() starts all three endpoints, so finishRequest() completes /groups/ and empties their shared fake queue. The test passes with /track/ still pending, so it cannot catch a missing lock release after event delivery. Return data only for MixpanelType.EVENTS, resolve that request, and check that a later flush can send another event.
Prompt To Fix With AI
This is a comment left during a code review.
Path: __tests__/core.test.js
Line: 138-145
Comment:
**Test completes the wrong request**
Both queue mocks ignore the endpoint, and each request overwrites `finishRequest`. The first `flush()` starts all three endpoints, so `finishRequest()` completes `/groups/` and empties their shared fake queue. The test passes with `/track/` still pending, so it cannot catch a missing lock release after event delivery. Return data only for `MixpanelType.EVENTS`, resolve that request, and check that a later flush can send another event.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.…failed flushes Review follow-up. React Native's Android fetch has no default timeout, so a request that never settles held the per-token flush lock for the rest of the session. A batch pending longer than sendRequest's full retry window (2 minutes, above the ~62s of backoff) now counts as stuck, and the next flush takes over. A taken-over flush stops without removing events from the queue. The batch loop now releases the lock in a finally block, so an unexpected throw (storage, logging, or the 400 path's spliceQueue) can't leave it held. The lock key also uses a separator. Related to #283 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| if (current && Date.now() - current.batchStartedAt < FLUSH_LOCK_STALE_MS) { | ||
| MixpanelLogger.log(token, `Flush already in progress for endpoint: ${type}`); | ||
| return; | ||
| } | ||
| if (current) { | ||
| MixpanelLogger.warn( | ||
| token, | ||
| `Previous flush for endpoint ${type} appears stuck, starting a new one.` | ||
| ); | ||
| } | ||
| const lock = { batchStartedAt: Date.now() }; | ||
| flushLocks.set(flushKey, lock); |
There was a problem hiding this comment.
Slow requests send batches twice
If a request takes longer than two minutes, a later timer flush replaces its lock and sends the same queued batch again. sendRequest has no timeout or cancellation, and its 62 seconds of backoff excludes time spent in fetch and response.json(). The old request can therefore still deliver or retry the batch, causing duplicate events or profile updates.
The ownsLock() check only stops the old request from removing records. Keep the lock until the request settles, or stop the old request and its retries before replacing it.
Knowledge Base Used: Event delivery and persistence
Prompt To Fix With AI
This is a comment left during a code review.
Path: javascript/mixpanel-core.js
Line: 113-124
Comment:
**Slow requests send batches twice**
If a request takes longer than two minutes, a later timer flush replaces its lock and sends the same queued batch again. `sendRequest` has no timeout or cancellation, and its 62 seconds of backoff excludes time spent in `fetch` and `response.json()`. The old request can therefore still deliver or retry the batch, causing duplicate events or profile updates.
The `ownsLock()` check only stops the old request from removing records. Keep the lock until the request settles, or stop the old request and its retries before replacing it.
**Knowledge Base Used:** [Event delivery and persistence](https://app.greptile.com/-/switch-tenant?tenant=mixpanel&next=%2Fcustom-context%2Fknowledge-base%2Fmixpanel%2Fmixpanel-react-native%2F-%2Fdocs%2Fevent-delivery-and-persistence.md)
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
Summary
In JavaScript mode (
useNative: false, Expo, React Native Web), the event queue is shared by everyMixpanelinstance for a token, but each instance runs its own flush timer.processQueuealso starts the request without waiting for it. So the same batch was sent again before it was removed from the queue in these cases:new Mixpanel(...)inside a component, or React StrictMode mounting twice), and their timers fire together;flush()is called while a timer flush is in flight;sendRequestis in its own retry backoff (up to 5 retries, ~62s;mixpanel-network.js:101-118).JavaScript mode adds no
$insert_id, so the server ingests these duplicates. Overlapping flushes also each calledspliceQueuefor the same batch, so the second splice could delete events that had never been sent. This fits #283, which reports duplicate/trackand/engagerequests in an Expo app withuseNative: false.Fix
One flush per token and endpoint at a time, matching the native SDKs, which flush on a single worker:
AnalyticsMessages.java:435-460(oneHandlerThread)MixpanelInstance.swift:352(serialnetworkQueue)How it behaves:
flush(). The running flush keeps draining the queue, including events added while it runs.fetchhas no default timeout (OkHttp timeouts are 0), andsendRequesthas no abort. So a request that never settles, such as a half-open connection after a network switch, would otherwise hold the lock for the rest of the session. A batch pending longer than 2 minutes (above the ~62s retry window) is treated as stuck, and the next flush takes over. The stuck flush then stops without touching the queue, so it can't remove events the new flush hasn't sent. At worst, the batch it was sending is sent once more, which is what master did on every interval.finallyblock, so an unexpected throw (storage, logging, or the 400 path'sspliceQueue) can't leave it held.Nothing changes in what's sent, the payloads, the request timeouts, the defaults or the public APIs.
Tests
__tests__/core.test.jshas three new tests, and each fails without the fix:MixpanelMaininstances: before, 2/tracksends per event; after, 1. Slow network: 2 before, 1 after.Related to #283
🤖 Generated with Claude Code