Module 8 Notes
Module 8 Notes
Topics
Monday, June 16, 2025 10:16 PM
1. Caching
5. Benchmarking APIs
6. Monitoring APIs
What is Caching?
• Caching is the process of storing a copy of data or computational results in a temporary storage layer (cache)
• This is done so that future requests for that same data can be served much faster, without needing to recompute or fetch it
from the original source
• Reduces Latency: Cached responses are served from nearby or in-memory storage, which is significantly faster than from a
database or an external API call
• Improves Performance: Applications become more responsive since frequently requested data is readily available
• Reduces Load on Backend: By reducing repeated data fetches or computations, the pressure on databases, ML models, or third-
party APIs is minimized
• Scalability: Helps applications scale better under high load, as the same data doesn't need to be processed repeatedly
• Web content: Static assets (images, CSS, JS files) are cached by browsers or CDNs (Content Delivery Network)
• Databases: Frequently queried data are cached to avoid hitting the DB each time
• API responses: Slow or rate-limited third-party API calls are cached to avoid repeated calls
• ML Predictions: Expensive predictions (e.g., fraud scores, recommendations) are cached for identical inputs
• Session Data: In web apps, user sessions are often stored in a cache like Redis for fast retrieval
Types of Caching:
• Client-side caching: Done in browsers or frontends using mechanisms like HTTP headers (Cache-Control)
• Server-side caching: Caching happens on the server using tools like Redis, Memcached, or in-memory dictionaries
• CDN caching: Content Delivery Networks cache static resources close to users for faster load times
○ A Content Delivery Network (CDN) is a network of geographically distributed servers that work together to deliver digital
content (websites, videos, images, scripts, etc.) to users more efficiently and reliably
○ Instead of every user fetching content from a single central server (which can be slow or get overloaded), a CDN caches and
serves content from a server that is geographically closer to the user
○ This reduces latency, speeds up loading times, and improves scalability and availability
• Cache Invalidation: When data changes, how do you ensure the cache is updated? This is a crucial challenge in caching systems
• Eviction Policies: Caches have limited memory, so older or less-used data must be removed using strategies like:
• Consistency: Make sure cached data doesn't become stale or inconsistent with the source
• Redis: An in-memory key-value store, widely used for caching due to its speed and flexibility
• CDNs: Used to cache and serve static content globally (e.g., Cloudflare, Akamai)
• Local Memory Cache: Python dictionaries or FastAPI lru_cache decorators for lightweight scenarios
What is Redis?
• Redis (short for REmote DIctionary Server) is a fast, open-source, in-memory data structure store
• Redis stores everything in memory, which allows for blazing fast reads and writes — often under 1
millisecond latency
• Redis is commonly used as:
○ Key-Value Database: Stores data as key-value pairs, similar to a Python dictionary
○ Cache: Frequently used to cache database queries, API responses, and ML model predictions
○ Message Broker: Supports publish/subscribe (pub/sub), streams, and queues for building messaging
systems
Redis Persistence:
• Real-time Analytics
• Pub/Sub Messaging
1. Caching ML Predictions
Code:
• to_list():
○ Converts features into a list so they can be passed to the model
• cache_key():
○ Serializes the input into JSON (sorted for consistency)
○ Hashes it using SHA-256 to generate a unique Redis key like predict:<hash>
App Workflow:
• The prediction result is cached in Redis with a TTL (Time To Live) of 1 hour (3600 seconds)
Code:
• get_db_connection():
○ Opens a connection to sqlite3 database
○ row_factory = [Link] makes rows behave like dictionaries
App Workflow:
• This application will fetch data from a public API, cache the result in Redis, and return the cached result for
repeated calls with the same input
• API: [Link]
• Ensure to have httpx installed if not already
App Workflow:
Profiling Tools:
• time: Quick & dirty timing of functions
• cProfile: Built-in profiler to capture function calls & time
• line_profiler: Line-by-line profiling
• Run snakeviz:
○ snakeviz profiles\<profile_name>.prof
• Install line_profiler
• Write code for [Link]
• Write code for benchmark_test.py
• Run the profiler --> kernprof -l -v profiling_test.py
○ -l: line-by-line profiling
○ -v: verbose output
Note:
• line_profiler doesn't run inside an ASGI server like uvicorn directly; needs isolated functions for
benchmarking
• line_profiler installs a command-line tool called kernprof
• Run the profiler with kernprof
• @profile is not a built-in python decorator, it tells line_profiler - Profile this function line by line
2. Assess Scalability:
• Benchmarking simulates varying loads to evaluate how well your system scales
○ How many concurrent users can your API support?
○ How does the performance degrade as the load increases?
○ What’s the tipping point before errors or timeouts occur?
• These insights are critical when preparing for traffic spikes, product launches, or promotional campaigns
1. Latency: The time taken by the API to respond to a request, typically measured in milliseconds
○ Importance:
▪ Indicates user experience
▪ High tail latency often causes performance jitter under load
○ Use Cases:
▪ Detect performance regression after code changes
▪ Optimize specific endpoints for faster responsiveness
2. Throughput: The number of requests the API can handle per second
○ Importance:
▪ Tells you how much load the system can sustain
▪ Key for capacity planning and scaling decisions
○ Use Cases:
▪ Compare system performance under various configuration
▪ Ensure infrastructure can handle expected traffic peaks
3. Concurrency Handling: The ability of API to process multiple simultaneous requests without degradation in
performance or errors
○ Importance:
▪ Real-world users hit APIs simultaneously
▪ Poor concurrency support leads to timeouts and failed transactions
○ Use Cases:
▪ Test async vs sync performance in FastAPI
▪ Ensure proper thread/worker configurations in production environments
4. Error Rates: The percentage of requests that result in errors (HTTP 4xx or 5xx responses)
○ Importance:
▪ Indicates system instability or poor error handling under load
▪ Helps distinguish between functional errors and load-induced failures
Use Cases:
5. Resource Usage: The consumption of system resources (CPU, RAM, disk I/O) by API server during execution
○ Importance:
▪ High CPU usage can indicate inefficient code or unnecessary computation
▪ Memory bloat may lead to signal leaks or overuse of objects in memory
▪ Important for cloud cost optimization and container-based deployments
○ Use Cases:
▪ Optimize code paths or data processing
▪ Determine resource requirements for autoscaling in Kubernetes or cloud VMs
▪ Tune configurations
Summary:
1. wrk: CLI
• Pros:
○ High performance
○ Lightweight and fast
○ Ideal for simple stress testing
• Cons:
○ No detailed report
○ No scripting logic for real user scenarios
2. ApacheBench (ab):
• Pros:
▪ Very simple to use
▪ Comes pre-installed on many systems
• Cons:
▪ Single-threaded (not suitable for high-scale)
▪ Basic reporting
▪ No user behavior scripting
• Pros:
▪ Web-based control panel
▪ Easy scenario scripting (supports login, flows, etc.)
▪ Supports distributed testing
• Cons:
▪ Heavier than CLI tools
▪ Slightly more setup
• Pros:
▪ Great for automation
▪ JavaScript-based scripting
▪ Detailed metrics, CI/CD integration
▪ Cloud options available (k6 Cloud)
• Cons:
▪ Slightly complex setup for beginners
○ [Link]
▪ HttpUser: Represents a simulated user making HTTP requests
▪ @task: Used to mark methods as tasks that Locust will execute
▪ between: Used to set wait time between tasks (to simulate real user behavior)
• Run locust:
○ Execute -- locust / locust -f [Link]
○ Open -- [Link]
• Provide details:
○ Number of users to simulate - 100
○ Spawn rate - 10
○ Host - [Link]
• Use monitoring tools (Grafana + Prometheus) to correlate performance with system usage
1. Availability Monitoring:
○ Ensures the API is reachable and responsive
○ Uptime checks at regular intervals
○ Alerts when the API is down or returns errors
2. Performance Monitoring:
○ Measures response time, latency, throughput
○ Identifies slow endpoints or inefficient logic
○ Helps in tuning APIs for better user experience
3. Error Tracking:
○ Logs and analyzes status codes
○ Tracks frequency and type of errors
○ Useful for debugging and root cause analysis (RCA)
4. Usage Analytics:
○ Monitors request volume, endpoints usage, and consumer behavior
○ Helps in capacity planning and scaling
5. Resource Monitoring:
○ Tracks CPU, memory, I/O utilization at the infrastructure level
○ Useful in understanding backend stress caused by API calls
What is Prometheus?
• Prometheus is an open-source systems monitoring and alerting toolkit, originally developed by SoundCloud
• It’s designed for reliability and scalability, and is especially strong in environments like cloud-native
applications, microservices, and containerized deployments (like Kubernetes)
Characteristics:
1. Pull-based Model: Prometheus pulls (scrapes) metrics from instrumented targets (applications/services) at
specified intervals
2. Time Series Storage: Metrics are stored as time series and they’re indexed by :-
○ A metric name
○ One or more labels
3. Flexible Query Language: PromQL lets you perform complex queries to aggregate, filter, and compute metrics
4. Built-in Alert Manager: Allows to configure alert rules and send alerts to email, Slack, PagerDuty, etc.
1. Configuration: Prometheus reads a YAML configuration file ([Link]) to determine what to scrape,
when, and how often
2. Targets: Each target is an HTTP endpoint that exposes metrics, commonly at the /metrics route
3. Scrape Format: The data should be exposed in Prometheus text format or OpenMetrics format
Use Cases:
prometheus-fastapi-instrumentator:
• Installation:
○ pip install prometheus-fastapi-instrumentator (Python 3.9+)
○ pip install prometheus-fastapi-instrumentator==5.9.1 (up to Python 3.8)
• instrument(app):
○ Hooks into FastAPI's routing layer
○ Captures HTTP-level metrics:
• Request count
• Request duration
• Status code distribution
• Method and endpoint path
○ Wraps every route handler with logic to collect and export the metrics
• expose(app):
○ Adds a /metrics route (by default)
○ This endpoint serves metrics in a Prometheus-compatible format
File Structure:
project-folder/
- app/
- [Link]
- prometheus/
- [Link]
- [Link]
- Dockerfile
Docker-compose:
What is Grafana?
1. Data Sources:
○ Grafana connects to databases and time-series backends via data source plugins
○ Common sources include: Prometheus, InfluxDB, Loki, Elasticsearch, PostgreSQL, MySQL
2. Queries:
○ You can write custom queries or use built-in query builders to extract data from the source
3. Dashboards:
○ Dashboards are made of panels (charts, tables, gauges, heatmaps, etc.) where the data is visualized
○ You can save and share dashboards with teams
4. Alerting:
○ Grafana provides rule-based alerting on your metrics
○ You can integrate with Slack, PagerDuty, Microsoft Teams, Email, etc., for notifications
1. Infrastructure Monitoring:
○ Monitor server CPU, RAM, disk usage, network I/O
○ Integrate with Prometheus, Telegraf, InfluxDB, or Node Exporter
3. Database Monitoring:
○ Connect to MySQL, PostgreSQL, MongoDB, etc., and visualize query performance, connections, latency
7. Security Monitoring:
○ Visualize login attempts, suspicious activity using Elasticsearch or Loki for log aggregation
Advantages of Grafana:
• Open-source and free: Core Grafana is free to use and has a large community of contributors
• Custom Dashboards: Easy to build and customize dashboards tailored to specific needs
• Plugin Ecosystem: Rich library of community-developed plugins for new data sources or visuals
• Multiple Data Sources: Combine metrics from multiple tools in a single unified dashboard
• Time-Series Friendly: Especially powerful for time-series and real-time streaming data
• Integrations: Works with Prometheus, Loki, Elasticsearch, InfluxDB, AWS CloudWatch, etc.
• Alerting System: Allows users to receive notifications when metrics cross thresholds
• Collaboration: Share dashboards with teams and define permissions for access control
File Structure:
project-folder/
- app/
- [Link]
- Dockerfile
- prometheus/
- [Link]
- [Link]
- [Link]
• Grafana: [Link]
○ Username: admin
○ Password: admin