MTTR: How to measure and reduce mean time to recovery

At 10:20 the on-call engineer disables a change that made new document uploads fail. The error graph drops within two minutes. Support closes the incident at 11:05 after answering the last customer. Meanwhile, a queue of documents accepted before the fix is still waiting to be indexed. Which timestamp belongs in the recovery report?
Mean time to recovery (MTTR) is the sum of recovery durations for a defined set of incidents divided by the number of those incidents. To make the number useful, define what starts the clock, what qualifies as recovered, and which incidents enter the denominator. For a customer-facing service, one defensible definition runs from the beginning of customer impact to independently verified restoration of the affected capability. You can also measure the interval from alert to mitigation, but that answers a different operational question.
Choose the service promise before choosing the timestamps
In the document service, users may care about both “can upload a file” and “can find that file in search within five minutes.” The system can satisfy the first promise while violating the second. If the incident interrupts both, the team can report separate restoration milestones or define full restoration as the point when both promises hold again. Pick a policy before the next incident. An outcome chosen after seeing which one recovers sooner will make the times easier to celebrate and harder to compare.
Write the reporting definition in a few lines that an incident commander and a customer support lead can both apply. Specify the population of service incidents, the evidence for impact start, the customer-visible recovery signal, and how long recovery must persist before the incident is considered restored. Decide what happens when a fault affects only one region, one client version, or a busy enterprise tenant. A healthy global average can conceal real customer failure.
Keep the clocks that answer other questions
MTTR has also been used for mean time to repair, respond, and resolve. Record the exact timestamps behind each concept so the acronym cannot silently change meaning between teams. If a database team repairs a corrupt replica after traffic has already failed over to a healthy one, the repair work remains important. It measures the restoration of redundancy, while the customer recovery clock may already have stopped. A final postmortem approval date describes a third activity.
| Interval | Example evidence | Decision it can inform |
|---|---|---|
| Impact to detection | First failed synthetic journey or first confirmed error, then the alert | Is the customer signal visible early enough? |
| Detection to coordinated response | Alert and acknowledged ownership | Does the page go to someone with the right context? |
| Response to effective mitigation | Response start and customer-visible change in behavior | Can the responder disable, reroute, or repair the affected path? |
| Mitigation to verified recovery | Recovery signal by affected cohort, including required backlog processing | Did customers actually regain the promised capability? |
These phases may overlap or have uncertain boundaries. A customer might report an incident before monitoring can locate its start. Record the earliest supported time and an uncertainty note. If all you know is that the service was healthy at 08:00 and failed by 08:06, pretending impact began at exactly 08:03 adds precision without evidence. Avoid converting a missing start into a duration of zero.
Choose related reliability measures for impact and change risk
Two ten-minute incidents can have radically different consequences. One affects a single internal reporting job. The other interrupts every checkout in a region. Publish a measure of impact alongside duration, such as failed customer journeys or affected account-minutes, with a clear method for estimating it. Avoid summing overlapping outages as if they hit distinct customers unless you actually know their overlap. Google SRE's analysis of incident metrics explains why time-based aggregates alone make weak evidence for comparing reliability or response performance.
For deployments, consider whether the team needs a metric restricted to recovery from a failed deployment. DORA narrowed its recovery measure to distinguish software delivery failures from unrelated disruptions in its research on software delivery performance. A payment provider outage, a storm at a data center, and a failed checkout release can all belong in a customer-facing incident dataset. Label the cause or trigger when known so deployment work is evaluated on the relevant subset.
Set the recovery clock by what customers experience
A payments team can usually find the exact minute an engineer acknowledged a page. It may take longer to establish when customers first lost the ability to pay. Choosing the easy timestamp can reward the wrong change. If a new alert detects an outage eight minutes sooner and the service recovers at the same moment, the interval from page to recovery gets eight minutes longer. Customers experienced the same outage. For a customer-impact MTTR, start at the first supported evidence of impairment and end when the affected service meets the agreed recovery condition.
Distinguish impact, mitigation, and verified restoration
Consider a checkout incident. A checkout probe starts failing at 09:04 UTC, the first page fires at 09:11, and an engineer acknowledges it at 09:13. At 09:22 the team rolls back a release. Cards work again in the largest region at 09:26. A smaller region still rejects valid payments until 09:41. The team then observes ten consecutive healthy minutes and closes the incident ticket at 10:17. These timestamps answer different questions.
Suppose the recovery rule says successful checkout must return to its operating range in every affected region for ten minutes. The team records the start of that healthy interval as restored time after confirmation. Its recovery duration is 09:41 minus 09:04, or 37 minutes. Detection took seven minutes. The period from rollback to full recovery lasted 19 minutes. A process that records the end of the confirmation window instead would report 47 minutes. Either convention can be audited when the recovery rule names the signal, affected population, persistence window, and timestamp convention.
A rollback command is evidence of an action. Record it separately from the observed return of successful payments. An operational kill switch may stop new calls quickly while cached clients or in-flight requests continue using the old path. A queue may still contain work customers were promised. Decide whether clearing it belongs in the recovery condition for that service. The answer depends on whether customers are still missing a time-sensitive outcome. Use release guardrails and rollback criteria to specify what responders should inspect after acting.
Rehearse a flag rollback
Explore the implementation choices that determine how a flag change reaches the clients involved in an incident.
Read the Flagging GuideGive one incident one row
A database failure can generate a page for each affected replica, several customer support tickets, and a status-page event. Keep those identifiers as evidence on one incident record when they describe the same episode. Systems such as Prometheus Alertmanager group and deduplicate notifications. The grouping rule alone cannot decide whether two simultaneous symptoms share a cause. Let the incident owner document the connection and retain separate records when two independent failures happen to overlap.
Record service, incident ID, customer-facing symptom, severity, impacted scope, best-supported impact start, restored time, and evidence for the boundaries. A customer report may be the earliest available signal when telemetry is missing. Mark that timestamp as approximate. If the last known good check was 14:00 and the next failed check was 14:10, report that uncertainty. An invented 14:05 onset can produce misleading precision.
Use stable severity definitions tied to scope and customer impact. Record the severity used for analysis, including whether it is the peak reached or the initial declaration. An incident downgraded after mitigation can otherwise migrate to a different monthly category. Keep incidents still open at the reporting cutoff visible with their age. An average of completed incidents can look unusually good when the longest ongoing outage has yet to contribute a duration.
Calculate the distribution from a five-incident ledger
This fictional checkout ledger uses UTC timestamps on five different days. Each row meets the same recovery definition. For an incident spanning midnight, store full dates alongside times before subtracting them.
| Incident | Peak severity | First impact | Restored | Recovery minutes |
|---|---|---|---|---|
| A | SEV-3 | 09:12 | 09:20 | 8 |
| B | SEV-3 | 12:10 | 12:22 | 12 |
| C | SEV-2 | 15:22 | 15:40 | 18 |
| D | SEV-2 | 08:07 | 08:39 | 32 |
| E | SEV-1 | 16:30 | 19:30 | 180 |
The sum is 250 incident-minutes. Divide by five incidents and the mean is 50 minutes. The middle ordered value gives a median of 18 minutes. Four incidents recovered within 32 minutes. The remaining incident accounts for 180 of the 250 minutes, or 72% of the total. That gives the team a specific case to examine. Adding customer impact would tell it whether those three hours represented a regional degradation or a fleet-wide inability to transact.
With only five observations, show the individual durations alongside the summary. A p95 calculated by the nearest-rank method would equal the maximum here. Labelling 180 minutes the “95th percentile” would add little information about how frequently the next outage might last that long. Over a longer period, show counts, the median, a tail percentile with its calculation method, and changes in the kinds of incidents the team handled. Google SRE's incident-duration analysis illustrates how variable durations and small samples can obscure trends.
Suppose the next five incidents all finish within half an hour because none involves the failed regional dependency. The lower mean describes that month's experience. Attributing it to a new runbook requires another comparison. Inspect comparable dependency incidents across periods, or rehearse the same failure and measure the particular step the runbook changed. A reduction in time to identify the affected region is something the on-call team can verify even in a month without another three-hour incident.
Find the part of recovery that an engineer can shorten
Consider a checkout incident. Customer-visible payment failures begin at 10:02. An alert fires at 10:08, the on-call engineer acknowledges it at 10:11, and the incident lead chooses a fallback at 10:23. The fallback reaches the affected service at 10:27. By 10:34, successful checkouts are back within the team's declared recovery threshold. The incident ticket stays open until 11:10 while support writes to affected customers.
Under an impact-to-restoration definition, the incident lasted 32 minutes. The parts are six minutes to detect, three to acknowledge, twelve from acknowledgement to a mitigation decision, four to apply it, and seven to observe recovery. Closing the ticket at 10:35 instead of 11:10 would save 35 minutes in the ticketing report and zero minutes for shoppers. Preserve both timestamps. They answer legitimate questions about different teams' work.
Match the intervention to the delay
Read the response timeline with the people who made those decisions. If the first six minutes passed because server health stayed green while card payments failed, add a customer-journey signal for that failure mode. Check its false-alarm burden too. If the alert reached someone who could diagnose the issue but couldn't operate the fallback, fix the on-call access and ownership path. A more sensitive alarm in that situation just asks someone to wait sooner.
The twelve-minute decision interval deserves a closer look before calling it waste. Responders may have been deciding whether the fallback could replay an already authorized payment. If that was the question, test the fallback with a duplicate transaction in a nonproduction environment and add the result to the runbook. One well-placed piece of evidence can make the next decision faster without asking responders to take an unjustified risk. Google's incident response guidance separates command, operations, and communications responsibilities so the person doing the mitigation has room to do it well.
For the seven minutes after the fallback was applied, inspect the customer's path again. Were workers draining a queue? Did a cached client configuration need to expire? Or was the monitoring panel refreshing on a five-minute schedule? Those demand different fixes. Record the best estimate of the first restored transaction and the time the team could confidently establish sustained recovery. Don't backdate an incident to a precision the telemetry can't support.
Separate failures caused by a deployment from failures caused by an external dependency or a traffic event. Both affect customer recovery time. Only the former belongs in DORA's failed deployment recovery time, which concerns a failed deployment requiring immediate intervention. Track the all-incident and deployment-specific populations with explicit names. A quieter month for an external payment provider can improve the overall mean while the team's ability to reverse a bad deploy stays exactly the same.
Rehearse one recovery from the customer's side
Choose a checkout test environment with synthetic orders and a known working payment stub. Have a facilitator switch the stub to a prearranged failure response, starting the clock when a test customer first cannot complete an order. One person acts as incident lead, one handles the technical response, and an observer records when each person obtained enough evidence to act. Keep the scenario within that test environment. Inspect the customer-facing error as well as application health during the rehearsal.
Ask the responder to locate an affected order, identify the failing dependency, and restore the working route. Have the observer follow that order to a final state and verify that exactly one payment outcome was recorded. A green health check alone leaves the most important customer question unanswered. End the recovery clock when the agreed transaction check stays healthy for its specified window. Capture the later ticket closure separately. Practicing incident response through exercises gives a team a way to find unclear ownership and stale runbooks before a customer outage.
Bring back one change with a named owner. For example, give the on-call dashboard a link from a failed checkout to its provider response, then repeat the same drill with a different responder. Compare the time and evidence needed to choose the fallback. Keep drill results separate from production MTTR. A faster rehearsal shows that the team improved a particular recovery step. Production incidents will show how often that step matters to actual customers.
Shorten a recovery by stopping the failing path
A parcel platform starts buying labels through a new carrier integration for a subset of merchants. Small parcels work. Multi-box shipments time out after the carrier accepts the request but before the platform records the label ID. Merchants retry. Some buy a second label, while others wait at a packing station with no printable label at all. Service CPU and request acceptance look fine. The incident is visible in the share of eligible shipment requests that produce a usable label within the promised time.
Give responders two questions. Can we stop sending new work into the failing path? What has already happened to requests that entered it? A flag can address the first question if the old integration is still available and compatible. It cannot answer the second. Some carrier purchases may have succeeded despite the timeout. Sending all affected requests through the old integration without reconciliation could buy labels twice.
Choose a mitigation that fits the state of the system
Inspect the rollout revision, targeted merchants, and evaluation records. Verify the old integration still supports multi-box shipments and has capacity for the traffic that will return. Have an authorized responder narrow or disable the new integration. Record when the platform accepted the configuration change, then check when workers in each affected region actually began selecting the old route. Cached configuration, long-running jobs, and delayed refreshes can make those times different. A feature flag rollback workflow can help trace the rule and change while keeping the responder responsible for verifying the result.
If the failure is in a shared serializer used by both integrations, disabling the new flag won't restore labels. A known-good deployment or a forward fix may be the useful mitigation. Check whether the older binary can read records and jobs emitted by the newer one. AWS's account of rollback safety during deployments describes the incompatibilities that can arise when newly written data outlives the software that produced it. Keep an explicit fallback for workers that encounter such records so they don't repeatedly crash on the same shipment.
Verify the customer journey by affected cohort
A successful test label from headquarters proves that one route works. Try the incident's exact combination of merchant, region, carrier, and multi-box request, using a test account or an approved nonbillable validation route. Then inspect real production outcomes for that cohort. A useful service-level indicator has successful, printable labels in its numerator and eligible shipment requests in its denominator. Define how retries and duplicate purchases count. Follow the SRE practice of building SLOs around user-visible success.
Compare affected merchants with merchants that never used the new integration. Overall success may already be back above target if most shipments are single-box. Check affected regions separately and inspect throughput. A 100% success rate based on two requests might mean the backlog isn't moving. Also look at time to usable label. An eventual success after the daily carrier pickup has little value to the merchant who missed it.
Agree on a recovery condition that responders can observe. For example, the affected cohort might need to satisfy its normal short-window success and latency thresholds for two full monitoring intervals at representative volume. Choose the actual thresholds from the service's objectives and historical traffic. An overnight region may need a synthetic probe and an explicit pending check when traffic resumes. Record the uncertainty in the incident timeline instead of allowing a pooled global metric to stand in for a region you haven't observed.
Recover queued requests without duplicating the original action
Group affected shipments by outcome. Some have a confirmed external label ID. Others have a confirmed rejection and can be retried through the restored path. A third group has an unknown external outcome. For those, look up the shipment reference or original request key with the carrier before resubmitting it. Idempotent retry design uses a stable identifier to distinguish a repeated request from a customer's intent to create another resource. Check the carrier's support and retention window for that key. An internal database constraint alone can't prevent duplicate purchases outside your system.
Resume a small slice of the queue, monitor both its oldest message and the rate at which new requests arrive, and hold the remainder if duplicate purchases recur. An empty queue is inconclusive if failed messages were diverted into a dead-letter queue. Count requests that reached a terminal business outcome and assign an owner to the unresolved group. Keep voiding duplicate labels or crediting merchants as explicit remediation work. That work may outlast restoration of service for new shipments.
After the immediate incident, maintain a watch on delayed retries, refunds, and the next carrier pickup. Record when fresh requests recovered and when the last affected merchant received a usable label. Preserve both timestamps if your MTTR definition uses only one. Rehearse the flag controls available to release owners before the next carrier migration, with a test that includes already accepted external work. That exercise can shorten the next recovery without asking the on-call team to guess what reversing a switch can undo.
Use recovery data to change one operational decision
Review a handful of recent incidents with the people who worked them. Pick one recurring delay backed by incident evidence and make a change whose effect you can observe. It might be routing an alert to the service owner, giving on-call staff a tested way to change traffic, or adding a customer-level signal that exposes a stuck queue. Rehearse the change with a plausible failure and record both the time to effective action and the time to verified recovery.
Teams using feature flags can put the configuration change in the same timeline as error rates and customer journeys. A flag edit has a timestamp. Evidence that the impacted users recovered has another. Preserving both gives the next reviewer a way to identify what actually helped. A lower quarterly average is welcome, but the operational achievement is a specific failure mode that customers now recover from faster.
Test a recovery control
Use a small release in GrowthBook to compare the time a flag changes with the time the affected experience actually recovers.
Try GrowthBook FlagsRelated Articles
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.
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.
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.
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 GuideThe 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.
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.
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.
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.
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 GrowthBookTwo 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.
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.
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.
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 GuideCreate 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.
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.
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.
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 GrowthBookYour 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.
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.
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.
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 GuideThe 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.
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.
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.
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.
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.
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 GrowthBookReady to ship faster?
No credit card required. Start with feature flags, experimentation, and product analytics—free.




