Skip to content

Screenshot replay: the render(in:) fallback blocks the main thread for 1–18 s on React Native screens (iPhone and iPad) #1035

Open

Description

@beqramo

Summary

In screenshot replay, the render(in:) fallback in UIView.toImage blocks the main thread for 1 to 18 seconds per capture in our React Native app, on iPhones and iPads alike. The fallback renders the presentation tree. Sentry's app-hang tracker and MetricKit attribute every one of these hangs to the same frame. For us, session replay is the main way to see where new users get stuck. Today our only lever against the freezes is to stop recording, so we would much rather help fix the capture.

Environment

  • PostHog iOS 3.88.2, through posthog-react-native 4.81.2, posthog-react-native-session-replay 1.6.0 and @posthog/react-native-plugin 2.12.6.
  • React Native 0.88 (new architecture), Expo SDK 58, iOS 18.x, App Store builds.
  • Replay is screenshot mode, as React Native uses.
  • Config:
    • maskAllTextInputs: true
    • maskAllImages: true
    • maskAllSandboxedViews: true
    • captureNetworkTelemetry: true
    • throttleDelayMs: 3000 (already throttled)

What we see

One Sentry issue has 577 hang events from 380 users in 15 days. The culprit is closure in UIView.toImage every time.

Values in the most recent events
Hang length 2.4 to 3.6 s for most; 5 to 7.7 s often; one 17.8 to 18.6 s, fully blocked (iPad15,3); MetricKit MXHangDiagnostic from 1.0 to 1.3 s
iPads iPad6,8, iPad7,11, iPad8,7, iPad12,1, iPad12,2, iPad15,3
iPhones iPhone10,5 (8 Plus), iPhone12,5 (11 Pro Max), iPhone14,2 (13 Pro), iPhone14,5 (13)
Device class Sentry's device.class is high on several of them, so this is not only old hardware
Screen Almost always our deck screen: a large React Native tree with shadows, images, a WKWebView rich-text editor, and on iPad a second WKWebView (PDF.js) in a two-pane layout
Low Power Mode On in several events, which makes it worse

An earlier build also had a "Fatal App Hang" here, meaning the watchdog killed the app.

Android records the same screens with the same remote config and shows nothing comparable. We understand Android captures asynchronously with PixelCopy.

Stack

Same path in every event (3.88.2 line numbers):

closure in PostHogReplayIntegration.scheduleSettledCapture (PostHogReplayIntegration.swift:1673)
PostHogReplayIntegration.performScreenshotCapture (PostHogReplayIntegration.swift:1309)
PostHogReplayIntegration.collectScreenshotMetadata (PostHogReplayIntegration.swift:1241)
UIView.toImage (UIView+Util.swift:134)
PostHogGraphicsImageRenderer.image (PostHogGraphicsImageRenderer.swift:60)
closure in UIView.toImage (UIView+Util.swift:150)      <- (layer.presentation() ?? layer).render(in: context)
-[CALayer renderInContext:]  (x15+ levels of _renderSublayersInContext:)

Under renderInContext:, the time is spent in software rasterisation. From one MetricKit diagnostic (iPhone12,5, iOS 18.6):

  • Software shadow blur:
    CGContextEndTransparencyLayer → ripc_EndLayer → RIPLayerGaussianBlur → RIPLayerSymmetricConvolve → vImageConvolve_Planar8.
    It shows up several times per capture, once per shadowed layer.
  • Per-image colour conversion:
    CGContextDrawImage → … → CGColorTransformConvertUsingCMSConverter → convert_icc → vImageConvert_AnyToAny → vConvert_16Fto16Q12_vec / vUnpremultiplyData_RGBA16Q12.
    It shows up once per image layer, and some of those images are half-float or extended range.
  • Group-opacity transparency layers and image resampling:
    CGContextEndTransparencyLayer, RIPLayerBltImage → argb32_sample_argb32.

Why we think it gets this expensive

  1. When the fallback runs. scheduleSettledCapture picks render(in:) whenever the settle check sees mask geometry move, or cannot pair the samples. With maskAllImages and maskAllTextInputs, almost any animated React Native screen hits that branch on most captures: a looping animation, streamed text reflowing, a list settling after a scroll. So the "rare" path becomes the common one.
  2. How much it renders. render(in:) rasterises the whole window on the CPU, on the main thread, at the native screen scale (PostHogGraphicsImageRenderer(size:scale: nativeScale)). Since 3.92.x the upload is one pixel per point, so on a 3x phone the fallback does about 9x the pixel work that ends up in the upload; on a 2x iPad, 4x. Blur and colour conversion both scale with pixel count. A 2x iPad window in a two-pane layout is the largest case, and that matches the worst hangs we see.
  3. No upper bound. Nothing caps one capture's main-thread time, so a heavy screen costs the user seconds instead of costing the recording frames.

