performance
MUST be used when fixing Flows app performance — re-renders, query patterns, pagination, unbounded fetches, LLM-over-query-results, bundles, memory leaks. Measure before and after. Triggers: performance, slow, laggy, optimize, re-render, bundle size, CDF query, virtualize, chat completions, LLM cost
By cognitedata · 1,880 installs
npx skills add cognitedata/builder-skills --skill performance
Source repository · Upstream listing
Performance Fix
Systematically find and fix performance issues in $ARGUMENTS (or the whole app if no argument is given). Always measure first — never optimize blindly.
Step 1 — Measure baseline before touching anything
Run the production build and capture metrics before making any changes:
Open the app in Chrome and capture:
Lighthouse score (Performance tab → Run audit)
React Profiler (React DevTools → Profiler → Record an interaction)
Note the components with the longest render times and highest render counts
Record baseline numbers. Every fix must be measured against these.
Step 2 — Find and fix unnecessary re renders
Read the component tree (start from src/App.tsx ) and search for these patterns:
For each instance found, apply the fix directly :
Inline object/array creation in JSX → wrap with useMemo :
Event handlers recreated on every render → wrap with useCallback :
Context that changes on every render → memoize the context value:
Apply React.memo to pure presentational components that receive stable props. Do NOT wrap every component — only those confirmed to re render unnecessarily via the Profiler.
Step 3 — Find and fix DMS query patterns
For read heavy workloads, prefer APIs that hit the search/Elasticsearch path ( query or search on instances) rather than list paths that stress Postgres .
For each instances.list call in a read heavy path (e.g. populating a table, dropdown, or search results), rewrite it to use instances.query with the equivalent filter. Preserve the existing filter logic but express it in the query API format:
API used When it's correct When to rewrite
instances.query Read with filters that map to Elasticsearch (text, equals, range) —
instances.search Full text or fuzzy search —
instances.list Writing, syncing, or need for semantics not available on query/search Rewrite to instances.query if used for read heavy UI display
instances.retrieve Fetching by known external IDs —
instances.aggregate Counts, histograms —
For deeper rationale on search vs relational paths, cardinality, and materialization tradeoffs, consult the semantic knowledge/ directory if available in the workspace.
Hard gate — LLM over query results
Do not map completions over DMS rows. Fix: one sendAgentMessage or agent resource ( integrate fusion agent ). If per item completions remain: 5 / ceiling 50 , cache by space:externalId:lastUpdatedTime , user initiated only.
Step 4 — Find and fix client side filtering (move to server side)
Filters, limits, and projections must be applied in the API request — not by downloading large result sets and filtering in the browser.
For each client side filter pattern, move the filter logic into the SDK call's filter parameter and remove the .filter() call :
Issue Fix
.filter() after SDK call on full result set Move the filter into the API request's filter parameter and delete the .filter()
No properties selection in DMS query Add a sources or properties parameter to fetch only needed fields
Fetching all items then rendering a subset Add limit and filter to the API call to fetch only what's displayed
Client side text search on fetched array Replace with the SDK's search endpoint
Hard rule: If the API supports a filter for the criterion being applied client side, move it server side now . Client side filtering is acceptable only for trivial local state (e.g. filtering a cached list of 10 user preferences). If the API does not support the exact filter, add a code comment explaining why client side filtering is necessary.
Step 5 — Find and fix CDF data fetching and pagination
Read all CDF SDK calls (search for sdk. , client. , useQuery , useCogniteClient ).
For each call, find the issue and apply the fix :
Issue Fix to apply
No limit set Add limit: 100 (or the actual page size needed) to the SDK call
Fetching all properties Add a properties filter to select only required fields
Fetching on every render Move inside useQuery / useMemo with a stable dependency array
Sequential requests that could be parallel Rewrite to Promise.all or batched SDK methods
Missing limit parameter Add explicit limit matching the UI's page size (e.g. 25, 50, 100)
Offset based pagination for large datasets Replace with cursor based pagination using nextCursor from the response
"Fetch all" loop (exhausts cursors up front) Replace with on demand pagination using TanStack Query's useInfiniteQuery
Fixing fetch all loops — replace the while loop with useInfiniteQuery :
Fixing offset based pagination — switch to cursor based:
Step 6 — Find and fix excessive API call rates
For each issue found, apply the fix :
Search inputs that fire on every keystroke → add debounce with 300ms delay:
useQuery calls without staleTime → add appropriate staleTime:
Duplicate parallel identical requests → lift the query to a shared hook:
Issue Fix to apply
Search input fires query on every keystroke Add useDebouncedValue hook with 300ms delay
Polling with no backoff or very short interval Set interval to ≥30s with exponential backoff on errors
Re fetching on every render (no caching) Add staleTime: 30 000 (or appropriate) to useQuery options
refetchOnWindowFocus: true for expensive queries Set refetchOnWindowFocus: false or use a longer stale time
Duplicate parallel identical requests Lift the query to a shared hook and import from both components
Multiple components triggering the same fetch Extract to a shared hook in hooks/ directory
Step 7 — Find and fix large un virtualized lists
Search for lists that render more than ~50 items:
For any list where the data source could exceed 50 items, replace the plain .map() render with a virtualized list . Install @tanstack/react virtual if not present:
Apply the virtualizer pattern directly:
Step 8 — Find and fix missing code splitting
Read the router setup and identify routes that are imported statically but not shown on the landing page.
For each statically imported heavy page, convert to lazy import with React.lazy() and Suspense :
Similarly, large third party components (chart libraries, PDF viewers, map renderers) should be dynamically imported inside the component that needs them, not at the module level. Apply the transformation directly to each heavy import found.
Step 9 — Analyse and fix bundle size
Add to vite.config.ts temporarily:
Run pnpm run build and inspect the treemap. For any chunk 100 KB (gzipped) that is not a necessary initial dependency, apply the fix :
Issue Fix to apply
lodash (full bundle) Replace with lodash es individual imports or native equivalents (e.g., Array.prototype.map , Object.entries , structuredClone )
moment Replace with date fns or native Intl.DateTimeFormat
Chart libraries not tree shaken Switch to named imports (e.g., import { LineChart } from "echarts/charts" )
Large library used in one place Dynamically import it with React.lazy or inline import()
After analysis, remove the visualizer plugin from vite.config.ts and uninstall it:
Step 10 — Find and fix memory leaks
Search for useEffect hooks that set up subscriptions, timers, or event listeners without cleanup:
For every useEffect that calls addEventListener , setInterval , setTimeout , subscribe , or sets up a CDF streaming connection, add the missing cleanup function :
Fetch without abort → add AbortController:
Timer without cleanup → add clearInterval/clearTimeout:
Event listener without cleanup → add removeEventListener:
Step 11 — Measure after and report the delta
Re run the same Lighthouse audit and React Profiler session from Step 1. Report the delta and list every file changed:
Metric Before After Change
Lighthouse Performance 72 91 +19
Largest Contentful Paint 3.2 s 1.8 s −1.4 s
Total Blocking Time 420 ms 80 ms −340 ms
Bundle size (gzipped) 410 KB 290 KB −120 KB
AssetTable render count (on filter change) 8 2 −6
If a step produced no improvement, state that explicitly. Do not fabricate numbers.
Done
List every file changed with the absolute path and a one line explanation of what was fixed. If further gains require server side or infrastructure changes (e.g., CDF response caching, CDN configuration), note them separately as out of scope recommendations.