Experiments

Best product analytics tools for developers and engineering teams

A graphic of a bar chart with an arrow pointing upward.

A developer removes a retry from a document editor. The success rate in the service dashboard stays flat, support tickets fall, and product analytics suddenly shows fewer exports. Before the team can decide whether to keep the change, somebody has to answer a simple question. Did fewer people get their documents, or did the old instrumentation count some exports twice?

That question makes a better starting point for choosing product analytics than a chart gallery. A developer needs to follow a number back to the business action that produced it, repair history when the definition changes, and show a product manager how to use the corrected measure. The best choice depends on which parts of that job already work in your stack.

Four choices for different engineering jobs

ToolChoose it to solve this problemWhat your team still owns
GrowthBookA trusted warehouse already exists and experiments need the same metrics as product dashboardsEvent quality, warehouse models, query costs, and assignment instrumentation
PostHogA product squad wants to explore captured behavior and inspect individual journeys in one applicationCapture scope, identity calls, sensitive-field controls, and volume estimates
SnowplowSeveral consumers need governed events that will outlive the reporting toolEvent contracts, pipeline monitoring, transformations, and the reporting interface
ClickHouseAn engineering team needs to serve analytical queries with custom logic or user-facing latency requirementsCollection, ingestion, table design, metric definitions, and analyst or PM tooling

These options can coexist. A Snowplow pipeline can feed a warehouse queried by GrowthBook, for example. Compare the incremental work in your own architecture. A team that already has a reliable collector gains little by buying another one to answer a retention question. A team whose mobile events disappear in transit needs to fix that gap before a new dashboard can help.

Separate the product action from its diagnostic trail

Take a document export that passes through a browser, an API, a queue, and a worker. Four services might record success. Only one knows whether a finished document exists. Decide which service can authoritatively report completion, what identifies the export, and who can consume that event. You can still attach a trace identifier for diagnosis. Treat the trace and the business record as separate evidence. Trace sampling can intentionally retain failures at a different rate from successes, which makes a raw trace count a poor estimate of a product conversion rate.

One question for every vendor is what happens when the worker succeeds before its acknowledgement reaches the queue. A retry turns into two attempts to deliver the same fact. Ask to see the original records, the count on the chart, and the rule that reconciles them. Then ask whether another engineer can recover those same records after the trial. A tool can make perfect sense for a weekly roadmap review and still leave the platform team with an unanswerable incident ticket.

Decide what an engineer should be able to change

Separate changes to collection from changes to interpretation. Fixing a missing account identifier may take a mobile release. Excluding internal workspaces from a chart may take only a query or a filter. When a trial makes both changes look equally easy, inspect what happened to old records. A label can change immediately without backfilling a single historical value.

For each candidate, have a developer introduce one new optional property and have a different teammate answer a question about it the next day. Ask where the field is documented, whether anyone can see its raw value, and how the chart treats older clients that never sent it. That is a small enough exercise to complete before procurement and a good predictor of who will field the next dashboard question.

GrowthBook for engineering teams with a usable warehouse

Best fit for shared definitions across releases and dashboards

GrowthBook is the strongest fit here if you already collect product and transaction data and the next question after “What changed?” is “Did our release cause it?” Its warehouse-native Product Analytics can explore metrics and fact tables from that warehouse. Its experimentation platform can evaluate an assigned variation against those definitions. The team gets a place to use its data without rebuilding a separate definition of successful export inside every reporting tool.

For a trial, choose a completed business action that crosses systems. Consider an export that a worker finishes on behalf of a workspace. Your application database records the completion, the feature assignment happens on the API server, and seats and billing tiers live in another table. Agree on a reporting unit first. A count of exporting workspaces can answer whether more customers use the capability. A count of successful files can answer whether worker throughput increased. If one workspace exports a million files, those measures can move in quite different directions.

Trace a chart to the records that explain it

Create a fact table from the finished export records. Keep the workspace ID, export ID, and completion timestamp available. Pick one week of completed workspaces and reconcile the distinct count against an independent query. Ask a PM to build the trend using the same metric catalog used by experiment analysis. Then have an engineer walk through one workspace that appears on the trend. A successful evaluation ends with both people agreeing why that workspace counts.

Reuse the measure in a release experiment only after checking the assignment unit and eligibility. A trend across all active workspaces includes teams that never reached the export feature. An experiment readout can compare only eligible assigned workspaces with an appropriate observation window. The shared definition keeps the outcome consistent. The populations can still differ. Put that distinction in the dashboard description so a PM can explain why the two percentages do not match.

What you need to make the integration pay off

Warehouse-native reporting makes upstream mistakes visible. It also makes your team responsible for fixing them. If an export row is overwritten with the most recent status, it may be impossible to tell when an earlier failure first succeeded. Check the actual change history before promising a time-to-first-success dashboard. Likewise, if workspace membership is stored as a current snapshot, an employee who moves to another company can accidentally carry past outcomes with them in a careless join. Inspect the warehouse model with somebody who knows the application.

Give the analytics connection the data access it needs for the selected questions. Start with a view restricted to the required identifiers, timestamps, and numeric properties. Have a warehouse owner check query execution and resource usage under an ordinary dashboard refresh. If the underlying fact table scans an entire history for a one-week chart, that workload has a cost even when the platform subscription stays flat.

Pricing and deployment questions to bring to a trial

GrowthBook publishes separate Cloud and self-hosted plan details. In a bring-your-own-warehouse deployment, model the plan and seat count alongside warehouse compute and operational ownership. The Managed Warehouse option carries its own event allowances. Check the rows for Product Analytics capabilities, warehouse choice, and access controls when selecting a plan. If exported results have to stay inside a particular environment, take a data-flow diagram to a technical demo and walk through the connection and permissions you expect to use.

PostHog for engineers who want an event to end in an investigation

Where it fits

Pick PostHog for a team that wants developers to follow their own telemetry into product questions. A frontend developer can capture an interaction, a backend developer can add its eventual outcome, and a PM can use the resulting events in a funnel. Engineers can look at the underlying events or a related session recording when an aggregate seems wrong. That short path is valuable when the developer who added the event is also the person expected to explain a change in conversion after the next release.

