Event Capture and Funnel Analytics for an Independent Shop

Medium · System Design · Software Engineer · Technical Screen

Prompt

Design a visitor behavior and conversion analytics solution for an independent online retail shop. The store owner is the primary reader of the dashboards and wants to understand where shoppers come from, how they browse products and move through checkout, and whether they end up purchasing — though you should clarify which business questions take priority before sizing any components.

Center the first half of your design on data collection at the source: what events you define, whether each event belongs in client-side browser code or backend server code, how shopper identity bridges anonymous browsing to paid orders, and how events reliably reach storage. Address database storage and reporting queries once collection is solid.

Key context & constraints: - Right-sized for a small merchant: Assume modest engineering capacity; clarify traffic volume, maintenance budget, privacy/consent obligations, storefront stack (hosted commerce platform vs. custom web application), and whether third-party analytics tools are allowed before committing to infrastructure. - Product analytics focus: Scope the design to shopper journeys, attribution, and order conversion rather than server health or application performance monitoring.

Scope & Expectations

  • Clarification & prioritization: Ask targeted scoping questions (business priorities, storefront stack, daily traffic/order scale, consent rules, build-vs-buy constraints) and order the owner's analytical questions pragmatically.
  • Trusted point of capture: Define a clean event schema and justify which events originate in the browser versus the backend server, accounting for ad blockers, external payment redirects, and page reloads.
  • End-to-end visitor stitching: Trace how anonymous cookies, session IDs, shopping carts, and customer IDs connect across multi-day visits, checkout completion, and consent choices.
  • Proportionate storage & trustworthy reporting: Propose right-sized storage, ordered funnel/attribution queries, and automated checks ensuring reported sales reconcile with real accounting orders.

