©Code by Samnoon
Blog
← All posts

observability

An observability stack a small team can run on AWS

The OpenTelemetry Collector, Prometheus and Grafana on one EC2 instance, with alerts nobody learns to ignore.

6 min read

When a team is small, the monitoring setup has to be something one person can understand end to end, because one person is going to be fixing it. That rules out a lot of impressive architecture diagrams.

This post builds a setup that fits: the OpenTelemetry Collector, Prometheus, Alertmanager and Grafana, in Docker Compose on a single EC2 instance. It isn't highly available and doesn't pretend to be. It's small enough to rebuild from Git in half an hour, and for a small team that's worth more than redundancy.

Managed services (CloudWatch, Grafana Cloud, Amazon Managed Service for Prometheus) are worth pricing out first. They charge per metric, per host or per query, but they also take patching, storage and upgrades off your plate. Self-hosting makes sense when that bill would be larger than one small instance and a few hours of upkeep a month, or when the data has to stay in your own account.

The shape

apps (OTLP) ──► OTel Collector ──► Prometheus ──► Grafana
                     ▲                  │
host metrics ────────┘                  └──► Alertmanager ──► Slack

Applications send metrics (and traces, if you want them later) to the Collector over OTLP. The Collector also gathers host metrics, adds resource labels, and exposes everything on one endpoint for Prometheus to scrape. Prometheus stores the data and evaluates the alert rules, Alertmanager sends the notifications, and Grafana draws the dashboards.

You could leave the Collector out. Prometheus 3 can accept OTLP directly if you start it with --web.enable-otlp-receiver. The Collector is still worth keeping, because it gives you batching, a memory limit, host metrics and one place to add or drop attributes, and because it turns a future change of backend into a config change instead of a code change.

Compose file

compose.yaml
services:
  otel-collector:
    image: otel/opentelemetry-collector-contrib:0.115.1
    volumes:
      - ./otelcol.yaml:/etc/otelcol-contrib/config.yaml:ro
      - /:/hostfs:ro
    ports:
      - "4317:4317"
      - "4318:4318"
    restart: unless-stopped
 
  prometheus:
    image: prom/prometheus:v3.1.0
    command:
      - --config.file=/etc/prometheus/prometheus.yml
      - --storage.tsdb.retention.time=15d
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml:ro
      - ./alerts.yml:/etc/prometheus/alerts.yml:ro
      - prometheus-data:/prometheus
    restart: unless-stopped
 
  alertmanager:
    image: prom/alertmanager:v0.28.0
    volumes:
      - ./alertmanager.yml:/etc/alertmanager/alertmanager.yml:ro
      - ./slack-webhook:/etc/alertmanager/slack-webhook:ro
    restart: unless-stopped
 
  grafana:
    image: grafana/grafana:11.4.0
    ports:
      - "127.0.0.1:3000:3000"
    volumes:
      - grafana-data:/var/lib/grafana
    restart: unless-stopped
 
volumes:
  prometheus-data:
  grafana-data:

Pin your image versions. These are the ones this configuration was written against, and it's worth reading the release notes before bumping any of them, the Collector in particular. Grafana only listens on localhost, for reasons that come up below.

Collector config

otelcol.yaml
receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
      http:
        endpoint: 0.0.0.0:4318
  hostmetrics:
    root_path: /hostfs
    collection_interval: 30s
    scrapers:
      cpu: {}
      memory: {}
      load: {}
      filesystem: {}
      network: {}
 
processors:
  memory_limiter:
    check_interval: 1s
    limit_percentage: 80
    spike_limit_percentage: 20
  resourcedetection:
    detectors: [env, ec2, system]
  batch: {}
 
exporters:
  prometheus:
    endpoint: 0.0.0.0:8889
    resource_to_telemetry_conversion:
      enabled: true
 
service:
  pipelines:
    metrics:
      receivers: [otlp, hostmetrics]
      processors: [memory_limiter, resourcedetection, batch]
      exporters: [prometheus]

Three details here have cost people afternoons.

Recent Collector versions bind receivers to localhost by default. Inside a container that means nothing outside can reach them, so those 0.0.0.0 endpoints are required, not decoration.

memory_limiter goes first in the processor list. Its job is to refuse data before the Collector runs out of memory, and it can't do that from the back of the queue.

resource_to_telemetry_conversion copies resource attributes (host name, instance ID, region) onto every metric as Prometheus labels. Without it they only appear in a separate target_info metric, and every query that needs to know which host something came from turns into a join. Option names in this exporter have changed between releases, so check its README for the version you run.