Use a file export as the trial feature. A click requests an export, a worker generates the file, and the customer later downloads it. These are three different observations. Give the job a stable export ID so a developer can follow one request through the system. Record the workspace and actor separately. A background worker processing thousands of jobs should preserve the actor for each job where appropriate. Putting the same worker identity on every completion can turn a busy product into a funnel with one remarkably active user.

Follow a retry all the way to the chart

Ask the developer who owns the worker to send a completion, then resend it from the same job record. Compare the raw events immediately and again after the system has had time to process duplicates. PostHog's event deduplication rules use the event UUID, name, distinct ID, and UTC date of the event timestamp. Matching copies across requests can coexist temporarily before background processing retains the later one. If a retry gets a new UUID or records today's date for yesterday's completion, the system can correctly treat it as a different event even though your business considers it the same export.

There are two kinds of identity in that example. The export ID connects the click, completion, and download to a single job. Each of those three events also needs its own event identity, stable across retries of that particular event. The CloudEvents specification describes a similar distinction at the producer boundary, where the event source and event ID together identify a distinct event. That principle is useful even when the analytics SDK uses a different envelope.

Verify who appears in the funnel

Try a logged-out browser opening the export page, followed by login and a server-generated completion. Can the person who started the flow be followed through the identified action? Repeat with two accounts using the same browser and check that the second person's activity belongs to the correct account. Include a genuine download by a different user in the same workspace. A person-level funnel should expose the handoff. A workspace-level report might count it as a success. Record which interpretation your PM expects before giving either chart the name “export adoption.”

Review exports as well as the UI if the warehouse feeds finance or customer success. An analytics system can eventually collapse duplicate events in its own storage while a downstream consumer sees both deliveries. Check a representative destination with the exact retry fixture, then establish where that consumer enforces uniqueness. The answer belongs next to the pipeline configuration where its next maintainer will look.

What to measure for pricing

PostHog's product analytics pricing includes the first million events per month with usage-based pricing beyond the allowance. Estimate browser interactions, domain events, and worker activity separately. A new progress indicator might generate twenty client events per export while still representing one customer outcome. Monitor identified profile usage and price any additional products the team plans to enable. A projection based only on successful exports will miss the noisy work that generated them.

Compare two analytics architectures

See how GrowthBook and PostHog handle data ownership and exploration before choosing where your events should live.

Compare GrowthBook and PostHog

Snowplow for teams that need a contract between event producers

Where it fits

Snowplow is a candidate when your immediate problem is the quality and portability of the events feeding multiple analyses. A desktop client, a mobile client, and a partner integration might all report that a customer accepted an invitation. If one uses a workspace ID, another supplies a display name, and the third omits the workspace entirely, you cannot safely group those outcomes by customer. A nice funnel in the presentation layer can make the disagreement harder to notice.

Snowplow's Customer Data Infrastructure lets teams describe events and associated entities, validate incoming records against their schemas, and send enriched data to destinations such as a warehouse, lake, or stream. A record that fails schema validation follows a failed-event path. That makes it possible to investigate a class of missing records from a particular release while preserving the distinction between data you can trust and data that still needs repair.

Test the change that crosses a release boundary

Give two engineers the same invitation example. One takes an old client fixture and the other changes the new producer to include the method of acceptance, such as link or in-app notification. Both versions should continue to produce valid events if that new field is optional. In JSON Schema's object model, describing a property and requiring its presence are separate decisions. A field that looks necessary to the latest application can be unknowable to an app released three months earlier.

Write down three expected results before the run. The old fixture should load with the method unknown. The new fixture should carry the correct method. A deliberately malformed fixture, for instance an array where the schema expects a string, should show up as a validation failure with enough information to identify its producing version. Confirm each result in the corresponding destination. Also try a well-formed event with the wrong workspace ID. A type check can accept it. Catching that problem needs a business-level test against the invitation or membership records.

Know who owns recovery and the reporting layer

The real procurement question is what happens after the mobile team fixes the faulty producer. Ask someone outside the original implementation to find the affected hour, classify the failed events, and calculate how many legitimate invitations the dashboard missed. They should be able to distinguish a repairable type error from a missing identifier that cannot be reconstructed. When a repair is possible, compare the revised total with the accepted invitations in the application database. Preserve the original occurrence times during recovery so yesterday's fix does not appear as today's adoption spike.

This architecture also leaves you a choice about how PMs explore the data. Give a PM access to the proposed reporting tool and a dataset with repeated invites, revoked invites, and eventual acceptances. Ask for a conversion rate for unique invitations that were still valid when accepted. If it takes an engineer writing new SQL each time the date range changes, the team has proved event collection but still needs to fund a usable analytics layer. That might be an excellent trade for a company already operating a warehouse and shared metrics.

What to include in the quote

Compare a Snowplow-managed pipeline in Snowplow's cloud with one managed in your own cloud account. The latter has infrastructure and access requirements your platform team will want to review. Snowplow pricing depends on the chosen components, which can include monthly event volume, hosting, consumption, and destinations. Ask for the production configuration with its destination and expected peak volume. Include the downstream warehouse, modeling jobs, dashboard tooling, and the time someone will spend handling failed events. The pilot's collection bill covers only one part of the finished workflow.

ClickHouse for a product analytics stack your team builds

Where it fits

ClickHouse makes sense when the team wants to own the tables, queries, and interface that turn behavior into a product. One example is an API provider showing customers which endpoints their teams adopted and how that usage changed between SDK versions. The same facts can support an internal PM's adoption report, but the two audiences have different access rules, response-time requirements, and tolerance for late data. Teams with that combination of needs have a concrete reason to consider an analytical database as the foundation for a custom system.

Draw the components you would still own. Somebody has to generate an event ID, convey events from the application, document the schema, and decide what identifies a customer. Somebody also has to expose trusted metrics in a dashboard. A ClickHouse proof of concept should include one user who needs to answer a second question without editing a table definition. If the only person who can use the prototype is the engineer who created it, you have measured a database workload and can separately estimate the product work that remains.

Benchmark both correctness and query time