Step-by-step walkthrough

  1. Clarify requirements and prioritize the owner's questions

    For an independent online retail shop, the main engineering risk is not big-data scale — it is building something too heavy for one developer to maintain, or showing a purchase count on the analytics chart that disagrees with the store's real order book (which destroys the owner's trust immediately).

    Begin by clarifying the store's setup and proposing a clear priority order for the owner's questions:

    1. Checkout conversion funnel: Do shoppers who start checkout finish paying, and on which step do they drop out?
    2. Traffic sources to real revenue: Which ads, newsletters, or referrers bring actual paying buyers rather than window-shoppers?
    3. Product interest vs. sales: Which products get plenty of views and cart adds but rarely convert to orders?
    4. Repeat purchase rate and revenue trends: Are customers coming back, and is net revenue growing?

    Notice why this order helps right away: Question 4 can be answered today directly from the store's existing orders table with zero front-end tracking! Questions 1–3 require connecting pre-purchase browsing behavior to completed orders, so that is where our event-capture design focuses.

    Clarified assumptions for this design

    • Storefront stack: Assume a custom web storefront (server + database where we control both HTML/JS and server routes), while noting alongside each component how it adapts to a hosted commerce service (where we inject a storefront script and subscribe to server-side order/refund webhooks).
    • Volume and freshness: ~2,000 visits/day normally (spiking 10x to ~20,000 on sale or email-blast days) and ~50 orders/day. Daily reports are enough; refreshing "today so far" every ~15–60 minutes is plenty.
    • Privacy and consent: Visitors include EU/UK (strict opt-in before setting non-essential analytics cookies) and California residents. Using a single clear opt-in analytics banner for all visitors is the simplest compliant choice for a small team.
    • Build vs. buy & staffing: One part-time developer maintains the store (< 1 hour/week of analytics upkeep, tens of dollars/month budget). Using an existing analytics tool for storage and charts is welcome, provided we own the capture guarantees that no off-the-shelf snippet solves automatically.

    Non-functional guardrails: Revenue and order totals must match the accounting orders table to the dollar; analytics calls must be asynchronous and fail-open so a broken collector never slows a page or blocks a sale; no raw emails, names, or street addresses enter the event table.

  2. Back-of-the-envelope numbers and statistical reality

    Sizing both event volume and statistical sample size keeps the architecture grounded in reality:

    Event volume and storage
      Daily visits                      2,000 normal  |  20,000 on a 10x sale day
      Events per visit                  ~8 (landing, product views, cart actions, checkout steps)
      Daily events                      16,000 normal |  160,000 on a sale day
      Average ingestion rate            16,000 / 86,400 s         = ~0.2 events/s!
      Sale-day peak hour (4x day avg)   (160,000 x 4) / 86,400 s  = ~7.4 events/s
      Orders (~2.5% visit conversion)   ~50 orders/day            = ~18,250 orders/year
    
    Disk footprint
      Average event row (with JSONB)    ~600 bytes
      Storage growth                    16,000 x 600 B = ~10 MB/day -> ~3.5 GB/year (~6M rows/year)
    
    Minimum sample size to detect a 10% relative conversion lift (80% power, 5% two-sided significance)
      Rule of thumb per group: n = 16 x p x (1 - p) / delta^2
      1) Site-wide visit -> order (p = 2.5% = 0.025; 10% relative change means delta = 0.0025):
         n = 16 x 0.025 x 0.975 / (0.0025)^2 = ~62,400 visits per group -> ~125,000 total visits
         At 2,000 visits/day total -> ~62 days (~2 months!) for one A/B test.
      2) Checkout -> order only (~100 checkouts/day at p = 50%; 10% relative change means delta = 0.05):
         n = 16 x 0.50 x 0.50 / (0.05)^2     = 1,600 checkouts per group -> 3,200 total checkouts
         At 100 checkouts/day total -> ~32 days (~1 month).
    

    Three big lessons from these numbers: 1. A single small Postgres database (or the starter tier of an analytics product) holds years of raw events. Adding Kafka, Spark, or a cloud data warehouse for 0.2 events/s wastes engineering time for zero benefit. 2. Developer maintenance time is the real bottleneck, so every moving part must be boring and automated. 3. Daily conversion percentages at 50 orders/day are mostly random coin-flip noise (38 orders vs. 55 orders looks like a huge swing on a daily line chart). Dashboards should emphasize 28-day rolling windows and raw counts alongside percentages.

  3. Event tracking plan and capture API

    A tracking plan is a single version-controlled specification listing every event name, where it is recorded (browser vs. server), and its exact property types. Using consistent past-tense object_action names prevents ambiguous duplicates like buy, Purchase, and checkout_done.

    We also capture UTM parameters — standard marketing query tags such as ?utm_source=instagram&utm_medium=paid_social&utm_campaign=fall_drop attached to links so the landing page knows which campaign brought the visitor.

    Event name             Observed in                Key properties
    page_viewed            Browser                    path, title, referrer, utm_source/medium/campaign
    product_viewed         Browser                    product_id, variant_id, price, currency
    search_performed       Browser                    query, results_count
    cart_item_added        Server (cart endpoint)     cart_id, product_id, variant_id, quantity, price
    cart_item_removed      Server (cart endpoint)     cart_id, product_id, quantity
    checkout_started       Server (checkout created)  cart_id, item_count, cart_value, currency
    checkout_step_viewed   Browser                    step ('shipping' | 'payment' | 'review')
    order_completed        Server (payment confirmed) order_id, revenue, tax, shipping, discount,
                                                      currency, items[], payment_method, is_first_order
    order_refunded         Server (refund processed)  order_id, refund_amount, reason
    customer_identified    Server (login/signup/paid) customer_id (internal DB ID — never raw email!)
    

    Every event shares a uniform JSON envelope carrying an idempotency key (event_id, a random UUID generated at the moment the event occurs so network retries never create duplicate rows):

    {
      "event_id":       "0b7c5d0e-8b2a-4f1a-9d31-2f6a91c04e11",
      "event":          "product_viewed",
      "source":         "browser",                       # browser | server | backfill
      "anonymous_id":   "a_7f3c91",                      # from first-party cookie (null if no consent)
      "session_id":     "s_19ab04",
      "customer_id":    null,                            # internal user ID once logged in or checked out
      "client_ts":      "2026-11-02T10:02:11.120Z",      # device clock when event happened
      "sent_at":        "2026-11-02T10:02:14.002Z",      # device clock when batch was flushed
      "consent":        "granted",
      "page":           { "path": "/products/mug-12", "referrer": "https://www.instagram.com/" },
      "campaign":       { "utm_source": "instagram", "utm_medium": "paid_social", "utm_campaign": "fall" },
      "properties":     { "product_id": "mug-12", "price": 24.00, "currency": "USD" },
      "schema_version": 1
    }
    

    Capture endpoints (served on the store's own domain): - POST /t/batch — accepts browser batches (up to 50 events / 64 KB); returns 204 No Content. The ~5 KB browser script flushes every 5 seconds or 10 events, and uses navigator.sendBeacon (or fetch(..., { keepalive: true })) on visibilitychange so events fired right before clicking an external payment link survive page unload. - POST /t/server/batch — authenticated with an internal server secret (or calls the insert helper directly if sharing the store backend). On a hosted platform, a tiny serverless webhook receiver translates orders/paid and refunds/create webhooks into order_completed and order_refunded.

  4. Data model and source-of-truth separation

    Keep financial truth (orders) and behavioral logs (events) cleanly separated — they can live in two schemas inside the same Postgres instance:

    events (analytics schema — append-only)
      event_id        UUID PRIMARY KEY                  # deduplicates retries via ON CONFLICT DO NOTHING
      event           TEXT NOT NULL, source TEXT NOT NULL, schema_version INT NOT NULL
      anonymous_id    TEXT NULL, session_id TEXT NULL, customer_id TEXT NULL
      occurred_at     TIMESTAMPTZ NOT NULL              # client_ts corrected for device clock skew
      received_at     TIMESTAMPTZ NOT NULL
      path            TEXT, referrer_host TEXT, utm_source TEXT, utm_medium TEXT, utm_campaign TEXT
      properties      JSONB NOT NULL, consent TEXT NOT NULL, is_bot BOOLEAN NOT NULL DEFAULT FALSE
      -- Indexes: (occurred_at), (anonymous_id, occurred_at), (event, occurred_at)
      -- Partial unique index: UNIQUE ((properties->>'order_id')) WHERE event = 'order_completed'
    
    identity_links (maps anonymous browser IDs to internal customer IDs)
      anonymous_id    TEXT, customer_id TEXT, linked_at TIMESTAMPTZ, method TEXT
      PRIMARY KEY (anonymous_id, customer_id)
    
    quarantine (stores malformed payloads instead of silently dropping them)
      id BIGSERIAL PRIMARY KEY, raw_payload JSONB, validation_error TEXT, received_at TIMESTAMPTZ
    
    orders (existing store schema — financial source of truth, plus 2 nullable columns)
      order_id, customer_id, paid_at, status, net_revenue, tax, shipping, discount, currency
      anonymous_id    TEXT NULL, session_id TEXT NULL   # copied from cart at checkout when consented!
    
    Nightly derived tables (disposable; can always be rebuilt from raw `events` + `orders`)
      sessions        (one row per visit: landing_path, channel, utm_*, flags, order_id)
      first_touch     (per person_key: earliest session's channel and utm_* campaign)
      daily_metrics   (pre-aggregated daily/weekly funnel and channel counts)
      reconciliation  (daily diff between `orders` and `order_completed` events)
    

    Notice the partial unique index on order_completed: even if a webhook fires twice and a backfill job runs later, the database physically guarantees an order_id can only be recorded once.

  5. High-level architecture and build-vs-buy boundary

      Shopper's Browser                                    Store Backend (or Hosted Webhooks)
      +-------------------------------+                    +----------------------------------------+
      | Opt-in consent banner         |  1st-party cookie  | Cart & Checkout endpoints              |
      | Tiny tracker (~5 KB):         |  (anon_id, sess_id)|  - Saves anon_id & sess_id on Cart row |
      |  - page_viewed, product_viewed| -----------------> |  - Copies IDs onto Order row           |
      |  - search, checkout_step      |                    |  - Writes Order + Outbox event in ONE  |
      |  - 5s batch + sendBeacon      |                    |    DB transaction on payment confirm   |
      +---------------+---------------+                    +-------------------+--------------------+
                      | POST /t/batch (same domain)                            | Outbox worker / webhook
                      v                                                        v
               +----------------------------------------------------------------------+
               | Collector Route (separate small DB pool, 1 s timeout, fail-open)     |
               |  1. Validate against tracking plan -> invalid rows go to `quarantine`|
               |  2. Fix client clock skew, flag bots, strip PII query params         |
               |  3. Coarse country/region lookup from IP, then discard raw IP        |
               |  4. INSERT INTO events ... ON CONFLICT (event_id) DO NOTHING         |
               +-----------------------------------+----------------------------------+
                                                   v
               +----------------------------------------------------------------------+
               | Single Postgres Instance: `analytics` schema + `store` orders schema |
               +-----------------------------------+----------------------------------+
                                                   v  Nightly cron job (~1–2 min runtime)
               +----------------------------------------------------------------------+
               | Build `sessions`, `first_touch`, `daily_metrics`                     |
               | Reconcile `orders` vs `order_completed` -> alert if gap > 1 order    |
               +-----------------------------------+----------------------------------+
                                                   v
               Owner's Read-Only BI Dashboard (Funnel | Sources->Revenue | Products | Retention)
    

    Build vs. buy in practice: If the developer adopts an existing product-analytics tool (cloud or self-hosted), that tool replaces the generic browser SDK, collector, event storage, and chart UI. However, four store-specific pieces must still be built by the store developer either way: 1. Defining the tracking plan (object_action names and required fields), 2. Emitting order_completed and order_refunded from the server when payment settles, 3. Passing anonymous_id and session_id from the browser into the server-side cart and order, and 4. Running a daily reconciliation check comparing tracked purchases against the real orders table.

  6. Deep dive 1: browser vs. server capture (point of truth)

    For every metric the owner reads, ask two questions: Where does this fact genuinely happen? and What could block the event on the way to storage?

    • Facts about shopper attention live in the browser: Only the browser knows whether a user scrolled through a product page, typed a search query, switched tabs inside a single-page app, or viewed the shipping form.
    • Facts about money and inventory live on the server: Only the server knows that a card charge or bank redirect actually settled, what the final post-coupon total was, whether an order was later refunded, or whether a renewal order happened automatically with no browser open at all.

    Why counting purchases from a browser "Thank You" page always drifts from reality: 1. External payment redirects (PayPal, Apple Pay redirects, Buy-Now-Pay-Later, bank transfers): The buyer pays on the provider's screen and closes their phone tab before redirecting back to /thank-you — real money arrived, zero browser purchase event fired. 2. Ad blockers and declined consent: Roughly 15–35% of shoppers block third-party trackers or decline cookies; their real purchases vanish from browser-only analytics. 3. Bookmarking or refreshing /thank-you: Reloading the receipt page two days later to check shipping status fires a duplicate browser purchase unless carefully deduplicated. 4. Page-close race conditions: Navigating away immediately cancels normal fetch requests unless sendBeacon / keepalive is used. 5. Pending/failed payments: Reaching a confirmation screen before asynchronous payment settlement counts orders whose charges later fail.

    The server-side fix — the transactional outbox pattern: The transactional outbox pattern writes both the business state change (UPDATE orders SET status = 'paid') and a pending event row (INSERT INTO event_outbox) inside one atomic database transaction, with a background loop copying outbox rows into events (or inserting straight into analytics.events when sharing Postgres). That guarantees every paid order produces exactly one order_completed event — zero lost sales, zero phantom sales.

    Two extra capture safeguards keep browser data honest: - Same-domain collection (/t/batch): Serving the collector on the store's own domain avoids false-positive blocks aimed at third-party ad networks (while strictly honoring the user's opt-in consent choice — never use first-party routing to sneak past declined consent!). - Flag bots instead of deleting blindly: Crawlers hit product pages constantly without buying, which artificially craters conversion rates if mixed into human visits. Set is_bot = true (from known bot user-agents and headless signals) and filter WHERE NOT is_bot in reports while keeping raw rows inspectable.

  7. Deep dive 2: tracing one visitor's identifiers across days and devices

    Now trace one real shopper who discovers the store on Monday, checks out on Thursday, and buys again from a different device next month. Watch which IDs attach to every single row:

    Time          Shopper action                         Event                 Source   anon_id sess_id cart_id cust_id order_id
    Mon 10:00     Clicks Instagram ad, accepts cookies   page_viewed           browser  A1      S1      -       -       -
                  (?utm_source=instagram&utm_campaign=f)
    Mon 10:02     Views ceramic mug                      product_viewed        browser  A1      S1      -       -       -
    Mon 10:04     Clicks "Add to Cart"                   cart_item_added       server   A1      S1      C1      -       -
    Mon 10:05     Closes browser tab                     -                     -        -       -       -       -       -
    Thu 20:00     Types store URL directly into browser  page_viewed           browser  A1      S2      -       -       -
    Thu 20:03     Begins guest checkout, enters email    checkout_started      server   A1      S2      C1      -       -
    Thu 20:06     Pays on external redirect, closes tab  order_completed       server   A1      S2      C1      K9      O55
                                                         customer_identified   server   (links A1 -> K9 in identity_links)
    Next month    Clicks email newsletter on work laptop page_viewed           browser  A2      S3      -       -       -
                  Logs into account, buys coffee beans   customer_identified   server   (links A2 -> K9 in identity_links)
                                                         order_completed       server   A2      S3      C2      K9      O71
    

    Walk through the five identity mechanics that make this entire timeline stitch together cleanly:

    1. Server-set first-party anonymous_id cookie: After consent, set anonymous_id = A1 via an HTTP Set-Cookie header from the store's own web server rather than document.cookie in JavaScript. Safari's Intelligent Tracking Prevention (ITP) (browser privacy rules that shorten cookie lifetimes to curb cross-site tracking) caps JavaScript-written cookies to 7 days — and down to 24 hours after links carrying ad-click parameters! Without a server-set first-party cookie, Monday's A1 would expire before Thursday evening.
    2. Session rotation (S1 -> S2): session_id rotates after 30 minutes of inactivity or whenever new UTM campaign parameters appear. Thus Thursday's return becomes session S2 (channel = direct), while A1's earliest session stays S1 (channel = paid_social / instagram).
    3. The cart-to-order ID handoff (the step most teams miss!): Every call to the cart and checkout endpoints reads the current anonymous_id (A1) and session_id (S2) from the request cookie and updates them on cart C1, which then copies (A1, S2) onto order O55. That is why Thursday's asynchronous payment confirmation at 20:06 — which arrives server-to-server from the payment processor with no browser cookie at all — still knows it came from A1 and S2!
    4. Cross-device stitching via identity_links: When the shopper enters their email at checkout on Thursday (creating/matching internal customer K9) and later logs in on a work laptop (A2), the server inserts (A1, K9) and (A2, K9) into identity_links. Analytical queries define person_key = COALESCE(link.customer_id, event.anonymous_id), uniting A1 and A2 as one repeat buyer (K9) whose first touch was Monday's Instagram ad!
    5. Shared-computer safety and declined consent: On logout, immediately generate a fresh anonymous_id so the next family member on a shared computer is not merged into K9. And if a shopper declines analytics consent, the server still writes order_completed when they buy — but with anonymous_id = NULL, session_id = NULL, and customer_id = NULL. Total order count and revenue still match the bank account 100%, and channel charts honestly show that slice as Unattributed (no analytics consent).
  8. Deep dive 3: ordered funnel SQL and nightly reconciliation

    1. Computing a true ordered checkout funnel without the MIN() trap A tempting shortcut computes MIN(occurred_at) per step inside a session and checks min_cart >= min_view. Watch why that breaks: if a shopper removes or re-adds an old item in their cart at 10:01 (min_cart = 10:01), then views a mug at 10:02 (min_view = 10:02), adds the mug at 10:03, and buys at 10:05, min_cart >= min_view (10:01 >= 10:02) is false — wrongly dropping a real buyer from the funnel!

    Instead, each stage should find the earliest event occurring at or after the prior stage's timestamp:

    WITH human_events AS (
      -- Scan the last 28 days (~450k rows), excluding bots and unconsented server-only orders
      SELECT session_id, event, occurred_at
      FROM events
      WHERE occurred_at >= now() - interval '28 days'
        AND NOT is_bot
        AND session_id IS NOT NULL
    ),
    step1_view AS (
      -- Stage 1: earliest product view in each session
      SELECT session_id,
             MIN(occurred_at) FILTER (WHERE event = 'product_viewed') AS viewed_at
      FROM human_events
      GROUP BY session_id
    ),
    step2_cart AS (
      -- Stage 2: earliest cart add AT OR AFTER `viewed_at` (NULL if viewed_at is NULL)
      SELECT s1.session_id, s1.viewed_at,
             MIN(e.occurred_at) AS carted_at
      FROM step1_view s1
      LEFT JOIN human_events e
        ON e.session_id = s1.session_id
       AND e.event = 'cart_item_added'
       AND e.occurred_at >= s1.viewed_at
      GROUP BY s1.session_id, s1.viewed_at
    ),
    step3_checkout AS (
      -- Stage 3: earliest checkout start AT OR AFTER `carted_at`
      SELECT s2.session_id, s2.viewed_at, s2.carted_at,
             MIN(e.occurred_at) AS checkout_at
      FROM step2_cart s2
      LEFT JOIN human_events e
        ON e.session_id = s2.session_id
       AND e.event = 'checkout_started'
       AND e.occurred_at >= s2.carted_at
      GROUP BY s2.session_id, s2.viewed_at, s2.carted_at
    ),
    step4_order AS (
      -- Stage 4: earliest completed order AT OR AFTER `checkout_at`
      SELECT s3.session_id, s3.viewed_at, s3.carted_at, s3.checkout_at,
             MIN(e.occurred_at) AS ordered_at
      FROM step3_checkout s3
      LEFT JOIN human_events e
        ON e.session_id = s3.session_id
       AND e.event = 'order_completed'
       AND e.occurred_at >= s3.checkout_at
      GROUP BY s3.session_id, s3.viewed_at, s3.carted_at, s3.checkout_at
    )
    SELECT COUNT(*)            AS total_sessions,
           COUNT(viewed_at)    AS viewed_product,
           COUNT(carted_at)    AS added_to_cart,
           COUNT(checkout_at)  AS started_checkout,
           COUNT(ordered_at)   AS completed_order
    FROM step4_order;
    

    Because our Monday-browse, Thursday-buy shopper split their journey across S1 and S2, the dashboard displays both this session funnel (measuring single-visit friction) and the same query grouped by person_key over a 7-day conversion window.

    2. Nightly reconciliation and coverage indicators Every night, a 20-line SQL job compares yesterday's paid orders rows against order_completed events:

    -- Find any paid database orders missing an `order_completed` analytics event
    SELECT o.order_id, o.net_revenue
    FROM orders o
    LEFT JOIN events e
      ON e.event = 'order_completed'
     AND e.properties->>'order_id' = o.order_id
    WHERE o.status = 'paid'
      AND o.paid_at >= current_date - interval '1 day'
      AND o.paid_at <  current_date
      AND e.event_id IS NULL;
    

    Alongside alerting if > 1 order or > 0.5% of revenue diverges, the dashboard surfaces two plain-English health badges: - Attribution coverage: % of paid orders carrying a non-null anonymous_id (shows what share of sales consented to behavioral tracking). - Browser tracker coverage: page_viewed events / non-bot HTML page responses in server logs (shows what share of visits are hidden by blockers or declined consent).

  9. Scaling path, failure handling, and privacy

    Proportionate scaling roadmap (don't over-build today, don't paint into a corner tomorrow):

    Scale tier                  Events/day   Architecture changes needed
    1x today (2k visits/day)    16,000       Single Postgres + nightly SQL rollups (~3.5 GB/year)
    10x growth (20k visits/day) 160,000      Still one Postgres (~35 GB/year)! Add a BRIN index (a tiny block-range
                                             index ideal for append-only time-ordered rows) on occurred_at and
                                             refresh rollups hourly. If monthly partitioning is added, keep event_id
                                             dedup in a lightweight 7-day lookup table.
    1,000x (2M visits/day)      16,000,000   Stateless collector -> managed queue (e.g. SQS/Kafka) -> micro-batch
                                (~185/s avg) load into a columnar data warehouse (a database storing each column
                                             contiguously for fast billion-row scans, e.g. ClickHouse/BigQuery),
                                             or migrate storage to a dedicated analytics vendor.
    

    Resilience against everyday failures: - Collector slow or down: Browser tracker buffers up to 100 consented events in localStorage with exponential retry; server events sit safely in event_outbox; storefront pages enforce a 1 s async timeout and never block checkout. - Skewed shopper device clocks: If a user's laptop clock is 5 minutes fast (client_ts = 10:05:00, sent_at = 10:05:04), and the server receives the batch at received_at = 10:00:04, computing occurred_at = client_ts + (received_at - sent_at) cancels out the 5-minute clock offset (10:05:00 - 00:05:00 = 10:00:00) while preserving exact millisecond event ordering inside the batch! (Clamp absurd offsets > 7 days to received_at.) - Broken front-end deploy: Malformed payloads land in quarantine (replayable once fixed) rather than vanishing, and the nightly job alerts if any core event's volume drops > 50% below its 4-week same-weekday average.

    Privacy and deletion compliance: - Before opt-in consent, set zero analytics cookies and fire zero identified browser events. - Strip non-allowlisted URL query parameters (?email=..., ?reset_token=...) at the collector, map IP addresses to coarse country/region, and immediately discard the raw IP. - Honor right-to-erasure requests by looking up all anonymous_ids linked to customer_id in identity_links, deleting matching rows in events and identity_links, setting anonymous_id = NULL, session_id = NULL on their orders rows (preserving legally required tax/accounting totals), and rebuilding rollups.

  10. Summary of key design choices

    Decision area            Choice                                      Why it fits a small store / trade-off
    Build vs. buy            Buy SDK/charts if possible; own plan,       Under 1 hr/week upkeep while keeping 100%
                             server orders, cart ID handoff, recon       financial accuracy
    Where to capture         Browser for attention; server transactional Eliminates lost redirect sales & reload dupes;
                             outbox for cart, checkout, and money        requires passing anon_id onto the Cart row
    Storage & compute        Single Postgres + nightly SQL rollups       Trivial cost & ops at 0.2 events/s; ~15–60 min lag
    Funnel & stats display   Step-ordered SQL + 28-day windows           Avoids MIN() funnel bug & 50-order/day daily noise
    Privacy & blockers       Strict opt-in + same-domain collector +     Respects consent while explicitly quantifying the
                             "Unattributed" row on revenue charts        untracked share instead of losing real revenue
    

    In one sentence: capture browsing in the browser and money on the server inside the order transaction, bridge the two by copying the first-party anonymous_id onto the cart and order, store append-only events in a single Postgres database (or lightweight analytics tool), and reconcile tracked purchases against the order book every night.

Intuition & how it works

Think of analytics for a small shop like combining a doorway clicker on the sales floor (counting how many visitors walk in, pick up a mug, and head toward the register) with the cash register's paper receipt roll (recording every actual paid order and refund). You would never do your bookkeeping from the doorway clicker because someone can slip past it or walk through twice — and if you want to know whether your Instagram poster brought in Thursday's buyer, you simply clip the visitor's doorway ticket stub (anonymous_id) onto their shopping basket (cart) before they step up to pay.

Two opposite naive approaches fail small e-commerce owners all the time. Counting purchases only from a browser JavaScript snippet on the /thank-you page misses 15–35% of real orders (shoppers who close external PayPal/Apple Pay tabs early, decline cookies, or run ad blockers) and double-counts anyone who refreshes their receipt page, causing the owner to distrust the whole dashboard. At the other extreme, standing up Kafka, stream processors, and a cloud data warehouse for a store getting 2,000 visits/day (~0.2 events per second!) buries a part-time developer in infrastructure chores when one small Postgres database can hold years of events in a few gigabytes.

Trace one shopper across four moments to see how every piece connects: 1. Monday (10:00, browser): An anonymous visitor clicks an Instagram ad (?utm_source=instagram), accepts analytics consent, gets a server-set first-party cookie anonymous_id = A1 in session S1, and fires page_viewed and product_viewed to /t/batch. 2. Monday (10:04, server): They click "Add to Cart"; the store's cart endpoint creates cart C1, stamps A1 and S1 onto the C1 database row, emits cart_item_added, and the shopper closes the tab. 3. Thursday (20:03, browser + server): They return directly (session_id = S2), begin guest checkout on cart C1 (updating the cart's session to S2 and copying (A1, S2) onto order O55), and pay on an external payment page before closing their phone tab. 4. Thursday (20:06, server outbox): Even though /thank-you never loaded in the browser, the payment confirmation transaction atomically marks O55 paid, emits order_completed carrying (A1, S2, customer_id = K9, order_id = O55), and writes (A1 -> K9) into identity_links — keeping revenue 100% equal to the order book while crediting K9's first touch back to Monday's Instagram ad!

