Skip to content

Latest commit

 

History

History
371 lines (292 loc) · 15.6 KB

README.md

File metadata and controls

371 lines (292 loc) · 15.6 KB

Callstack Performance Analytics SDK

Performance analytics SDK suite for React Native, React Nitro, native Android, and native iOS apps.

Monorepo Layout

  • packages/react-native-sdk: React Native adapter package (@callstack/performance-analytics-react-native)
  • packages/android-native-sdk: Native Android SDK sources (Maven artifact: com.callstack:performance-analytics-android)
  • packages/react-native-sdk/apple: Native iOS SDK sources (CocoaPod/SPM product: CallstackPerformanceAnalytics, podspec at packages/react-native-sdk/apple/CallstackPerformanceAnalytics.podspec)
  • packages/core-cpp: Shared C++ components (Android Prefab provider: com.callstack:performance-analytics-core-cpp)
  • apps/example-react-native: Example React Native app
  • apps/example-expo: Example Expo development app
  • packages/react-nitro-sdk: React Nitro adapter (@callstack/performance-analytics-react-nitro)
  • apps/example-react-nitro: React Nitro example for iOS and Android

React Nitro example

With Bun and the iOS or Android toolchain installed, run the following from the repository root.

corepack yarn install
cd apps/example-react-nitro
bun run prepare:nitro
bun run start

Press i or a in the dev server to open the example on iOS or Android. Enter an instance URL and project ingest key, then tap Start recording. Flush samples persists the active session and asks the SDK to upload completed sessions. See the React Nitro package guide to integrate another app.

React Native Usage

npm install @callstack/performance-analytics-react-native
import { PerformanceAnalytics } from '@callstack/performance-analytics-react-native';

PerformanceAnalytics.init({
  host: 'https://perf.example.com',
  apiKey: 'ps_your_project_ingest_key',
  sampleIntervalMs: 10_000,
  enableBackgroundSampling: false,
});

PerformanceAnalytics.flushNow();
const files = await PerformanceAnalytics.readStoredPayloadFilesForDebug();

Create a project and an API key in your instance's Settings screen. host is the instance's base URL, including any deployment path. It is required for both hosted and self-hosted installations; there is no implicit destination. The key determines the project that owns the uploaded data. Use a different key for each app, and revoke a key in the instance to stop accepting its uploads.

The apiToken configuration field has been replaced by apiKey. Both native SDKs also require the instance host. Invalid host URLs and empty keys throw during React Native configuration.

After PerformanceAnalytics.init(...), the React Native SDK also records these performance measures automatically:

  • app.foreground
  • app.background
  • app.keyboard.show
  • app.keyboard.hide

First contentful paint and custom draw markers

By default, the SDK records app.fcp once per app process. Call PerformanceAnalytics.init before mounting your React root so the SDK can observe its first content. The duration runs from app.launchStart to the native draw pass following React Native's first root child. Set autoInjectFCP: false to disable this automatic measure.

The SDK registers two React Native performance marks for the first visible app open in a process. Both are available with automatic FCP disabled.

Mark Cold start Warm start
app.processStart iOS process creation or Android SDK early initialization Same timestamp, including time spent in the background
app.launchStart Same as app.processStart First activity creation on Android or first activation on prewarmed iOS

Android classifies a first activity created within three seconds of early initialization as cold. iOS recognizes prewarm through ActivePrewarm. An iOS background launch without that flag is classified as cold. PerformanceAnalytics.getAppStartType() returns 'cold' or 'warm' once the launch anchor is available. Subsequent foregrounds keep the original marks.

For example, suppose Home is the initial route and its populated feed is the largest content you want to measure. Initialize the SDK before registering the React root, then mount the marker when the feed replaces the skeleton on the visible Home screen.

import {
  MeasurementView,
  PerformanceAnalytics,
  type FirstDrawnFinishedEvent,
} from '@callstack/performance-analytics-react-native';

PerformanceAnalytics.init({ host, apiKey, autoInjectFCP: true });

let recordedHomeLCP = false;

function recordHomeLCP({ uptimeMs }: FirstDrawnFinishedEvent) {
  if (recordedHomeLCP) return;
  const appStartType = PerformanceAnalytics.getAppStartType();
  if (appStartType === undefined) return;

  performance.measure('home.lcp', {
    start: 'app.launchStart',
    end: uptimeMs,
  });
  recordedHomeLCP = true;
}

function HomeScreen() {
  const feed = useHomeFeed();
  if (feed === undefined) return <HomeSkeleton />;

  return (
    <>
      <HomeFeed items={feed} />
      <MeasurementView onFirstDrawnFinished={recordHomeLCP} />
    </>
  );
}