Build a small fixture with two requests by one customer, one retry of the first record, and a legitimate third request with the same endpoint and timestamp. The answer is three unique requests. Deduplicating by timestamp and endpoint could lose the third one. Counting every inserted row could give you four. With ReplacingMergeTree, the sorting key determines which rows are candidates for replacement during background merges. Choose it with the actual record identity in mind. If your read path needs replacement semantics before those merges, test the query using FINAL and measure its cost on your workload.

Now replay the same fixture after a request's SDK version is corrected. Confirm that a report filtered to the old version loses one request and the corresponding report for the correct version gains one. Test the two reports while ingestion is active. A fast, cached dashboard running a total count can hide both the correction cost and the effect on customer-facing queries. Measure slow queries and response-time percentiles during ingestion, alongside errors, scanned data, and the time it takes for the correction to become visible.

Prove the data can be rebuilt

Choose a narrow time window and reconstruct one report in a separate destination. If the design retains event history in Apache Parquet, the columnar file format gives other tools a way to read the archive. Define who can access it, which fields and historical versions it retains, and how to recover the relevant partitions. A file format alone cannot recover the identity rules an engineer once kept in an unversioned query.

Give the team one change to interpret during the rebuild. For example, a customer changed its display name halfway through the week. Reports keyed by a stable customer ID should keep the same request total. A historical display name and a current one may both be appropriate, depending on the chart. Specify the expected behavior and confirm it from an ordinary customer account with access to one tenant.

Calculate the price of the operating model

For the managed option, ClickHouse Cloud pricing covers compute and storage with additional charges that can include transfers, backups, and ingestion services. Estimate three workloads separately: normal ingest and dashboards, weekday exploratory queries, and a historical rebuild running alongside production reads. For a self-managed deployment, include upgrades, capacity planning, restore exercises, and on-call ownership. The deciding factor is whether the custom querying and user experience justify supporting those responsibilities across multiple releases.

Give each SDK a delivery problem to solve

A notes app adds offline export. A customer taps Export on a train, the phone writes the file, and the client sends an event when connectivity returns. The upload succeeds, but the acknowledgement gets lost and the phone retries. The PM sees two exports the next day. Did the customer export twice? Did the second export happen the next day? Could you still answer either question six months after changing analytics providers?

Take that journey into a trial. Choose one event, file export completed, that an engineer can verify from the application's own state. Record it when the write succeeds. A button click remains a useful event for diagnosing the export dialog, but it can't confirm that the customer received a file. Give the candidate one retry, one schema change, one anonymous-to-known transition, and one customer who declined analytics. Each case should have an expected outcome independent of the platform.

Generate a fixture you can send twice

Save this as export_trial.py and run it with Python 3 in a scratch directory. It writes a JSON Lines file, one object per line, containing only synthetic records that the trial's consent policy permits sending. The integer timestamps are UTC epoch seconds. The fields called occurred and received represent the origin clock and the simulated collection clock. They model the two timestamps used in the OpenTelemetry data model.

import json
from pathlib import Path

start = 1735689600  # 2025-01-01 00:00:00 UTC
events = []

def add(event_id, actor, name, hour, lag=0, version=1, consent=True):
    record = {
        "source": "notes-app", "id": event_id, "actor": actor,
        "event": name, "v": version, "occurred": start + hour * 3600,
        "received": start + (hour + lag) * 3600,
    }
    if version == 2:
        record["format"] = "markdown"
    if consent:
        events.append(record)

add("e1", "anon-a", "export_completed", 1)
add("e2", "user-7", "signed_in", 2)
add("e3", "user-7", "export_completed", 22, lag=5, version=2)
add("e3", "user-7", "export_completed", 22, lag=6, version=2)
add("e4", "user-9", "export_completed", 25)
add("e5", "user-8", "export_completed", 26, consent=False)

with Path("trial-input.jsonl").open("w", encoding="utf-8") as out:
    for event in events:
        out.write(json.dumps(event) + "\n")
print(f"{len(events)} permitted deliveries")

Expect five permitted deliveries and four distinct event IDs. The test script deliberately emits historical timestamps so its output is deterministic. If a candidate's ingestion endpoint limits how far back you can send events, change start in the generator to midnight UTC two days before the trial. Update the two expected dates in the verification script and use the same dates for every candidate. Verify the permitted backfill route and any charge associated with it. An endpoint can accept a request and still exclude an old event from reports.

Use the candidate's test project or a disposable warehouse schema. Map id to the documented idempotency field if the endpoint has one, occurred to event time, and actor to the documented user or anonymous identifier. Where a service sets its own receipt timestamp, retain the fixture's simulated received value as a separate test property. Send the five rows as generated, then submit the same file again. The exact SDK or import route matters. A warehouse integration and a mobile SDK might offer different retry, backfill, or identity behavior. Record which route passed.

Separate retries, returning people, and late arrivals

There are three distinct completions in the file. Two occurred on January 1, even though one of those arrived on January 2. A chart grouped by the simulated collection date would put only one completion on January 1. Ask a developer to produce both charts or queries and show the underlying records. If a chart increases each time the file is resent, check which field the collector treats as a stable ID and whether the replay happened within its deduplication window. CloudEvents pairs a source with an event ID so different producers can assign their own IDs without a collision.

For identity, anon-a is the pre-login identity of user-7. That fact lives outside the events intentionally. Give the candidate an explicit identity link through the supported aliasing flow or a small warehouse mapping table. The three completions belong to two resolved people. Inspect the pre-login record before and after applying the link. A report that counts three actors can still have the correct number of completions. Ask whether the link reclassifies historical reports and whether a person who logs out and shares their device can later be disentangled from the next user.

Now send a malformed copy in your test environment. Remove actor from a single event with a new ID. Do you get a rejection with a reason, a quarantined record you can replay, or a successful response and an uninspectable drop? Give each case an owner. A supplier may reasonably delegate validation to your pipeline. You then need a team willing to own the required fields and type checks in the tracking schema, along with a place to inspect failures during an incident.

Prove you can rebuild the report after export

Export the candidate's records. For a tool that reads the warehouse directly, select the exact input rows and the identifiers used by the reporting model. Normalize that extract back to the field names in the fixture and save it as trial-export.jsonl. Preserve original IDs and event times. Never use the original input file as a substitute for the extract when grading the candidate. Run the following in the same directory as a separate script.

import json
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path