Key trade-offs

  • Buying an analytics product vs. building in-house. Adopting an existing analytics tool (hosted or self-hosted) eliminates maintaining a browser SDK, collector, and chart UI for a team of one, whereas Postgres in-house keeps events right next to the orders table with zero vendor lock-in. Crucially, both choices still require custom code for the tracking plan (the shared schema of event names and properties), server-side order_completed capture, cart-to-order ID handoff, and order reconciliation.
  • Browser capture vs. server capture. Only the browser observes shopper attention (rendered views, searches, client-side navigation), but blockers, declined consent, and tab closes make it lossy. Only the server observes settled payments, exact post-discount amounts, and refunds reliably via the transactional outbox pattern (writing the order update and pending analytics event in the exact same database transaction).
  • Same-domain /t/batch endpoint vs. third-party collector domain. Routing consented browser batches through the store's own domain prevents coarse third-party domain blocklists from dropping consented events and lets the main server set first-party cookies that survive Safari's Intelligent Tracking Prevention (ITP) (browser rules that cap JavaScript-set cookies to 1–7 days), at the small cost of maintaining one lightweight route or proxy.
  • Single Postgres + nightly SQL jobs vs. real-time streaming. At 16,000 events/day (~3.5 GB/year), one Postgres database and a 1-minute nightly rollup script cost almost nothing to run and debug, trading sub-second real-time charts for a 15-minute to 24-hour refresh cycle while keeping raw append-only events ready for any future migration.
  • Session-level funnel vs. 7-day person-level funnel. A single-session funnel highlights immediate UI friction inside one visit, but misses shoppers who fill a cart on Monday and buy on Thursday; a 7-day person funnel captures multi-day buyers, but relies on cookie persistence and identity_links. Displaying both side-by-side prevents misreading buyer behavior.
  • Strict opt-in consent vs. 100% behavioral coverage. Honoring declined consent leaves ~15–30% of orders without an anonymous_id. Because order_completed still fires on the server with NULL visitor IDs, total revenue and order counts stay 100% exact while acquisition charts honestly show an Unattributed (no analytics consent) slice.

