Claude Code Performance Optimization: मापन से Core Web Vitals तक
Claude Code से LCP, INP, API latency, bundle और cache को मापकर सुधारने की व्यावहारिक गाइड।
Web app performance optimization का मतलब केवल “ऐप को तेज महसूस कराना” नहीं है। इसका मतलब है कि user कितनी देर इंतजार करता है, click के बाद screen कब प्रतिक्रिया देती है, loading के दौरान layout कितना हिलता है, और server कितना extra CPU या database work कर रहा है, इन सबको संख्या में मापना और फिर कम करना।
Claude Code इस काम में उपयोगी है क्योंकि यह code पढ़ सकता है, bottleneck खोज सकता है, छोटे patch सुझा सकता है और verification commands लिख सकता है। लेकिन सही क्रम जरूरी है: पहले measure करें, फिर hypothesis बनाएं, एक छोटा बदलाव करें, और उसी तरीके से फिर measure करें। अगर prompt सिर्फ “performance optimize करो” होगा, तो बदलाव अच्छे दिख सकते हैं लेकिन साबित नहीं होंगे।
Official reference के लिए web.dev Core Web Vitals, Lighthouse docs और MDN Performance API देखें।
पहले Fast को Define करें
Performance एक single score नहीं है। LCP, यानी Largest Contentful Paint, बताता है कि main content कब दिखा। INP, यानी Interaction to Next Paint, बताता है कि click, tap या typing के बाद UI कितनी जल्दी react करता है। CLS, यानी Cumulative Layout Shift, बताता है कि loading के दौरान page अनचाहे तरीके से हिला या नहीं।
Application level पर API p75 latency, database query count, JavaScript bundle size, image transfer size और browser main thread पर heavy synchronous work भी देखना चाहिए। Average value कई बार slow users को छिपा देती है। p75, यानी 75th percentile, normal traffic के धीमे हिस्से को बेहतर दिखाता है।
flowchart LR
Measure["Measure"] --> Hypothesis["Hypothesis"]
Hypothesis --> Patch["Small patch"]
Patch --> Verify["Measure again"]
Verify --> Keep["Keep proven wins"]
| Metric | मतलब | पहला लक्ष्य |
|---|---|---|
| LCP | Main content visible | 2.5s या कम |
| INP | Interaction response | 200ms या कम |
| CLS | Unexpected layout shift | 0.1 या कम |
| API p75 | ज्यादातर users की API latency | Screen के हिसाब से तय करें |
| JS transfer | शुरुआत में loaded JavaScript | Route के हिसाब से compare करें |
Claude Code को बेहतर Input दें
अच्छे prompt में symptom, reproduction, current metrics और constraints होने चाहिए।
इस repository की /products page slow है।
Goal mobile LCP और /api/products p75 को कम करना है।
Current measurements:
- Lighthouse mobile Performance: 58
- LCP: 4.2s
- INP: 180ms
- CLS: 0.04
- /api/products p75: 920ms
Please:
1. Images, bundle, API और database access को इस order में inspect करें।
2. Guess के आधार पर code change न करें; file name और evidence लिखें।
3. Low-risk और measurable patch को priority दें।
4. Change के बाद verification commands भी दें।
Related reading के लिए Claude Code debugging guide, Claude Code React development और Claude Code image optimization guide देखें।
Runnable Measurement Script
Node.js 18+ पर यह script किसी page या API का average और p75 latency measure करता है।
// measure-url.mjs
import { performance } from "node:perf_hooks";
const url = process.argv[2] ?? "https://example.com/";
const runs = Number(process.argv[3] ?? 5);
async function measureOnce() {
const start = performance.now();
const res = await fetch(url, { cache: "no-store" });
await res.arrayBuffer();
return {
status: res.status,
ms: performance.now() - start,
};
}
const samples = [];
for (let i = 0; i < runs; i += 1) {
samples.push(await measureOnce());
}
samples.sort((a, b) => a.ms - b.ms);
const avg = samples.reduce((sum, s) => sum + s.ms, 0) / samples.length;
const p75Index = Math.floor((samples.length - 1) * 0.75);
const p75 = samples[p75Index].ms;
console.table(
samples.map((sample, index) => ({
run: index + 1,
status: sample.status,
ms: sample.ms.toFixed(1),
}))
);
console.log(`avg=${avg.toFixed(1)}ms p75=${p75.toFixed(1)}ms`);
node measure-url.mjs http://localhost:3000/api/products 7
इस output को patch से पहले और बाद में Claude Code के साथ share करें। इससे discussion “लग रहा है तेज” से बदलकर repeatable comparison बन जाता है।
Realistic Use Cases
| Use case | Common cause | Claude Code से क्या करवाएं |
|---|---|---|
| SaaS dashboard slow | सारे widgets first paint पर load, chart library भारी | Secondary widgets defer करें और chart code split करें |
| Ecommerce listing slow | Images बड़ी, stock/review में N+1 queries | Image size और DB include/select सुधारें |
| Media article का LCP खराब | Hero image late, ad scripts जल्दी run | Main image prioritize करें और third-party scripts defer करें |
| Admin search freeze | बड़े arrays main thread पर filter | Complexity घटाएं, paginate करें या work move करें |
N+1 का मतलब है list एक बार fetch करना और फिर हर row के लिए extra query चलाना। Cache का मतलब result को थोड़ी देर reuse करना है, लेकिन user-specific data, permissions, price और stock को shared cache में बिना सही key और TTL के नहीं रखना चाहिए।
Runnable Cache Example
यह Express example intentionally slow endpoint और cached endpoint compare करता है। Production में Redis या CDN बेहतर हो सकते हैं, लेकिन concept समझने के लिए memory cache काफी है।
npm init -y
npm install express
node cached-api.mjs
// cached-api.mjs
import express from "express";
import { performance } from "node:perf_hooks";
const app = express();
const cache = new Map();
const ttlMs = 30_000;
async function loadProducts() {
await new Promise((resolve) => setTimeout(resolve, 800));
return [
{ id: 1, name: "Starter Plan", price: 1200 },
{ id: 2, name: "Pro Plan", price: 4800 },
];
}
async function cached(key, loader) {
const now = Date.now();
const hit = cache.get(key);
if (hit && hit.expiresAt > now) return { data: hit.data, cache: "hit" };
const data = await loader();
cache.set(key, { data, expiresAt: now + ttlMs });
return { data, cache: "miss" };
}
app.get("/api/products/raw", async (_req, res) => {
const start = performance.now();
const data = await loadProducts();
res.json({ cache: "none", ms: performance.now() - start, data });
});
app.get("/api/products/cached", async (_req, res) => {
const start = performance.now();
const result = await cached("products", loadProducts);
res.json({ ...result, ms: performance.now() - start });
});
app.listen(3000, () => {
console.log("Open http://localhost:3000/api/products/raw");
});
node measure-url.mjs http://localhost:3000/api/products/raw 3
node measure-url.mjs http://localhost:3000/api/products/cached 3
Claude Code से cache add करवाते समय scope साफ लिखें: popular products 30 seconds cache, stock cache नहीं, user data में userId key का हिस्सा।
Runnable Algorithm Example
हर bottleneck network नहीं होता। Heavy synchronous JavaScript INP खराब कर सकता है। नीचे repeated includes scan को Set से बदला गया है।
// compare-lookup.mjs
import { performance } from "node:perf_hooks";
const a = Array.from({ length: 40_000 }, (_, i) => i);
const b = Array.from({ length: 40_000 }, (_, i) => i * 2);
function slowIntersection(left, right) {
return left.filter((item) => right.includes(item));
}
function fastIntersection(left, right) {
const rightSet = new Set(right);
return left.filter((item) => rightSet.has(item));
}
function time(label, fn) {
const start = performance.now();
const result = fn();
const ms = performance.now() - start;
console.log(`${label}: ${ms.toFixed(1)}ms (${result.length} hits)`);
}
time("slow", () => slowIntersection(a, b));
time("fast", () => fastIntersection(a, b));
node compare-lookup.mjs
Common Pitfalls
सिर्फ Lighthouse score optimize न करें। Lighthouse lab data है; real users अलग devices, network और cache state पर होते हैं। Search Console, RUM और server logs भी देखें।
Cache add करते समय correctness मत तोड़ें। Price, stock, permission और personal data के लिए cache key, TTL और invalidation strategy चाहिए।
हर जगह useMemo न लगाएं। React memoization measured hot path पर use करें, पूरे codebase में नहीं।
हर image को priority न दें। Above-the-fold image को stable dimensions और कभी-कभी priority चाहिए, लेकिन नीचे की images आमतौर पर lazy रहनी चाहिए।
Bundle splitting भी blindly न करें। Claude Code bundle analysis और Claude Code code splitting से route-level effect compare करें।
CLAUDE.md Rules
## Performance rules
- Before optimizing, record the current metric and target metric.
- Prefer small, measurable changes over broad rewrites.
- Do not introduce shared cache for user-specific data.
- Avoid N+1 queries; use select/include or batching.
- Keep above-the-fold images sized and stable.
- After changes, report commands used for verification.
ये rules Claude Code को cosmetic changes के बजाय measurable improvement पर केंद्रित रखते हैं।
Consulting CTA
ClaudeCodeLab Claude Code की मदद से existing web apps का performance audit, Core Web Vitals improvement, API/DB latency diagnosis और practical runbook बनाने में मदद कर सकता है। पहली review के लिए target URL, key screens, Lighthouse result, slow API logs और desired deadline तैयार रखें।
Hands-On Result
Local run में intentionally delayed /api/products/raw लगभग 800ms के आसपास रहता है, जबकि /api/products/cached पहली request के बाद कुछ milliseconds तक गिर जाता है। compare-lookup.mjs में भी Set version काफी तेज दिखता है। Real projects इतने साफ नहीं होते, लेकिन pattern वही रहता है: पहले p75 measure करें, एक change करें, फिर उसी tool से दोबारा measure करें।
मुफ़्त PDF: Claude Code cheatsheet
Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.
हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.
लेखक के बारे में
Masa
Claude Code workflow और team adoption पर काम करने वाला engineer.
संबंधित लेख
Claude Code Permission Receipt Pattern: scope, proof और rollback लिखना
Claude Code के लिए permission receipt: allowed actions, approval boundary, verification commands, rollback note और revenue CTA checks।
Claude Code और Codex के लिए सुरक्षित Agent Harness: permissions, verification और rollback
Claude Code और Codex agents के लिए सुरक्षित harness: permissions, plan, verification और rollback.
Claude Code Subagents गाइड: article और code work को सुरक्षित तरीके से delegate करें
Claude Code subagents से article और code work बांटें: delegation rules, prompts, pitfalls, checklist और examples.