Implement dead-letter queue (DLQ) functionality for handling permanent failures in message processing. Update configuration to enable DLQ and specify the subject for routing failed messages. Enhance observability by adding metrics for message handling, retries, and database operations. Introduce structured logging for better traceability of message processing events.

This commit is contained in:
windyboy
2025-11-16 09:15:37 +08:00
parent c98baa0ff4
commit a96cb8a40b
12 changed files with 1053 additions and 31 deletions
+74
View File
@@ -0,0 +1,74 @@
## High-Level Architecture and HA / Scaling
### Components
- **NATS / JetStream** message broker providing durable storage and redelivery:
- Stream: `TELEGRAM` (configurable via `nats.stream`).
- Consumer: durable pull consumer per deployment (`nats.consumer`).
- Subjects:
- Inbound telegrams: `subscription.topic` (e.g. `telegram.serial`).
- Parsed telegrams (publisher): `publisher.topic` (e.g. `telegram.json`).
- Dead-letter: `dlq.subject` (e.g. `caatsm.dlq`).
- **Receiver service (`caatsm`)**:
- NATS JetStream **pull consumer** (`internal/infra/nats/consumer.go`).
- Telegram parser and domain model (`internal/app`, `internal/parsers`, `internal/domain`).
- PostgreSQL repository (`internal/infra/postgres`).
- Monitoring/observability server (`internal/infra/monitoring`).
### HA and Failover
- NATS/JetStream is expected to run as a **cluster** with `replicas` configured on the stream to ensure message durability.
- The receiver service is stateless aside from DB side effects and can be deployed with multiple replicas:
- Each replica connects to the same NATS cluster and JetStream stream.
- Durability and at-least-once semantics are handled by JetStream.
Consumer behaviour:
- Pull-based consumption with configurable batch size/timeout (`app.batch_size`, `app.batch_timeout`).
- When a receiver instance stops or crashes:
- Its NATS connection is drained and closed.
- Remaining messages remain in the stream.
- Another healthy instance continues pulling from the durable consumer.
### Scaling and Rebalancing
Scaling out:
- Increase the number of receiver replicas.
- All replicas share the same durable consumer name; for pull-based consumption, each instance independently fetches messages.
- JetStream distributes messages across fetch calls; with more instances, aggregate throughput increases.
Scaling in / failure:
- When replicas are reduced or fail, the remaining instances continue to fetch messages.
- No explicit rebalancing logic is required in the application; JetStream manages which messages are available for pull.
Tuning:
- **Per-instance throughput** is primarily influenced by:
- `app.batch_size`
- `app.batch_timeout`
- the number of concurrent instances
- **Backpressure** is provided through:
- JetStream `backoff` and `max_deliver` settings.
- Additional sleeps in the consumer when many consecutive errors occur.
- Readiness checks exposing DB/NATS health.
### Failure Scenarios
1. **DB outage**:
- Insert operations fail and are treated as transient.
- Messages are NAKed with delay and the error streak causes additional consumer sleep.
- `/readyz` returns 503, signalling this instance should be removed from traffic.
2. **NATS outage**:
- Connection events are logged via `ProvideNATSConn` callbacks.
- The consumer will stop fetching; once NATS is back and reconnected, consumption resumes.
3. **Single instance crash**:
- Other instances continue consuming from JetStream.
- No messages are lost; unacked messages remain pending and will be fetched by surviving instances.
+111
View File
@@ -0,0 +1,111 @@
## Observability
### Metrics
The service exposes Prometheus metrics via the monitoring HTTP server (default `:2112`):
- `caatsm_messages_total{stream,consumer,result}`
Total number of messages handled by the receiver, labelled by stream/consumer and result (`ok`, `fail`, `permanent_fail`, `retry`).
- `caatsm_handle_latency_seconds{stream,consumer}`
End-to-end handling latency from NATS receive to handler completion.
- `caatsm_retries_total{stream,consumer,reason}`
Number of retries (NAKs) issued by the consumer, labelled by reason (e.g. `processor_error`).
- `caatsm_js_api_calls_total{operation}`
JetStream API calls performed by the service.
- `caatsm_db_queries_total{operation,result}`
Database operations grouped by operation (`insert_one`, `insert_batch`, `insert_raw`) and result (`ok`, `error`).
- `caatsm_db_query_latency_seconds{operation}`
DB operation latency.
Additional OTEL metrics are emitted via the configured OTEL endpoint, including:
- `caatsm_messages_processed_total`
- `caatsm_parse_duration_ms`
- `caatsm_publish_failures_total`
- `caatsm_nats_consumer_ack_pending`
- `caatsm_nats_consumer_redelivered`
- `caatsm_nats_consumer_pending`
- `caatsm_nats_consumer_delivered`
These metrics are intended to be scraped by Prometheus (either directly or via the OTEL collector) and visualised in Grafana dashboards. Recommended dashboard panels include:
- Per-stream/consumer message rate and error rate.
- Handling latency P50/P95/P99.
- NATS consumer backlog and redelivery counts.
- DB query rates and latencies.
#### CAATSM Receiver Overview Dashboard
The `caatsm-overview` Grafana dashboard (provisioned from `configs/grafana-dashboards.dev/caatsm-overview.json`) focuses on the CAATSM receiver service and surfaces:
- **Message throughput by result** derived from `caatsm_messages_total{result}`.
- **Per stream/consumer rates** `caatsm_messages_total{stream,consumer}`.
- **End-to-end handle latency** P50/P95/P99 from `caatsm_handle_latency_seconds_bucket`.
- **DB query rate and latency** from `caatsm_db_queries_total` and `caatsm_db_query_latency_seconds_bucket`.
- **Retry and permanent failure rates** from `caatsm_retries_total` and `caatsm_messages_total{result="permanent_fail"}`.
- **Publish failures** from `caatsm_publish_failures_total`.
### Health and Readiness
The monitoring server exposes:
- `/healthz` basic liveness and dependency check.
- `/readyz` readiness endpoint with the same logic as `/healthz`, intended for load balancers / orchestrators.
Checks performed:
- PostgreSQL: `pgxpool.Pool.Ping` with configurable timeout (`monitoring.health_timeout`).
- NATS: connection status must be `CONNECTED`.
A non-200 response indicates the service is not healthy/ready and should be removed from traffic.
### Tracing
Tracing is configured via the `telemetry` section:
- `telemetry.enabled` enables OTEL exporters.
- `telemetry.endpoint` OTLP HTTP endpoint (e.g. `localhost:4318`).
- `telemetry.insecure` disables TLS for local/dev.
Key spans:
- `caatsm/nats`
- `Consumer.processMessage`
- `caatsm/app`
- `MessageProcessor.Handle`
- `Publisher.Publish`
- `caatsm/postgres`
- `Repository.InsertOne`
- `Repository.InsertBatch`
- `Repository.InsertRaw`
Important attributes:
- `nats.subject`, `nats.msg_id`, `nats.js.stream_seq`, `nats.js.consumer_seq`
- `telegram.message_id`, `telegram.category`, `telegram.status`
- `db.table`, `db.inserted`
### Structured Logging Contract
Logging is done with Zap. The `internal/observability/logging` package standardises fields via `MessageFields`:
- `service` logical component (`caatsm-consumer`, `caatsm-processor` etc.).
- `transport_msg_id` NATS/envelope message ID (derived from `Nats-Msg-Id` or JetStream sequence).
- `telegram_message_id` business telegram message ID from the payload.
- `category` telegram category (ARR, DEP, FPL, etc.).
- `stream`, `consumer`, `subject` JetStream context.
- `nats_sequence` JetStream stream sequence, when available.
- `request_id`, `trace_id` correlation identifiers.
- `error_type` high-level classification:
- `business` payload/validation/domain issues; not suitable for retry.
- `transient` network/DB/NATS glitches that may succeed on retry.
- `fatal` programming errors, schema mismatches, or configuration issues requiring operator attention.
Handler and consumer logs should always be emitted through `WithMessageContext` to ensure these fields are present where applicable.
+119
View File
@@ -0,0 +1,119 @@
## Reliability and Fault Handling
This document summarises how the service handles failures, provides resilience, and avoids data loss or duplication.
### Dead-Letter Queue (DLQ) and Poison Messages
Configuration is defined under `dlq`:
```toml
[dlq]
enabled = true
subject = "caatsm.dlq"
```
- When `dlq.enabled` is `true` and `dlq.subject` is non-empty, **permanent** failures are routed to the DLQ subject.
- A permanent failure is indicated by wrapping an error with `app.Permanent` and is treated as a **poison message**.
Behaviour (JetStream mode):
1. The NATS consumer calls `processor.Handle`.
2. If an error is returned and `app.IsPermanent(err)` is true:
- The original NATS message is copied into a DLQ payload with metadata:
- `transport_msg_id` (NATS message ID)
- `subject`, `stream`, `consumer`
- `nats_sequence`, `deliveries`
- `error` (stringified cause)
- `received_at` (DLQ event time)
- `body` (raw message body)
- The payload is published to `dlq.subject` using JetStream.
- The original message is **ACKed**, so it will not be redelivered.
The DLQ subject should be consumed by an offline repair/analysis tool or operational dashboard that can:
- Inspect poison messages.
- Decide whether to fix and re-publish, or discard with justification.
- Track DLQ volume over time for alerting.
### Transient Errors and Backoff
Transient errors (not marked permanent) result in:
- Negative acknowledgements with delay (`NakWithDelay`) according to `nats.consumer_rules.backoff`.
- A retry streak counter inside the consumer:
- Each transient error increases `consecutiveProcessErrors`.
- After 10 or more consecutive errors, the consumer applies an additional **sleep**:
- `backoff = min(consecutive_errors * 100ms, 5s)`.
- A warning log with the sleep duration and error count is emitted.
This combination provides **backpressure** when downstream systems (especially the DB) are in trouble, slowing down consumption instead of aggressively retrying.
### Persistence and Idempotency
The primary persistence path is `Repository.InsertOne` into `aviation.telegrams`. To avoid applying the same business event multiple times, a **minimal idempotency check** is implemented:
- If both `message_id` and `date_time` are non-empty:
- `InsertOne` first calls `messageExists(message_id, date_time)`.
- If a row already exists, the insert is **skipped** and an informational log is written.
- Otherwise, the insert proceeds.
This makes repeated delivery of the same telegram (same `message_id`/`date_time`) safe from a business perspective, even if JetStream redelivers messages or upstream replays.
For higher guarantees in production environments, you may:
- Add a unique index on `(message_id, date_time)` at the DB level, and treat any conflict as a duplicate.
- Extend the idempotency key with additional fields (e.g. originator, category) if required by the business model.
### DB Degradation and Backpressure
Database write failures in `Repository.InsertOne` and related methods are treated as **transient** by default:
- Errors propagate back to the NATS consumer.
- The consumer issues a NAK (with delay) and increases the transient error counter.
- When errors persist, the added sleep in the consumer reduces message throughput and gives the DB time to recover.
DB health also feeds into readiness:
- The monitoring server hits `pgxpool.Pool.Ping` on `/readyz` and `/healthz`.
- If the DB is not reachable, the endpoints return `503`, signalling to orchestrators that this instance should be drained from traffic.
Together, this yields:
- **Backpressure** via reduced consumption rate and NATS-level backoff.
- **Degradation signalling** via health probes for external systems to act upon.
### Retry and Max Deliver
JetStream consumer configuration (via `nats.consumer_rules`) controls:
- `max_deliver` maximum number of redeliveries before JetStream gives up.
- `ack_wait` how long JetStream waits for an ACK before considering the message pending.
- `backoff` per-attempt delays for `NakWithDelay`.
Recommended pattern:
- Keep `max_deliver` modest (e.g. 5).
- Use a backoff array such as `[5s, 30s, 2m]`.
- Treat messages that still fail after `max_deliver` as candidates for DLQ, via the permanent error/poison message path where applicable.
### Alerts and Dashboards
Prometheus alert suggestions:
- High failure rate:
- `rate(caatsm_messages_total{result!="ok"}[5m])` above a small threshold.
- `rate(caatsm_retries_total[5m])` above a threshold.
- DLQ growth:
- Alerts on DLQ stream message count, using NATS/JetStream exporter metrics.
- Readiness / health:
- Alert when `/readyz` fails or when DB/NATS checks start failing consistently.
Dashboards should combine:
- Message rates, error rates, and DLQ rates.
- NATS consumer statistics (pending, redelivered, ack_pending).
- DB health indicators (latency, error counts, connection usage).