

Also from Kynth Studios


Also from Kynth Studios


Also from Kynth Studios
1# Performance Optimization — Cursor Rules2# Comprehensive rules for writing performant code across the stack34## Project Context5You are working on a performance-sensitive application. The codebase must be efficient6in terms of response time, memory usage, CPU utilization, and network bandwidth. Every7code change should consider its performance implications. However, always profile before8optimizing — never guess where bottlenecks are.910## Core Principles11- Measure first, optimize second — use profiling tools, not intuition12- Optimize the critical path — 80% of time is spent in 20% of code13- Premature optimization is the root of all evil (but known patterns should be followed)14- Readability matters — don't sacrifice clarity for marginal gains15- Set performance budgets and test against them1617## Frontend Performance1819### Loading Performance20- **Bundle size**: Set budgets (e.g., <200KB JS gzipped for initial load)21- **Code splitting**: Split by route and load on demand22- **Tree shaking**: Use ES modules, avoid side effects in imports23- **Lazy loading**: `React.lazy()`, `defineAsyncComponent()`, dynamic `import()`24- **Preloading**: Use `<link rel="preload">` for critical resources25- **Font loading**: Use `font-display: swap`, subset fonts, use `next/font`2627### Image Optimization28```tsx29// GOOD — responsive images with lazy loading30<img31 src="/images/hero.webp"32 srcSet="/images/hero-400.webp 400w, /images/hero-800.webp 800w, /images/hero-1200.webp 1200w"33 sizes="(max-width: 768px) 100vw, 50vw"34 loading="lazy"35 decoding="async"36 alt="Product hero"37 width={800}38 height={600}39/>4041// Or use framework image components42// Next.js: <Image src="..." width={800} height={600} />43// Nuxt: <NuxtImg src="..." />44```4546### Rendering Performance47- Avoid layout thrashing — batch DOM reads and writes48- Use `transform` and `opacity` for animations (GPU-accelerated)49- Use `will-change` sparingly for elements that will animate50- Use `content-visibility: auto` for off-screen content51- Debounce scroll/resize handlers (150-300ms)52- Use `requestAnimationFrame` for visual updates53- Virtualize long lists (react-window, vue-virtual-scroller)5455### React-Specific56```tsx57// Memoize expensive components (only when profiling shows re-render issues)58const ExpensiveList = React.memo(function ExpensiveList({ items }) {59 return items.map(item => <ExpensiveItem key={item.id} item={item} />);60});6162// useMemo for expensive computations63const sortedItems = useMemo(64 () => items.slice().sort((a, b) => a.price - b.price),65 [items]66);6768// useCallback for stable function references passed to memoized children69const handleSelect = useCallback((id: string) => {70 setSelectedId(id);71}, []);7273// Avoid: creating objects/arrays in render74// BAD75<MyComponent style={{ color: 'red' }} options={[1, 2, 3]} />76// GOOD — lift constants77const style = { color: 'red' };78const options = [1, 2, 3];79<MyComponent style={style} options={options} />80```8182### Core Web Vitals Targets83- **LCP** (Largest Contentful Paint): < 2.5s84- **FID/INP** (Interaction to Next Paint): < 200ms85- **CLS** (Cumulative Layout Shift): < 0.186- **TTFB** (Time to First Byte): < 800ms8788## Backend Performance8990### Database Query Optimization91```sql92-- Use EXPLAIN ANALYZE to find slow queries93EXPLAIN ANALYZE SELECT * FROM orders WHERE user_id = 123 AND status = 'pending';9495-- Add indexes for frequently filtered/sorted columns96CREATE INDEX idx_orders_user_status ON orders(user_id, status);9798-- Use pagination — never return unbounded results99SELECT * FROM products WHERE category = 'electronics'100ORDER BY created_at DESC LIMIT 20 OFFSET 0;101102-- Use EXISTS instead of COUNT for existence checks103SELECT EXISTS(SELECT 1 FROM users WHERE email = 'test@example.com');104105-- Avoid SELECT * — fetch only needed columns106SELECT id, name, price FROM products WHERE category = $1;107```108109### N+1 Query Prevention110```ts111// BAD — N+1: 1 query for orders + N queries for users112const orders = await db.order.findMany();113for (const order of orders) {114 order.user = await db.user.findUnique({ where: { id: order.userId } });115}116117// GOOD — eager loading118const orders = await db.order.findMany({119 include: { user: { select: { id: true, name: true } } },120});121122// GOOD — batch loading123const orders = await db.order.findMany();124const userIds = [...new Set(orders.map(o => o.userId))];125const users = await db.user.findMany({ where: { id: { in: userIds } } });126const userMap = new Map(users.map(u => [u.id, u]));127orders.forEach(o => { o.user = userMap.get(o.userId); });128```129130### Caching Strategy131```132Request → CDN Cache → Application Cache → Database Cache → Database133```134135- **CDN/Edge**: Static assets, public pages (Cache-Control headers)136- **Application**: Frequently accessed data (Redis, in-memory)137- **Database**: Query result cache, materialized views138- **HTTP caching**: `Cache-Control`, `ETag`, `Last-Modified` headers139140### Caching Patterns141```ts142// Cache-Aside (Lazy Loading)143async function getUser(id: string): Promise<User> {144 const cached = await redis.get(`user:${id}`);145 if (cached) return JSON.parse(cached);146147 const user = await db.user.findUnique({ where: { id } });148 if (user) {149 await redis.setex(`user:${id}`, 3600, JSON.stringify(user)); // 1 hour TTL150 }151 return user;152}153154// Cache invalidation on write155async function updateUser(id: string, data: UpdateUserInput) {156 const user = await db.user.update({ where: { id }, data });157 await redis.del(`user:${id}`); // Invalidate cache158 return user;159}160```161162### Connection Pooling163- Use connection pools for database connections (don't open/close per request)164- Size pool appropriately: 2-4x CPU cores for database connections165- Monitor pool utilization and adjust166- Set connection timeouts to prevent pool exhaustion167168## API Performance169- Compress responses (gzip/brotli)170- Paginate all list endpoints171- Use GraphQL or sparse fieldsets to avoid over-fetching172- Batch related API calls where possible173- Use HTTP/2 for multiplexed requests174- Implement request deduplication for concurrent identical requests175176## Algorithmic Efficiency177178### Common Patterns179```ts180// Use Map/Set for lookups instead of Array.find/includes (O(1) vs O(n))181// BAD182const user = users.find(u => u.id === targetId); // O(n)183184// GOOD185const userMap = new Map(users.map(u => [u.id, u]));186const user = userMap.get(targetId); // O(1)187188// Use Set for membership checks189// BAD190const isAllowed = allowedIds.includes(id); // O(n)191192// GOOD193const allowedSet = new Set(allowedIds);194const isAllowed = allowedSet.has(id); // O(1)195```196197### Avoid Unnecessary Work198```ts199// BAD — recomputing on every call200function getExpensiveData() {201 return rawData.map(transform).filter(validate).sort(compare);202}203204// GOOD — compute once, cache result205let cachedResult: Data[] | null = null;206function getExpensiveData() {207 if (!cachedResult) {208 cachedResult = rawData.map(transform).filter(validate).sort(compare);209 }210 return cachedResult;211}212```213214## Memory Management215- Avoid memory leaks: clean up event listeners, timers, subscriptions216- Use weak references (`WeakMap`, `WeakRef`) for caches of large objects217- Stream large files instead of loading into memory218- Paginate large database result sets219- Profile memory with Chrome DevTools or `process.memoryUsage()`220- Watch for closure-captured variables keeping objects alive221222## Monitoring and Profiling223224### Tools225- **Frontend**: Chrome DevTools Performance tab, Lighthouse, WebPageTest226- **Backend**: Application Performance Monitoring (Datadog, New Relic, OpenTelemetry)227- **Database**: `EXPLAIN ANALYZE`, `pg_stat_statements`, slow query logs228- **Node.js**: `--inspect` flag, `clinic.js`, `0x` for flame graphs229- **Python**: `cProfile`, `py-spy`, `memory_profiler`230231### What to Monitor232- Response time (p50, p95, p99)233- Error rate234- Throughput (requests per second)235- Database query time and count per request236- Memory usage over time237- CPU utilization238- Cache hit rate239240## Common Pitfalls241- Optimizing without profiling (solving the wrong problem)242- Premature optimization at the cost of readability243- N+1 database queries (most common backend performance issue)244- Not using indexes on frequently queried columns245- Loading entire datasets when only a page is needed246- Missing cache invalidation (stale data)247- Not compressing API responses248- Blocking the event loop with synchronous operations (Node.js)249- Creating objects in hot loops (GC pressure)250- Not setting memory limits on containers (OOM kills)251
One repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| survivorforge/cursor-rulesrules/ai-ml-python/.cursorrules · 16 | .cursorrules | teststylearchdeployment+2 | 81/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/langchain-ai/.cursorrules · 16 | .cursorrules | testlint-formatstylearch+4 | 84/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/aws-serverless/.cursorrules · 16 | .cursorrules | teststylearchtypes+6 | 73/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/tailwindcss/.cursorrules · 16 | .cursorrules | lint-formatstylearchui+3 | 81/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/mern-stack/.cursorrules · 16 | .cursorrules | setupteststylearch+6 | 81/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/api-design-rest/.cursorrules · 16 | .cursorrules | lint-formatstylesecurityapi+3 | 69/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/api-microservices/.cursorrules · 16 | .cursorrules | buildteststylearch+5 | 92/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/chrome-extension/.cursorrules · 16 | .cursorrules | teststylearchtesting-strategy+4 | 81/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/clean-code/.cursorrules · 16 | .cursorrules | styledo-notagent-behaviourdocs | 57/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/database-sql/.cursorrules · 16 | .cursorrules | styletypessecuritydatabase+3 | 65/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/devops-docker/.cursorrules · 16 | .cursorrules | setupbuildteststyle+4 | 93/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/devops-infrastructure/.cursorrules · 16 | .cursorrules | buildteststylesecurity+3 | 93/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/django-rest/.cursorrules · 16 | .cursorrules | buildteststylearch+5 | 84/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/docker-devops/.cursorrules · 16 | .cursorrules | setupteststylearch+6 | 85/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/flutter-dart/.cursorrules · 16 | .cursorrules | teststylearchtypes+5 | 89/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/fullstack-nextjs-prisma/.cursorrules · 16 | .cursorrules | teststylearchtypes+7 | 96/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/go-gin/.cursorrules · 16 | .cursorrules | testlint-formatstylearch+5 | 84/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/mobile-react-native/.cursorrules · 16 | .cursorrules | teststylearchtypes+7 | 89/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/nextjs-14-app-router/.cursorrules · 16 | .cursorrules | teststyletypestesting-strategy+3 | 71/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/nextjs-app-router/.cursorrules · 16 | .cursorrules | teststylearchtypes+5 | 81/100 | 13 days ago |
A badge carrying the measured quality of the strongest agent config file in this repository, out of 100. It reads from this index every time somebody loads your page, so it changes when the measurement changes and there is nothing to keep up to date. Free, no account, and the value is not something you or we can set by hand.
[](https://rulestack.kynth.studio/configs/survivorforge-cursor-rules-rules-performance-optimization-cursorrules)Would rather not hotlink us? Every badge is also served in shields.io’s endpoint schema, so shields renders the image and your readers never talk to our domain:
Published by Toolproof, the masthead over this index and eight others. The method behind the number is at toolproof.kynth.studio/methodology, and the whole thing is readable as JSON with no key at /api.