Skip to content
advanced Phase 84 · Observability Advanced

Application Metrics

Application metrics with Prometheus, Grafana, custom metrics, and metric types

45m
0 problems
Topic Progress 0%

Prometheus Integration

Prometheus Architecture

Application ──▶ /metrics ──▶ Prometheus ──▶ Grafana
(magento)      (endpoint)    (scrape/store)  (visualize)

Magento Prometheus Setup

// composer.json
require {
    "promphp\prometheus_client_php": "^3.0"
}

// Metrics endpoint
// pub/metrics.php
use Prometheus\CollectorRegistry;
use Prometheus\RenderTextFormat;
use Prometheus\Storage\Redis;

$adapter = new Redis(['host' => 'redis']);
$registry = CollectorRegistry::getDefault($adapter);

$renderer = new RenderTextFormat();
header('Content-Type: ' . RenderTextFormat::MIME_TYPE);
echo $renderer->render($registry->getMetricFamilySamples());

Scrape Config

# prometheus.yml
scrape_configs:
  - job_name: 'magento'
    static_configs:
      - targets: ['magento:9090']
    metrics_path: '/metrics'
    scrape_interval: 15s

Metric Types

Prometheus Metric Types

Type       | Description              | Use Case
───────────|──────────────────────────|─────────────────────
Counter    | Monotonically increasing | Total requests, errors
Gauge      | Value that can go up/down| Active connections
Histogram  | Distribution of values   | Request duration
Summary     | Quantiles over window    | Latency percentiles

Counter Example

$counter = $registry->registerCounter(
    'magento_http_requests_total',
    'Total HTTP requests',
    ['method', 'status', 'route']
);

$counter->inc(['GET', '200', '/catalog/product/view']);

Histogram Example

$histogram = $registry->registerHistogram(
    'magento_http_request_duration_seconds',
    'HTTP request duration',
    ['method', 'route'],
    [0.01, 0.05, 0.1, 0.5, 1.0, 2.0, 5.0]
);

$histogram->observe($duration, ['GET', '/checkout']);

Gauge Example

$gauge = $registry->registerGauge(
    'magento_active_sessions',
    'Active user sessions'
);

$gauge->set($sessionCount);

Custom Business Metrics

Business Metrics

// Orders metrics
$ordersTotal = $registry->registerCounter(
    'magento_orders_total',
    'Total orders placed',
    ['status', 'payment_method']
);
$ordersTotal->inc(['pending', 'stripe']);

// Revenue metrics
$orderValue = $registry->registerHistogram(
    'magento_order_value_dollars',
    'Order value distribution',
    [], [10, 25, 50, 100, 250, 500, 1000]
);
$orderValue->observe($order->getTotal());

// Cart metrics
$cartCount = $registry->registerGauge(
    'magento_active_carts',
    'Active shopping carts'
);
$cartCount->set($activeCarts);

// Search metrics
$searchLatency = $registry->registerHistogram(
    'magento_search_duration_seconds',
    'Search query duration',
    ['type']
);
$searchLatency->observe($duration, ['fulltext']);

Inventory Metrics

$stockLevel = $registry->registerGauge(
    'magento_stock_level',
    'Current stock level',
    ['product_id', 'sku']
);
$stockLevel->set($qty, [$productId, $sku]);

Grafana Dashboards

Dashboard Panels

Panel 1: Request Rate
  - Total requests/sec
  - By status code (2xx, 4xx, 5xx)
  - By endpoint

Panel 2: Latency
  - P50, P95, P99 latency
  - Latency by endpoint

Panel 3: Errors
  - Error rate %
  - Top error endpoints
  - Error trend

Panel 4: Business
  - Orders per minute
  - Revenue per hour
  - Cart count

PromQL Queries

# Request rate
rate(magento_http_requests_total[5m])

# Error rate
rate(magento_http_requests_total{status=~"5.."}[5m])
  / rate(magento_http_requests_total[5m])

# P99 latency
histogram_quantile(0.99, 
  rate(magento_http_request_duration_seconds_bucket[5m])
)

# Orders per minute
rate(magento_orders_total[5m]) * 60

Dashboard JSON

{
  "title": "Magento Overview",
  "panels": [
    {
      "title": "Request Rate",
      "type": "graph",
      "targets": [{
        "expr": "rate(magento_http_requests_total[5m])",
        "legendFormat": "{{method}} {{status}}"
      }]
    },
    {
      "title": "Error Rate",
      "type": "singlestat",
      "targets": [{
        "expr": "rate(magento_http_requests_total{status=~'5..'}[5m]) / rate(magento_http_requests_total[5m]) * 100"
      }]
    }
  ]
}

Quiz

1. Which metric type only increases?

Question 1 options

2. What does rate() calculate in PromQL?

Question 2 options

3. What is the default Prometheus scrape interval?

Question 3 options

Flashcards

Question

Counter metric?

Answer

Monotonically increasing (total requests, errors)

Question

Gauge metric?

Answer

Value that can go up or down (connections, stock)

Question

Histogram metric?

Answer

Distribution of values (request duration)

Question

PromQL rate()?

Answer

Per-second rate of increase for counters

Revision Notes

Key Takeaways

  • 1. Counters track totals (requests, errors), never decrease
  • 2. Gauges track values that change (connections, stock levels)
  • 3. Histograms track value distributions (latency)
  • 4. rate() calculates per-second rate from counters
  • 5. Grafana visualizes metrics with PromQL queries

Interview Tips

  • Explain when to use each metric type
  • Write PromQL queries for common metrics
  • Design dashboard panels for business and technical metrics

Cheat Sheet

Metric Types:
  Counter: Only increases (requests, errors)
  Gauge: Up/down (connections, stock)
  Histogram: Distribution (latency)
  Summary: Quantiles over window

PromQL:
  rate(): Per-second rate
  histogram_quantile(): Percentiles
  sum by (): Group metrics

Grafana:
  Panels: Graph, Singlestat, Table
  Queries: PromQL expressions
  Alerts: Threshold-based