← 목록으로

Collecting Web Behavior Logs at Karrot: Building the KarrotAnalytics Web SDK

Collecting Web Behavior Logs at Karrot: Building the KarrotAnalytics Web SDK

요약

Hi, I’m Mika (Mika.kang), a frontend engineer on Karrot’s Data team.

In my last post, Karrot’s User Behavior Logging Platform: Building Event Center, I walked through the conventions we use to organize user behavior logs and how we manage them with an internal tool called Event Center.

This is part two. I’ll cover how we extended our app logging system to the web, and the web logging SDK we built along the way.

Background

Karrot has been an app-first product for a long time, but our web footprint has grown fast. Real estate, part-time jobs, used cars, Neighborhood Life, and Groups are all usable from a desktop browser now.

App logs and web logs lived in different places

We were already collecting user behavior logs on the web, using a third-party analytics service to ingest and analyze events. When we only had a handful of web products and each team looked at its own data, that was fine.

As the number of web products grew, though, we increasingly needed to look at app and web data together, and we kept hitting the same wall: app and server logs lived in KarrotAnalytics, our in-house system, while web logs lived in a third-party service. Different identity models, different event naming conventions, different tools. Stitching the two together was a one-off project every single time, and the gap only got wider as we shipped more web products.

So we decided to bring web logging into KarrotAnalytics. Here’s what that got us:

  • App and web logs land in the same place. No more reconciling data across two systems, and for logged-in users we can follow their journey across app and web.
  • We get all our internal tooling for free. Define events in Event Center, run experiments on our experimentation platform, and ask an AI agent questions about the data.
  • Web logs are instrumented the same way as app logs. Same naming conventions, so there’s nothing new to learn.
  • We own the data. No sampling to keep vendor costs down — we capture every event — and since the Data Value team manages everything from ingestion to storage, we can make it more reliable.

What makes web events different

The first thing we did was nail down the policy, because web events and app events behave very differently.

1. Most visitors aren’t logged in

The app requires login, so we can group behavior by user. On the web, the typical visit is: land from a search result, look around, leave. So instead of identifying people, we needed a way to identify browsers.

2. Not every visitor is a human

The web isn’t just people. Search engine crawlers and automated scripts open pages too, and they emit logs just like real users do. If bot traffic gets mixed in, your analysis is skewed — so to get meaningful numbers, you have to be able to filter bots out.

  • Search engine crawlers — index pages to show in search results.
  • AI search bots — services like ChatGPT collecting content to use in answers.
  • Headless browsers — a program launches Chrome without a visible UI and loads pages.
  • Ad and SEO tooling bots — check that pages running ads work correctly, or analyze what affects search ranking.

3. We had to redefine “a visit”

If you don’t pin down where one visit (session) ends, metrics like visit count, time on site, and bounce rate drift all over the place. Apps have a clear open and close. On the web, people leave a bunch of tabs open or just walk away.

So we defined it this way: a visit ends after 30 minutes of inactivity since the last action.

4. We defined the fields every log must carry

A log needs to capture not just what the user did but in what context. So we defined a set of fields that must be present on every event for web analysis to be meaningful.

Turning policy into code: the KarrotAnalytics Web SDK

With the policy in place, we needed something that actually collects and ships logs according to it. That’s the KarrotAnalytics Web SDK.

Install it in your web app, initialize it once at startup, and baseline events like page views start flowing automatically. You only call track() for behavior specific to your product.

karrotAnalytics.init({ serviceName: "<service name>", countryCode: "<country>" });

karrotAnalytics.track("<event name>", {
[paramName]: paramValue,
});

That’s the whole API. But there’s a lot the SDK has to handle behind those two calls, so we split the internals into modules by responsibility.

A unique ID per browser

To tell anonymous visitors apart, we assign each browser an identifier (web_device_id). On first visit we generate a UUID and persist it; on subsequent visits we read it back.

  1. Bots start with a clean browser every time, so storage is always empty. As a result, every bot visit shows up as a new visitor.
  2. Where localStorage isn't available (private browsing, etc.), we keep the ID in memory only. A reload issues a new one, but we don't count that as a first visit, so metrics don't get inflated.

When a user logs in, the host app calls identify(). From then on, every event carries the user ID until reset() clears it.

Splitting visits on a 30-minute window

A session is a single {sessionId, lastActivityAt, startedAt} record in localStorage. Expiry isn't driven by a timer — it's a comparison done at read time.

const SESSION_TIMEOUT_MS = 30 * 60 * 1000;

function isExpired(session: StoredSession, at: number): boolean {
return at - session.lastActivityAt > SESSION_TIMEOUT_MS;
}

