# Orca Performance Optimization: Best Practices for the StablyAI Code Editor

> Optimize Orca performance with selective Zustand subscriptions, debounced disk I/O, and ResizeObserver for a smoother StablyAI code editor experience. Learn best practices now.

- Repository: [Stably/orca](https://github.com/stablyai/orca)
- Tags: best-practices
- Published: 2026-05-25

---

**The most effective approach to Orca performance optimization combines selective Zustand state subscriptions, aggressive debouncing (150–300 ms) for all disk I/O operations, and ResizeObserver paired with requestAnimationFrame to eliminate layout thrashing.**

Orca, the open-source code editor from **stablyai/orca**, maintains snappy UI responsiveness even under heavy workloads by adhering to three architectural pillars: selective state subscriptions, debounced persistence, and efficient rendering patterns. Understanding these implementation details allows developers to extend the Electron-based application without introducing performance regressions.

## Selective State Subscriptions with Zustand

Orca manages global state through a single Zustand store, but components subscribe only to the minimal data slices they actually render. This pattern prevents cascading re-renders when unrelated state mutates.

### The Autosave Input Equality Pattern

In [`src/renderer/src/store/index.ts`](https://github.com/stablyai/orca/blob/main/src/renderer/src/store/index.ts), the store leverages the `autosaveSubscriberInputsEqual` helper (defined in [`src/renderer/src/components/editor/editor-autosave-controller.ts`](https://github.com/stablyai/orca/blob/main/src/renderer/src/components/editor/editor-autosave-controller.ts)) to compare previous and next inputs—such as open files and editor dirty flags—before allowing updates to propagate. If the relevant inputs haven't changed, the subscription short-circuits, preventing the UI from re-rendering thousands of times per second when background processes update unrelated slices.

When adding new UI state that affects persistence, you must explicitly expose an "input selector" via `getAutosaveSubscriberInputs` in the autosave controller. This ensures the store recognizes whether a state change matters for the persistence layer:

```typescript
// src/renderer/src/components/my-feature.tsx
import { useStore } from '@/store'

function RepositoryPanel() {
  // Selective subscription: only re-renders when worktrees change
  const worktrees = useStore(state => state.worktreesByRepo)
  
  // This component ignores changes to settings, terminals, or search state
  return <div>{worktrees.length} repositories active</div>
}

```

## Debounced Persistence and I/O Management

Disk writes are the most expensive operation in a desktop Electron app. Orca batches all persistence through carefully tuned debounces, then rotates a small ring of backups to guard against corruption.

### Editor Autosave Controller

Located in [`src/renderer/src/components/editor/editor-autosave-controller.ts`](https://github.com/stablyai/orca/blob/main/src/renderer/src/components/editor/editor-autosave-controller.ts), this controller queues file writes using the `queueSave` method after a configurable `editorAutoSaveDelayMs`. It collapses multiple rapid edits into a single write, guaranteeing that a burst of keystrokes doesn't translate into dozens of filesystem calls.

### Session Write Subscriber

The `session-write-subscriber` in [`src/renderer/src/lib/session-write-subscriber.ts`](https://github.com/stablyai/orca/blob/main/src/renderer/src/lib/session-write-subscriber.ts) observes only four specific "autosave inputs" and flushes the entire workspace session after at most **150 ms** of inactivity. This centralized debounce configuration ensures consistent timing across the application.

### Persistence Layer Backup Rotation

The `Store` class in [`src/main/persistence.ts`](https://github.com/stablyai/orca/blob/main/src/main/persistence.ts) implements a **300 ms** trailing-edge debounce for any state-to-disk write. After persisting to [`orca-data.json`](https://github.com/stablyai/orca/blob/main/orca-data.json), it calls `rotateBackupsAsync` to maintain five hourly snapshots. The `shouldRotateBackups` check itself is debounced to avoid spamming the filesystem during heavy state churn.

Always funnel disk writes through the existing debounce pipeline rather than using raw `window.setTimeout`:

```typescript
// Correct: Using the existing queue system
import { attachEditorAutosaveController } from '@/renderer/src/components/editor/editor-autosave-controller'

function scheduleSave(fileId: string, content: string) {
  const store = getZustandStore()
  // Handles timer cancellation, generation bumping, and write coalescing
  store.getState().queueSave({ id: fileId }, content)
}

```

## Efficient Layout and Rendering Strategies

To prevent layout thrashing when resizing terminals or sidebars, Orca combines `ResizeObserver` with `requestAnimationFrame` (rAF) and short debounces.

### Terminal Container Synchronization

The [`use-terminal-container-fit-sync.ts`](https://github.com/stablyai/orca/blob/main/use-terminal-container-fit-sync.ts) hook (located in the terminal components directory) schedules a rAF to read the new container size, then applies a **150 ms** debounce before persisting the layout state. This guarantees that rapid window resizes only trigger a single layout write and one disk persistence event.

### Search and Markdown Processing

Large documents trigger expensive re-matching operations if searched on every keystroke. The editor's rich-markdown search implementation in [`useRichMarkdownSearch.ts`](https://github.com/stablyai/orca/blob/main/useRichMarkdownSearch.ts) debounces the query input, ensuring the search only executes after the user pauses typing.

Use this pattern for any layout-dependent calculations:

```typescript
import { debounce } from '@/utils/debounce'

const recomputeLayout = () => {
  // Expensive DOM measurements and calculations
}

// Match the session writer's 150 ms timing
const debouncedRecompute = debounce(recomputeLayout, 150)

// Hook into ResizeObserver with rAF to avoid layout thrashing
new ResizeObserver(() => {
  requestAnimationFrame(() => debouncedRecompute())
}).observe(containerElement)

```

## Performance Patterns for Contributors

When extending Orca, adhere to these architectural constraints to maintain responsiveness across macOS, Linux, and Windows.

### Avoid Direct Disk Access

Never implement `window.setTimeout` that writes directly to disk. Always route through `syncAutoSave` → `queueSave` pipelines to ensure proper debounce handling and backup rotation.

### Prefer Cross-Platform Path Helpers

Use `path.join` or `path.resolve` instead of manual string concatenation for file paths. This prevents hidden bugs that can cause extra filesystem calls or cache misses in [`src/main/persistence.ts`](https://github.com/stablyai/orca/blob/main/src/main/persistence.ts).

### Reuse Debounced Slices

When creating new store slices that require persistence, follow the patterns in [`src/renderer/src/store/slices/editor.ts`](https://github.com/stablyai/orca/blob/main/src/renderer/src/store/slices/editor.ts) (debounced markdown serialization) and [`src/renderer/src/store/slices/terminals.ts`](https://github.com/stablyai/orca/blob/main/src/renderer/src/store/slices/terminals.ts) (debounced terminal cache writes). The [`settings-search-state.ts`](https://github.com/stablyai/orca/blob/main/settings-search-state.ts) slice demonstrates immediate UI response with delayed filter application.

## Summary

- **Selective subscriptions** via Zustand and `autosaveSubscriberInputsEqual` prevent unnecessary component re-renders when background state updates
- **150–300 ms debouncing** protects the filesystem across the editor autosave controller, session writer, and main process persistence layer
- **ResizeObserver + requestAnimationFrame** eliminates layout thrashing; always pair with a 150 ms debounce for persistence
- **Existing pipeline methods** like `queueSave` must be used instead of raw timers to ensure write coalescing and backup rotation
- **Path utilities** and input selectors maintain cross-platform compatibility and subscription efficiency

## Frequently Asked Questions

### How does Orca prevent excessive re-renders when the global state updates?

Orca uses Zustand's selective subscription pattern where components only extract specific state slices. The autosave controller further optimizes this via the `autosaveSubscriberInputsEqual` helper in [`src/renderer/src/components/editor/editor-autosave-controller.ts`](https://github.com/stablyai/orca/blob/main/src/renderer/src/components/editor/editor-autosave-controller.ts), which compares previous and next inputs to short-circuit updates when unrelated data changes. This prevents thousands of unnecessary renders per second during background operations.

### What is the recommended debounce timing for disk I/O operations in Orca?

According to [`src/main/persistence.ts`](https://github.com/stablyai/orca/blob/main/src/main/persistence.ts) and [`src/renderer/src/lib/session-write-subscriber.ts`](https://github.com/stablyai/orca/blob/main/src/renderer/src/lib/session-write-subscriber.ts), Orca uses a **300 ms** trailing-edge debounce for state-to-disk writes in the main process Store class, and a **150 ms** debounce for workspace session updates. The editor autosave delay is configurable via `editorAutoSaveDelayMs` but follows the same batching principles to prevent filesystem hammering.

### Why does Orca use requestAnimationFrame with ResizeObserver?

The terminal container implementation in [`src/renderer/src/components/terminal/useTerminalContainerFitSync.ts`](https://github.com/stablyai/orca/blob/main/src/renderer/src/components/terminal/useTerminalContainerFitSync.ts) demonstrates this pattern: `requestAnimationFrame` ensures DOM reads and writes occur during the browser's paint cycle to avoid layout thrashing, while the subsequent **150 ms** debounce limits how often these measurements trigger expensive state updates or disk persistence during rapid window resizing.

### How should I implement autosave functionality when extending Orca?

Never use `window.setTimeout` directly for file operations. Instead, import `attachEditorAutosaveController` and use the `queueSave` method from the Zustand store state, which automatically handles timer cancellation, generation bumping, and write coalescing. Ensure you also add any new state dependencies to `getAutosaveSubscriberInputs` in the autosave controller to maintain selective subscription efficiency.