lines = Path("trial-export.jsonl").read_text(encoding="utf-8").splitlines()
rows = [json.loads(line) for line in lines if line.strip()]
assert {r["id"] for r in rows} == {"e1", "e2", "e3", "e4"}
completions = {}
for row in rows:
    if row["event"] == "export_completed":
        key = (row["source"], row["id"])
        completions[key] = row

people = {"anon-a": "user-7"}
days = Counter(datetime.fromtimestamp(r["occurred"], timezone.utc).date()
               for r in completions.values())
actors = {people.get(r["actor"], r["actor"]) for r in completions.values()}
assert len(completions) == 3 and actors == {"user-7", "user-9"}
assert {str(day): count for day, count in days.items()} == {
    "2025-01-01": 2, "2025-01-02": 1
}
assert completions[("notes-app", "e3")]["format"] == "markdown"
print("Distinct completions, resolved users, UTC dates and format verified.")

If you moved the fixture's dates, update the two expected days in the assertion. The script deduplicates the raw export by source and ID. Compare its result to the platform's count as displayed before any repair. Raw exports that preserve every delivery can be useful for debugging. A product dashboard needs an explicit rule for which of those deliveries counts. Investigate any discrepancy before signing off, and keep the mapping needed to rebuild the result with your application code.

The format property exists only in version 2. Build one report across both versions and another for Markdown exports. The first should include all three completions. The second should include just the one known Markdown export. Absence of the property in version 1 means unknown. Giving every old record a default of Markdown would rewrite history. Document the policy for compatible and breaking changes to event schemas before a second team starts producing events.

The fixture's consent filter also deserves a separate client test. Run the declined journey with a test device and inspect the outgoing requests. Check that no analytics delivery leaves on a later flush or restart. A missing row in the export confirms only what you can retrieve. It doesn't establish where filtering occurred. Keep a field inventory for the event, exclude private note contents, and verify the payload itself. The W3C's data minimization guidance is a useful design constraint when a single completion signal answers the whole product question.

Try a recovery from an incomplete export, too. Put the five permitted deliveries into two pages or files. Interrupt your reader after saving the first page but before acknowledging it, then restart it from the last durable checkpoint. A one-time export that fits on a laptop can conceal a costly problem once history spans hundreds of daily files. The recovered result should still contain all four distinct IDs. Record the cursor or partition key that made recovery possible, how long it stays valid, and how you would detect a missing file.

For a warehouse source, run the same exercise against an incremental load. The late completion has an earlier occurrence time than a row your reader may already have processed. If the job asks only for events that occurred after the latest observed occurrence, it can skip the late row. Try the same load using a receipt-time cursor or a bounded overlap plus deduplication. Save the before-and-after differences. That comparison tells a reviewer how far back a repair needs to read, and which table or report will change when the delayed event arrives.

Assign ownership before selecting the tool

Record who owns the metric calculation after the trial. If it's a warehouse model, a reviewer should be able to trace the event name, occurrence timestamp, and identifier into the aggregate. GrowthBook's metrics and fact tables give teams a place to define that mapping against an existing warehouse. Its data source setup is a useful checkpoint for the credentials and connectivity that workflow requires. If a hosted event service handles the mapping, identify who can inspect changed results and what they can export when the contract ends.

Finish by swapping developers. Give someone who missed the vendor session the example file, the extraction instructions, and the failed assertions. Have them reproduce the discrepancy and estimate the change needed to fix it. Their pull request or support ticket tells you more about long-term engineering cost than the time it took to paste the installation snippet.

Put a price on the pipeline you'll actually operate

A quote for a million events tells you little until you know what produces them. Take a desktop editor with 20,000 monthly users. Each saves 30 documents a month. At one event per successful save, you get 600,000 events. Now imagine an SDK update that also emits a notification on each autosave. Ten autosaves for every manual save add 6 million events. The audience hasn't grown. Neither has the number of documents customers chose to save. The proposed instrumentation decision has increased the monthly volume elevenfold.

Start the cost exercise by sampling a normal release and a busy one. Count rows by producer, event name, environment, and schema version. Look at the largest events as well as the most frequent. A document title may appear cheap in bytes and still create an unnecessary privacy obligation. A three-kilobyte diagnostic object attached to every save could be better suited to a sampled engineering log. Ask the engineer responsible for the event and the person consuming it which properties they would miss if the field disappeared tomorrow.

Convert usage into the units on the quote

On an event-priced contract, ask which autosaves count, whether imports of historical data have their own price, and how retries affect metering. On an identity-priced contract, test the definition with actual visitors. A person who signs in on two devices may have generated two anonymous histories during the month. As one concrete example, Segment's monthly tracked user calculation includes identified users and distinct anonymous IDs that weren't associated with an identified user. Another vendor can count differently. A spreadsheet cell labeled “MAU” needs a formula that matches the contract.

For a warehouse or database you operate, translate the same workload into bytes and operations. If the combined events average 1,000 bytes each, 6.6 million events add about 6.6 GB of uncompressed payload a month in decimal units. Twelve such months add about 79.2 GB before compression, indexes, replicas, derived tables, or backups. Measure one real partition on disk before turning that number into a storage forecast. If you archive an export in S3, storage, requests, retrieval, and transfer can contribute separately. Compare bulk files with a design that stores one tiny object per event.

Run your three most common investigations on that representative data. One might look up a single document, one might aggregate this week's saves by release, and one might rebuild six months of account activity. Capture query time and work performed. In BigQuery, for example, filtering the partition column can exclude entire partitions from a scan. A fast single-day demonstration says little about the cost of running a six-month dashboard every morning. Estimate the actual workload, including scheduled refreshes and ad hoc queries after a release.

Assign an owner to each recurring job

Follow one deliberately delayed event from the producer to the PM's report. Who can tell whether it is waiting in a queue, was rejected by a schema check, or has landed in a table that refreshes nightly? If the team owns a collector, its own counters can help distinguish accepted, enqueued, and successfully exported records. The business dashboard also needs an owner who can explain why Monday's number changed on Tuesday. Write those names next to the freshness target that the product team can live with.