The callback fires once per mount. uptimeMs uses the same clock as performance.now(). timestampMs gives the same draw in Unix milliseconds. The guard counts Home once if navigation remounts it. The SDK includes the measure in the uploaded session. Group FCP and custom Home LCP measures by sessionMetadata.appStartType (cold or warm). Automatic FCP also carries dimensions.appStartType. The startup sample records appStartTimeType (1 cold, 2 warm).

SDK-owned performance entry names now use the app.* prefix. Update saved queries for FCP, app state, keyboard, navigation, and touch entries. Previously uploaded sessions retain their original names.

This replaces autoInjectTTI, TTIMeasurementView, and the automatic margelo.tti entry. Apps can define their own interactive or content-ready milestones using the callback.

Frames and screen navigation

After setup, the SDK collects foreground frame timing even when the app has no screen markers. To split each screen's frames into entering and steady, register the root React Navigation container on readiness and attach the same integration's listeners to each participating navigator. The Expo Router example uses the same integration for its root stack and nested tabs.

const navigation = reactNavigationIntegration();
const ref = createNavigationContainerRef();

<NavigationContainer ref={ref} onReady={() => navigation.registerNavigationContainer(ref)}>
  <Stack.Navigator screenListeners={navigation.screenListeners}>
    {/* screens */}
  </Stack.Navigator>
</NavigationContainer>

For a custom navigator, call the public markers from its transition callbacks. Use stable screen names such as ProductDetails across visits. Keep the handle for the individual transition.

import { screenNavigation } from '@callstack/performance-analytics-react-native';

screenNavigation.screen('Feed'); // Feed is visible and settled.
const opening = screenNavigation.beginTransition('Feed', 'ProductDetails');
// In the animation completion callback:
opening.settle();
// A cancelled gesture calls opening.cancel() instead.

A frame during an observed transition belongs to the destination and carries its source and transition ID. A cancelled gesture restores the source. A superseding transition interrupts the previous handle. A route change without an observed animation boundary has an unknown phase. React Navigation markers take effect when JavaScript delivers the callbacks. A busy JS thread can shift these boundaries relative to the native animation. Frame durations are measured natively.

Measurement Availability Meaning
Android late frames Android 7+ Hardware-rendered activity window frames. Android 12+ compares total duration to the OS frame deadline. Older versions use the display refresh budget. First draws are excluded. Dropped callback reports are recorded separately.
iOS late frames and estimated hitch time iOS 18+ Passive UIKit updates in foreground window scenes. Counts app commits past their deadline and estimates missed presentation time from refresh cadence. GPU and compositor delays can differ from this estimate.
Apple MetricKit hitch ratios iOS 14+ OS-reported scroll hitch ratio for the payload period. With the iOS 26+ SDK and runtime, animation hitch ratio is also recorded. Apple supplies the units and reporting period.

The Performance page computes aggregate and per-screen late-frame rates from summed frame counts. Unknown-phase and unattributed frames contribute to totals. iOS hitch time is additive across scopes. MetricKit ratios appear in their own dated reports. Google Play Android vitals and MetricKit each apply their own reporting and aggregation rules.

iOS dependency managers

The npm package includes its Swift sources and a React Native SwiftPM manifest. In a SwiftPM app, run React Native’s SwiftPM setup after installing the SDK. The app’s codegen package supplies the matching native module and Fabric headers. In a CocoaPods app, add the bundled native pod inside your app target before running pod install (the path below assumes a Podfile under ios/):

pod 'CallstackPerformanceAnalytics', :path => '../node_modules/@callstack/performance-analytics-react-native/apple'

Native SDK installation

iOS with Swift Package Manager

In Xcode, add https://github.com/callstackincubator/performance-analytics.git as a package dependency, select version 0.2.1, and link the CallstackPerformanceAnalytics product to the app target. Xcode and CI need read access to the private repository.

Android with Gradle

For native Android, React Native, and React Nitro apps, add the GitHub Packages repository to the app's Gradle dependency repositories. In settings.gradle.kts:

dependencyResolutionManagement {
  repositories {
    google()
    mavenCentral()
    maven {
      name = "GitHubPackages"
      url = uri("https://maven.pkg.github.com/callstackincubator/performance-analytics")
      credentials(org.gradle.api.credentials.PasswordCredentials::class.java)
      content { includeGroup("com.callstack") }
    }
  }
}

Set GitHubPackagesUsername and GitHubPackagesPassword in your user-level ~/.gradle/gradle.properties. Use a GitHub username and a classic personal access token with read:packages and access to the SDK packages.