Suggestions

In order of how much we think each would help:

  • Render the render(in:) fallback at the upload scale (one pixel per point, or screenshotScale), not the native scale. Today the extra pixels are thrown away when the frame is downscaled.
  • Give the capture a main-thread budget. Time each capture, and if it goes past a threshold (say 50 to 100 ms), back off: skip the next fallback captures, use drawHierarchy with inflated masks, or lengthen the interval for that screen. Then a heavy screen degrades the recording, never the app.
  • Let apps opt out of the presentation-tree fallback. That means always using drawHierarchy and accepting mask drift with inflated masks. The render server already composites shadows and colour on the GPU.

We saw related work and think it would help too:

Our hangs are dominated by the CPU render(in:) fallback, not drawHierarchy itself, so the scale and the budget would help even before those land.

We can test a branch or a prerelease build on the affected devices and share before and after hang numbers.

Activity

  1. marandaneto commented on Nov 5, 2026

    @marandaneto
    Member

    Thanks for the detailed report. We reproduced the multi-second main-thread stalls without React Native, using a native UIKit stress screen hosted in the iOS example app.

    Environment and setup

    • SDK 3.93.6, current main at 29d7d862b.
    • iPhone 17 Pro and iPad Pro 13-inch (M5) simulators, both reporting iOS 26.4.1, on an M4 Pro Mac; optimized Swift build.
    • Synthetic cards with nested UIViews, extended-range 16-bit images, text fields, group opacity, and radius-24 shadows without a shadowPath. The 48-card case intentionally overlaps cards to stress compositing; it is not a reconstruction of your deck screen. No React Native or WKWebView involved.
    • Screenshot replay with image/input/sandbox masking enabled and a 3-second throttle.

    Results

    Direct renderer comparisons, median of three captures, all on the main thread:

    Screen drawHierarchy SDK native-scale render(in:) fallback Same layer render at 1× (control)
    iPhone, 12 shadowed cards 43 ms 519 ms 154 ms
    iPhone, 48 shadowed cards 51 ms 2,112 ms 599 ms
    iPad, 12 shadowed cards 69 ms 769 ms 294 ms
    iPad, 48 shadowed cards 95 ms 2,965 ms 1,071 ms

    We also reproduced this through normal SDK replay scheduling, not only forced renderer calls. Stable masks used drawHierarchy. Changing maskable image owners between settle samples caused the SDK to select the fallback:

    • iPhone: three fallback captures took 1.93–2.02 seconds, with corresponding display-link gaps of 1.95–2.04 seconds.
    • iPad, unprofiled: six consecutive fallback captures took 2.87–2.88 seconds. For this run, the image owner was replaced every display tick to deterministically exercise unpairable samples; an initial blinking-owner test did not consistently select the fallback.

    A separate CPU sample of the normal iPad replay path matches the reported stack:

    scheduleSettledCapture
      UIView.toImage
        PostHogGraphicsImageRenderer.image
          CALayer.renderInContext (many nested calls)
            RIPLayerGaussianBlur → RIPLayerSymmetricConvolve → vImageConvolve_Planar8
            CGContextDrawImage → CGColorTransformConvertUsingCMSConverter → vImageConvert_AnyToAny
    

    This confirms that React Native is not required for this failure mechanism: native screenshot capture can incur the reported software shadow-blur and image-colour-conversion costs, even with image masking enabled. Rendering at 1× substantially reduced the cost, but still exceeded one second in the iPad stress case; this was only a diagnostic control, not a validated fix.

    Limits: we have not reproduced the 18-second extreme, tested physical devices/Low Power Mode, or run your exact SDK/iOS versions or application. The synthetic owner churn is intentionally aggressive, so these results do not establish how often your production screen enters the fallback. No fix has been implemented yet.

  2. marandaneto commented on Nov 5, 2026

    @marandaneto
    Member

    as you linked, theres some work going on optimizing this code path with #911 and other similar issues/PRs, watch this space, @ioannisj is on it

  3. ioannisj commented on Nov 5, 2026

    @ioannisj
    Contributor

    Thanks for the detailed report, and for the stacks and MetricKit breakdown.

    While I look at the fallback itself, could you try the screenshotModeBackgroundCapture option on the affected devices? it's a one-line config change:

    <PostHogProvider
      apiKey="..."
      options={{
          ...
          screenshotModeBackgroundCapture: true,
        },
      }}
    >

    In this mode the SDK skips the settle check and never uses the presentationrender(in:) path. So every frame comes from drawHierarchy, rendered on a background queue. Android ignores the option.

    I think there's enough info here for me to dig in. I'll let you know if I need anything more though.

  4. beqramo commented on Nov 5, 2026

    @beqramo
    Author

    Thanks @marandaneto and @ioannisj for the quick reply and the repro!

    To be honest, we haven't tried screenshotModeBackgroundCapture yet. We held off because it's marked experimental and runs drawHierarchy off the main thread. We're testing it now on our app (SDK 3.88.2, iPad deck screen) and will share the before/after hang numbers here.

    Quick question: is the option considered safe for production yet?

  5. posthog commented on Nov 6, 2026

    @posthog
    Contributor

    PostHog self-driving picked up this issue. Status: Research is done.

    Somebody may already be working on it, so ask before you start a fix.

    Report (team access only): https://us.posthog.com/project/2/inbox/reports/01a1ae52-9d6f-73a7-9a6a-0b30704e23b1?link_source=github_comment

  6. ioannisj commented on Nov 6, 2026

    @ioannisj
    Contributor

    Thanks @marandaneto and @ioannisj for the quick reply and the repro!

    To be honest, we haven't tried screenshotModeBackgroundCapture yet. We held off because it's marked experimental and runs drawHierarchy off the main thread. We're testing it now on our app (SDK 3.88.2, iPad deck screen) and will share the before/after hang numbers here.

    Quick question: is the option considered safe for production yet?

    That's right, drawHierarchy (which is the expensive call) is called off main, mask hops and reading rects are done on main thread though. We've had the experimental option since posthog-ios 3.58.1 (May 2026) with zero reports so far. Would be great if you test this out and let us know how it performs.

    As you well spotted #911 is something new we are trying, which keeps everything on the main thread. It does, add, however overhead. No matter how performant and how small the footprint, this adds up to the work the app is doing on main, so could lead to dropped frames in scenarios where main thread is struggling.

  7. beqramo commented on Nov 6, 2026

    @beqramo
    Author

    Thanks @ioannisj, that's reassuring. A first A/B of screenshotModeBackgroundCapture, on a simulator for now:

    Setup: iPad Pro 13" (M5) simulator, iPadOS 26.5, debug build, posthog-ios 3.88.2 via posthog-react-native 4.81 and the session-replay plugin, throttleDelayMs: 3000, masking on. The screen is the one from the report (deck screen, several WebViews and a PDF). A fixed 48 s script switches tabs every 3 s, and macOS sample samples the app process at 1 ms for 40 s. Two runs per variant.

    main-thread time in PostHog capture share of busy main thread PostHog replay queue (samples)
    option off 706 ms, 693 ms 16.0%, 15.2% 7.4k, 12.8k
    option on 73 ms, 67 ms 2.0%, 1.7% 8.5k, 10.9k

    With the option on, main-thread time in capture drops about 10×: what's left is performBracketedBackgroundCapture's bracket closures and the touch hook. Work on the replay queue stays about the same, so the capture moved off the main thread rather than being added. A debug build on a simulator says nothing about absolute cost, only the ratio. We'll repeat this on physical iPads and post those numbers.

    Update: I'd asked here about the native SDK refusing manual startSessionRecording() calls. Please ignore that: it was our project's own replay sampleRate (0.25) sampling the session out, logged on the JS side as "remote config is not loaded yet". The message could name sampling as a possible reason, but that's all.

  8. ioannisj commented on Nov 10, 2026

    @ioannisj
    Contributor

    Thanks for running this, a 10x drop looks about right. What's left on main with the option on is reading mask rects before and after the background draw and the touch hooks.

    Good catch on the sampling log. That message lives on the React Native side and it only knows the native SDK refused to start. I'll see if I can improve

    Physical iPad numbers would be super interesting when you have them 🙏

  9. turnipdabeets commented on Nov 15, 2026

    @turnipdabeets
    Contributor

    @ioannisj, given the ~10× drop with background capture and your point that GPU capture still adds work on main, should 'background' be what we recommend for React Native, or even the plugin's default? GPU opt-in for React Native comes with posthog-ios 4.0 and plugin 3.0 (PostHog/posthog-js#5734).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions