Performance Monitoring
Deployed AI applications and integrations need monitoring and observability. That’s what this section is all about.
The purpose of monitoring is to see how our AI applications perform in production. In this lesson, we’ll focus on important metrics to track for LLMs.
This Lesson Will Cover
- ⏳ Latency monitoring and optimization
- 📊 Throughput metrics and tracking
- 🖥️ Resource utilization monitoring
- 🔢 Token usage tracking and optimization
Latency
What is Latency?
Latency is the time it takes for a system to process a request and return a response. High latency can degrade user experience, especially in real-time applications like chatbots or recommendation engines.
Tracking Latency with Python
Here’s a simple example of measuring request latency:
import time
from openai import OpenAI
client = OpenAI()
def get_chat_completion(prompt: str):
start_time = time.time()
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}]
)
latency = time.time() - start_time
print(f"Latency: {latency:.2f} seconds")
return response.choices[0].message.content
get_chat_completion("what is the meaning of life in 5 words?")
# Output:
# Latency: 1.05 seconds
# 'Finding purpose, connection, and joy.'
Here, we print the latency measurement to stdout. By using the logging standard library in Python, we can have more control over log formatting, levels, and output destinations.
Here’s an implementation of the code above using logging:
import time
import openai
import logging
from openai import OpenAI
client = OpenAI()
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def get_chat_completion(prompt: str):
start_time = time.time()
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}]
)
latency = time.time() - start_time
logger.info(f"Request completed successfully. Latency: {latency:.2f} seconds")
return response.choices[0].message.content
except Exception as e:
latency = time.time() - start_time
logger.error(f"Request failed after {latency:.2f} seconds. Error: {str(e)}")
raise
# Example usage
get_chat_completion("why do you think life has meaning?")
# Output:
# INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions "HTTP/1.1 200 OK"
# INFO:__main__:Request completed successfully. Latency: 2.13 seconds
# "The question of whether life has meaning is a deeply philosophical one, ...
LLM Latency Considerations
Here are some optimization techniques to consider for handling LLM latency with API platforms like OpenAI and Anthropic:
- Model Size Selection: Consider using smaller models which are capable of providing outputs with lower latency.
- Sampling Settings: Temperature changes the next-token probability distribution. Treat latency effects as implementation-dependent and measure them; lowering temperature is not a general latency optimization.
- Input and Output Length: Send the context the task needs and set appropriate output limits. More tokens generally require more work; measure the effect with your actual model and serving configuration.
- Streaming Responses: Enable streaming to start displaying results immediately while processing continues.
- Batching Strategy: Group similar requests together to leverage model loading efficiency.
Throughput Metrics
What is Throughput?
Throughput refers to the number of requests that a system can handle in a given time frame. It’s an important measure of scalability.
Monitoring Throughput
Use-metrics dashboards (e.g., Prometheus with Grafana) are an effective way to measure throughput.
For example, if we log each response to a postgres database, then we can connect that table to a dashboard tool in order to get visibility into throughput.
import os
import time
import openai
import logging
import psycopg2
import uuid
from datetime import datetime
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
conn = psycopg2.connect(
dbname=os.environ["DB_NAME"],
user=os.environ["DB_USER"],
password=os.environ["DB_PASSWORD"],
host=os.environ["DB_HOST"],
)
def log_chat_completion(prompt: str, conn: psycopg2.extensions.connection):
cur = conn.cursor()
# Create request ID
request_id = str(uuid.uuid4())
# Log prompt details
cur.execute("""
INSERT INTO prompt_logs (request_id, prompt)
VALUES (%s, %s)
""", (request_id, prompt))
conn.commit()
# Log request
cur.execute("""
INSERT INTO request_logs (request_id, time_set, status)
VALUES (%s, %s, %s)
""", (request_id, datetime.now(), 'STARTED'))
conn.commit()
completion_text = get_chat_completion(prompt)
# Log completed request
cur.execute("""
INSERT INTO request_logs (request_id, time_set, status)
VALUES (%s, %s, %s)
""", (request_id, datetime.now(), 'COMPLETED'))
conn.commit()
cur.close()
return completion_text
for prompt in (
"What's that song that that girl sings in frozen?",
"How many apples can I fit in my mouth?",
"Why is life so hard?",
):
log_chat_completion(prompt, conn)
conn.close()
With monitoring like this, we could:
- Calculate the completion rate of incoming requests per hour:
SELECT
DATE_TRUNC('hour', time_set) as hour,
COUNT(CASE WHEN status = 'COMPLETED' THEN 1 END) * 100.0 / COUNT(*) as completion_rate
FROM request_logs
GROUP BY DATE_TRUNC('hour', time_set)
ORDER BY hour DESC;
- Aggregate completed responses by hour, in order to see the number of requests per hour that the system can handle:
SELECT
DATE_TRUNC('hour', time_set) as hour,
COUNT(*) as requests_handled
FROM request_logs
WHERE status = 'COMPLETED'
GROUP BY DATE_TRUNC('hour', time_set)
ORDER BY hour DESC;
LLM Throughput Considerations
Here are some considerations for LLM throughput for self-hosted and API platform LLMs like Claude.
Self-hosted LLMs:
- Hardware Constraints: GPU memory and compute power directly limit concurrent requests
- Batch Processing: Request batching can help to maximize GPU utilization
- Model Loading: Keep models loaded in memory to avoid cold starts
- Instance Scaling: Add more GPU instances for horizontal scaling
- Model Size: Balance model size with hardware capabilities—smaller models allow more concurrent requests
API Platform LLMs:
- Rate Limits: Respect API rate limits to avoid throttling
- Retry Logic: Handle rate limit errors with backoff (e.g. exponential)
- Cost Management: Throughput allowance depends on API spend tier
- Noisy Neighbor: Shared infrastructure means performance can vary based on other users’ load
Resource Utilization
What to Monitor?
Resource utilization is especially relevant if self-hosting LLM models (e.g. Llama, Gemma, DeepSeek). Metrics to watch include:
- CPU/GPU Usage: High GPU utilization is expected for inference, but sustained 100% usage may indicate need for model parallelization or additional GPUs.
- Memory Usage: RAM capacity directly limits model size and batch processing—monitor for OOM errors when loading weights or processing long sequences.
- Disk I/O: Critical for loading model weights and tokenizer files—slow disk speeds can increase cold start times.
How to Monitor?
Cloud platforms have built-in tools that provide logging into resource utilization. We can see real-time metrics, create custom dashboards, and configure alert systems that notify us when resource usage exceeds defined thresholds.
For monitoring inside the app itself, libraries can be used to track system resources. Here’s a simple example using the psutil library for Python:
Example: Tracking Resource Usage with psutil
import psutil
def log_resource_usage():
cpu = psutil.cpu_percent()
memory = psutil.virtual_memory().percent
print(f"CPU Usage: {cpu}%")
print(f"Memory Usage: {memory}%")
# Example usage
log_resource_usage()
# Outputs:
# CPU Usage: 16.5%
# Memory Usage: 72.4%
Tools for Resource Monitoring
- Prometheus/Grafana: Monitor resource utilization across distributed systems.
- AWS CloudWatch: Monitor cloud resources like EC2 instances and Lambda functions.
- Local Tools: Use
htopfor to show system resources on a single server.
Prompt Tokens
Understanding API Costs
LLM providers typically charge based on the number of tokens: Input size of prompt + output size of response.
Different models and providers have varying pricing structures - for example, GPT-4o costs roughly 10x more per token than GPT-4o-mini.
Also, input tokens typically cost less than output tokens (e.g., half or even a quarter of the price).
It’s important to understand the pricing details of the models we’re using in order to optimize costs in production.
Monitoring Token Usage
The real “source of truth” for API costs is the billing dashboard in the platform itself, where you can see the aggregate usage in a given timeframe.
However, API platforms like OpenAI also provide token usage in their response metadata, which can be helpful for understanding token consumption patterns for specific features or user segments in our applications.
Here’s an example that logs token usage to PostgreSQL:
import os
import time
import uuid
import logging
import psycopg2
from openai import OpenAI
from datetime import datetime
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
conn = psycopg2.connect(
dbname=os.environ["DB_NAME"],
user=os.environ["DB_USER"],
password=os.environ["DB_PASSWORD"],
host=os.environ["DB_HOST"],
)
client = OpenAI()
def log_chat_completion(prompt: str, conn: psycopg2.extensions.connection):
cur = conn.cursor()
request_id = str(uuid.uuid4())
# Log prompt
cur.execute("""
INSERT INTO prompt_logs (request_id, prompt)
VALUES (%s, %s)
""", (request_id, prompt))
conn.commit()
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}]
)
completion_text = response.choices[0].message.content
# Log token usage
cur.execute("""
INSERT INTO token_logs (
request_id,
input_tokens,
completion_tokens,
total_tokens,
time_set
) VALUES (%s, %s, %s, %s, %s)
""", (
request_id,
response["usage"]["prompt_tokens"],
response["usage"]["completion_tokens"],
response["usage"]["total_tokens"],
datetime.now()
))
conn.commit()
cur.close()
logger.info(f"Request {request_id} completed. Total tokens: {response['usage']['total_tokens']}")
return completion_text
# Example usage
prompts = [
"Write a haiku about the quantum world",
"What is 'spooky action at a distance?'",
]
for prompt in prompts:
log_chat_completion(prompt, conn)
conn.close()
To get more granular insights, we can also implement independent token tracking in our application, for example by using the tiktoken library:
import tiktoken
def count_tokens(text: str, model: str = "gpt-4o-mini") -> int:
encoding = tiktoken.encoding_for_model(model)
return len(encoding.encode(text))
Prompt Token Considerations
The topic of prompt token considerations could be an entire lesson in itself. For now, we can think about a handful of the most important considerations:
-
Monitor Token Usage by Service
- Track token consumption per application service/feature
- Identify which parts of your application are most token-intensive
- Set budgets and alerts for different services
-
Model Management
- Use cheaper models for simpler tasks
- Implement token input and output limits per request
- Monitor and alert on unusual token usage patterns
-
Optimize Prompt Length
- Remove unnecessary context and instructions
- Limit the size of user-generated input
- Cache responses for common queries (often not practical due to changing context)
Conclusion
What’s more terrifying? An out-of-control generative model that you can see (i.e., you have good monitoring in place) or one that you can’t see at all?
My guess is the one you can see would be more terrifying in practice. But conceptually, it’s the second one, right?
Whatever. Let’s forget about that. There’s no way a generative model would get out of our control anyway…[1]
Key Takeaways
⏳ Monitoring latency helps identify performance bottlenecks and optimize response times.
🚀 Throughput monitoring is essential for understanding system capacity and scaling needs.
🖥️ Resource utilization tracking is critical for self-hosted models to prevent outages.
💰 Token usage monitoring helps control costs and optimize prompt efficiency.
📊 Proper logging and monitoring tools are essential for production AI applications.
🗄️ Use structured logging and databases to track metrics over time.
Next: LLM Evals
In this lesson we talked mostly about monitoring from a performance and cost point of view. Next, we’ll talk about monitoring of LLM response quality[2], with LLM evaluation.
Footnotes
AI will be our UNDOING—a thought experiment. If you’ve never thought about the “out of control” AI system in detail (not theoretically, but very concretely, with current-day tech) then this video essay I made might be eye opening. ↩︎
I can’t see this word (quality) without thinking of Zen and the Art of Motorcycle Maintenance. I do not recommend reading this book (although many do). There is, however, this one fantastic quote that I love thinking about: “Precision instruments are designed to achieve an idea, dimensional precision, where perfection is impossible. There is no perfectly shaped part of the motorcycle and never will be, but when you come as close as these instruments take you, remarkable things happen, and you go flying across the countryside under a power that would be called magic if it were not so completely rational in every way.” ↩︎
Comments (0)
No comments yet.