Common mistakes

  • Firing order_completed only from browser JavaScript on /thank-you. Redirect payments where the buyer closes the tab go missing, ad blockers drop sales, and page refreshes create fake duplicate revenue.
  • Emitting server-side orders without copying anonymous_id and session_id onto the cart and order. Server payment webhooks arrive from Stripe/PayPal with zero browser cookies; if the cart did not save the shopper's IDs earlier, server-side orders become completely disconnected from marketing sources and funnels.
  • Using raw email addresses as the primary analytics user ID or leaving emails in URL query strings. That scatters personal data across immutable event logs, complicates privacy deletion requests, and breaks continuity whenever a customer updates their email.
  • Forgetting to rotate anonymous_id on logout. If Person B logs in on a shared home laptop after Person A logs out, keeping the same anonymous_id permanently merges two different people in identity_links.
  • Writing funnel SQL with MIN(cart_at) >= MIN(view_at). If a shopper removes or adjusts an old cart item before viewing and adding a new product in the same session, MIN(cart_at) precedes MIN(view_at) and falsely excludes a real completed purchase; always match each funnel step at or after the prior step's timestamp.
  • Over-reacting to single-day conversion swings at 50 orders/day. Because random daily variance at 50 orders/day is wide (and detecting a 10% site-wide conversion lift takes ~62 days), daily conversion rate charts encourage chasing statistical noise instead of reading 28-day windows.
  • Silently dropping invalid events (/dev/null) or skipping event_id deduplication. Without a client-generated UUID event_id and a quarantine table, mobile retries double-count activity and a typo in a new deploy silently throws away days of data.