function resolveSession(fireOnSessionCreated: boolean): SessionInfo {
const current = now();
const stored = currentSession();
if (!stored || isExpired(stored, current)) {
const session = startNewSession(current);
return { sessionId: session.sessionId, isNewlyCreated: true };
}
setSession({ ...stored, lastActivityAt: current });
return { sessionId: stored.sessionId, isNewlyCreated: false };
}

We deliberately avoided a setTimeout that ends the session after 30 minutes, for two reasons:

  • Browsers throttle or pause timers when a tab is in the background.
  • In an MPA, the timer is gone the moment you navigate, along with everything else in memory.

Instead, every event bumps lastActivityAt, and if more than 30 minutes have passed, we start a new session and emit web_session_start. Since tabs on the same origin share localStorage, multiple tabs naturally roll up into the same session.

As a fallback for storage failures, we also keep an in-memory cache and use whichever copy has the more recent lastActivityAt. This covers environments where writes fail but reads don't — without it, a stale stored value would shadow the cache and we'd spin up a new session on every event.

What the SDK fills in vs. what the server fills in

Common fields on web events are populated by the SDK in buildEvent().

Browser, OS, device type, country, and bot status are not set by the SDK — the server derives them from the request. Anything the browser self-reports can be spoofed, so it’s safer to decide on the collection side.

Having separate event_ts and sent_ts is also intentional. Events don't go out the instant they fire; they sit in a buffer first, so the delta between the two is your queueing latency.

The host app can also enrich or filter events after the SDK builds them:

  • register() — values registered here get attached to every subsequent event. Handy for things you don't want to pass on every call.
  • beforeSend — receives the finished event right before it's sent, so you can transform it or drop it.

We flag bot events instead of dropping them

I mentioned earlier that bots are mixed into web traffic. When we actually measured it, there were way more than we expected. Over a two-week window, 13.6% of web events came from bots, and 64% of browser IDs were classified as bots. Because every bot visit starts with empty storage, bots massively inflate “new visitor” counts relative to their event volume.

There are two ways to handle this: drop bot events at ingestion, or accept everything and tag it as a bot. We went with tagging.

  • Detection rules keep changing. When a new bot shows up, we need to update the rules — and once data is dropped, it’s gone for good.
  • Humans who get misclassified still have their data, so we can go back and check.

So every web event has an is_bot column, and analyses filter with is_bot IS NOT TRUE. A NULL means there wasn't enough information to decide.

Two signals for bot detection

We look at two signals to keep non-human traffic out of the stats:

  • User-Agent. The “name tag” a browser sends with every request. Search crawlers and AI bots identify themselves here. The server uses it to classify the browser, and if the UA names a known bot, the event is flagged.
  • Automation flag (navigator.webdriver). Per the web standard, a browser controlled by automation tooling sets this to true. This is the only bot-related value the SDK puts on the event.

Bot detection happens on the collection server

A browser telling us “I’m not a bot” isn’t something we can trust. So the verdict happens after the event reaches the server.

The ingestion server ignores any User-Agent in the event body and overwrites it with the User-Agent from the HTTP request headers. It also only accepts events from allowlisted domains.

In the cleansing stage (Flink), a User-Agent parser classifies browser, OS, and device type. The event is then flagged as a bot if any of the following is true. If the event body already contains an is_bot value, we strip it and keep only the server's verdict.

  • The parser classifies the device as “Robot”
  • The User-Agent contains HeadlessChrome
  • webdriver is true

Things the browser made us think about

Never break the host app

A logging SDK runs inside the host app. Any problem in the SDK is a problem in the product, and taking the product down is a much bigger incident than losing some logs. So we set three invariants:

  • Errors never escape. Exceptions are swallowed and recorded; they only hit the console when debug: true.
  • Nothing blows up under SSR. We never touch browser APIs at module top level, and browser features are only used behind an isBrowser() guard.
    - The singleton registry also skips globalThis during SSR and returns a fresh instance every time, because on the server globalThis is shared across requests.
  • shutdown() undoes everything. The SDK doesn't get to decide its own lifetime. When the host tears it down with shutdown(), it flushes remaining events and then reverts every listener, timer, global patch, and stored value.

Logs still have to go out when the page is closing

An app keeps running in the background, but on the web, closing a tab wipes everything instantly.

Events aren’t sent the moment they fire — they’re buffered. A flush runs every 3 seconds or once 30 events pile up. Each flush drains the whole buffer, and the transport splits that batch into chunks of up to 100 events or 64 KB per request.

keepalive lets a request outlive the page, but browsers cap the total size of in-flight keepalive requests at 64 KB per page. Slap keepalive on a big batch and you blow through that limit, and the request fails silently. So we only use keepalive for payloads of 16 KB or less; anything bigger goes out as a regular fetch.

