Solution: Invisible to Users, Data Waits in Line
Imagine your restaurant just opened. The back-office POS system is still booting up, but customers are already walking in to order. The servers can't say "the system isn't ready, this order doesn't count" — they write orders on paper slips first, then key them into the POS once it's up.
Those paper slips are the "queue" in the code. The ready POS system (the actual data backend, like Datadog) is the "Sink." In code, src/services/analytics/index.ts is the entry point for the entire analytics system; all other modules call logEvent() to record events:
// src/services/analytics/index.ts
const eventQueue: QueuedEvent[] = [] // Paper slips pile
let sink: AnalyticsSink | null = null // POS system — null at startup
export function logEvent(eventName: string, metadata: LogEventMetadata): void {
if (sink === null) {
eventQueue.push({ eventName, metadata, async: false }) // POS not ready: write paper slip
return
}
sink.logEvent(eventName, metadata) // POS ready: key in directly
}
When the POS is ready, it's like the server getting the signal "you can start entering those paper orders" — but they don't drop what they're doing mid-table; they finish the current table first:
// src/services/analytics/index.ts
export function attachAnalyticsSink(newSink: AnalyticsSink): void {
if (sink !== null) return // Idempotent: POS already open, ignore duplicate signals
sink = newSink
if (eventQueue.length > 0) {
const queuedEvents = [...eventQueue]
eventQueue.length = 0
queueMicrotask(() => { // Async flush: wait until this round is done, don't block current work
for (const event of queuedEvents) {
sink!.logEvent(event.eventName, event.metadata)
}
})
}
}
queueMicrotask is precisely the mechanism for "wait until the current round of tasks is done, then handle this in the next gap." Every millisecond at startup is precious — you can't let flushing historical events slow down the startup process.