8.0 KiB
8.0 KiB
Observability Architecture / Kiến trúc Khả năng Quan sát
EN: Comprehensive observability with metrics, logging, and tracing VI: Khả năng quan sát toàn diện với metrics, logging và tracing
Overview Diagram / Sơ đồ Tổng quan
graph TD
subgraph "Services"
Service1[Service A]
Service2[Service B]
end
subgraph "Metrics"
Service1 -->|/metrics| Prom[Prometheus]
Service2 -->|/metrics| Prom
Prom --> Grafana[Grafana<br/>Dashboards]
end
subgraph "Logging"
Service1 -->|JSON Logs| Loki
Service2 -->|JSON Logs| Loki
Loki --> GrafanaLogs[Grafana<br/>Log Explorer]
end
subgraph "Tracing"
Service1 -->|Spans| Jaeger
Service2 -->|Spans| Jaeger
Jaeger --> JaegerUI[Jaeger UI]
end
style Prom fill:#d4edda
style Loki fill:#fff4e1
style Jaeger fill:#e1f5ff
Three Pillars of Observability / Ba Trụ cột
1. Metrics (Prometheus + Grafana)
graph LR
Service[Service] -->|Expose /metrics| Prom[Prometheus]
Prom -->|Scrape every 15s| Metrics[Time Series DB]
Metrics --> Grafana[Grafana]
Grafana --> Dashboard1[Request Dashboard]
Grafana --> Dashboard2[Error Dashboard]
Grafana --> Dashboard3[Performance Dashboard]
style Prom fill:#d4edda
style Grafana fill:#e1f5ff
EN: Numerical measurements over time (requests/sec, latency, errors).
VI: Các phép đo số theo thời gian (requests/sec, latency, errors).
Implementation:
import { Counter, Histogram, Gauge } from 'prom-client';
// HTTP request metrics
export const httpRequestDuration = new Histogram({
name: 'http_request_duration_seconds',
help: 'Duration of HTTP requests in seconds',
labelNames: ['method', 'route', 'status'],
buckets: [0.001, 0.01, 0.05, 0.1, 0.5, 1, 2, 5]
});
export const httpRequestTotal = new Counter({
name: 'http_requests_total',
help: 'Total HTTP requests',
labelNames: ['method', 'route', 'status']
});
export const activeRequests = new Gauge({
name: 'http_requests_active',
help: 'Number of active HTTP requests'
});
// Middleware to track metrics
export function metricsMiddleware(req, res, next) {
const start = Date.now();
activeRequests.inc();
res.on('finish', () => {
const duration = (Date.now() - start) / 1000;
httpRequestDuration.observe(
{ method: req.method, route: req.route?.path || req.path, status: res.statusCode },
duration
);
httpRequestTotal.inc({
method: req.method,
route: req.route?.path || req.path,
status: res.statusCode
});
activeRequests.dec();
});
next();
}
2. Logging (Winston + Loki)
sequenceDiagram
participant Service
participant Winston as Winston Logger
participant Loki
participant Grafana
Service->>Winston: Log event
Winston->>Winston: Format JSON
Winston->>Winston: Add metadata<br/>(correlation ID, trace ID)
Winston->>Loki: Push logs
Loki->>Loki: Index & store
User->>Grafana: Query logs
Grafana->>Loki: LogQL query
Loki-->>Grafana: Log results
EN: Structured logging with correlation IDs for request tracing.
VI: Structured logging với correlation IDs để tracing requests.
Implementation:
import winston from 'winston';
export const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: true }),
winston.format.json()
),
defaultMeta: {
service: process.env.SERVICE_NAME || 'unknown-service',
environment: process.env.NODE_ENV || 'development'
},
transports: [
new winston.transports.Console(),
// Loki transport (if configured)
]
});
// Logger middleware
export function loggerMiddleware(req, res, next) {
const correlationId = req.headers['x-correlation-id'] || generateId();
req.correlationId = correlationId;
req.logger = logger.child({ correlationId });
req.logger.info('Incoming request', {
method: req.method,
path: req.path,
ip: req.ip
});
res.on('finish', () => {
req.logger.info('Request completed', {
method: req.method,
path: req.path,
status: res.statusCode,
duration: Date.now() - req.startTime
});
});
next();
}
3. Tracing (OpenTelemetry + Jaeger)
graph LR
Request[Incoming Request] --> Trace[Create Trace]
Trace --> SpanA[Span: HTTP Request]
SpanA --> SpanB[Span: DB Query]
SpanA --> SpanC[Span: Cache Check]
SpanA --> SpanD[Span: External API]
SpanB --> Jaeger[Jaeger]
SpanC --> Jaeger
SpanD --> Jaeger
Jaeger --> Timeline[Trace Timeline]
style Trace fill:#e1f5ff
style Jaeger fill:#d4edda
EN: Distributed tracing to track requests across services.
VI: Distributed tracing để track requests giữa các services.
Implementation:
import { trace, SpanStatusCode } from '@opentelemetry/api';
// Create traced function
export function traced<T>(
name: string,
fn: () => Promise<T>
): Promise<T> {
const tracer = trace.getTracer('app');
const span = tracer.startSpan(name);
return fn()
.then(result => {
span.setStatus({ code: SpanStatusCode.OK });
return result;
})
.catch(error => {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
});
span.recordException(error);
throw error;
})
.finally(() => {
span.end();
});
}
// Usage
async getUserWithTracing(userId: string): Promise<User> {
return traced('getUserById', async () => {
return await userRepository.findById(userId);
});
}
Health Checks / Kiểm tra Sức khỏe
// Liveness probe - is service running?
app.get('/health/live', (req, res) => {
res.json({ status: 'ok', timestamp: new Date().toISOString() });
});
// Readiness probe - is service ready for traffic?
app.get('/health/ready', async (req, res) => {
const checks = {
database: await checkDatabase(),
redis: await checkRedis(),
disk: await checkDiskSpace()
};
const ready = Object.values(checks).every(check => check === true);
res.status(ready ? 200 : 503).json({
ready,
checks,
timestamp: new Date().toISOString()
});
});
async function checkDatabase(): Promise<boolean> {
try {
await prisma.$queryRaw`SELECT 1`;
return true;
} catch {
return false;
}
}
Alerting Rules / Quy tắc Cảnh báo
# Prometheus alerting rules
groups:
- name: service_alerts
interval: 30s
rules:
# High error rate
- alert: HighErrorRate
expr: |
rate(http_requests_total{status=~"5.."}[5m]) > 0.05
for: 2m
labels:
severity: warning
annotations:
summary: "High error rate detected"
description: "Error rate is {{ $value }} (> 5%)"
# High latency
- alert: HighLatency
expr: |
histogram_quantile(0.95, http_request_duration_seconds_bucket) > 1
for: 5m
labels:
severity: warning
annotations:
summary: "High latency detected"
description: "P95 latency is {{ $value }}s"
# Service down
- alert: ServiceDown
expr: up == 0
for: 1m
labels:
severity: critical
annotations:
summary: "Service is down"
Performance Targets / Mục tiêu Hiệu suất
| Metric | Target | Alert Threshold |
|---|---|---|
| Response Time (P95) | < 200ms | > 500ms |
| Response Time (P99) | < 500ms | > 1s |
| Error Rate | < 1% | > 5% |
| Availability | > 99.9% | < 99% |
| Cache Hit Rate | > 80% | < 50% |
Related Documentation / Tài liệu Liên quan
- System Design - Overall architecture
- Caching Architecture - Cache metrics
Last Updated: 2024-01-15
Authors: GoodGo Architecture Team