Follow-up questions

  • Analytics dashboards show fewer completed purchases than the backend orders table. How would you isolate the discrepancy, and which figure should the merchant rely on? Left-join the orders table to order_completed events on order_id to list the exact missing orders, then slice those missing rows by payment method (a spike in PayPal/redirect methods points to shoppers closing external payment tabs before /thank-you), order channel (manual phone orders or recurring subscription renewals never touch the website), browser/consent state (Safari ITP or ad blockers when capture is browser-based), and timestamp (a sudden drop starting after a specific deploy points to a broken snippet or webhook). Also check the reverse join (events LEFT JOIN orders) for duplicate reloads, unpaid pending orders, or staff test orders. Always report revenue and order totals from the orders database (the accounting truth), label behavioral funnels with their measured attribution coverage (e.g., "traffic source known for 84% of orders"), and move order_completed into the server's payment-confirmation transaction (plus a nightly backfill) so the count gap drops permanently to zero.
  • Suppose a shopper discovers the shop via an ad link early in the week and completes a purchase days later. How do you attribute that sale back to the initial acquisition source? On every session's landing page_viewed, extract UTM parameters (utm_source, utm_medium, utm_campaign) and HTTP referrer, map them to a clean channel, and persist each person's earliest-known session in a set-once first_touch table keyed by person_key = COALESCE(customer_id, anonymous_id). Because the shopper's first-party server-set anonymous_id cookie persists across days and gets copied onto the cart and order at checkout (and linked across devices via identity_links once they identify), joining the order back to sessions lets you report first-touch attribution within a lookback window (such as 30 days) right alongside last-touch attribution (what closed the sale today). Always surface the Unattributed bucket openly because declined consent, cleared cookies, Safari ITP caps on ad-click links, or browsing on a phone before buying as a guest on a laptop cannot be stitched deterministically.
  • If storefront traffic eventually expands by 10x to 1,000x, which parts of your ingestion and storage architecture evolve and which stay unchanged? At 10x traffic (~160,000 events/day, ~35 GB/year), a single Postgres instance still handles everything comfortably by adding a BRIN index (a tiny block-range index tailored for time-ordered append-only tables) on occurred_at and refreshing summary tables hourly instead of nightly. At 1,000x traffic (~16M events/day, ~185 events/s average and ~7,000/s on sale peaks), separate ingestion from storage: put stateless autoscaling collectors in front of a managed message queue (such as SQS or Kafka) that micro-batches events into a columnar data warehouse (a database like ClickHouse or BigQuery that stores each column together on disk for fast analytical scans) partitioned by date, switch sessionization and identity merging to incremental jobs, and optionally sample high-volume page_viewed events while never sampling cart, checkout, or purchase events. Even at 1,000x scale, the tracking plan, server-side outbox purchases, event_id deduplication, cart ID handoff, and daily order reconciliation stay identical.
  • As developers ship new storefront pages and checkout flows over time, how do you prevent event schemas and property names from becoming inconsistent? Store the tracking plan as a JSON Schema or YAML file right inside the store's Git repository (defining every allowed event name, description, capture location, and required property types) and code-generate typed wrapper functions (such as trackProductViewed({ productId, price, currency })) so engineers get compile-time errors instead of typing raw strings. Have the CI pipeline fail if code calls an unregistered event, and configure the collector to validate incoming payloads against schema_version, routing non-conforming events into the quarantine table rather than polluting events or losing them. Pair schema validation with an automated morning check that alerts whenever a new unknown event appears in quarantine or an existing core event's volume drops sharply after a release.

Follow-up questions

Similar questions

More Posthog interview questions

All 1 Posthog questions →