In a native Android app, add the dependency below. The React adapters declare it for you. Gradle also resolves the SDK's C++ dependency.

dependencies {
  implementation("com.callstack:performance-analytics-android:0.2.1")
}

Native APIs (v1)

The Android and iOS SDKs expose CallstackPerformanceAnalytics with these methods:

  • setup(...)
  • flushNow()
  • readStoredPayloadFilesForDebug() (debug helper: returns current and pending JSON files)
  • mark(...)
  • measure(...)
  • recordEntry(...)

Upload request bodies are sent to POST <host>/api/v1/sessions as gzip-compressed JSON (Content-Encoding: gzip), authenticated with x-api-key. Device details, session metadata, and samples retain their native schema and units.

A session lasts for one app process. flushNow() persists the active session, but uploads only completed sessions from previous app processes. Restart the app and flush to send a completed session. The server commits sessions before acknowledging them and deduplicates retries by project and session ID.

Thread benchmarks

React Native and React Nitro export ThreadBenchmark on Android and iOS. Import it from the adapter your app uses. Swift apps can construct try ThreadBenchmark(name:) from CallstackPerformanceAnalytics. Kotlin apps use com.callstack.performanceanalytics.ThreadBenchmark on any app thread. Each instance starts a named window and returns its result once, on the thread that created it. Opening a window opts into the hardware counters. The API can run independently of analytics setup, sampling and upload.

val window = ThreadBenchmark("decode")
try {
  decode()
} finally {
  val result = window.end()
  reportToCI(result)
}
Field Meaning
name, threadId Window name and OS thread ID of the caller.
elapsedMs Monotonic wall time including waits within this window.
threadCpuMs CPU time consumed by this thread, from CLOCK_THREAD_CPUTIME_ID. The telemetry field cpuTotalTimeMs covers the whole process.
instructions, cycles Raw retired instructions and CPU cycles for user-space execution on this thread. Both events share one Linux perf group.
countersAvailable True when the group supplied counts with positive running time.
timeEnabledNs, timeRunningNs Android kernel-reported enabled and scheduled time. Equal positive values mean full coverage. A smaller running time means partial coverage. Counts are unscaled.
counterErrno Platform error number when the counters are unavailable. The clocks remain available.

Unavailable hardware values are nullable on Android and optional in JavaScript. A group scheduled for zero time reports its coverage and omits both counts. Each participating thread needs its own window. Use a separate monotonic timer from dispatch to completion for the duration of a multi-thread action. On iOS, both adapters return the Darwin thread ID and the two clocks. countersAvailable is false and counterErrno is ENOTSUP. The in-app result omits instructions, cycles and counter coverage. XCTest can separately collect CPU metrics for a performance-test block on its calling thread. Apple’s XCTCPUMetric

React Native Release example · Android instrumentation and CI invocation

Development

corepack yarn install
cp apps/example-react-native/.env.example apps/example-react-native/.env
cp apps/example-expo/.env.example apps/example-expo/.env
# Set each example's host and project key in its .env file.
yarn example start
yarn example android
yarn example ios

The bare example uses React Native 0.89.0-rc.3 with Swift Package Manager on iOS. The Expo SDK 58 example uses React Native 0.88.1 and CocoaPods. Both use React 19.3.0. The React Native adapter requires React Native 0.87 or newer. Node 22.13 or newer, Xcode with an installed iOS simulator, and the Android SDK are required for the respective platforms. The SDK and Expo example use React Native's Strict TypeScript API.

The bare example reads PERFKIT_HOST and PERFKIT_API_KEY from its .env file when Metro builds the JavaScript bundle. To open the iOS example in Xcode, run yarn example ios:setup after installing dependencies and open the MargeloAnalyticsSdkExample.xcodeproj. Setup resolves the native packages and runs React Native codegen.

For the Expo example:

yarn workspace @callstack/performance-analytics-example-expo start --port 8082
yarn workspace @callstack/performance-analytics-example-expo ios
yarn workspace @callstack/performance-analytics-example-expo android

Its config plugin links the monorepo's native packages during expo prebuild. Use a development build; Expo Go does not include this SDK's native code.

The SaaS runs directly with Bun in the adjacent performance-saas checkout:

cd ../performance-saas
bun install
bun dev

For a local instance, use http://localhost:3000 as the host. On Android, forward the device's port to the computer with adb -s <serial> reverse tcp:3000 tcp:3000. For a physical iPhone, use a host reachable from the device.

Validation:

yarn typecheck
yarn lint
yarn workspace @callstack/performance-analytics-example-expo exec tsc --noEmit
yarn build:ios-native:spm

License

MIT