Put a cost against the work that repeats. If an analyst spends three hours every Friday translating common questions into SQL, that is roughly twelve hours in a four-week planning period. Compare that with the time it would take to publish one maintained dataset and teach the PM to use it. Run the same exercise for the self-service option. If someone spends a morning repairing dashboards every time a client changes its event schema, count that time as well. Keep one-time integration separate from the operating budget so a quick installation doesn't hide a recurring obligation.

An engineering team can reasonably choose two interfaces over the same data. The engineer debugging a save needs a document ID, a release version, and the time the server committed the write. The PM deciding whether to change autosave needs a stable account-level measure and a way to compare complete weeks. One row-level explorer and one shared metric can serve both people. During the trial, change one eligible record and trace its effect in both places. If a fresh warehouse query reflects the correction while the PM's dashboard stays wrong, document who will repair the discrepancy and how often you expect it to recur.

When the finalists come back with different bills, compare one cost both teams recognize, such as monthly operating cost per thousand active workspaces. That is the practical use of FinOps unit economics. Keep the underlying rows visible. A lower unit cost caused by more customers sharing the same infrastructure warrants a different decision from a lower cost caused by silently dropping the most valuable event.

Pick the stack your on-call engineer can explain

Before you sign, hand the trial results to an engineer who missed the demos. Give them one anomalous chart point and the IDs for a few affected events. Ask what happened, how they would correct it, which consumers would see the correction, and how they would discover an unintended change in the next scheduled run. If their answer depends on the one person who configured the demo, add the missing definition or query to the handoff and repeat the exercise.

For an engineering team that already trusts its warehouse and wants releases and dashboards to share outcomes, GrowthBook is the best starting point in this shortlist. Start a GrowthBook trial with one warehouse view and one release decision. Reconcile the result at the same unit you use to assign the feature. Let the product owner reproduce the chart before expanding beyond that metric.

If the immediate pain is missing or inconsistent event capture, spend the trial on collection first. If the blocker is a custom dashboard that must answer thousands of customer queries, spend it on serving those queries against representative data. The deliverable to take back to your team is a working answer to its hardest question, the records that substantiate it, and the name of the person who owns each step of the answer.

Try one warehouse metric

Connect your data and give a developer and a product manager the same outcome to investigate in GrowthBook.

Start With Your Data

Table of Contents

Related Articles

See All Articles
Feature Flags
Experiments

Add local feature flags to a React app with TypeScript

Nov 20, 2026
x
min read

A magazine's home page shows two recent issues. The design team wants subscribers to try a shelf with four. All four covers are public, and changing editions while the page is open should update the shelf immediately. That gives you a small React feature with a useful acceptance test. Click from guest to subscriber and back, and count the covers each time.

We'll put the display limit in a typed local flag, evaluate it inside a React component, and leave the choice of edition with the app. The example runs in a client-rendered React app without a GrowthBook account, an SDK key, or a request for flag rules. For the wider workflow, free feature flags for coding agents explains what to ask an agent to implement and how to review the result.

Define what one flag controls

Start with an existing React and TypeScript app, or create a Vite React project for the example. Install both GrowthBook packages so the definitions and the hooks resolve against compatible SDK versions.

npm create vite@latest issue-shelf -- --template react-ts
cd issue-shelf
npm install
npm install @growthbook/growthbook@^2.2.0 @growthbook/growthbook-react@^2.2.0

Create src/flags.ts. Here the feature value is a number, which lets the component use the same rendering code for either edition. A future change from four covers to three is one edit to the rule.

import type { LocalFeatures } from "@growthbook/growthbook";

export type Edition = "guest" | "subscriber";
type Features = { issueLimit: number };
type Attributes = { id: string; edition: Edition };

declare module "@growthbook/growthbook" {
  interface Register {
    features: Features;
    attributes: Attributes;
  }
}

export const features: LocalFeatures = {
  issueLimit: {
    defaultValue: 2,
    rules: [
      { condition: { edition: "subscriber" }, force: 4 },
    ],
  },
};

A guest falls through to the default of two. A subscriber matches the rule and gets four. This rule applies to every subscriber, so the ID has no effect on the result here. If you later roll the shelf out to a percentage of subscribers, you already have an identity to use for repeatable assignment.

The type registration release note explains the version requirement for LocalFeatures. The registration connects the definition, the attributes, and the value returned by the hook. For the TypeScript mechanics, see Jeremy Dorn's Register pattern walkthrough.

Put the current reader above the shelf

Replace src/App.tsx with the component below. The edition switch is a local fixture so anyone reviewing the change can reproduce both states. In an existing app, take those two values from the active reader in your session layer.

import { useMemo, useState } from "react";
import { GrowthBook, GrowthBookProvider } from "@growthbook/growthbook-react";
import { features, type Edition } from "./flags";
import { IssueShelf } from "./IssueShelf";

export default function App() {
  const readerId = "reader-17";
  const [edition, setEdition] = useState<Edition>("guest");

  const gb = useMemo(() => new GrowthBook({
    attributes: { id: readerId, edition },
    defaultHashVersion: 2,
  }).initSync({ payload: { features } }), [readerId, edition]);

  return (
    <GrowthBookProvider growthbook={gb}>
      <main>
        <h1>Recent issues</h1>
        <p>Current edition: {edition}</p>
        <button onClick={() => setEdition(
          edition === "guest" ? "subscriber" : "guest"
        )}>
          Switch edition
        </button>
        <IssueShelf />
      </main>
    </GrowthBookProvider>
  );
}

The provider receives an instance initialized with the current reader and the checked-in rules. React can render the correct shelf on the first pass for that reader. If the app is still loading a session, decide what should occupy the shelf in the meantime. For this public list a two-cover guest view is reasonable. On a page where a switch would interrupt the reader, wait for the session before mounting the shelf.

Give your agent the React setup

Use the local flags guide to ask for a typed definition, a provider with the current reader, and a test that changes the edition.

Open the Agent Guide

The useMemo dependencies include the ID and the edition. If a reader subscribes while signed in, their ID can stay the same while their edition changes. Depending only on the ID would leave the old SDK instance in place. Passing a fresh object as the dependency on every render would create unnecessary instances. The example uses the two primitive values the rule setup actually needs.

Read the numeric flag where React renders the list