const DEFAULT_MAX_COUNT = 100;
const DEFAULT_MAX_BYTES = 64 * 1024;
const KEEPALIVE_MAX_BYTES = 16 * 1024;

const response = await fetch(url, {
method: "POST",
headers,
body: payload, // gzipped if CompressionStream is available
keepalive: byteLength(body) <= KEEPALIVE_MAX_BYTES,
});

When the page is actually going away, we use navigator.sendBeacon instead of fetch. You don't get a response back, but the browser takes responsibility for delivering the request even after the document unloads.

function sendBeacon(events: TransportEvent[]): void {
for (const chunk of splitIntoChunks(events)) {
navigator.sendBeacon(endpoint, new Blob([serialize(chunk)], { type: "text/plain" }));
}
}

We also distinguish “switched to another tab for a sec” from “actually left.” Both fire events, but they mean different things.

If you emit web_page_leave on visibilitychange → hidden, every tab switch registers as a "leave" and your time-on-page numbers are garbage. So on hidden we only flush what's buffered, and we emit web_page_leave only on pagehide. When a page is restored from the bfcache via back navigation, we check the persisted flag on pageshow, re-emit web_page_view, and resume tracking.
onVisibilityChange = errorGuard("visibilitychange", () => {
if (document.visibilityState === "hidden") flushBeacon(); // flush only
});

onPageHide = errorGuard("pagehide", () => {
autocapture?.onPageHide(); // send web_page_leave
flushBeacon();
});

onPageShow = errorGuard("pageshow", (event) => {
autocapture?.onPageShow(event.persisted); // re-send page_view on bfcache restore
});

Retries are bounded with exponential backoff

We bucket send results into three outcomes based on the HTTP status code.

function classifyResponse(status: number, headers: Headers) {
if (status >= 200 && status < 300) return { outcome: "success" };
if (status === 429) return { outcome: "retry", retryAfterMs: parseRetryAfter(headers) };
if (status === 408 || status >= 500) return { outcome: "retry" };
return { outcome: "drop" }; // 400, 403, etc.: retrying won't change anything
}

Retries use exponential backoff starting at 3 seconds, doubling each time, capped at 30 seconds. That cap effectively acts as a circuit breaker: even if the server keeps returning 5xx, we only hit it once every 30 seconds. If a 429 comes back with a Retry-After header, we honor that instead of the backoff.

Failed events get their retry count bumped and are put back at the front of the buffer to preserve ordering. Any event that’s been attempted more than 10 times is dropped.

function recordFailure(now: number, retryAfterMs?: number): void {
attempt += 1;
const backoff = Math.min(3_000 * 2 ** (attempt - 1), 30_000);
nextAttemptAt = now + (retryAfterMs ?? backoff);
}

Baseline events come for free

The SDK captures these events out of the box:

  • web_first_visit — first visit
  • web_session_start — a new visit started
  • web_page_view — viewed a page
  • web_page_leave — left a page

The thing we sweated most in autocapture was emitting web_page_view exactly once per page, in every environment. Every web app renders pages differently, so the signal for "the page changed" is different in each setup:

  • MPA: Every page is a fresh load, so we emit once on load.
  • SPA: Only the URL changes, so we wrap history.pushState / replaceState and catch back/forward via popstate. Rapid successive calls are coalesced, and a URL identical to the previous one isn't double-counted.
  • SSR: Do nothing on the server; emit once at init after hydration completes.
  • Back navigation (bfcache): A restore from cache fires no load event, so we emit again on pageshow.

Developer tooling

After instrumenting an event, checking “is this actually going out correctly?” was always a pain. The SDK batches events in 3-second windows and gzips them, so the request bodies are basically unreadable in the browser’s Network panel. So we built an internal Chrome extension that lets you inspect events right inside Chrome DevTools.

Beyond that, you can define and analyze web events through MCP, a CLI, AI agents, and more.

Wrapping up

In this post, I walked through how we extended our app behavior logging system to the web. We started by defining a web-specific policy, then codified it in the KarrotAnalytics Web SDK. App and web logs now land in the same place, under the same conventions. Huge thanks to the web product teams who adopted the SDK early and reported issues — that’s how we were able to shake out so many edge cases quickly.

There’s still work to do. We want to make sure logs arrive reliably even on pages that live for only a moment, and we want to get better at catching new kinds of bots as they show up.

We’re hiring people who want to help change how product decisions get made with data:

Thanks for reading all the way through!

Collecting Web Behavior Logs at Karrot: Building the KarrotAnalytics Web SDK was originally published in 당근 기술 블로그 on Medium, where people are continuing the conversation by highlighting and responding to this story.

← 목록으로