Requirement mapping
Trace architecture / observability requirements in the BR/NFR catalog and related docs:
Truy vết yêu cầu kiến trúc / quan sát trong catalog BR/NFR và tài liệu liên quan:
1. Summary
This document describes the monitoring stack architecture for the Crypto Payment Gateway system. The monitoring infrastructure is deployed on-premise to comply with data residency requirements and provide comprehensive observability across all system components.
1.1 Monitoring Strategy
The monitoring stack follows the three pillars of observability: Metrics, Logs, and Traces. All monitoring components are deployed on-premise in the Singapore datacenter to ensure compliance with PDPA data residency requirements and minimize network latency for real-time alerting.
| Monitoring Stack Overview |
| Metrics: Prometheus + Grafana Logs: Loki + Promtail Traces: Grafana Tempo (OpenTelemetry) Alerting: Alertmanager + Slack Deployment: On-Premise (Singapore DC) |
1.2 Architecture Overview
| Component |
Technology |
Purpose |
| Metrics Collection |
Prometheus |
Time-series metrics scraping and storage |
| Visualization |
Grafana |
Dashboards and metric visualization |
| Log Aggregation |
Loki + Promtail |
Centralized log collection and querying |
| Distributed Tracing |
Grafana Tempo |
Request tracing across microservices |
| Alerting |
Alertmanager |
Alert routing, grouping, and notification |
| Uptime Monitoring |
Blackbox Exporter |
External endpoint health checks |
2. Monitoring Architecture
2.1 Deployment Topology
All monitoring components are deployed on dedicated nodes within the Management Zone (10.2.30.0/24) of the On-Premise datacenter. This ensures monitoring data remains within Singapore for compliance purposes.
| Component |
Nodes |
Storage |
HA Mode |
| Prometheus |
2 (HA pair) |
500 GB SSD |
Active-Active |
| Grafana |
2 (HA pair) |
50 GB SSD |
Active-Standby |
| Loki |
3 (cluster) |
1 TB SSD |
Distributed |
| Tempo |
3 (cluster) |
200 GB SSD |
Distributed |
| Alertmanager |
3 (cluster) |
20 GB SSD |
Clustered |
2.2 Data Flow
The monitoring data flows through the following path:
| Metrics Data Flow |
| 1. Application pods expose /metrics endpoint (Prometheus format) 2. Prometheus scrapes metrics every 15 seconds 3. Prometheus stores time-series data locally (15 days retention) 4. Grafana queries Prometheus for visualization 5. Alertmanager receives alerts from Prometheus rules 6. Alerts route to PagerDuty (critical) or Slack (warning) |
| Logs Data Flow |
| 1. Application pods write logs to stdout/stderr 2. Promtail (DaemonSet) collects logs from each node 3. Promtail adds labels (namespace, pod, container) and ships to Loki 4. Loki indexes and stores logs (30 days retention) 5. Grafana queries Loki using LogQL for log exploration |
| Traces Data Flow |
| 1. Applications instrumented with OpenTelemetry SDK 2. Traces sent to Tempo Distributor via OTLP (gRPC port 4317) 3. Tempo stores traces in local storage backend (no external DB required) 4. Grafana queries Tempo directly for trace visualization (native integration) |
3. Metrics Collection
3.1 Prometheus Configuration
Prometheus is configured to scrape metrics from all system components including Kubernetes pods, infrastructure services, and external endpoints.
| Target |
Scrape Interval |
Retention |
Discovery |
| Kubernetes Pods |
15 seconds |
15 days |
kubernetes_sd_config |
| Node Exporter |
30 seconds |
15 days |
static_config |
| PostgreSQL |
30 seconds |
15 days |
static_config |
| Redis |
30 seconds |
15 days |
static_config |
| Kafka |
30 seconds |
15 days |
static_config |
| Kong Gateway |
15 seconds |
15 days |
static_config |
| Istio (Envoy) |
15 seconds |
15 days |
kubernetes_sd_config |
| Blackbox (HTTP) |
30 seconds |
15 days |
static_config |
3.2 Key Metrics by Component
3.2.1 Application Metrics
| Metric |
Description |
| http_requests_total |
Total HTTP requests by method, path, status code |
| http_request_duration_seconds |
Request latency histogram (p50, p95, p99) |
| payment_transactions_total |
Total payment transactions by status, currency, network |
| payment_amount_total |
Total payment amount processed by currency |
| blockchain_scan_height |
Current blockchain scanning height by network |
| webhook_deliveries_total |
Webhook delivery attempts by status, merchant |
3.2.2 Infrastructure Metrics
| Metric |
Description |
| node_cpu_seconds_total |
CPU usage per node and mode |
| node_memory_MemAvailable_bytes |
Available memory per node |
| node_disk_io_time_seconds_total |
Disk I/O time per device |
| node_network_receive_bytes_total |
Network bytes received per interface |
| kube_pod_status_phase |
Pod phase status (Pending, Running, Failed) |
| kube_deployment_status_replicas |
Current vs desired replicas per deployment |
3.2.3 Database Metrics
| Metric |
Description |
| pg_stat_activity_count |
Active database connections by state |
| pg_replication_lag_seconds |
Replication lag from leader to replicas |
| pg_stat_statements_calls |
Query execution count and timing |
| patroni_master |
Current Patroni leader node indicator |
| haproxy_backend_up |
HAProxy backend health status |
4. Log Aggregation
4.1 Loki Architecture
Loki is deployed in microservices mode for horizontal scalability. Logs are collected by Promtail agents running as DaemonSet on each Kubernetes node.
| Component |
Description |
| Promtail |
Log collection agent deployed as DaemonSet, tails log files and ships to Loki |
| Loki Distributor |
Receives logs from Promtail, validates and distributes to Ingesters |
| Loki Ingester |
Writes log chunks to storage, maintains in-memory index |
| Loki Querier |
Handles LogQL queries from Grafana, reads from Ingesters and storage |
| Storage Backend |
Local SSD for chunks, BoltDB for index (on-premise deployment) |
4.2 Log Labels and Retention
| Label |
Source |
Example |
Cardinality |
| namespace |
Kubernetes |
crypto-prod |
Low |
| app |
Pod label |
payment-service |
Low |
| pod |
Kubernetes |
payment-service-abc123 |
Medium |
| container |
Kubernetes |
payment-api |
Low |
| level |
Log parsing |
error, warn, info |
Low |
| Log Type |
Retention Period |
Storage Estimate |
| Application Logs |
30 days |
\~500 GB |
| Audit Logs |
90 days (then archive) |
\~200 GB |
| Infrastructure Logs |
14 days |
\~300 GB |
5. Alerting Strategy
5.1 Alert Severity Levels
| Severity |
Response Time |
Notification Channel |
Examples |
| Critical |
Immediate (\< 5 min) |
Phone Call + SMS + Email + Slack |
Service down, DB unavailable |
| Warning |
\< 30 minutes |
SMS + Email + Slack |
High latency, disk 80% |
| Info |
Next business day |
Email + Slack |
Deployment complete |
5.2 Critical Alerts
| Alert Name |
Condition |
For Duration |
| ServiceDown |
Any critical service is unreachable or not responding |
1 minute |
| DatabaseUnavailable |
PostgreSQL cluster is completely unavailable |
30 seconds |
| HighErrorRate |
HTTP 5xx error rate exceeds 10 requests per minute |
2 minutes |
| PaymentProcessingFailed |
Payment failure rate exceeds 5 transactions per minute |
1 minute |
| ReplicationLagCritical |
Database replication lag exceeds 60 seconds |
2 minutes |
| BlockchainScannerStuck |
Blockchain scanner has not progressed for 10 minutes |
10 minutes |
5.3 Warning Alerts
| Alert Name |
Condition |
For Duration |
| HighLatency |
95th percentile response time exceeds 2 seconds |
5 minutes |
| DiskSpaceWarning |
Available disk space is less than 20% |
5 minutes |
| HighMemoryUsage |
Available memory is less than 10% |
5 minutes |
| PodRestartLoop |
Pod has restarted more than 5 times in the last hour |
10 minutes |
| CertificateExpiring |
SSL certificate expires in less than 7 days |
1 hour |
| WebhookDeliveryFailures |
Webhook delivery failure rate exceeds 1 per minute |
5 minutes |
6. Grafana Dashboards
6.1 Dashboard Inventory
| Dashboard |
Purpose |
Refresh Rate |
| System Overview |
High-level system health, request rates, error rates |
10 seconds |
| Payment Operations |
Transaction volumes, success rates, processing times |
30 seconds |
| Blockchain Scanner |
Scan heights, confirmation times, network status |
1 minute |
| Database Performance |
Connections, queries, replication lag, Patroni status |
30 seconds |
| Kubernetes Cluster |
Node resources, pod status, deployment health |
30 seconds |
| API Gateway (Kong) |
Request rates, latency, upstream health |
15 seconds |
| Service Mesh (Istio) |
Traffic flow, success rates, circuit breakers |
15 seconds |
| Infrastructure |
CPU, memory, disk, network across all nodes |
1 minute |
6.2 Key Dashboard Panels
6.2.1 System Overview Dashboard
| Panel |
Visualization |
| Service Health Matrix |
Status grid showing up/down for each microservice |
| Request Rate (RPS) |
Time series graph of requests per second by service |
| Error Rate (%) |
Percentage of 5xx errors over time |
| P95 Latency |
95th percentile response time by endpoint |
| Active Alerts |
Table of currently firing alerts with severity |
6.2.2 Payment Operations Dashboard
| Panel |
Visualization |
| Transactions per Minute |
Real-time transaction volume by network (BTC, ETH, etc.) |
| Transaction Success Rate |
Percentage of successful vs failed transactions |
| Volume by Currency |
Pie chart of transaction volume distribution |
| Average Confirmation Time |
Time from detection to confirmed by network |
| Webhook Delivery Status |
Success/failure rates for merchant callbacks |
7. Distributed Tracing
7.1 Grafana Tempo Overview
Grafana Tempo is deployed for distributed tracing, providing a cost-effective and scalable solution that integrates natively with Grafana. Tempo uses object storage for trace data, eliminating the need for external databases like Elasticsearch.
| Why Tempo? |
| • Native Grafana integration - seamless trace exploration in Grafana UI • No external database required - uses local/object storage • Cost-effective - only indexes trace IDs, not full payload • Same architecture as Loki - familiar operations model • Full OpenTelemetry support - OTLP, Jaeger, Zipkin protocols |
7.2 Tempo Configuration
| Parameter |
Value |
| Deployment Mode |
Microservices mode (Distributor, Ingester, Querier, Compactor) |
| Receiver Protocols |
OTLP gRPC (4317), OTLP HTTP (4318), Jaeger (14250), Zipkin (9411) |
| Storage Backend |
Local SSD (filesystem) - no external database required |
| Trace Retention |
7 days |
| Sampling Strategy |
Tail-based sampling (1% normal, 100% on errors) |
| Query Frontend Port |
3200 (Grafana datasource) |
7.3 Tempo Architecture Components
| Component |
Description |
| Distributor |
Receives spans from applications, validates and forwards to Ingesters |
| Ingester |
Batches incoming spans into blocks, writes to storage backend |
| Querier |
Handles trace queries from Grafana, reads from Ingesters and storage |
| Compactor |
Compacts trace blocks for efficient storage and querying |
| Query Frontend |
Caching layer for queries, splits large requests |
7.4 Instrumented Services
| Service |
Instrumentation |
Key Spans |
| Kong Gateway |
OpenTelemetry Plugin |
HTTP request, upstream call |
| Core Services |
OTel Go SDK |
Business logic, internal calls |
| Payment Service |
OTel Go SDK |
Payment processing, DB queries |
| Scanner Service |
OTel Go SDK |
Block scan, transaction detection |
| Webhook Service |
OTel Go SDK |
Webhook delivery, retry logic |
| Wallet Service |
OTel Go SDK |
Address generation, balance check |
7.5 Grafana Integration
Tempo integrates natively with Grafana, providing powerful trace exploration capabilities:
| Feature |
Description |
| Trace to Logs |
Click from trace span to related logs in Loki (same time window, same service) |
| Trace to Metrics |
Link traces to related Prometheus metrics (RED metrics) |
| Service Graph |
Auto-generated service dependency map from trace data |
| TraceQL |
Query language for searching traces by attributes, duration, status |
| Span Metrics |
Automatic RED metrics generation from spans (optional) |
8. Monitoring for Disaster Recovery
8.1 DR Monitoring Requirements
The monitoring stack plays a critical role in disaster detection and DR activation. The following components are monitored to trigger DR failover:
| Component |
Health Check |
DR Trigger |
| On-Premise Istio |
HTTP probe every 30 seconds from GCP |
Unreachable > 5 min |
| PostgreSQL Cluster |
Patroni REST API + pg_isready |
All nodes down > 2 min |
| Network Connectivity |
Interconnect + VPN tunnel status |
Both paths down > 5 min |
| Kubernetes API |
kubectl cluster-info from external |
API unreachable > 5 min |
8.2 GCP Cloud Monitoring Integration
For DR scenarios, additional monitoring is deployed on GCP to provide external observability of the on-premise infrastructure:
| Component |
Purpose |
| Cloud Monitoring |
Uptime checks for on-premise endpoints (external perspective) |
| Cloud Logging |
Aggregates logs from GCP DR components (GKE, Cloud SQL) |
| Cloud Alerting |
Backup alerting path if on-premise Alertmanager is unreachable |
8.3 DR Alert Rules
Specific alerts configured to detect DR scenarios:
| Alert |
Condition |
Action |
| OnPremiseUnreachable |
All uptime checks failing for more than 5 minutes |
Initiate DR |
| DatabaseClusterDown |
No Patroni leader detected across all nodes |
Initiate DR |
| NetworkConnectivityLost |
Both Interconnect and VPN connections are down |
Initiate DR |
| ReplicationLagExtreme |
Cloud SQL replication lag exceeds 5 minutes |
Warning |
Mapped Requirements
BR/NFR/REQ items from the master catalog mapped to this document. IDs link to anchors in 01_BR; local id anchors still accept deep-links from the catalog.Các BR/NFR/REQ từ catalog master được ánh xạ tới tài liệu này. ID liên kết tới anchor trong 01_BR; id cục bộ vẫn nhận deep-link từ catalog.
BR-CORE-OBS-001 BR — Request Logging and Monitoring.Request Logging và Monitoring.BR-CORE-OBS-002 BR — All backend microservices are required to be containerized (e.g., Docker).Tất cả backend microservices bắt buộc phải được containerized (ví dụ: Docker).BR-CORE-OBS-003 BR — You must use a container orchestration platform to manage deployment, scaling, and health for microservices.Phải sử dụng một container orchestration platform để quản lý deployment, scaling và health cho microservice.BR-CORE-OBS-004 BR — Proposal: Kubernetes (K8s).Đề xuất: Kubernetes (K8s).BR-CORE-OBS-005 BR — Backup: Must have Point-in-Time Recovery (PITR) allowing restore to any point within 30 days, and daily snapshots storedBackup: Phải có Point-in-Time Recovery (PITR) cho phép restore bất kỳ thời điểm nào trong 30 ngày, và daily snapshots lưuBR-CORE-OBS-006 BR — Set up a robust CI/CD pipeline (e.g., GitLab CI, Jenkins, GitHub Actions) to automatically build, test (unit/integration), and deployThiết lập CI/CD pipeline robust (ví dụ: GitLab CI, Jenkins, GitHub Actions) để tự động build, test (unit/integration), và deployBR-CORE-OBS-007 BR — Enable WAL/PITR (Write-Ahead Logging/Point-in-Time Recovery) and store on high-speed storage.Bật WAL/PITR (Write-Ahead Logging/Point-in-Time Recovery) và lưu trữ trên storage tốc độ cao.BR-CORE-OBS-008 BR — Hot data (hot data, e.g., transactions, realtime logs) is stored on high-speed storage for up to 90 days, then automaticallyData nóng (hot data, ví dụ: transactions, realtime logs) lưu trên storage tốc độ cao tối đa 90 ngày, sau đó tự độngBR-CORE-OBS-009 BR — Webhook logs & notifications are stored for 180 days on hot storage and then archived.Webhook logs & notifications lưu 180 ngày trên hot storage rồi archive.BR-CORE-OBS-010 BR — Application logs are stored for 30 or 90 days in hot storage, then archived according to policy.Application logs lưu 30 hoặc 90 ngày ở hot storage, archive sau đó theo policy.BR-CORE-OBS-011 BR — Large data tables (transactions, logs, events,…) must be partitioned by time (day/month/year)Các bảng dữ liệu lớn (transactions, logs, events,…) bắt buộc phân vùng (partition) theo thời gian (ngày/tháng/năm)BR-CORE-OBS-012 BR — The CRM Admin must have an interface that allows the Admin to configure data retention time (logs, transactions, ...) instead ofAdmin CRM phải có giao diện cho phép Admin tự cấu hình thời gian lưu giữ dữ liệu (logs, transactions, …) thay choBR-CORE-OBS-013 BR — Fee logic (on-chain fee-splitting BPS, flat SaaS fee, ...) must allow per-merchant configuration on the Admin CRM,Logic về phí (on-chain fee-splitting BPS, SaaS fee phẳng, …) phải cho phép cấu hình per-merchant trên Admin CRM,BR-CORE-OBS-014 BR — The observability stack integrates directly with on-call management tools (PagerDuty, Opsgenie, ...).Observability stack tích hợp trực tiếp với on-call management tool (PagerDuty, Opsgenie, ...).BR-CORE-OBS-015 BR — All backend microservices must expose the /metrics endpoint for Prometheus to scrape data.Tất cả backend microservices phải expose endpoint /metrics để Prometheus scrape dữ liệu.BR-CORE-OBS-016 BR — Grafana is the only visualization tool for observability with 3 sources:Grafana là công cụ visualization duy nhất cho observability với 3 nguồn:BR-CORE-OBS-017 BR — Metrics: from PrometheusMetrics: từ PrometheusBR-CORE-OBS-018 BR — Logs: from Loki or ElasticLogs: từ Loki hoặc ElasticBR-CORE-OBS-019 BR — Grafana dashboard must correlate both metrics, logs, and traces.Dashboard Grafana phải tương quan (correlate) cả metrics, logs và traces.BR-CORE-OBS-020 BR — IP, Device ID, User ID MUST NOT be used as Prometheus labels; only store them in structured logs (JSON) with correlationIdIP , Device ID, User ID KHÔNG được dùng làm Prometheus label; chỉ lưu vào structured log (JSON) với correlationIdBR-CORE-OBS-021 BR — All services (API Gateway, Merchant Service, Scanner…) must expose metrics according to the RED standard: Rate, Errors, Duration.Tất cả các service (API Gateway, Merchant Service, Scanner…) phải expose metrics theo chuẩn RED: Rate, Errors, Duration.BR-CORE-OBS-022 BR — Counter http_requests_total, labeled by service, endpoint, method, http_status_code, merchant_id (ifCounter http_requests_total, gắn nhãn theo service, endpoint, method, http_status_code, merchant_id (nếuBR-CORE-OBS-023 BR — Monitor the request rate (fail, reject) as well.Theo dõi cả request rate (fail, reject).BR-CORE-OBS-024 BR — Counter application-level errors (payment_failed, webhook_failed…), detailed reason (reason).Counter application-level errors (payment_failed, webhook_failed…), lý do chi tiết (reason).BR-CORE-OBS-025 BR — Monitor http_requests_total with 4xx/5xx status.Theo dõi http_requests_total với status 4xx/5xx.BR-CORE-OBS-026 BR — Histogram/Summary http_request_duration_seconds, label theo service, endpoint.BR-CORE-OBS-027 BR — Calculate p99, p95, p50 for requests and transaction execution time.Tính toán p99, p95, p50 cho các request và thời gian thực thi giao dịch.BR-CORE-OBS-028 BR — All hosts/pods (Kubernetes) must expose USE metrics: Utilization, Saturation, Errors.Tất cả host/pod (Kubernetes) phải expose metrics USE: Utilization, Saturation, Errors.BR-CORE-OBS-029 BR — Monitor CPU, Memory, Disk I/O, Network I/O.Theo dõi CPU, Memory, Disk I/O, Network I/O.BR-CORE-OBS-030 BR — Database: max_connections compared to active_connections, replication lag.Database: max_connections so với active_connections, replication lag.BR-CORE-OBS-031 BR — Queues (Redis/Kafka): queue_depth, consumer_lag.BR-CORE-OBS-032 BR — Sockets: socket_states (ESTABLISHED, TIME_WAIT,...) of the system and app.Sockets: socket_states (ESTABLISHED, TIME_WAIT,...) của hệ thống và app.BR-CORE-OBS-033 BR — payment_value_usd: Gauge/Histogram theo merchant_id, chain, token.BR-CORE-OBS-034 BR — Including deals, orders that are abstracted into payment.Bao gồm các deal, order được abstract thành payment.BR-CORE-OBS-035 BR — gateway_fee_collected_total: Counter theo merchant_id, chain, token.BR-CORE-OBS-036 BR — gateway_fee_collected_usd: Counter theo chain, token.BR-CORE-OBS-037 BR — blockchain_scanner_lag_blocks: Gauge (chain), measures the difference between the head block (Node SaaS) andblockchain_scanner_lag_blocks: Gauge (chain), đo chênh lệch giữa head block (Node SaaS) vàBR-CORE-OBS-038 BR — treasury_wallet_balance: Gauge (chain, token).NFR-Obs1 NFR — Centralized logs (JSON format) have correlationId (requestId, merchantId, txHash).Centralized logs (định dạng JSON) có correlationId (requestId, merchantId, txHash).NFR-Obs2 NFR — Tracing: end-to-end distributed tracing (UI→API→workers→RPC).NFR-Obs3 NFR — Alerting: SLO-based alerts (error budget burn), queue backlog thresholds, RPC health.NFR-Obs4 NFR — Audit trails must be immutable, retrievable, and have a minimum retention of 2 years (or according to the prescribed policy).Audit trails phải immutable, truy xuất được và retention tối thiểu 2 năm (hoặc theo chính sách quy định).REQ-OBS-4 REQ — Rate (R)REQ-OBS-5 REQ — Errors (E)REQ-OBS-6 REQ — Duration (D)REQ-OBS-7 REQ — Utilization (U) & Saturation (S)REQ-OBS-8 REQ — Network Errors (E)REQ-OBS-9 REQ — Transaction & Order MetricsREQ-OBS-10 REQ — Gateway Revenue MetricsREQ-OBS-11 REQ — On-Chain Operations Metrics