Create src/IssueShelf.tsx. Keep one stable ID per issue and let the component use the resolved value to select how many items to render.

import { useFeatureValue } from "@growthbook/growthbook-react";

const issues = [
  { id: "nov", title: "November · Print shops" },
  { id: "oct", title: "October · Bookbinders" },
  { id: "sep", title: "September · Type designers" },
  { id: "aug", title: "August · Paper mills" },
];

export function IssueShelf() {
  const limit = useFeatureValue("issueLimit", 2);

  return (
    <ul aria-label="Recent magazine issues">
      {issues.slice(0, limit).map(issue => (
        <li key={issue.id}>{issue.title}</li>
      ))}
    </ul>
  );
}

Keep the hook at the top of the component, inside the provider's subtree. The React SDK supplies the flag value through that provider. Calling a hook inside a click handler or inside the list loop would break the Rules of Hooks. Use the returned number in ordinary render logic.

There are two places you can see the number two in this implementation. The definition's defaultValue is what an ordinary guest gets through evaluation. The 2 passed to the hook is a fallback for a value the SDK can't supply. Giving them the same value makes the basic shelf a sensible fallback, but checking only the guest case would let a broken provider arrangement or missing definition go unnoticed. The subscriber case proves that the component actually received the rule.

The list keys identify magazine issues. Keep those keys independent of the flag. Switching from two covers to four should preserve the identity of the first two rows. There's also no need to remount the whole app with an edition-specific key. React preserves state according to component position and keys. For example, a search input outside the shelf shouldn't lose its text because someone subscribed.

Check the transition in both directions

Use the template's build script to type-check and bundle the app. Once that passes, start the dev server and open the local address it prints.

npm run build
npm run dev

On first load, the page says guest and lists November and October. Click Switch edition. The same page should say subscriber and add September and August. Click again. The list should return to the original two issues, in order. This last check catches code that appends more results on upgrade and never removes them on downgrade.

For a compile-time check, temporarily replace the numeric fallback with the string "2". Run the build again and inspect the error on the hook call. Then restore 2 and rebuild. If the string compiles, check that src/flags.ts belongs to the same TypeScript project as the component and that the package manager resolved compatible core and React versions.

npm ls @growthbook/growthbook @growthbook/growthbook-react

Look for the core package used by your app and by the wrapper. If the app has several incompatible installations, align the versions before diagnosing the JSX. A team using an existing build script should also confirm it actually runs the TypeScript checker.

Hand off a React change someone can review

Give your coding agent the one-shot local feature flags guide and a short description of the observable behavior. For this shelf, the request can be as specific as the test.

Show two public issues to guests and four to subscribers.
Keep the same reader ID when switching editions in the test.
Report the initial titles, the titles after upgrading, and the titles
after switching back. Include the type-check command you ran.

The shelf controls how many public titles to display. If your actual feature unlocks paid articles, enforce access when the server serves an article. A client-rendered flag only decides what to show in that browser. Whenever a change to the display limit can wait for a deployment, the small local file keeps the decision reviewable alongside the component. When an editor needs to change it between issues without an engineering release, compare the free GrowthBook options for managing flag rules.

Manage the shelf in GrowthBook

Start a GrowthBook workspace when your magazine team is ready to manage shelf rules between deployments.

Get Started with GrowthBook
Feature Flags
Experiments

Use local feature flags per request in Node.js

Nov 20, 2026
x
min read

Two customers download the same weekly report. One has agreed to preview a new CSV column. The other feeds the old two-column format into an importer. Both requests can land on the same Node.js process, and each needs the right file even if the other request arrives while the report is loading.

This tutorial builds that endpoint with one checked-in feature flag. The process loads the rules once. Each request supplies its own workspace attributes and receives its own evaluation. You can run the whole example on your machine without an account, a client key, or a flag server. The free feature flags for coding agents walkthrough introduces the local approach. Here we'll give the agent a server-specific test to pass.

Set up a small TypeScript service

Use Node.js 22 or newer for this example. In an empty directory, create an npm project that uses ES modules, install the core SDK, and add the TypeScript tools.

npm init -y
npm pkg set type=module
npm install @growthbook/growthbook@^2.2.0
npm install -D typescript tsx @types/node@22

Create tsconfig.json at the project root. The sample runs TypeScript directly with tsx and checks types in a separate step. Type checking with tsx explains why the two commands serve different purposes.

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "strict": true,
    "noEmit": true,
    "skipLibCheck": true,
    "types": ["node"]
  },
  "include": ["*.ts"]
}

The following files all live next to that configuration. The server imports ./flags.js even though the source file is flags.ts. That spelling follows TypeScript's Node.js module resolution for ESM and works with this runner.

Define the report contract in one flag

Create flags.ts. The public format has two columns. The sample preview workspace gets one additional column. The only targeting attribute the rule needs today is reportPreview. Carry the workspace ID too, so two people downloading a report on behalf of the same workspace can share an assignment if you introduce a percentage rollout later.

import type { LocalFeatures } from "@growthbook/growthbook";

type Features = { includeUniqueReaders: boolean };
export type Workspace = { workspaceId: string; reportPreview: boolean };

declare module "@growthbook/growthbook" {
  interface Register {
    features: Features;
    attributes: Workspace;
  }
}

export const features: LocalFeatures = {
  includeUniqueReaders: {
    defaultValue: false,
    rules: [{ condition: { reportPreview: true }, force: true }],
  },
};

The SDK type registration update covers this rule syntax and the 2.2.0 minimum. If you misspell reportPreview in a condition or use a string where the boolean flag expects a value, TypeScript can point at the definition. The Register pattern also makes the same feature name available in other modules without threading a generic type through each handler.

Before you add the endpoint, decide what belongs to the process and what belongs to the request. The feature definitions are identical for both customers. Their identity and preview enrollment can differ. If a handler changes an attribute on a single shared user instance before awaiting a database query, another handler could replace that attribute before the first handler resumes.

Give your agent a server-side task

Use the one-shot guide to add checked-in rules. Ask your agent to keep workspace attributes local to each request and demonstrate both CSV formats.

Open the Local Flags Guide

Create a scope when the request arrives

Create server.ts. The Node.js SDK provides GrowthBookClient for the process and createScopedInstance for the current request. The two fixture paths below stand in for two authenticated workspaces. The server binds to the loopback address so you can exercise it locally.

