This prompt helps developers systematically profile LLM application performance by guiding them through key metrics collection, bottleneck identification, and optimization recommendations.
Usage
Use this prompt when you need to analyze and optimize the performance of an LLM-powered application in production. It works best with access to your application's logging, metrics, and tracing infrastructure. The prompt is designed for teams running LLM applications at scale who need a structured approach to performance engineering.
Variables
- model_name: The LLM model being used (e.g., "gpt-4", "claude-3-sonnet", "llama-2-70b")
- deployment_type: How the model is deployed (e.g., "api", "self-hosted", "edge")
- traffic_profile: Typical request patterns (e.g., "steady", "bursty", "batch")
- latency_target: Acceptable response time in milliseconds
- cost_budget: Monthly or per-request cost constraint
Worked Example
Given a customer support chatbot using GPT-3.5-turbo via API with steady traffic and 2-second latency target:
Input Variables:
- model_name: "gpt-3.5-turbo"
- deployment_type: "api"
- traffic_profile: "steady"
- latency_target: "2000"
- cost_budget: "$0.002 per request"
Output: A structured performance profile with specific optimization recommendations for this deployment.
Detailed Analysis Framework
Baseline Metrics Collection Strategy
Before optimizing, you must establish a comprehensive baseline. This section defines the essential metrics and collection methodologies:
Latency Metrics: Collect p50, p95, p99 latency percentiles for both cold and warm requests separately. Cold requests include model loading, authentication, and initial tensor allocation. Warm requests represent steady-state performance. Track these at multiple layers: end-to-end API latency, model inference time, tokenization overhead, and network round-trip time. Use distributed tracing with OpenTelemetry to correlate spans across services.
Throughput Metrics: Measure requests per second (RPS) and tokens per second (TPS) at both the API gateway and model server levels. For streaming responses, track time-to-first-token (TTFT) separately from tokens-per-second after first token. Monitor how throughput degrades under load and identify the saturation point.
Error Rate Classification: Categorize errors by type: rate_limit_exceeded, context_length_exceeded, validation_failure, timeout, model_unavailable, internal_error. Each category requires different mitigation strategies. Track error rates over time windows (1m, 5m, 15m) and correlate with deployments or traffic changes.
Token Usage Analysis: Profile input token distributions, output token distributions, and their ratio. Identify prompts that consistently produce verbose outputs. Track token usage by prompt template, user tier, and feature. This data drives cost optimization and prompt engineering priorities.
Resource Utilization: For self-hosted models, monitor GPU memory utilization, GPU compute utilization, CPU usage, system memory, and network I/O. Use tools like nvidia-smi, DCGM, or vendor-specific monitoring. For API deployments, track quota consumption and rate limit headroom.
Cost Tracking: Calculate cost per request, cost per 1K tokens (input/output separately), and project monthly spend based on current trajectory. Break down by model, feature, and user segment. Set up budget alerts at 50%, 75%, and 90% of monthly allocation.
Bottleneck Identification Framework
This section provides a systematic methodology for identifying where your LLM application spends time and resources:
Request Queue Analysis: Measure queue depth, wait time distribution, and queue time as percentage of total latency. High queue times with low GPU utilization suggest the bottleneck is in request scheduling or batching logic, not model inference. Look for priority inversion where low-priority batch requests block high-priority interactive requests.
Inference vs. Overhead Breakdown: Instrument your code to separately measure: input preprocessing (tokenization, formatting, embedding lookup), model forward pass, output postprocessing (detokenization, validation, formatting), and network serialization. In many applications, preprocessing and postprocessing consume 30-50% of total latency.
Token Generation Profiling: For autoregressive models, profile per-token generation time. Early tokens are typically faster (cached KV), while later tokens slow down due to growing KV cache. Identify if your workload hits the quadratic attention scaling limit. Measure speculative decoding acceptance rates if applicable.
Memory Bandwidth Analysis: For self-hosted models, GPU memory bandwidth is often the limiting factor, not compute. Monitor HBM utilization and memory controller occupancy. Profile kernel-level metrics with NVIDIA Nsight or AMD ROCm profiler. Look for memory-bound vs. compute-bound kernels.
Network and Serialization Overhead: For API deployments, measure TLS handshake time, request serialization, response deserialization, and compression overhead. For streaming, track chunk delivery intervals. Consider protocol choices: HTTP/2 multiplexing vs. WebSocket vs. gRPC streaming.
Cold Start Impact: For serverless or auto-scaled deployments, measure cold start latency distribution. Separate model loading time, runtime initialization, and first-request warmup. Track cold start frequency and its correlation with scaling events.
Optimization Recommendations by Category
The following sections provide specific, actionable optimization strategies organized by implementation layer:
Model-Level Optimizations
Quantization Strategy: Evaluate quantization options based on your hardware and quality requirements:
- INT8 Dynamic Quantization: 2-4x speedup, 1-2% quality loss. Best for CPU inference. Use torch.quantization.quantize_dynamic() for PyTorch models.
- INT4/GPTQ/AWQ: 3-5x speedup, 2-5% quality loss. Requires calibration dataset. Best for GPU inference with compatible kernels (exllama, llama.cpp, vLLM).
- FP8/BF16: Native on H100/A100. 2x memory reduction with minimal quality loss. Requires model conversion and compatible serving stack.
- Mixed Precision: Apply different quantization to different layers. Keep attention and output layers in higher precision.
Model Distillation and Routing: Train smaller specialist models for high-volume, narrow tasks. Route requests using a lightweight classifier or LLM-based router. Implement cascade: try small model first, escalate to large model on low confidence. Target 10-20x cost reduction for eligible traffic.
Context Window Optimization: Implement sliding window attention for long contexts. Use prompt compression (selective context, summarization) for multi-turn conversations. Cache KV for repeated prefixes across requests. Set maximum context per use case and enforce truncation with clear user messaging.
Structured Output: Use constrained generation (JSON Schema, regex, grammar-guided) to eliminate post-processing validation retries. This reduces average output tokens and eliminates format-error retries. Tools: outlines, guidance, llama.cpp grammar, vLLM guided decoding.
Inference-Level Optimizations
Batching Configuration: Configure batch size based on your latency budget and throughput requirements. Larger batches improve throughput but increase queue wait time. Use adaptive batching: small batches for interactive traffic, large batches for background jobs. Set batch timeout to 10-50ms. Pad sequences efficiently to minimize wasted compute.
Caching Strategy: Implement multi-layer caching:
- Response Cache: Exact prompt match → instant response. Target 10-30% hit rate for repetitive workloads. Use Redis with TTL based on data freshness requirements.
- Embedding Cache: Cache prompt embeddings for RAG retrieval. Reduces embedding API calls by 50-80% for repeated queries.
- Prefix Cache: Share KV cache for common prompt prefixes (system prompts, few-shot examples). vLLM and TensorRT-LLM support this natively.
Parallelism Strategy: For self-hosted models >7B parameters:
- Tensor Parallelism: Split layers across GPUs. Best for single-request latency. Requires high-bandwidth interconnect (NVLink, NVSwitch).
- Pipeline Parallelism: Split layers into stages. Best for throughput with multiple concurrent requests. Adds pipeline bubble overhead.
- Data Parallelism: Replicate model across GPUs. Simplest scaling but doesn't help with model size limits.
Speculative Decoding: Use a small draft model to predict multiple tokens, verified by the target model. 2-3x speedup for autoregressive generation. Works best with greedy or low-temperature sampling. Implement with vLLM, Medusa, or custom draft heads.
Infrastructure Optimizations
Instance Sizing: Match instance to model and batch size:
- 7B FP16: 16GB VRAM minimum → A10G, T4, RTX 3090/4090
- 13B FP16: 28GB VRAM → A100 40GB, 2x A10G tensor parallel
- 70B FP16: 140GB VRAM → 4x A100 40GB tensor parallel, or 8x A10G
- INT4 quantized: divide VRAM requirements by ~4
Auto-Scaling Policies: Scale on queue depth or p95 latency, not CPU utilization. Set minimum replicas to handle baseline + 50% headroom. Maximum replicas based on budget. Scale-up cooldown: 60-120s. Scale-down cooldown: 300-600s to prevent thrashing. Use predictive scaling for known traffic patterns.
Geographic Routing: Deploy model replicas in regions close to users. Route requests based on user location or latency probing. For global deployments, consider edge inference for small models (7B and below) with cloud fallback for complex requests.
CDN and Edge Caching: Cache static assets (model weights for edge deployment, tokenizer files, documentation) at edge locations. Use Cloudflare Workers, AWS CloudFront, or similar. For API responses, cache at edge only for idempotent, non-personalized requests.
Cost Optimizations
Model Tier Selection: Route requests to the cheapest model that meets quality requirements. Implement quality gates: if small model output fails validation or confidence check, escalate. Typical tier structure: 7B local → 13B local → 70B local → GPT-3.5 API → GPT-4 API. Track escalation rates and optimize tier boundaries.
Spot Instance Utilization: Use spot/preemptible instances for batch workloads and fault-tolerant services. Implement graceful degradation: drain connections on spot interruption notice (2-min warning on AWS, 30s on GCP). Maintain minimum on-demand capacity for SLA-critical traffic. Target 60-80% spot utilization for batch workloads.
Request Routing: Classify requests by business criticality. Route non-critical (analytics, batch processing, internal tools) to cheaper models. Reserve premium models for user-facing, revenue-generating features. Implement feature flags to adjust routing in real-time.
Token Budget Enforcement: Set per-request and per-session token limits. Compress prompts using: summarization of conversation history, selective context retrieval, prompt template optimization. Use token counting in middleware to reject or truncate oversized requests before they reach the model.
Monitoring and Alerting Setup
Key Dashboards:
- Real-time Operations: Current RPS, p50/p95/p99 latency, error rate, active connections, queue depth. Alert: p95 > 2x target for 5m.
- Cost Tracking: Spend rate ($/hour), projected monthly, cost per 1K tokens by model, budget utilization. Alert: projected > 90% budget.
- Model Health: Token generation speed, KV cache hit rate, GPU utilization, memory pressure. Alert: generation speed < 50% baseline.
- Business Metrics: Feature adoption, user satisfaction (if measurable), task completion rate. Alert: completion rate drop > 20%.
Synthetic Monitoring: Run canary requests every minute: health check endpoint, simple generation, complex generation, streaming generation. Verify latency, correctness, and format compliance. Alert on any failure or latency regression > 50%.
A/B Testing Framework: Deploy new model versions to 1-5% of traffic. Compare: latency, error rate, token usage, user feedback (explicit or implicit). Automated rollback if error rate > 2x baseline or latency > 1.5x baseline. Statistical significance testing for business metrics.
Regression Detection: Track performance metrics per model version per deployment. Compare against baseline with statistical process control (CUSUM or EWMA charts). Alert on sustained shifts > 10% in latency or cost. Correlate with code deployments, config changes, and traffic pattern changes.
Validation Plan
Load Test Scenarios:
- Baseline: Steady traffic at 50%, 75%, 100% of expected peak. Measure latency percentiles and error rates.
- Burst: Sudden 10x traffic increase for 30s. Measure queue behavior, auto-scaling response, recovery time.
- Soak: 24-48 hours at 80% capacity. Monitor for memory leaks, connection exhaustion, performance degradation.
- Failure Injection: Kill model replicas, add network latency, simulate rate limits. Verify circuit breakers, fallback behavior, and alerting.
Canary Deployment Metrics: For each new model version:
- Compare p50/p95/p99 latency against previous version
- Compare error rates by category
- Compare token usage (input/output ratio)
- Compare cost per request
- Run automated quality evaluation (if available)
- Rollback criteria: any metric > 1.5x baseline or error rate > 2x baseline
Performance Regression Test Suite: Automated tests run on every deployment:
- Latency benchmarks for standard prompts
- Correctness tests for structured output
- Token usage bounds for known prompt templates
- Memory usage stability over 1000 requests
- Concurrency handling at target RPS
Cost Tracking and Budget Alerting:
- Daily spend report by model, feature, environment
- Anomaly detection on cost per request (seasonal ARIMA or simple threshold)
- Forecasted monthly spend with confidence intervals
- Alert at 50%, 75%, 90%, 100% of monthly budget
- Automated cost attribution to product features for chargeback
Conclusion
This profiling template provides a comprehensive framework for understanding and optimizing LLM application performance. The key to success is systematic measurement: establish baselines before making changes, validate each optimization in isolation, and maintain continuous monitoring to catch regressions early. Remember that optimization is iterative—start with the highest-impact, lowest-effort changes (caching, batching, quantization) before investing in complex infrastructure changes.
For complementary guidance on production deployment infrastructure, see the related article: LLM Production Deployment: Essential Checklist and Best Practices.
Sources
Prompt template
You are an LLM performance engineering expert. Create a comprehensive performance profiling analysis for the following LLM application:
**Application Context:**
- Model: {{model_name}}
- Deployment: {{deployment_type}}
- Traffic Pattern: {{traffic_profile}}
- Latency Target: {{latency_target}}ms
- Cost Budget: {{cost_budget}}
**Required Analysis Sections:**
## 1. Baseline Metrics Collection
Define the key metrics to collect for establishing a performance baseline:
- Latency percentiles (p50, p95, p99) for cold/warm requests
- Throughput (requests/second, tokens/second)
- Error rates by category (rate limits, timeouts, validation failures)
- Token usage distributions (input/output ratios)
- Resource utilization (GPU/CPU memory, network I/O)
- Cost per request and per 1K tokens
## 2. Bottleneck Identification Framework
Provide a systematic approach to identify performance bottlenecks:
- Request queue analysis and wait time breakdown
- Model inference vs. preprocessing/postprocessing latency
- Token generation speed analysis
- Memory bandwidth and GPU utilization patterns
- Network latency and serialization overhead
- Cold start impact for serverless deployments
## 3. Optimization Recommendations by Category
Generate specific, actionable recommendations organized by type:
### Model-Level Optimizations
- Quantization strategy (INT8/INT4/GPTQ/AWQ) with expected impact
- Model distillation or specialist model routing opportunities
- Context window optimization and sliding window strategies
- Structured output vs. free-form generation trade-offs
### Inference-Level Optimizations
- Batching configuration (size, timeout, padding strategy)
- Caching strategy (response, embedding, prefix) with cache hit rate targets
- Parallelism approach (tensor, pipeline, data) for self-hosted models
- Speculative decoding or early exit criteria
### Infrastructure Optimizations
- Instance type and sizing recommendations
- Auto-scaling policies and thresholds
- Geographic routing for latency optimization
- CDN and edge caching for static assets
### Cost Optimizations
- Model tier selection for different request types
- Spot/preemptible instance utilization strategies
- Request routing to cheaper models for non-critical workloads
- Token budget enforcement and prompt compression techniques
## 4. Monitoring and Alerting Setup
Define the observability stack needed for ongoing performance management:
- Key dashboards and their alert thresholds
- Synthetic monitoring scenarios
- A/B testing framework for model version comparisons
- Regression detection for performance degradation
## 5. Validation Plan
Create a structured validation approach:
- Load test scenarios matching production traffic profiles
- Canary deployment metrics and rollback criteria
- Performance regression test suite
- Cost tracking and budget alerting
**Output Format:** Provide the analysis as a structured markdown document with clear headings, code snippets for instrumentation, and a prioritized action plan with estimated impact for each recommendation.