Prometheus and Alertmanager

prometheus.yml
global:
  scrape_interval: 30s
  evaluation_interval: 30s
 
rule_files:
  - /etc/prometheus/alerts.yml
 
alerting:
  alertmanagers:
    - static_configs:
        - targets: ["alertmanager:9093"]
 
scrape_configs:
  - job_name: otel-collector
    honor_labels: true
    static_configs:
      - targets: ["otel-collector:8889"]

honor_labels: true is easy to miss. The Collector already sets job and instance on each series from the service that sent it. Without this line Prometheus overwrites them with its own scrape labels and moves yours to exported_job, so every metric looks like it came from the Collector.

alertmanager.yml
route:
  receiver: team
  group_by: [alertname]
  repeat_interval: 4h
 
receivers:
  - name: team
    slack_configs:
      - api_url_file: /etc/alertmanager/slack-webhook
        channel: "#alerts"
        send_resolved: true

api_url_file reads the webhook URL from a separate file, so the config itself can live in Git without leaking it.

Alerts nobody learns to ignore

The fastest way to ruin monitoring is to alert on everything. After a few weeks of noise people mute the channel, and then the one alert that matters lands where nobody's looking.

So start with very few alerts, all about things users would actually feel:

alerts.yml
groups:
  - name: service
    rules:
      - alert: HighErrorRate
        expr: |
          sum by (job) (rate(http_server_request_duration_seconds_count{http_response_status_code=~"5.."}[5m]))
            /
          sum by (job) (rate(http_server_request_duration_seconds_count[5m]))
            > 0.05
        for: 10m
        labels:
          severity: page
        annotations:
          summary: "{{ $labels.job }}: more than 5% of requests failing"
          runbook: https://wiki.example.com/runbooks/high-error-rate
 
      - alert: SlowRequests
        expr: |
          histogram_quantile(0.95,
            sum by (job, le) (rate(http_server_request_duration_seconds_bucket[5m]))) > 1
        for: 15m
        labels:
          severity: ticket
        annotations:
          summary: "{{ $labels.job }}: p95 latency above 1s"
 
  - name: hosts
    rules:
      - alert: DiskFillingUp
        expr: |
          sum by (host_name, mountpoint) (system_filesystem_usage_bytes{state="used"})
            /
          sum by (host_name, mountpoint) (system_filesystem_usage_bytes)
            > 0.85
        for: 30m
        labels:
          severity: ticket
        annotations:
          summary: "{{ $labels.host_name }} {{ $labels.mountpoint }} is over 85% full"

The metric names follow the OpenTelemetry HTTP semantic conventions, translated into Prometheus naming, so http.server.request.duration becomes http_server_request_duration_seconds. Older or hand-rolled instrumentation will use different names. Look at what's actually in Prometheus before you copy these.

A few rules are worth sticking to. Alert on symptoms, not causes: high CPU isn't a problem if requests are fast and succeeding, while error rate and latency always are. Give every alert a for, so blips that fix themselves never page anyone. Give every paging alert a runbook link, even if the runbook is three lines. And if an alert fires and the honest reaction is "huh, OK", delete it or turn it into a dashboard panel.

One more alert is worth adding on day one: a watchdog rule with expr: vector(1) that always fires, routed to an external dead man's switch service. If that service stops hearing from Alertmanager, your alerting is what's broken, and you'd never find that out from your alerting.

Keep it private

None of these ports belong on the internet. Grafana is bound to localhost in the compose file; reach it through an SSM port forward rather than opening a security group:

aws ssm start-session --target i-0123456789abcdef0 \
  --document-name AWS-StartPortForwardingSession \
  --parameters '{"portNumber":["3000"],"localPortNumber":["3000"]}'

Then Grafana is at localhost:3000 on your own machine. The OTLP ports, 4317 and 4318, only need to be reachable from your application subnets, so restrict the security group to those.

Sizing

Disk is usually what you outgrow first. Prometheus's documentation suggests planning on 1 to 2 bytes per sample, so the estimate is retention in seconds, times samples ingested per second, times 2 bytes. Measure your ingestion rate after a day or two (Prometheus reports it about itself) and size the EBS volume from that instead of guessing.

Keep it in Git

Everything above is plain files, so it lives in a repository. Dashboards should too. Grafana can load dashboards from JSON files through provisioning, and a dashboard someone built by clicking around for an afternoon is one dead disk away from gone. The Prometheus data itself usually isn't worth backing up. Fifteen days of metrics is useful, not precious.

References

#observability #opentelemetry #aws