import { createServer } from "node:http";
import { setTimeout as delay } from "node:timers/promises";
import { GrowthBookClient } from "@growthbook/growthbook";
import { features, type Workspace } from "./flags.js";

const client = new GrowthBookClient({ defaultHashVersion: 2 })
  .initSync({ payload: { features } });

const demos = new Map<string, Workspace>([
  ["/demo/preview", { workspaceId: "press-a", reportPreview: true }],
  ["/demo/standard", { workspaceId: "press-b", reportPreview: false }],
]);

createServer(async (req, res) => {
  const workspace = demos.get(req.url ?? "");
  if (req.method !== "GET" || !workspace) {
    res.writeHead(404).end();
    return;
  }

  const gb = client.createScopedInstance({ attributes: workspace });
  await delay(10); // Stand-in for loading this workspace's report.
  const expanded = gb.isOn("includeUniqueReaders");
  const csv = expanded
    ? "period,downloads,unique_readers\nweek-1,80,55\n"
    : "period,downloads\nweek-1,80\n";

  res.writeHead(200, {
    "Content-Type": "text/csv; charset=utf-8",
    "Cache-Control": "private, no-store",
  });
  res.end(csv);
}).listen(4178, "127.0.0.1", () => {
  console.log("Report server listening on http://127.0.0.1:4178");
});

The HTTP handler looks up a workspace, creates its scope, and holds that scope across an asynchronous operation. The short promise-based timer gives a second request time to arrive. In a real export, that's where the database or storage read would happen. Keep the stable client at module scope and the scoped instance inside the handler. If a formatter needs the decision, pass it the boolean or the scoped instance.

In production, resolve the workspace and its access rights from the authenticated session before reading the report. The two selectable paths here are fixtures for public sample data. A caller's choice of a header, query string, or workspace slug can't establish permission to read another customer's report. The endpoint also prevents shared response caching. If you cache real exports, the cache needs to distinguish the workspace and the report format, along with any other inputs that change the response.

Test two requests that overlap

In the first terminal, type-check the service and start it. A successful type check exits quietly. The next command prints the loopback address and keeps the server running.

npx tsc --noEmit
npx tsx server.ts

Save the following as verify.mjs. In a second terminal, run node verify.mjs. Node's built-in fetch calls the local server. Strict assertions compare the full header and data row, including where each row ends.

import assert from "node:assert/strict";

async function report(name) {
  const response = await fetch("http://127.0.0.1:4178/demo/" + name);
  assert.equal(response.status, 200);
  return response.text();
}

const [preview, standard, previewAgain] = await Promise.all([
  report("preview"), report("standard"), report("preview"),
]);

assert.equal(preview, "period,downloads,unique_readers\nweek-1,80,55\n");
assert.equal(standard, "period,downloads\nweek-1,80\n");
assert.equal(previewAgain, preview);
console.log("Both workspaces received the expected CSV.");

You should see the single success line. Testing just the preview workspace proves that the code can add a column. Testing both responses catches the more expensive mistake of silently changing an existing customer's export. Keeping the old format assertion around is especially valuable when the downstream importer belongs to someone outside your team.

To check the compile-time boundary, temporarily change gb.isOn("includeUniqueReaders") to gb.isOn("includeUniqueReader") and rerun npx tsc --noEmit. The diagnostic should identify the misspelled key. Restore it before running the server again. A coding agent can include the before-and-after type check and the two CSV headers in its pull request.

Decide when to expand the report

When one preview customer is ready, leave everyone else on the default. If the next step is to enroll a fraction of workspaces, choose an attribute that matches the promise you're making. Hashing a workspace ID lets colleagues downloading the same report share a format. Hashing each user's ID could give two analysts in the same company different column sets. The one-shot guide shows how to express a percentage and hash attribute in a local rule.

A new rule in flags.ts reaches a process through your deployment. During a rolling deploy, the same workspace might hit old and new processes. If customers need a durable choice of export schema, keep supporting the agreed format in the API itself. When the operational requirement is to change targeting between deploys, you can keep the scoped evaluation in the handler and change how the process receives its rules. The free GrowthBook offerings overview covers Cloud Starter and self-hosting for teams that want to manage those rules.

Manage report targeting in Cloud

Create a GrowthBook workspace when the team supporting exports needs to expand the preview independently of a server release.

Get Started with GrowthBook
Feature Flags
Experiments

Use local feature flags in the Next.js App Router

Nov 20, 2026
x
min read

Your conference agenda has a new “Show room” button. Reviewers should see it on the first page load. Everyone else should get the existing agenda. If a Server Component renders the old agenda and a browser hook independently decides to show the new button, the first HTML and the browser can disagree.

In the Next.js App Router, the server can make this decision once and pass a boolean to the interactive component. We'll define the flag in the repo, select the preview audience with a local test cookie, and verify the actual HTML for both visitors. Clicking the button will still work after hydration. You can follow along without a GrowthBook account or client key. If you're assigning this work to an agent, the free feature flags for coding agents walkthrough gives the background.

Keep the flag definitions on the server

Use a TypeScript App Router project, or create a small one with create-next-app. These paths assume the project has an app directory at its root. If yours uses src/app, put both app and lib under src so the relative imports still match.

npx create-next-app@latest agenda-flags --ts --app --empty --use-npm --no-src-dir --no-tailwind --yes
cd agenda-flags
npm install @growthbook/growthbook@^2.2.0 server-only

Keep the starter's root layout. Create lib/agenda-flags.ts with the following code. The SDK type registration update explains how LocalFeatures checks the flag and its rule against the registered types. This setup requires version 2.2.0 or later.

import "server-only";
import { GrowthBookClient, type LocalFeatures } from "@growthbook/growthbook";

type Features = { agendaRoomDetails: boolean };
type Attributes = { audience: "preview" | "public" };

declare module "@growthbook/growthbook" {
  interface Register {
    features: Features;
    attributes: Attributes;
  }
}

const features: LocalFeatures = {
  agendaRoomDetails: {
    defaultValue: false,
    rules: [{ condition: { audience: "preview" }, force: true }],
  },
};

