Full answer
Clarify the goals: acceptable loss rate, event volume, payload size, offline behavior, and privacy rules (consent, personal data).
Design:
- API:
track(name, props)returns immediately and never throws. It adds metadata: an event id (crypto.randomUUID()), a client timestamp, session id, page, and library version. - Queue: an in-memory array with a maximum length. When it is full, drop the oldest events (or sample) and count the drops. Optionally persist to
localStorageor IndexedDB so events survive reloads, with a size cap. - Flush triggers: batch size reached (for example 20), a timer (for example 5 seconds after the first event, not a ticking interval), and page lifecycle. On
visibilitychangeto hidden and onpagehide, flush withnavigator.sendBeacon(url, blob)orfetch(url, { keepalive: true }). Do not useunloadorbeforeunload, which are unreliable and block the back/forward cache. Beacon payloads have a size limit (about 64 KB), so split big batches. - Sending: one request per batch, compressed JSON if needed, a first-party or token-based endpoint, and the send time in the payload so the server can correct client clock errors.
- Failure handling: on network errors or 5xx, put events back in the queue and retry with exponential backoff and jitter, limited attempts. On 4xx (except 429), drop the batch because retry cannot help. Respect
Retry-After. - Idempotency: event ids let the server remove duplicates caused by retries or by beacon and fetch both succeeding.
- Performance: do the work in idle time or after the interaction, keep payloads small, do not block rendering, and avoid synchronous storage on hot paths.
- Privacy and consent: do not send before consent when required, support opt-out and a "Do Not Track" or Global Privacy Control signal, avoid personal data in properties, and allow a data deletion path.
- Resilience of the host app: wrap all calls in
try/catch, and keep the library's error reporting separate from the application's. - Observability: count queued, sent, dropped, and retried events, and expose a debug mode.
- Ad blockers: use a first-party endpoint path to reduce loss, and accept that some loss remains.
Trade-offs: larger batches save requests but increase loss on a crash, and persistence improves delivery but adds storage code and privacy duties.
const { mock } = require('node:test');
mock.timers.enable({ apis: ['setTimeout'] });
function createAnalytics({ send, maxBatch = 3, flushMs = 5000, maxQueue = 5, maxAttempts = 3 }) {
let queue = [];
let timer = null;
let inFlight = false;
let id = 0;
const stats = { sent: 0, dropped: 0, retried: 0, requests: 0 };
const schedule = (delay) => {
if (!timer) timer = setTimeout(() => ((timer = null), flush()), delay);
};
async function flush({ unloading = false } = {}) {
if (inFlight || queue.length === 0) return;
clearTimeout(timer);
timer = null;
const batch = queue.splice(0, maxBatch);
inFlight = true;
stats.requests++;
try {
const status = await send(batch, { beacon: unloading });
if (status >= 500 || status === 429) throw new Error('retry');
if (status >= 400) stats.dropped += batch.length;
else stats.sent += batch.length;
} catch {
const keep = batch.filter((e) => ++e.attempts < maxAttempts);
stats.dropped += batch.length - keep.length;
stats.retried += keep.length;
queue.unshift(...keep);
} finally {
inFlight = false;
}
if (queue.length >= maxBatch && !unloading) flush();
else if (queue.length) schedule(flushMs);
}
return {
stats,
track(name, props = {}) {
try {
queue.push({ id: ++id, name, props, attempts: 0 });
if (queue.length > maxQueue) {
queue.shift();
stats.dropped++;
}
if (queue.length >= maxBatch) flush();
else schedule(flushMs);
} catch {}
},
flush,
pending: () => queue.map((e) => e.id),
};
}
const settle = () => new Promise((resolve) => setImmediate(resolve));
const requests = [];
let nextStatus = 200;
const send = async (batch, options) => {
requests.push(`${options.beacon ? 'beacon' : 'fetch '} [${batch.map((e) => e.id)}] -> ${nextStatus}`);
return nextStatus;
};
(async () => {
const analytics = createAnalytics({ send });
analytics.track('a');
analytics.track('b');
await settle();
console.log('two events, no request yet:', requests.length, analytics.pending());
analytics.track('c');
await settle();
console.log('size limit reached:', requests.at(-1), analytics.pending());
analytics.track('d');
mock.timers.tick(5000);
await settle();
console.log('timer flush:', requests.at(-1));
nextStatus = 503;
analytics.track('e');
await analytics.flush();
console.log('server error keeps the event:', analytics.pending(), analytics.stats);
nextStatus = 200;
mock.timers.tick(5000);
await settle();
console.log('retry succeeded:', requests.at(-1), analytics.pending());
analytics.track('f');
await analytics.flush({ unloading: true });
console.log('page hide uses a beacon:', requests.at(-1));
nextStatus = 400;
analytics.track('g');
await analytics.flush();
console.log('client error drops the batch:', analytics.pending(), analytics.stats);
nextStatus = 200;
const small = createAnalytics({ send: async () => 200, maxQueue: 2, maxBatch: 100 });
['x', 'y', 'z', 'w'].forEach((n) => small.track(n));
console.log('queue cap drops the oldest:', small.pending(), small.stats.dropped);
console.log(requests.join('\n'));
mock.timers.reset();
})();Run with Node.js v24.22.1 as js-186.js; two runs gave identical output. Output: two events, no request yet: 0 [ 1, 2 ] size limit reached: fetch [1,2,3] -> 200 [] timer flush: fetch [4] -> 200 server error keeps the event: [ 5 ] { sent: 4, dropped: 0, retried: 1, requests: 3 } retry succeeded: fetch [5] -> 200 [] page hide uses a beacon: beacon [6] -> 200 client error drops the batch: [] { sent: 6, dropped: 1, retried: 1, requests: 6 } queue cap drops the oldest: [ 3, 4 ] 2 fetch [1,2,3] -> 200 fetch [4] -> 200 fetch [5] -> 503 fetch [5] -> 200 beacon [6] -> 200 fetch [7] -> 400
Key points
- Non-throwing track(), event ids, timestamps, and a bounded queue.
- Flush on size, timer, and page hide using sendBeacon or fetch keepalive; avoid unload.
- Retry network and 5xx failures with backoff; drop non-retryable 4xx; use ids for idempotency.
- Keep it off the critical path; respect consent and avoid personal data.
- Measure drops and retries.
Common mistakes
- Relying on unload or beforeunload to send the last events.
- Retrying 4xx errors forever.
- Letting the queue grow without a limit.
- Allowing analytics errors to break the application.
Follow-ups
- How would you make delivery idempotent on the server?
- How would you respect consent changes after events are queued?
- What are the limits of sendBeacon?
Tips
- Name the flush triggers and the page hide trick.
- Explain retry rules: which statuses, backoff, and limits.
- Raise privacy and consent early.