const client = new GrowthBookClient({ defaultHashVersion: 2 })
  .initSync({ payload: { features } });

export function showRoomDetails(audience: Attributes["audience"]) {
  const gb = client.createScopedInstance({ attributes: { audience } });
  return gb.isOn("agendaRoomDetails");
}

The module can reuse the client and rules across requests handled by the same process. It only holds the current visitor's audience inside the function call. Two requests can therefore use the same flag file and get different results. The Node.js SDK documents the scoped client used under the App Router here.

This particular rule has no percentage and needs no visitor ID. The two audiences are sufficient. If the team later asks for a rollout to 10% of attendees, add a stable attendee or registration ID and choose which of those units should stay together. Jeremy Dorn's Register pattern article explains how a change to an attribute type reaches the call sites that construct it.

Read the cookie for this request

Create app/agenda/page.tsx. The static heading can render for everyone. The request-specific content sits behind a Suspense boundary, so the fallback can show a neutral loading message until the server has the cookie.

import { Suspense } from "react";
import { cookies } from "next/headers";
import { showRoomDetails } from "../../lib/agenda-flags";
import { Agenda } from "./Agenda";

async function AgendaForVisitor() {
  const jar = await cookies();
  const audience = jar.get("agenda-preview")?.value === "1"
    ? "preview"
    : "public";

  return <Agenda showRoom={showRoomDetails(audience)} />;
}

export default function AgendaPage() {
  return (
    <main>
      <h1>Conference agenda</h1>
      <Suspense fallback={<p>Loading the agenda…</p>}>
        <AgendaForVisitor />
      </Suspense>
    </main>
  );
}

The App Router's cookies function reads the incoming request asynchronously. Read it inside the visitor-specific component. Keeping that read out of shared cached code lets the surrounding page reuse common content without treating one visitor's decision as another's. This placement also accommodates App Router projects using Cache Components.

Give your agent the Next.js setup

Use the local flags guide with a concrete request to evaluate one flag on the server and return the same decision to the browser.

Open the Local Flags Guide

The cookie in this demo is a convenient way to preview a public UI treatment. Anyone with that cookie can see the room label. To target paying attendees or private sessions, obtain the audience from the verified session on the server and authorize the underlying data separately.

Pass one decision to the interactive component

Create app/agenda/Agenda.tsx. It's a Client Component because a visitor can open and close the room details. Its initial branch comes directly from the boolean supplied by the page.

"use client";

import { useState } from "react";

export function Agenda({ showRoom }: { showRoom: boolean }) {
  const [open, setOpen] = useState(false);

  return (
    <section data-agenda={showRoom ? "preview" : "standard"}>
      <h2>10:00 · Designing for print</h2>
      {showRoom && (
        <>
          <button aria-expanded={open} onClick={() => setOpen(!open)}>
            {open ? "Hide room" : "Show room"}
          </button>
          {open && <p>Room 204</p>}
        </>
      )}
    </section>
  );
}

The client boundary takes a serializable prop. The component receives true or false. The SDK instance, targeting rules, and cookie handling stay in the server module. You don't need a React provider for this component because its only browser-side choice is whether the visitor has clicked the button.

Follow one page load through server rendering and hydration. For a preview visitor, the server can send a section with a “Show room” button. React's first client render gets the same showRoom value and starts with open set to false. Hydration attaches the click handler. Opening the room detail then updates component state and doesn't require another flag evaluation.

Verify the HTML and the click separately

Build the production app and start it on port 3100.

npm run build
npm run start -- -p 3100

In a second terminal, save this as verify-agenda.mjs in the project root and run node verify-agenda.mjs. The test makes two requests to the same route and looks for a marker on the rendered section. A marker in the HTML helps catch an implementation that only adds the intended layout after JavaScript runs.

import assert from "node:assert/strict";

async function agenda(cookie) {
  const response = await fetch("http://localhost:3100/agenda", {
    headers: cookie ? { Cookie: cookie } : {},
  });
  assert.equal(response.status, 200);
  return response.text();
}

const [standard, preview] = await Promise.all([
  agenda(""), agenda("agenda-preview=1"),
]);
assert.match(standard, /<section data-agenda="standard"/);
assert.doesNotMatch(standard, /<section data-agenda="preview"/);
assert.match(preview, /<section data-agenda="preview"/);
assert.doesNotMatch(preview, /<section data-agenda="standard"/);
console.log("Both agenda layouts arrived in the server HTML.");

Now open http://localhost:3100/agenda in a fresh browser profile. You should see the session title without a room button. In that local page's browser console, set the demo cookie and reload.

document.cookie = "agenda-preview=1; Path=/; SameSite=Lax";
location.reload();

Click Show room and look for Room 204. Click Hide room and the room should disappear. This second check proves the component became interactive. If the server response test passes but the click fails, inspect the browser console for a hydration error before changing the flag rules.

Remove the fixture and reload once more. The button should disappear and the agenda title should remain.

document.cookie = "agenda-preview=; Path=/; Max-Age=0";
location.reload();

The reload is deliberate. Editing the cookie in an already open document doesn't rerun its Server Component. In your app, use the normal session-change flow to request a fresh server render when a visitor signs in, signs out, or leaves a preview group.

Choose where the next flag should be evaluated

For a decision needed in the initial HTML, give the agent an observable requirement. Ask it to show the two HTTP responses, then click the interactive control in the preview. The first check catches an incorrect layout. The second catches correct HTML that never becomes interactive.

If a later feature depends on an action entirely within the browser, evaluate whether its flag belongs in the client tree. The one-shot local flags guide covers both placements. This agenda only needs one server decision. Updating its checked-in rule takes a deployment. Keep that tradeoff in view if the event organizer needs to pause a preview while attendees are already arriving. For that case, compare GrowthBook’s free options for changing flags between deploys.

Manage the agenda rollout in Cloud

Create a GrowthBook workspace when the organizer needs to adjust a preview audience while your Next.js app is serving attendees.

Get Started with GrowthBook

Ready to ship faster?

No credit card required. Start with feature flags, experimentation, and product analytics—free.

Simplified white illustration of a right angle ruler or carpenter's square tool.White checkmark symbol with a scattered pixelated effect around its edges on a transparent background.