Hands-on Lab

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Checked on 2026-11-09 against Grafana 13.3.x and Kibana 9.5.x. Tested with Grafana Enterprise 13.3.0 (the free image, no licence key) and with Elasticsearch and Kibana 9.5.6 on Docker Desktop with 8 GB of memory.

Every other page in this section ends with a "Verify it in the lab" step. This page is the lab: a single Compose project that starts the same application, the same traffic and the same notification receiver in front of either monitoring stack, so that a dashboard or an alert built in Grafana can be compared line by line with the one built in Kibana. Nothing here is specific to a cloud account, a licence key or an outbound network connection once the images are pulled.

What the lab contains

Service Role Profile and port

bookshelf

A small stand-in for the Bookshelf Spring Boot service (see the note below). Serves /api/books, /api/books/{id}, /api/loans and /api/search, exposes Micrometer-style metrics at /actuator/prometheus, writes JSON log lines to a file and to stdout, and exports traces and logs over OTLP.

both; 8080

loadgen

Sends about ten requests per second. A control endpoint switches the traffic between normal, failing, slow, log-errors and stop.

both; 8090

webhook-receiver

Accepts any POST, prints it as one WEBHOOK line and keeps the last 50 deliveries, which any GET returns as JSON. Grafana posts to /grafana, Kibana to /kibana. Inside the network it also answers to the name webhook.lab, because the webhook connector form of Kibana 9.5 rejects a host name without a dot.

both; 8081 on the host, 8080 inside the network

postgres

Holds the placeholder tables book and loan that the Grafana data source pages query.

grafana

alloy

Grafana Alloy: receives OTLP traces and forwards them to Tempo, and tails the JSON log file into Loki with the label application="bookshelf".

grafana; 12345 for its own UI

prometheus

Scrapes bookshelf:8080/actuator/prometheus every 15 seconds. Started with --web.enable-remote-write-receiver, so Tempo’s span metrics and recording rules can be written to it.

grafana; 9090

loki, tempo

Single-binary log and trace stores on local disk. Tempo’s metrics generator writes span metrics to Prometheus.

grafana; 3100 and 3200

grafana

Grafana Enterprise 13.3.0 image (it runs as the open-source edition without a licence). Data sources, the dashboard and the alerting resources are provisioned from files. Alert state history is stored in Loki.

grafana; 3000

edot-collector

The Elastic Distribution of OpenTelemetry Collector in gateway mode: OTLP in, the elasticapm components for the APM views, Elasticsearch out.

kibana

elasticsearch, kibana-setup, kibana

Elasticsearch 9.5.6 with security on and a self-generated trial licence, a one-shot service that sets the kibana_system password, and Kibana 9.5.6.

kibana; 9200 and 5601

Lab topology: loadgen drives bookshelf; bookshelf feeds Alloy, Prometheus, Loki, Tempo and Grafana in one profile or the EDOT Collector, Elasticsearch and Kibana in the other; both notify the webhook receiver

The Bookshelf service in the lab is a stand-in written in about 150 lines of Python with no dependencies, not the Spring Boot application. It produces what the monitoring pages need: the metric names and labels that Micrometer publishes (http_server_requests_seconds_count, _sum and _bucket with application, method, outcome, status and uri, plus hikaricp_connections_active, hikaricp_connections_max and jvm_memory_used_bytes), JSON log lines with level, message, uri, status, trace_id and span_id, and one OTLP trace span per request with the OpenTelemetry HTTP attributes. Its failures are on demand and repeatable, which a real application’s are not. For the real setup of Spring Boot see Metrics and Observability, Logging and the other Bookshelf pages linked from there.

Source: Docker: Using profiles with Compose (services with a profiles list start only when a profile is selected; a service without one always starts), Grafana: Run Grafana Docker image and Elastic: Install Kibana with Docker.

Requirements

  • Docker with the Compose plugin (version 2.20 or later). The files were run with Docker Desktop 29.9 and Compose v2.

  • Memory: the grafana profile used about 1 GB in total; the kibana profile needs 4 GB or more (Elasticsearch alone is capped at 2 GB). Give Docker Desktop at least 6 GB if you run the Kibana profile. Start one profile at a time; they are built to be alternatives.

  • Free host ports 3000, 3100, 3200, 5601, 8080, 8081, 8090, 9090, 9200 and 12345.

  • Images are pulled on the first start: roughly 3 GB for the grafana profile and 4 GB for the kibana profile.

  • The tools curl and jq on the host for the verification commands.

The files

Create a directory (here lab) with this layout. Every listing below is the file exactly as it was run for this page; they are also available as the Antora example files of this repository under modules/ROOT/examples/monitoring-alerting-lab.

lab/
  compose.yaml
  .env
  bookshelf/app.py
  loadgen/loadgen.py
  webhook/receiver.py
  postgres/init.sql
  prometheus/prometheus.yml
  loki/loki.yaml
  tempo/tempo.yaml
  alloy/config.alloy
  grafana/provisioning/datasources/datasources.yaml
  grafana/provisioning/dashboards/dashboards.yaml
  grafana/provisioning/alerting/bookshelf.yaml
  grafana/dashboards/bookshelf-service-health.json
  otel/config.yaml
  kibana/setup.sh
  kibana/bookshelf-service-health.json
  kibana/bookshelf-books.csv

compose.yaml

The one Compose file. The alias otel-gateway points at Alloy in the grafana profile and at the EDOT Collector in the kibana profile, so Bookshelf has the same OTLP endpoint in both. The Elasticsearch and Kibana services are the ones explained on Kibana: Installation & Configuration.

compose.yaml
name: monitoring-lab

services:
  # ---- Shared by both profiles -------------------------------------------------------------
  bookshelf:
    image: python:3.13-slim
    profiles: ["grafana", "kibana"]
    command: ["python", "-u", "/app/app.py"]
    environment:
      DEPLOYMENT_ENVIRONMENT: lab
      OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-gateway:4318
      OTEL_LOGS_EXPORTER: otlp
      LOG_FILE: /logs/bookshelf.log
    volumes:
      - ./bookshelf/app.py:/app/app.py:ro
      - logs:/logs
    ports:
      - "8080:8080"

  loadgen:
    image: python:3.13-slim
    profiles: ["grafana", "kibana"]
    command: ["python", "-u", "/app/loadgen.py"]
    environment:
      TARGET: http://bookshelf:8080
      RATE: "10"
    volumes:
      - ./loadgen/loadgen.py:/app/loadgen.py:ro
    ports:
      - "8090:8090"
    depends_on:
      - bookshelf

  webhook-receiver:
    image: python:3.13-slim
    profiles: ["grafana", "kibana"]
    command: ["python", "-u", "/app/receiver.py"]
    volumes:
      - ./webhook/receiver.py:/app/receiver.py:ro
    ports:
      - "8081:8080"
    # The webhook connector form of Kibana 9.5 rejects a host name without a dot (except localhost),
    # so the receiver also answers to "webhook.lab".
    networks:
      default:
        aliases:
          - webhook.lab

  # ---- Profile grafana ---------------------------------------------------------------------
  postgres:
    image: postgres:17-alpine
    profiles: ["grafana"]
    environment:
      POSTGRES_DB: bookshelf
      POSTGRES_USER: bookshelf
      POSTGRES_PASSWORD: changeme
    volumes:
      - ./postgres/init.sql:/docker-entrypoint-initdb.d/init.sql:ro

  alloy:
    image: grafana/alloy:v1.10.0
    profiles: ["grafana"]
    command: ["run", "--server.http.listen-addr=0.0.0.0:12345", "--storage.path=/var/lib/alloy/data", "/etc/alloy/config.alloy"]
    volumes:
      - ./alloy/config.alloy:/etc/alloy/config.alloy:ro
      - logs:/logs:ro
    ports:
      - "12345:12345"
    networks:
      default:
        aliases: [otel-gateway]

  prometheus:
    image: prom/prometheus:v3.5.0
    profiles: ["grafana"]
    command:
      - --config.file=/etc/prometheus/prometheus.yml
      - --web.enable-remote-write-receiver
      - --storage.tsdb.retention.time=2d
    volumes:
      - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
    ports:
      - "9090:9090"

  loki:
    image: grafana/loki:3.5.0
    profiles: ["grafana"]
    command: ["-config.file=/etc/loki/loki.yaml"]
    volumes:
      - ./loki/loki.yaml:/etc/loki/loki.yaml:ro
    ports:
      - "3100:3100"

  tempo:
    image: grafana/tempo:2.8.0
    profiles: ["grafana"]
    user: root
    command: ["-config.file=/etc/tempo/tempo.yaml"]
    volumes:
      - ./tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro
    ports:
      - "3200:3200"

  grafana:
    image: grafana/grafana-enterprise:13.3.0
    profiles: ["grafana"]
    environment:
      GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:-admin}
      GF_SERVER_ROOT_URL: http://localhost:3000/
      GF_UNIFIED_ALERTING_STATE_HISTORY_ENABLED: "true"
      GF_UNIFIED_ALERTING_STATE_HISTORY_BACKEND: loki
      GF_UNIFIED_ALERTING_STATE_HISTORY_LOKI_REMOTE_URL: http://loki:3100
    volumes:
      - ./grafana/provisioning:/etc/grafana/provisioning
      - ./grafana/dashboards:/var/lib/grafana/dashboards/bookshelf:ro
      - grafana-data:/var/lib/grafana
    ports:
      - "3000:3000"
    depends_on:
      - prometheus
      - loki
      - tempo

  # ---- Profile kibana ----------------------------------------------------------------------
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:9.5.6
    profiles: ["kibana"]
    environment:
      - discovery.type=single-node
      - xpack.security.enabled=true
      - xpack.security.http.ssl.enabled=false
      - xpack.license.self_generated.type=trial
      - ELASTIC_PASSWORD=${ELASTIC_PASSWORD:-lab-elastic-password}
    mem_limit: 2g
    ports:
      - "9200:9200"
    volumes:
      - esdata:/usr/share/elasticsearch/data
    healthcheck:
      test: ["CMD-SHELL", "curl -fsS -u elastic:$${ELASTIC_PASSWORD} 'http://localhost:9200/_cluster/health?wait_for_status=yellow&timeout=5s' >/dev/null"]
      interval: 10s
      timeout: 10s
      retries: 30

  kibana-setup:
    image: docker.elastic.co/elasticsearch/elasticsearch:9.5.6
    profiles: ["kibana"]
    restart: "no"
    depends_on:
      elasticsearch:
        condition: service_healthy
    environment:
      ELASTIC_PASSWORD: ${ELASTIC_PASSWORD:-lab-elastic-password}
      KIBANA_PASSWORD: ${KIBANA_PASSWORD:-lab-kibana-password}
    entrypoint: ["/bin/sh", "-c"]
    command:
      - >
        curl -fsS -X POST -u "elastic:$${ELASTIC_PASSWORD}"
        -H "Content-Type: application/json"
        http://elasticsearch:9200/_security/user/kibana_system/_password
        -d "{\"password\":\"$${KIBANA_PASSWORD}\"}"

  kibana:
    image: docker.elastic.co/kibana/kibana:9.5.6
    profiles: ["kibana"]
    depends_on:
      kibana-setup:
        condition: service_completed_successfully
    environment:
      ELASTICSEARCH_HOSTS: '["http://elasticsearch:9200"]'
      ELASTICSEARCH_USERNAME: kibana_system
      ELASTICSEARCH_PASSWORD: ${KIBANA_PASSWORD:-lab-kibana-password}
      SERVER_PUBLICBASEURL: http://localhost:5601
      XPACK_ENCRYPTEDSAVEDOBJECTS_ENCRYPTIONKEY: ${KIBANA_SAVED_OBJECTS_KEY:-bookshelf-lab-saved-objects-key-0000}
      XPACK_SECURITY_ENCRYPTIONKEY: ${KIBANA_SECURITY_KEY:-bookshelf-lab-security-key-00000000}
      XPACK_REPORTING_ENCRYPTIONKEY: ${KIBANA_REPORTING_KEY:-bookshelf-lab-reporting-key-000000}
    ports:
      - "5601:5601"
    healthcheck:
      test: ["CMD-SHELL", "curl -fsS http://localhost:5601/api/status >/dev/null"]
      interval: 10s
      timeout: 10s
      retries: 30

  edot-collector:
    image: docker.elastic.co/elastic-agent/elastic-otel-collector:9.5.6
    profiles: ["kibana"]
    depends_on:
      elasticsearch:
        condition: service_healthy
    command: ["--config", "/etc/otel/config.yaml"]
    environment:
      ELASTIC_PASSWORD: ${ELASTIC_PASSWORD:-lab-elastic-password}
    volumes:
      - ./otel/config.yaml:/etc/otel/config.yaml:ro
    networks:
      default:
        aliases: [otel-gateway]

volumes:
  logs: {}
  grafana-data: {}
  esdata: {}

.env

The values are lab placeholders. Compose reads this file automatically; every variable also has a default in compose.yaml, so the file is optional. Never reuse these passwords or keys outside the lab.

# Lab-only values. Never reuse these outside the lab.
GRAFANA_ADMIN_PASSWORD=admin
ELASTIC_PASSWORD=lab-elastic-password
KIBANA_PASSWORD=lab-kibana-password
KIBANA_SAVED_OBJECTS_KEY=bookshelf-lab-saved-objects-key-0000
KIBANA_SECURITY_KEY=bookshelf-lab-security-key-00000000
KIBANA_REPORTING_KEY=bookshelf-lab-reporting-key-000000

Save the listing as .env in the lab directory (the file is called env.example in the repository only because Antora ignores files whose names start with a dot).

Bookshelf, the load generator and the webhook receiver

bookshelf/app.py is the stand-in service. The X-Fault request header (set by the load generator) chooses the fault: error answers 70 percent of the requests with a 500 and logs an ERROR line for each, slow adds 0.7 to 1.5 seconds, and log-errors keeps the answers at 200 but logs an ERROR line per request.

bookshelf/app.py
"""Bookshelf stand-in: a small HTTP service that exposes the telemetry of the Bookshelf Spring Boot application."""
import json, math, os, queue, random, threading, time, urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

APP = "bookshelf"
ENV = os.environ.get("DEPLOYMENT_ENVIRONMENT", "lab")
OTLP = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "")
OTLP_LOGS = os.environ.get("OTEL_LOGS_EXPORTER", "none") == "otlp"
LOG_FILE = os.environ.get("LOG_FILE", "")
BUCKETS = [0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0]
ROUTES = ["/api/books", "/api/books/{id}", "/api/loans", "/api/search"]

lock = threading.Lock()
counts, sums, buckets = {}, {}, {}
active = 0
export_q = queue.Queue(maxsize=10000)
started = time.time()


def now_ns():
    return str(time.time_ns())


def attrs(d):
    out = []
    for k, v in d.items():
        if isinstance(v, bool):
            out.append({"key": k, "value": {"boolValue": v}})
        elif isinstance(v, int):
            out.append({"key": k, "value": {"intValue": str(v)}})
        else:
            out.append({"key": k, "value": {"stringValue": str(v)}})
    return out


RESOURCE = {"attributes": attrs({"service.name": APP, "deployment.environment.name": ENV,
                                 "service.version": "1.0.0"})}


def log(level, message, **extra):
    rec = {"timestamp": time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()) + ".%03dZ" % (time.time() * 1000 % 1000),
           "level": level, "logger": "com.irurueta.bookshelf", "message": message, "application": APP}
    rec.update(extra)
    line = json.dumps(rec)
    print(line, flush=True)
    if LOG_FILE:
        with open(LOG_FILE, "a") as f:
            f.write(line + "\n")
    if OTLP and OTLP_LOGS:
        sev = {"INFO": 9, "WARN": 13, "ERROR": 17}[level]
        export_q.put(("logs", {"timeUnixNano": now_ns(), "severityNumber": sev, "severityText": level,
                               "body": {"stringValue": message},
                               "traceId": extra.get("trace_id", ""), "spanId": extra.get("span_id", ""),
                               "attributes": attrs({k: v for k, v in extra.items() if k not in ("trace_id", "span_id")})}))


def exporter():
    spans, logs = [], []
    last = time.time()
    while True:
        try:
            kind, item = export_q.get(timeout=1)
            (spans if kind == "spans" else logs).append(item)
        except queue.Empty:
            pass
        if time.time() - last >= 1 and (spans or logs):
            last = time.time()
            if spans:
                post("/v1/traces", {"resourceSpans": [{"resource": RESOURCE, "scopeSpans": [
                    {"scope": {"name": "bookshelf"}, "spans": spans}]}]})
                spans = []
            if logs:
                post("/v1/logs", {"resourceLogs": [{"resource": RESOURCE, "scopeLogs": [
                    {"scope": {"name": "bookshelf"}, "logRecords": logs}]}]})
                logs = []


def post(path, body):
    try:
        req = urllib.request.Request(OTLP + path, json.dumps(body).encode(), {"Content-Type": "application/json"})
        urllib.request.urlopen(req, timeout=5).read()
    except Exception as e:  # collector down: drop the batch
        print("otlp export failed:", e, flush=True)


def record(uri, method, status, seconds):
    outcome = "SUCCESS" if status < 400 else ("CLIENT_ERROR" if status < 500 else "SERVER_ERROR")
    key = (uri, method, str(status), outcome)
    with lock:
        counts[key] = counts.get(key, 0) + 1
        sums[key] = sums.get(key, 0.0) + seconds
        b = buckets.setdefault(key, [0] * (len(BUCKETS) + 1))
        for i, le in enumerate(BUCKETS):
            if seconds <= le:
                b[i] += 1
        b[-1] += 1


def metrics_text():
    out = ["# TYPE http_server_requests_seconds histogram"]
    with lock:
        for key in sorted(counts):
            uri, method, status, outcome = key
            lab = 'application="%s",method="%s",outcome="%s",status="%s",uri="%s"' % (APP, method, outcome, status, uri)
            for i, le in enumerate(BUCKETS):
                out.append('http_server_requests_seconds_bucket{%s,le="%s"} %d' % (lab, le, buckets[key][i]))
            out.append('http_server_requests_seconds_bucket{%s,le="+Inf"} %d' % (lab, buckets[key][-1]))
            out.append('http_server_requests_seconds_count{%s} %d' % (lab, counts[key]))
            out.append('http_server_requests_seconds_sum{%s} %.6f' % (lab, sums[key]))
        act = active
    out += ["# TYPE hikaricp_connections_active gauge",
            'hikaricp_connections_active{application="%s",pool="HikariPool-1"} %d' % (APP, min(10, act)),
            "# TYPE hikaricp_connections_max gauge",
            'hikaricp_connections_max{application="%s",pool="HikariPool-1"} 10' % APP,
            "# TYPE jvm_memory_used_bytes gauge",
            'jvm_memory_used_bytes{application="%s",area="heap"} %d' % (APP, 180e6 + 20e6 * math.sin(time.time() / 60)),
            "# TYPE process_uptime_seconds gauge",
            'process_uptime_seconds{application="%s"} %.1f' % (APP, time.time() - started)]
    return "\n".join(out) + "\n"


class Handler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def log_message(self, *a):
        pass

    def send(self, status, body, ctype="application/json"):
        data = body.encode()
        self.send_response(status)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        global active
        path = self.path.split("?")[0]
        if path == "/actuator/prometheus":
            return self.send(200, metrics_text(), "text/plain; version=0.0.4")
        if path == "/actuator/health":
            return self.send(200, '{"status":"UP"}')
        if not path.startswith("/api/"):
            return self.send(404, '{"error":"not found"}')
        route = "/api/books/{id}" if path.startswith("/api/books/") else path
        if route not in ROUTES:
            return self.send(404, '{"error":"not found"}')
        fault = self.headers.get("X-Fault", "")
        trace_id, span_id = "%032x" % random.getrandbits(128), "%016x" % random.getrandbits(64)
        start = time.time()
        start_ns = time.time_ns()
        with lock:
            active += 1
        try:
            delay = random.lognormvariate(math.log(0.08), 0.5)
            if fault == "slow":
                delay = random.uniform(0.7, 1.5)
            time.sleep(delay)
            status = 200
            if fault == "error" and random.random() < 0.7:
                status = 500
            elif route == "/api/books/{id}" and random.random() < 0.02:
                status = 404
            if status == 500:
                log("ERROR", "Unhandled exception while serving " + route, uri=route, status=status,
                    trace_id=trace_id, span_id=span_id)
            elif fault == "log-errors":
                log("ERROR", "Loan reminder job failed, retry scheduled", uri=route, status=status,
                    trace_id=trace_id, span_id=span_id)
            elif random.random() < 0.05:
                log("INFO", "Served " + route, uri=route, status=status, trace_id=trace_id, span_id=span_id)
            self.send(status, json.dumps({"route": route, "status": status}))
        finally:
            with lock:
                active -= 1
        seconds = time.time() - start
        record(route, "GET", status, seconds)
        if OTLP:
            export_q.put(("spans", {
                "traceId": trace_id, "spanId": span_id, "name": "GET " + route, "kind": 2,
                "startTimeUnixNano": str(start_ns), "endTimeUnixNano": str(time.time_ns()),
                "attributes": attrs({"http.request.method": "GET", "url.path": path, "http.route": route,
                                     "http.response.status_code": status}),
                "status": {"code": 2 if status >= 500 else 0}}))


if __name__ == "__main__":
    if OTLP:
        threading.Thread(target=exporter, daemon=True).start()
    log("INFO", "Bookshelf started")
    ThreadingHTTPServer(("0.0.0.0", 8080), Handler).serve_forever()
loadgen/loadgen.py
"""Load generator with a control endpoint: POST /mode/<normal|failing|slow|log-errors|stop> on port 8090."""
import os, random, threading, time, urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer

TARGET = os.environ.get("TARGET", "http://bookshelf:8080")
RATE = float(os.environ.get("RATE", "10"))
FAULTS = {"normal": "", "failing": "error", "slow": "slow", "log-errors": "log-errors"}
state = {"mode": "normal"}
URIS = ["/api/books", "/api/books/42", "/api/loans", "/api/search"]


def worker():
    while True:
        mode = state["mode"]
        if mode != "stop":
            req = urllib.request.Request(TARGET + random.choice(URIS), headers={"X-Fault": FAULTS[mode]})
            try:
                urllib.request.urlopen(req, timeout=10).read()
            except Exception:
                pass
        time.sleep(random.expovariate(RATE / 4))  # 4 workers share the rate


class Control(BaseHTTPRequestHandler):
    def log_message(self, *a):
        pass

    def reply(self, text):
        self.send_response(200)
        self.send_header("Content-Length", str(len(text)))
        self.end_headers()
        self.wfile.write(text.encode())

    def do_POST(self):
        name = self.path.rsplit("/", 1)[-1]
        if self.path.startswith("/mode/") and (name in FAULTS or name == "stop"):
            state["mode"] = name
        self.reply("mode=%s\n" % state["mode"])

    def do_GET(self):
        self.reply("mode=%s\n" % state["mode"])


for _ in range(4):
    threading.Thread(target=worker, daemon=True).start()
HTTPServer(("0.0.0.0", 8090), Control).serve_forever()
webhook/receiver.py
"""Webhook receiver: logs every POST (path and body) to stdout and keeps them for GET /received."""
import json, time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

received = []


class H(BaseHTTPRequestHandler):
    def log_message(self, *a):
        pass

    def do_POST(self):
        body = self.rfile.read(int(self.headers.get("Content-Length", 0))).decode(errors="replace")
        entry = {"time": time.strftime("%H:%M:%S"), "path": self.path, "body": body[:20000]}
        received.append(entry)
        print("WEBHOOK", json.dumps(entry), flush=True)
        self.send_response(200)
        self.send_header("Content-Length", "2")
        self.end_headers()
        self.wfile.write(b"ok")

    def do_GET(self):
        data = json.dumps(received[-50:], indent=1).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)


ThreadingHTTPServer(("0.0.0.0", 8080), H).serve_forever()

The Grafana profile files

postgres/init.sql creates the placeholder tables. The Prometheus, Loki, Tempo and Alloy files are the smallest configurations that work for one node; each is explained on the Grafana pages named in the reference lines.

postgres/init.sql
CREATE TABLE book (id serial PRIMARY KEY, title text NOT NULL, author text NOT NULL);
CREATE TABLE loan (id serial PRIMARY KEY, book_id integer REFERENCES book (id), borrowed_at timestamptz DEFAULT now());
INSERT INTO book (title, author) VALUES ('Site Reliability Engineering', 'Beyer et al.'), ('Observability Engineering', 'Majors et al.');
prometheus/prometheus.yml
global:
  scrape_interval: 15s
  evaluation_interval: 15s
scrape_configs:
  - job_name: bookshelf
    metrics_path: /actuator/prometheus
    static_configs:
      - targets: ["bookshelf:8080"]
  - job_name: prometheus
    static_configs:
      - targets: ["localhost:9090"]
loki/loki.yaml
auth_enabled: false
server:
  http_listen_port: 3100
common:
  instance_addr: 127.0.0.1
  path_prefix: /loki
  storage:
    filesystem:
      chunks_directory: /loki/chunks
      rules_directory: /loki/rules
  replication_factor: 1
  ring:
    kvstore:
      store: inmemory
schema_config:
  configs:
    - from: "2024-01-01"
      store: tsdb
      object_store: filesystem
      schema: v13
      index:
        prefix: index_
        period: 24h
limits_config:
  allow_structured_metadata: true
tempo/tempo.yaml
server:
  http_listen_port: 3200
distributor:
  receivers:
    otlp:
      protocols:
        http:
          endpoint: 0.0.0.0:4318
        grpc:
          endpoint: 0.0.0.0:4317
storage:
  trace:
    backend: local
    wal:
      path: /var/tempo/wal
    local:
      path: /var/tempo/blocks
metrics_generator:
  storage:
    path: /var/tempo/generator/wal
    remote_write:
      - url: http://prometheus:9090/api/v1/write
        send_exemplars: true
overrides:
  defaults:
    metrics_generator:
      processors: [service-graphs, span-metrics]
alloy/config.alloy
// Traces: OTLP from Bookshelf to Tempo. Logs: the JSON log file is tailed into Loki.
otelcol.receiver.otlp "default" {
  http {
    endpoint = "0.0.0.0:4318"
  }
  output {
    traces = [otelcol.processor.batch.default.input]
    logs   = [otelcol.processor.batch.default.input]
  }
}

otelcol.processor.batch "default" {
  // Logs that arrive over OTLP are not forwarded: the tailed file below is the source of truth for Loki.
  output {
    traces = [otelcol.exporter.otlphttp.tempo.input]
  }
}

otelcol.exporter.otlphttp "tempo" {
  client {
    endpoint = "http://tempo:4318"
    tls {
      insecure = true
    }
  }
}

local.file_match "bookshelf" {
  path_targets = [{"__path__" = "/logs/bookshelf.log", "application" = "bookshelf", "job" = "bookshelf"}]
}

loki.source.file "bookshelf" {
  targets    = local.file_match.bookshelf.targets
  forward_to = [loki.write.default.receiver]
}

loki.write "default" {
  endpoint {
    url = "http://loki:3100/loki/api/v1/push"
  }
}

Reference: Alloy: otelcol.receiver.otlp, Alloy: loki.source.file, Loki: Configuration, Tempo: Configuration (the metrics generator and its remote_write) and Prometheus: Configuration. The log pipeline is the file route on purpose: the stand-in writes the JSON line to a file on a shared volume, and Alloy sets application="bookshelf" and job="bookshelf" as labels, so the LogQL of the Grafana pages ({application="bookshelf"} | json | level="ERROR") works unchanged. The same log lines are also sent over OTLP; Alloy accepts them and drops them, because only the Elastic profile uses that route.

Grafana is provisioned from three folders that are explained on Data Sources, Dashboards as Code and Provisioning Alerting Resources.

grafana/provisioning/datasources/datasources.yaml
apiVersion: 1
datasources:
  - name: Prometheus
    uid: prometheus
    type: prometheus
    access: proxy
    url: http://prometheus:9090
    isDefault: true
    jsonData:
      timeInterval: 15s
      prometheusType: Prometheus
      prometheusVersion: 3.5.0
  - name: Loki
    uid: loki
    type: loki
    access: proxy
    url: http://loki:3100
    jsonData:
      derivedFields:
        - name: trace_id
          matcherRegex: '"trace_id":\s*"(\w+)"'
          urlDisplayLabel: Trace
          url: "$${__value.raw}"
          datasourceUid: tempo
  - name: Tempo
    uid: tempo
    type: tempo
    access: proxy
    url: http://tempo:3200
    jsonData:
      tracesToLogsV2:
        datasourceUid: loki
        filterByTraceID: true
      serviceMap:
        datasourceUid: prometheus
  - name: TestData
    uid: testdata
    type: grafana-testdata-datasource
    access: proxy
    isDefault: false

The file provisions four data sources: Prometheus (the default), Loki, Tempo and TestData. TestData (type grafana-testdata-datasource, uid testdata) generates random walks, CSV content and other test series inside Grafana, so it needs no back end and works in any panel exercise. PostgreSQL is not provisioned: the Grafana guide Add a Data Source adds it by hand, which is the point of that guide.

grafana/provisioning/dashboards/dashboards.yaml
apiVersion: 1
providers:
  - name: bookshelf
    orgId: 1
    folder: bookshelf
    type: file
    disableDeletion: false
    allowUiUpdates: false
    options:
      path: /var/lib/grafana/dashboards/bookshelf

The alert rules, the contact point, the template, the mute timing and the notification policy tree are one file, walked through on Provisioning Alerting Resources and used on Grafana: Bookshelf End to End. The dashboard JSON is explained on the same end-to-end page.

grafana/provisioning/alerting/bookshelf.yaml
apiVersion: 1

groups:
  - orgId: 1
    name: bookshelf-service-level
    folder: bookshelf
    interval: 1m
    rules:
      - uid: bookshelf-5xx-ratio
        title: Bookshelf high 5xx ratio
        condition: C
        data:
          - refId: A
            relativeTimeRange: { from: 600, to: 0 }
            datasourceUid: prometheus
            model:
              datasource: { type: prometheus, uid: prometheus }
              editorMode: code
              expr: 'sum(rate(http_server_requests_seconds_count{application="bookshelf",status=~"5.."}[5m])) / sum(rate(http_server_requests_seconds_count{application="bookshelf"}[5m]))'
              instant: true
              range: false
              intervalMs: 1000
              maxDataPoints: 43200
              refId: A
          - refId: B
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: A
              reducer: last
              settings: { mode: dropNN }
              refId: B
              type: reduce
          - refId: C
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: B
              conditions:
                - evaluator: { type: gt, params: [0.05] }
                  operator: { type: and }
                  query: { params: [C] }
                  reducer: { type: last, params: [] }
                  type: query
              refId: C
              type: threshold
        noDataState: OK
        execErrState: Error
        for: 2m
        isPaused: false
        annotations:
          summary: 'Bookshelf 5xx ratio is {{ printf "%.1f" $values.B.Value }} (threshold 0.05)'
          description: 'More than 5 percent of Bookshelf requests answered with a 5xx status for 2 minutes.'
          runbook_url: https://example.com/runbooks/bookshelf-5xx-ratio
          __dashboardUid__: bookshelf-service-health
          __panelId__: '2'
        labels:
          application: bookshelf
          team: bookshelf-sre
          severity: critical

      - uid: bookshelf-p95-latency
        title: Bookshelf p95 latency above SLO
        condition: C
        data:
          - refId: A
            relativeTimeRange: { from: 600, to: 0 }
            datasourceUid: prometheus
            model:
              datasource: { type: prometheus, uid: prometheus }
              editorMode: code
              expr: 'histogram_quantile(0.95, sum by (le) (rate(http_server_requests_seconds_bucket{application="bookshelf"}[5m])))'
              instant: true
              range: false
              intervalMs: 1000
              maxDataPoints: 43200
              refId: A
          - refId: B
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: A
              reducer: last
              settings: { mode: dropNN }
              refId: B
              type: reduce
          - refId: C
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: B
              conditions:
                - evaluator: { type: gt, params: [0.5] }
                  operator: { type: and }
                  query: { params: [C] }
                  reducer: { type: last, params: [] }
                  type: query
              refId: C
              type: threshold
        noDataState: OK
        execErrState: Error
        for: 5m
        isPaused: false
        annotations:
          summary: 'Bookshelf p95 latency is {{ printf "%.2f" $values.B.Value }} s (SLO 0.5 s)'
          description: 'The 95th percentile of Bookshelf request latency has been above the 0.5 s objective for 5 minutes.'
          runbook_url: https://example.com/runbooks/bookshelf-latency
        labels:
          application: bookshelf
          team: bookshelf-sre
          severity: warning

      - uid: bookshelf-slo-burn-rate
        title: Bookshelf SLO burn rate
        condition: E
        data:
          - refId: A
            relativeTimeRange: { from: 600, to: 0 }
            datasourceUid: prometheus
            model:
              datasource: { type: prometheus, uid: prometheus }
              editorMode: code
              expr: 'sum(rate(http_server_requests_seconds_count{application="bookshelf",status=~"5.."}[1h])) / sum(rate(http_server_requests_seconds_count{application="bookshelf"}[1h]))'
              instant: true
              range: false
              intervalMs: 1000
              maxDataPoints: 43200
              refId: A
          - refId: B
            relativeTimeRange: { from: 600, to: 0 }
            datasourceUid: prometheus
            model:
              datasource: { type: prometheus, uid: prometheus }
              editorMode: code
              expr: 'sum(rate(http_server_requests_seconds_count{application="bookshelf",status=~"5.."}[5m])) / sum(rate(http_server_requests_seconds_count{application="bookshelf"}[5m]))'
              instant: true
              range: false
              intervalMs: 1000
              maxDataPoints: 43200
              refId: B
          - refId: C
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: A
              reducer: last
              settings: { mode: dropNN }
              refId: C
              type: reduce
          - refId: D
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: B
              reducer: last
              settings: { mode: dropNN }
              refId: D
              type: reduce
          - refId: E
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: '$C > 0.072 && $D > 0.072'
              refId: E
              type: math
        noDataState: OK
        execErrState: Error
        for: 2m
        keepFiringFor: 5m
        isPaused: false
        annotations:
          summary: 'Bookshelf burns its error budget 14.4 times too fast (1h {{ printf "%.3f" $values.C.Value }}, 5m {{ printf "%.3f" $values.D.Value }})'
          description: 'The 5xx ratio exceeds 0.072 in both the 1 hour and the 5 minute window, a 14.4x burn of a 99.5 percent availability objective.'
          runbook_url: https://example.com/runbooks/bookshelf-slo-burn
        labels:
          application: bookshelf
          team: bookshelf-sre
          severity: critical

  - orgId: 1
    name: bookshelf-availability-and-logs
    folder: bookshelf
    interval: 1m
    rules:
      - uid: bookshelf-no-data
        title: Bookshelf no data
        condition: C
        data:
          - refId: A
            relativeTimeRange: { from: 600, to: 0 }
            datasourceUid: prometheus
            model:
              datasource: { type: prometheus, uid: prometheus }
              editorMode: code
              expr: 'max(up{job="bookshelf"})'
              instant: true
              range: false
              intervalMs: 1000
              maxDataPoints: 43200
              refId: A
          - refId: B
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: A
              reducer: last
              settings: { mode: dropNN }
              refId: B
              type: reduce
          - refId: C
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: B
              conditions:
                - evaluator: { type: lt, params: [1] }
                  operator: { type: and }
                  query: { params: [C] }
                  reducer: { type: last, params: [] }
                  type: query
              refId: C
              type: threshold
        noDataState: Alerting
        execErrState: Error
        for: 2m
        isPaused: false
        annotations:
          summary: 'Bookshelf is not reporting metrics or is down'
          description: 'The up series for job bookshelf is missing or 0 for 2 minutes.'
          runbook_url: https://example.com/runbooks/bookshelf-no-data
        labels:
          application: bookshelf
          team: bookshelf-sre
          severity: critical

      - uid: bookshelf-error-log-spike
        title: Bookshelf error-log spike
        condition: C
        data:
          - refId: A
            relativeTimeRange: { from: 600, to: 0 }
            datasourceUid: loki
            model:
              datasource: { type: loki, uid: loki }
              editorMode: code
              expr: 'sum(count_over_time({application="bookshelf"} | json | level="ERROR" [5m]))'
              queryType: instant
              intervalMs: 1000
              maxDataPoints: 43200
              refId: A
          - refId: B
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: A
              reducer: last
              settings: { mode: dropNN }
              refId: B
              type: reduce
          - refId: C
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: B
              conditions:
                - evaluator: { type: gt, params: [20] }
                  operator: { type: and }
                  query: { params: [C] }
                  reducer: { type: last, params: [] }
                  type: query
              refId: C
              type: threshold
        noDataState: OK
        execErrState: Error
        for: 1m
        isPaused: false
        annotations:
          summary: 'Bookshelf logged {{ printf "%.0f" $values.B.Value }} ERROR lines in 5 minutes'
          description: 'More than 20 ERROR log lines in 5 minutes, counted in Loki from the JSON logs of the service.'
          runbook_url: https://example.com/runbooks/bookshelf-error-logs
        labels:
          application: bookshelf
          team: bookshelf-sre
          severity: warning

contactPoints:
  - orgId: 1
    name: bookshelf-webhook
    receivers:
      - uid: bookshelf-webhook
        type: webhook
        disableResolveMessage: false
        settings:
          url: http://webhook-receiver:8080/grafana
          httpMethod: POST
          title: '{{ template "bookshelf.title" . }}'
          message: '{{ template "bookshelf.message" . }}'

templates:
  - orgId: 1
    name: bookshelf
    template: |
      {{ define "bookshelf.title" -}}
      [{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}
      {{- end }}

      {{ define "bookshelf.message" -}}
      {{ range .Alerts -}}
      * {{ .Labels.alertname }} ({{ .Labels.severity }}): {{ .Annotations.summary }}
        {{ if .Annotations.runbook_url }}Runbook: {{ .Annotations.runbook_url }}{{ end }}
      {{ end -}}
      {{- end }}

muteTimes:
  - orgId: 1
    name: bookshelf-weekends
    time_intervals:
      - weekdays: ['saturday', 'sunday']
        location: 'UTC'

policies:
  - orgId: 1
    receiver: bookshelf-webhook
    group_by: ['alertname', 'grafana_folder']
    group_wait: 30s
    group_interval: 5m
    repeat_interval: 4h
    routes:
      - receiver: bookshelf-webhook
        object_matchers:
          - ['team', '=', 'bookshelf-sre']
        routes:
          - receiver: bookshelf-webhook
            object_matchers:
              - ['severity', '=', 'critical']
            group_wait: 10s
            group_interval: 1m
            repeat_interval: 1h
          - receiver: bookshelf-webhook
            object_matchers:
              - ['severity', '=', 'warning']
            mute_time_intervals:
              - bookshelf-weekends
            repeat_interval: 12h
grafana/dashboards/bookshelf-service-health.json
{
  "uid": "bookshelf-service-health",
  "title": "Bookshelf service health",
  "tags": [
    "bookshelf",
    "golden-signals"
  ],
  "timezone": "utc",
  "schemaVersion": 41,
  "version": 1,
  "refresh": "30s",
  "time": {
    "from": "now-6h",
    "to": "now"
  },
  "graphTooltip": 1,
  "editable": true,
  "panels": [
    {
      "id": 20,
      "type": "row",
      "title": "Golden signals",
      "collapsed": false,
      "gridPos": {
        "h": 1,
        "w": 24,
        "x": 0,
        "y": 0
      },
      "panels": []
    },
    {
      "id": 1,
      "type": "stat",
      "title": "Requests per second",
      "description": "Request rate of the whole service.",
      "datasource": {
        "type": "prometheus",
        "uid": "prometheus"
      },
      "gridPos": {
        "h": 4,
        "w": 6,
        "x": 0,
        "y": 1
      },
      "targets": [
        {
          "datasource": {
            "type": "prometheus",
            "uid": "prometheus"
          },
          "editorMode": "code",
          "expr": "sum(rate(http_server_requests_seconds_count{application=\"bookshelf\"}[$__rate_interval]))",
          "legendFormat": "",
          "refId": "A",
          "range": true
        }
      ],
      "fieldConfig": {
        "defaults": {
          "unit": "reqps",
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "green",
                "value": null
              }
            ]
          },
          "mappings": [],
          "color": {
            "mode": "thresholds"
          }
        },
        "overrides": []
      },
      "options": {
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": false
        },
        "colorMode": "background",
        "graphMode": "area"
      }
    },
    {
      "id": 2,
      "type": "stat",
      "title": "5xx ratio",
      "description": "Share of requests answered with a 5xx status. The alert threshold is 0.05.",
      "datasource": {
        "type": "prometheus",
        "uid": "prometheus"
      },
      "gridPos": {
        "h": 4,
        "w": 6,
        "x": 6,
        "y": 1
      },
      "targets": [
        {
          "datasource": {
            "type": "prometheus",
            "uid": "prometheus"
          },
          "editorMode": "code",
          "expr": "sum(rate(http_server_requests_seconds_count{application=\"bookshelf\",status=~\"5..\"}[$__rate_interval])) / sum(rate(http_server_requests_seconds_count{application=\"bookshelf\"}[$__rate_interval]))",
          "legendFormat": "",
          "refId": "A",
          "range": true
        }
      ],
      "fieldConfig": {
        "defaults": {
          "unit": "percentunit",
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "green",
                "value": null
              },
              {
                "color": "red",
                "value": 0.05
              }
            ]
          },
          "mappings": [],
          "color": {
            "mode": "thresholds"
          }
        },
        "overrides": []
      },
      "options": {
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": false
        },
        "colorMode": "background",
        "graphMode": "area"
      }
    },
    {
      "id": 3,
      "type": "stat",
      "title": "p95 latency",
      "description": "95th percentile of the request duration. The latency objective is 0.5 s.",
      "datasource": {
        "type": "prometheus",
        "uid": "prometheus"
      },
      "gridPos": {
        "h": 4,
        "w": 6,
        "x": 12,
        "y": 1
      },
      "targets": [
        {
          "datasource": {
            "type": "prometheus",
            "uid": "prometheus"
          },
          "editorMode": "code",
          "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_requests_seconds_bucket{application=\"bookshelf\"}[$__rate_interval])))",
          "legendFormat": "",
          "refId": "A",
          "range": true
        }
      ],
      "fieldConfig": {
        "defaults": {
          "unit": "s",
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "green",
                "value": null
              },
              {
                "color": "red",
                "value": 0.5
              }
            ]
          },
          "mappings": [],
          "color": {
            "mode": "thresholds"
          }
        },
        "overrides": []
      },
      "options": {
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": false
        },
        "colorMode": "background",
        "graphMode": "area"
      }
    },
    {
      "id": 4,
      "type": "stat",
      "title": "Instances up",
      "description": "Scrape targets of job bookshelf that answer.",
      "datasource": {
        "type": "prometheus",
        "uid": "prometheus"
      },
      "gridPos": {
        "h": 4,
        "w": 6,
        "x": 18,
        "y": 1
      },
      "targets": [
        {
          "datasource": {
            "type": "prometheus",
            "uid": "prometheus"
          },
          "editorMode": "code",
          "expr": "count(up{job=\"bookshelf\"} == 1) or vector(0)",
          "legendFormat": "",
          "refId": "A",
          "range": true
        }
      ],
      "fieldConfig": {
        "defaults": {
          "unit": "none",
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "red",
                "value": null
              },
              {
                "color": "green",
                "value": 1
              }
            ]
          },
          "mappings": [
            {
              "type": "value",
              "options": {
                "0": {
                  "text": "DOWN",
                  "color": "red"
                }
              }
            }
          ],
          "color": {
            "mode": "thresholds"
          }
        },
        "overrides": []
      },
      "options": {
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": false
        },
        "colorMode": "background",
        "graphMode": "area"
      }
    },
    {
      "id": 5,
      "type": "timeseries",
      "title": "Requests per second by status",
      "description": "Request rate split by HTTP status.",
      "datasource": {
        "type": "prometheus",
        "uid": "prometheus"
      },
      "gridPos": {
        "h": 8,
        "w": 12,
        "x": 0,
        "y": 5
      },
      "targets": [
        {
          "datasource": {
            "type": "prometheus",
            "uid": "prometheus"
          },
          "editorMode": "code",
          "expr": "sum by (status) (rate(http_server_requests_seconds_count{job=\"$job\",application=\"$application\",uri=~\"$route\"}[$__rate_interval]))",
          "legendFormat": "{{status}}",
          "refId": "A",
          "range": true
        }
      ],
      "fieldConfig": {
        "defaults": {
          "unit": "reqps",
          "custom": {
            "lineWidth": 1,
            "fillOpacity": 10,
            "thresholdsStyle": {
              "mode": "off"
            }
          }
        },
        "overrides": []
      },
      "options": {
        "tooltip": {
          "mode": "multi"
        }
      }
    },
    {
      "id": 6,
      "type": "timeseries",
      "title": "p95 latency per route",
      "description": "95th percentile per route; the dashed line is the 0.5 s objective.",
      "datasource": {
        "type": "prometheus",
        "uid": "prometheus"
      },
      "gridPos": {
        "h": 8,
        "w": 12,
        "x": 12,
        "y": 5
      },
      "targets": [
        {
          "datasource": {
            "type": "prometheus",
            "uid": "prometheus"
          },
          "editorMode": "code",
          "expr": "histogram_quantile(0.95, sum by (le, uri) (rate(http_server_requests_seconds_bucket{job=\"$job\",application=\"$application\",uri=~\"$route\"}[$__rate_interval])))",
          "legendFormat": "{{uri}}",
          "refId": "A",
          "range": true
        }
      ],
      "fieldConfig": {
        "defaults": {
          "unit": "s",
          "custom": {
            "lineWidth": 1,
            "fillOpacity": 10,
            "thresholdsStyle": {
              "mode": "dashed"
            }
          },
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "green",
                "value": null
              },
              {
                "color": "red",
                "value": 0.5
              }
            ]
          }
        },
        "overrides": []
      },
      "options": {
        "tooltip": {
          "mode": "multi"
        }
      }
    },
    {
      "id": 21,
      "type": "row",
      "title": "Logs and traces",
      "collapsed": false,
      "gridPos": {
        "h": 1,
        "w": 24,
        "x": 0,
        "y": 13
      },
      "panels": []
    },
    {
      "id": 7,
      "type": "logs",
      "title": "Error logs",
      "description": "ERROR lines of the service; open a line to follow its trace_id into Tempo.",
      "datasource": {
        "type": "loki",
        "uid": "loki"
      },
      "gridPos": {
        "h": 8,
        "w": 12,
        "x": 0,
        "y": 14
      },
      "targets": [
        {
          "datasource": {
            "type": "loki",
            "uid": "loki"
          },
          "editorMode": "code",
          "expr": "{application=\"bookshelf\"} | json | level=\"ERROR\"",
          "queryType": "range",
          "refId": "A"
        }
      ],
      "options": {
        "showTime": true,
        "wrapLogMessage": true,
        "sortOrder": "Descending",
        "enableLogDetails": true
      }
    },
    {
      "id": 8,
      "type": "table",
      "title": "Slowest routes",
      "description": "p95 per route, over the dashboard range.",
      "datasource": {
        "type": "prometheus",
        "uid": "prometheus"
      },
      "gridPos": {
        "h": 8,
        "w": 12,
        "x": 12,
        "y": 14
      },
      "targets": [
        {
          "datasource": {
            "type": "prometheus",
            "uid": "prometheus"
          },
          "editorMode": "code",
          "expr": "histogram_quantile(0.95, sum by (le, uri) (rate(http_server_requests_seconds_bucket{job=\"$job\",application=\"$application\",uri=~\"$route\"}[$__rate_interval])))",
          "legendFormat": "{{uri}}",
          "refId": "A",
          "range": false,
          "instant": true,
          "format": "table"
        }
      ],
      "transformations": [
        {
          "id": "organize",
          "options": {
            "excludeByName": {
              "Time": true
            },
            "renameByName": {
              "Value": "p95 (s)"
            }
          }
        },
        {
          "id": "sortBy",
          "options": {
            "fields": {},
            "sort": [
              {
                "field": "p95 (s)",
                "desc": true
              }
            ]
          }
        }
      ],
      "fieldConfig": {
        "defaults": {
          "unit": "s"
        },
        "overrides": []
      }
    },
    {
      "id": 22,
      "type": "row",
      "title": "Dependencies",
      "collapsed": true,
      "gridPos": {
        "h": 1,
        "w": 24,
        "x": 0,
        "y": 22
      },
      "panels": [
        {
          "id": 9,
          "type": "timeseries",
          "title": "JVM heap used",
          "description": "Heap used by the service.",
          "datasource": {
            "type": "prometheus",
            "uid": "prometheus"
          },
          "gridPos": {
            "h": 8,
            "w": 12,
            "x": 0,
            "y": 23
          },
          "targets": [
            {
              "datasource": {
                "type": "prometheus",
                "uid": "prometheus"
              },
              "editorMode": "code",
              "expr": "jvm_memory_used_bytes{application=\"bookshelf\",area=\"heap\"}",
              "legendFormat": "heap",
              "refId": "A",
              "range": true
            }
          ],
          "fieldConfig": {
            "defaults": {
              "unit": "bytes",
              "custom": {
                "lineWidth": 1,
                "fillOpacity": 10,
                "thresholdsStyle": {
                  "mode": "off"
                }
              }
            },
            "overrides": []
          },
          "options": {
            "tooltip": {
              "mode": "multi"
            }
          }
        },
        {
          "id": 10,
          "type": "timeseries",
          "title": "Connection pool utilisation",
          "description": "Active over maximum pool connections.",
          "datasource": {
            "type": "prometheus",
            "uid": "prometheus"
          },
          "gridPos": {
            "h": 8,
            "w": 12,
            "x": 12,
            "y": 23
          },
          "targets": [
            {
              "datasource": {
                "type": "prometheus",
                "uid": "prometheus"
              },
              "editorMode": "code",
              "expr": "hikaricp_connections_active{application=\"bookshelf\"} / hikaricp_connections_max{application=\"bookshelf\"}",
              "legendFormat": "pool",
              "refId": "A",
              "range": true
            }
          ],
          "fieldConfig": {
            "defaults": {
              "unit": "percentunit",
              "custom": {
                "lineWidth": 1,
                "fillOpacity": 10,
                "thresholdsStyle": {
                  "mode": "off"
                }
              }
            },
            "overrides": []
          },
          "options": {
            "tooltip": {
              "mode": "multi"
            }
          }
        }
      ]
    }
  ],
  "templating": {
    "list": [
      {
        "name": "job",
        "label": "Job",
        "type": "query",
        "datasource": {
          "type": "prometheus",
          "uid": "prometheus"
        },
        "definition": "label_values(http_server_requests_seconds_count, job)",
        "query": {
          "qryType": 1,
          "query": "label_values(http_server_requests_seconds_count, job)",
          "refId": "PrometheusVariableQueryEditor-VariableQuery"
        },
        "refresh": 1,
        "sort": 1,
        "current": {
          "text": "bookshelf",
          "value": "bookshelf"
        }
      },
      {
        "name": "application",
        "label": "Application",
        "type": "query",
        "datasource": {
          "type": "prometheus",
          "uid": "prometheus"
        },
        "definition": "label_values(http_server_requests_seconds_count{job=\"$job\"}, application)",
        "query": {
          "qryType": 1,
          "query": "label_values(http_server_requests_seconds_count{job=\"$job\"}, application)",
          "refId": "PrometheusVariableQueryEditor-VariableQuery"
        },
        "refresh": 1,
        "sort": 1,
        "current": {
          "text": "bookshelf",
          "value": "bookshelf"
        }
      },
      {
        "name": "route",
        "label": "Route",
        "type": "query",
        "datasource": {
          "type": "prometheus",
          "uid": "prometheus"
        },
        "definition": "label_values(http_server_requests_seconds_count{job=\"$job\", application=\"$application\"}, uri)",
        "query": {
          "qryType": 1,
          "query": "label_values(http_server_requests_seconds_count{job=\"$job\", application=\"$application\"}, uri)",
          "refId": "PrometheusVariableQueryEditor-VariableQuery"
        },
        "refresh": 2,
        "sort": 1,
        "current": {
          "text": [
            "All"
          ],
          "value": [
            "$__all"
          ]
        },
        "multi": true,
        "includeAll": true,
        "allValue": ".+"
      }
    ]
  },
  "annotations": {
    "list": [
      {
        "builtIn": 1,
        "name": "Annotations & Alerts",
        "datasource": {
          "type": "grafana",
          "uid": "-- Grafana --"
        },
        "enable": true,
        "hide": true,
        "iconColor": "rgba(0, 211, 255, 1)",
        "type": "dashboard",
        "target": {
          "type": "dashboard",
          "limit": 100,
          "matchAny": false,
          "tags": []
        }
      },
      {
        "name": "Deployments",
        "datasource": {
          "type": "grafana",
          "uid": "-- Grafana --"
        },
        "enable": true,
        "hide": false,
        "iconColor": "blue",
        "target": {
          "type": "tags",
          "tags": [
            "bookshelf",
            "deploy"
          ],
          "limit": 100,
          "matchAny": false
        }
      }
    ]
  }
}

The Kibana profile files

otel/config.yaml is the EDOT Collector configuration, and kibana/setup.sh creates the space, data views, connector, rules, SLO, dashboard and maintenance window through the Kibana APIs; both are explained on the Kibana pages named in the reference lines.

otel/config.yaml
receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
      http:
        endpoint: 0.0.0.0:4318

connectors:
  elasticapm: {}

processors:
  batch:
    send_batch_size: 1000
    timeout: 1s
    send_batch_max_size: 1500
  batch/metrics:
    send_batch_max_size: 0
    timeout: 1s
  elasticapm: {}

exporters:
  elasticsearch/otel:
    endpoints: ["http://elasticsearch:9200"]
    user: elastic
    password: ${env:ELASTIC_PASSWORD}
    mapping:
      mode: otel

service:
  pipelines:
    metrics:
      receivers: [otlp]
      processors: [batch/metrics]
      exporters: [elasticsearch/otel]
    logs:
      receivers: [otlp]
      processors: [batch, elasticapm]
      exporters: [elasticsearch/otel]
    traces:
      receivers: [otlp]
      processors: [batch, elasticapm]
      exporters: [elasticapm, elasticsearch/otel]
    metrics/aggregated-otel-metrics:
      receivers: [elasticapm]
      processors: [batch/metrics]
      exporters: [elasticsearch/otel]

Reference: EDOT Collector: default configuration (standalone) (the two Elasticsearch exporter modes, the elasticapm processor and connector, and the aggregated-metrics pipeline) and Kibana: Ingesting Monitoring Data.

The setup script and the dashboard file are explained on Kibana: Bookshelf End to End.

kibana/bookshelf-books.csv is a small catalogue of 30 books with the columns title, author, genre, pages and published_year. It is not loaded by the setup script: the Kibana guide Upload a File and Create a Data View uploads it from the browser, so the reader sees the file upload flow and creates a data view on the result.

kibana/setup.sh
#!/usr/bin/env bash
# Creates the Kibana objects of the Bookshelf lab in the space "bookshelf": space, data views, webhook connector,
# the five alert rules, an availability SLO, a maintenance window and the dashboard.
# Run it once, after Kibana is ready and the load generator has produced some data. Needs curl and jq.
set -euo pipefail
cd "$(dirname "$0")"

export ELASTIC_PASSWORD="${ELASTIC_PASSWORD:-lab-elastic-password}"
export KIBANA_URL="${KIBANA_URL:-http://localhost:5601}"
export KIBANA="$KIBANA_URL/s/bookshelf"
export KAUTH="elastic:$ELASTIC_PASSWORD"
api() { curl -sS -u "$KAUTH" -H 'kbn-xsrf: true' -H 'Content-Type: application/json' "$@"; }

echo "== space"
api -X POST "$KIBANA_URL/api/spaces/space" -d '{
  "id": "bookshelf", "name": "Bookshelf",
  "description": "Bookshelf service dashboards, rules and connectors", "solution": "oblt"
}' | jq -c '{id, solution}'

echo "== data views"
api -X POST "$KIBANA/api/data_views/data_view" -d '{"data_view":{"id":"bookshelf-traces","name":"Bookshelf traces","title":"traces-*","timeFieldName":"@timestamp"}}' | jq -c '.data_view.id'
api -X POST "$KIBANA/api/data_views/data_view" -d '{"data_view":{"id":"bookshelf-logs","name":"Bookshelf logs (OTel)","title":"logs-*.otel-*","timeFieldName":"@timestamp"}}' | jq -c '.data_view.id'

echo "== connector"
api -X POST "$KIBANA/api/actions/connector/bookshelf-webhook" -d '{
  "name": "bookshelf-webhook",
  "connector_type_id": ".webhook",
  "config": {
    "url": "http://webhook-receiver:8080/kibana",
    "method": "post",
    "hasAuth": false,
    "headers": { "Content-Type": "application/json" }
  }
}' | jq -c '{id, is_missing_secrets}'

echo "== helpers that read the action group ids of the rule types"
types() { curl -s -u elastic:"$ELASTIC_PASSWORD" "$KIBANA_URL/s/bookshelf/api/alerting/rule_types"; }
default_group() { types | jq -r --arg t "$1" '.[] | select(.id == $t) | .default_action_group_id'; }
group_named()   { types | jq -r --arg t "$1" --arg n "$2" '.[] | select(.id == $t) | .action_groups[] | select(.name | ascii_downcase == $n) | .id'; }

echo "== rule: high 5xx ratio"
CT=observability.rules.custom_threshold
curl -s -u elastic:"$ELASTIC_PASSWORD" -X POST "$KIBANA_URL/s/bookshelf/api/alerting/rule/bookshelf-5xx-ratio" \
  -H 'kbn-xsrf: true' -H 'Content-Type: application/json' -d @- <<JSON
{
  "name": "Bookshelf high 5xx ratio",
  "rule_type_id": "$CT",
  "consumer": "alerts",
  "tags": ["bookshelf", "bookshelf-sre"],
  "schedule": { "interval": "1m" },
  "params": {
    "criteria": [
      {
        "aggType": "custom",
        "comparator": ">",
        "threshold": [0.05],
        "timeSize": 5,
        "timeUnit": "m",
        "equation": "A / B",
        "label": "5xx ratio",
        "metrics": [
          { "name": "A", "aggType": "count", "filter": "service.name: \"bookshelf\" and http.response.status_code >= 500" },
          { "name": "B", "aggType": "count", "filter": "service.name: \"bookshelf\"" }
        ]
      }
    ],
    "searchConfiguration": { "index": "bookshelf-traces", "query": { "language": "kuery", "query": "" } },
    "alertOnNoData": false,
    "alertOnGroupDisappear": false
  },
  "actions": [
    {
      "id": "bookshelf-webhook",
      "group": "$(group_named $CT alert)",
      "frequency": { "summary": false, "notify_when": "onActionGroupChange", "throttle": null },
      "params": { "body": "{\"rule\":\"{{rule.name}}\",\"reason\":\"{{context.reason}}\",\"url\":\"{{context.viewInAppUrl}}\"}" }
    }
  ]
}
JSON
echo

echo "== rule: p95 latency above SLO"
APM=apm.transaction_duration
curl -s -u elastic:"$ELASTIC_PASSWORD" -X POST "$KIBANA_URL/s/bookshelf/api/alerting/rule/bookshelf-p95-latency" \
  -H 'kbn-xsrf: true' -H 'Content-Type: application/json' -d @- <<JSON
{
  "name": "Bookshelf p95 latency above SLO",
  "rule_type_id": "$APM",
  "consumer": "apm",
  "tags": ["bookshelf", "bookshelf-sre"],
  "schedule": { "interval": "1m" },
  "params": {
    "serviceName": "bookshelf",
    "transactionType": "request",
    "environment": "lab",
    "aggregationType": "95th",
    "threshold": 500,
    "windowSize": 5,
    "windowUnit": "m",
    "groupBy": ["service.name", "service.environment"]
  },
  "actions": [
    {
      "id": "bookshelf-webhook",
      "group": "$(default_group $APM)",
      "frequency": { "summary": false, "notify_when": "onActionGroupChange", "throttle": null },
      "params": { "body": "{\"rule\":\"{{rule.name}}\",\"service\":\"{{context.serviceName}}\",\"value\":\"{{context.triggerValue}}\",\"threshold\":\"{{context.threshold}}\"}" }
    }
  ]
}
JSON
echo

echo "== rule: no data"
curl -s -u elastic:"$ELASTIC_PASSWORD" -X POST "$KIBANA_URL/s/bookshelf/api/alerting/rule/bookshelf-no-data" \
  -H 'kbn-xsrf: true' -H 'Content-Type: application/json' -d @- <<JSON
{
  "name": "Bookshelf no data",
  "rule_type_id": "$CT",
  "consumer": "alerts",
  "tags": ["bookshelf", "bookshelf-sre"],
  "schedule": { "interval": "1m" },
  "params": {
    "criteria": [
      {
        "aggType": "custom",
        "comparator": "<",
        "threshold": [1],
        "timeSize": 5,
        "timeUnit": "m",
        "equation": "A",
        "label": "requests",
        "metrics": [ { "name": "A", "aggType": "count", "filter": "service.name: \"bookshelf\"" } ]
      }
    ],
    "searchConfiguration": { "index": "bookshelf-traces", "query": { "language": "kuery", "query": "" } },
    "noDataBehavior": "alertOnNoData"
  },
  "actions": [
    {
      "id": "bookshelf-webhook",
      "group": "$(group_named $CT 'no data')",
      "frequency": { "summary": false, "notify_when": "onActionGroupChange", "throttle": null },
      "params": { "body": "{\"rule\":\"{{rule.name}}\",\"reason\":\"{{context.reason}}\"}" }
    },
    {
      "id": "bookshelf-webhook",
      "group": "$(group_named $CT alert)",
      "frequency": { "summary": false, "notify_when": "onActionGroupChange", "throttle": null },
      "params": { "body": "{\"rule\":\"{{rule.name}}\",\"reason\":\"{{context.reason}}\"}" }
    }
  ]
}
JSON
echo

echo "== rule: error-log spike"
curl -s -u elastic:"$ELASTIC_PASSWORD" -X POST "$KIBANA_URL/s/bookshelf/api/alerting/rule/bookshelf-error-log-spike" \
  -H 'kbn-xsrf: true' -H 'Content-Type: application/json' -d '{
    "name": "Bookshelf error-log spike",
    "rule_type_id": ".es-query",
    "consumer": "stackAlerts",
    "tags": ["bookshelf", "bookshelf-sre"],
    "schedule": { "interval": "1m" },
    "params": {
      "searchType": "searchSource",
      "searchConfiguration": {
        "index": "bookshelf-logs",
        "query": { "language": "kuery", "query": "severity_text: \"ERROR\"" }
      },
      "aggType": "count",
      "groupBy": "all",
      "excludeHitsFromPreviousRun": false,
      "size": 10,
      "threshold": [20],
      "thresholdComparator": ">",
      "timeWindowSize": 5,
      "timeWindowUnit": "m"
    },
    "actions": [
      {
        "id": "bookshelf-webhook",
        "group": "query matched",
        "frequency": { "summary": false, "notify_when": "onActionGroupChange", "throttle": null },
        "params": {
          "body": "{\"rule\":\"{{rule.name}}\",\"value\":\"{{context.value}}\",\"conditions\":\"{{context.conditions}}\",\"link\":\"{{context.link}}\"}"
        }
      }
    ]
  }'
echo

echo "== SLO and its burn rate rule"
api -X POST "$KIBANA/api/observability/slos" -d '{
  "id": "bookshelf-availability",
  "name": "Bookshelf availability",
  "description": "99.5 percent of requests succeed over 30 days",
  "indicator": {
    "type": "sli.kql.custom",
    "params": {
      "index": "traces-*",
      "timestampField": "@timestamp",
      "filter": "service.name : \"bookshelf\"",
      "good": "http.response.status_code < 500",
      "total": "http.response.status_code : *"
    }
  },
  "timeWindow": { "duration": "30d", "type": "rolling" },
  "budgetingMethod": "occurrences",
  "objective": { "target": 0.995 },
  "tags": ["bookshelf", "lab"]
}'
echo
api -X POST "$KIBANA/api/alerting/rule/bookshelf-slo-burn-rate" -d '{
  "name": "Bookshelf availability burn rate",
  "rule_type_id": "slo.rules.burnRate",
  "consumer": "slo",
  "schedule": { "interval": "1m" },
  "tags": ["bookshelf", "lab"],
  "params": {
    "sloId": "bookshelf-availability",
    "windows": [
      { "id": "w-1h",  "burnRateThreshold": 14.4, "longWindow": { "value": 1,  "unit": "h" }, "shortWindow": { "value": 5,   "unit": "m" }, "actionGroup": "slo.burnRate.alert" },
      { "id": "w-6h",  "burnRateThreshold": 6,    "longWindow": { "value": 6,  "unit": "h" }, "shortWindow": { "value": 30,  "unit": "m" }, "actionGroup": "slo.burnRate.high" },
      { "id": "w-24h", "burnRateThreshold": 3,    "longWindow": { "value": 24, "unit": "h" }, "shortWindow": { "value": 2,   "unit": "h" }, "actionGroup": "slo.burnRate.medium" },
      { "id": "w-72h", "burnRateThreshold": 1,    "longWindow": { "value": 72, "unit": "h" }, "shortWindow": { "value": 6,   "unit": "h" }, "actionGroup": "slo.burnRate.low" }
    ]
  },
  "actions": [
    {
      "id": "bookshelf-webhook", "group": "slo.burnRate.alert",
      "frequency": { "notify_when": "onActionGroupChange", "summary": false },
      "params": { "body": "{\"rule\":\"{{rule.name}}\",\"status\":\"critical burn\",\"reason\":\"{{context.reason}}\",\"link\":\"{{context.alertDetailsUrl}}\"}" }
    },
    {
      "id": "bookshelf-webhook", "group": "slo.burnRate.high",
      "frequency": { "notify_when": "onActionGroupChange", "summary": false },
      "params": { "body": "{\"rule\":\"{{rule.name}}\",\"status\":\"high burn\",\"reason\":\"{{context.reason}}\"}" }
    },
    {
      "id": "bookshelf-webhook", "group": "recovered",
      "frequency": { "notify_when": "onActionGroupChange", "summary": false },
      "params": { "body": "{\"rule\":\"{{rule.name}}\",\"status\":\"recovered\"}" }
    }
  ]
}'
echo

echo "== maintenance window"
api -X POST "$KIBANA/api/maintenance_window" -d '{
  "title": "Bookshelf weekly deploy",
  "enabled": true,
  "schedule": {
    "custom": {
      "start": "2026-11-15T22:00:00.000Z",
      "duration": "1h",
      "timezone": "UTC",
      "recurring": { "every": "1w", "onWeekDay": ["SU"] }
    }
  },
  "scope": { "alerting": { "query": { "kql": "kibana.alert.rule.tags : \"bookshelf\"" } } }
}'
echo

echo "== dashboard"
api -X PUT "$KIBANA/api/dashboards/bookshelf-service-health" -d @bookshelf-service-health.json | jq -c '{id}'
kibana/bookshelf-service-health.json
{
  "title": "Bookshelf service health",
  "description": "RED overview of the Bookshelf service (lab)",
  "time_range": {
    "from": "now-6h",
    "to": "now"
  },
  "refresh_interval": {
    "pause": false,
    "value": 30000
  },
  "query": {
    "language": "kql",
    "expression": ""
  },
  "pinned_panels": [
    {
      "type": "options_list_control",
      "width": "medium",
      "grow": false,
      "config": {
        "title": "Service",
        "data_view_id": "bookshelf-traces",
        "field_name": "service.name"
      }
    }
  ],
  "panels": [
    {
      "grid": {
        "x": 0,
        "y": 0,
        "w": 48,
        "h": 4
      },
      "type": "markdown",
      "config": {
        "content": "## Bookshelf service health\n\nGolden signals from traces and logs. Alert thresholds: 5xx ratio 0.05, p95 0.5 s. Runbook: https://wiki.example.com/bookshelf/runbooks"
      }
    },
    {
      "grid": {
        "x": 0,
        "y": 4,
        "w": 12,
        "h": 6
      },
      "type": "vis",
      "config": {
        "type": "metric",
        "title": "Requests",
        "data_source": {
          "type": "esql",
          "query": "FROM traces-* | WHERE @timestamp >= ?_tstart AND @timestamp < ?_tend AND service.name == \"bookshelf\" | STATS requests = COUNT(*)"
        },
        "metrics": [
          {
            "type": "primary",
            "column": "requests"
          }
        ]
      }
    },
    {
      "grid": {
        "x": 12,
        "y": 4,
        "w": 12,
        "h": 6
      },
      "type": "vis",
      "config": {
        "type": "metric",
        "title": "5xx ratio",
        "data_source": {
          "type": "esql",
          "query": "FROM traces-* | WHERE @timestamp >= ?_tstart AND @timestamp < ?_tend AND service.name == \"bookshelf\" | STATS errors = COUNT(*) WHERE http.response.status_code >= 500, total = COUNT(*) | EVAL ratio = TO_DOUBLE(errors) / total | KEEP ratio"
        },
        "metrics": [
          {
            "type": "primary",
            "column": "ratio"
          }
        ]
      }
    },
    {
      "grid": {
        "x": 24,
        "y": 4,
        "w": 12,
        "h": 6
      },
      "type": "vis",
      "config": {
        "type": "metric",
        "title": "p95 latency (s)",
        "data_source": {
          "type": "esql",
          "query": "FROM traces-* | WHERE @timestamp >= ?_tstart AND @timestamp < ?_tend AND service.name == \"bookshelf\" | STATS p95 = PERCENTILE(duration, 95) | EVAL p95_s = p95 / 1000000000.0 | KEEP p95_s"
        },
        "metrics": [
          {
            "type": "primary",
            "column": "p95_s"
          }
        ]
      }
    },
    {
      "grid": {
        "x": 36,
        "y": 4,
        "w": 12,
        "h": 6
      },
      "type": "vis",
      "config": {
        "type": "metric",
        "title": "ERROR log lines",
        "data_source": {
          "type": "esql",
          "query": "FROM logs-* | WHERE @timestamp >= ?_tstart AND @timestamp < ?_tend AND service.name == \"bookshelf\" AND severity_text == \"ERROR\" | STATS error_lines = COUNT(*)"
        },
        "metrics": [
          {
            "type": "primary",
            "column": "error_lines"
          }
        ]
      }
    },
    {
      "grid": {
        "x": 0,
        "y": 10,
        "w": 24,
        "h": 12
      },
      "type": "vis",
      "config": {
        "type": "xy",
        "title": "Requests over time",
        "layers": [
          {
            "type": "line",
            "data_source": {
              "type": "esql",
              "query": "FROM traces-* | WHERE @timestamp >= ?_tstart AND @timestamp < ?_tend AND service.name == \"bookshelf\" | STATS requests = COUNT() BY BUCKET(@timestamp, 75, ?_tstart, ?_tend)"
            },
            "x": {
              "column": "BUCKET(@timestamp, 75, ?_tstart, ?_tend)"
            },
            "y": [
              {
                "column": "requests"
              }
            ]
          }
        ],
        "axis": {
          "x": {
            "title": {
              "visible": false
            }
          }
        }
      }
    },
    {
      "grid": {
        "x": 24,
        "y": 10,
        "w": 24,
        "h": 12
      },
      "type": "vis",
      "config": {
        "type": "xy",
        "title": "5xx responses over time",
        "layers": [
          {
            "type": "line",
            "data_source": {
              "type": "esql",
              "query": "FROM traces-* | WHERE @timestamp >= ?_tstart AND @timestamp < ?_tend AND service.name == \"bookshelf\" AND http.response.status_code >= 500 | STATS errors = COUNT() BY BUCKET(@timestamp, 75, ?_tstart, ?_tend)"
            },
            "x": {
              "column": "BUCKET(@timestamp, 75, ?_tstart, ?_tend)"
            },
            "y": [
              {
                "column": "errors"
              }
            ]
          }
        ],
        "axis": {
          "x": {
            "title": {
              "visible": false
            }
          }
        }
      }
    },
    {
      "title": "Dependencies",
      "collapsed": true,
      "grid": {
        "y": 22
      },
      "panels": [
        {
          "grid": {
            "x": 0,
            "y": 0,
            "w": 24,
            "h": 8
          },
          "type": "markdown",
          "config": {
            "content": "JVM heap and connection pool panels go here. The lab stand-in exports no metrics to Elasticsearch."
          }
        }
      ]
    }
  ]
}

Start the grafana profile

cd lab
docker compose --profile grafana up -d
docker compose --profile grafana ps

Wait about one minute, then check each component:

curl -s http://localhost:3000/api/health                 # Grafana: "database": "ok", version 13.3.0
curl -s http://localhost:9090/-/ready                    # Prometheus
curl -s http://localhost:3100/ready                      # Loki ("ready" after about 15 seconds)
curl -s http://localhost:3200/ready                      # Tempo
curl -s http://localhost:9090/api/v1/targets | jq -r '.data.activeTargets[] | "\(.labels.job) \(.health)"'
curl -s -u admin:admin http://localhost:3000/api/datasources | jq -r '.[] | "\(.uid) \(.type)"'
curl -s -u admin:admin http://localhost:3000/api/v1/provisioning/alert-rules | jq -r '.[].title'

Expect the targets bookshelf up and prometheus up, the data sources prometheus, loki, tempo and testdata, and five rule titles. Grafana is at http://localhost:3000 (user admin, password admin, from GF_SECURITY_ADMIN_PASSWORD in compose.yaml; change it in the UI if you expose the port). Open Dashboards and the folder bookshelf for "Bookshelf service health", and Alerting for the five rules. A rule file whose folder does not exist creates it, and the dashboard provider finds the same folder by title, so the folder bookshelf exists once; its uid is generated.

To check the telemetry paths:

curl -s -G http://localhost:9090/api/v1/query --data-urlencode 'query=sum(rate(http_server_requests_seconds_count{application="bookshelf"}[1m]))' | jq '.data.result[0].value[1]'
curl -s -G http://localhost:3100/loki/api/v1/query_range --data-urlencode 'query={application="bookshelf"} | json' --data-urlencode limit=1 | jq '.data.result[0].stream.level'
curl -s 'http://localhost:3200/api/search?limit=1' | jq '.traces[0].rootTraceName'

Start the kibana profile

Stop the other profile first (docker compose --profile grafana down), then:

docker compose --profile kibana up -d
until curl -fsS http://localhost:5601/api/status >/dev/null; do sleep 5; done

The one-shot kibana-setup service exits after setting the kibana_system password; docker compose ps -a shows it as exited with code 0. Kibana takes one to two minutes to become ready. Log in at http://localhost:5601 as elastic with the password from .env. The self-generated trial licence is requested by xpack.license.self_generated.type=trial: webhook connectors need a Gold or higher licence and maintenance windows need Platinum, so on a Basic licence those two features are unavailable. Check it with curl -s -u elastic:lab-elastic-password http://localhost:9200/_license | jq .license.type, which prints trial. The trial lasts 30 days from the first start.

Once the load generator has run for a minute or two, create the Kibana objects (the space bookshelf, the data views, the webhook connector, the five rules, the SLO, the maintenance window and the dashboard) with kibana/setup.sh. It needs curl and jq, and reads ELASTIC_PASSWORD (default lab-elastic-password) and KIBANA_URL (default http://localhost:5601), so export the values from .env first:

set -a; . ./.env; set +a
bash kibana/setup.sh

Force the five breaches

The load generator listens on port 8090. A request to /mode/<name> changes the traffic for every later request; GET / shows the current mode. The other pages of this section call the failing mode the failing-request mode and the slow mode the slow mode.

Alert Command What changes Where to look

High 5xx ratio

curl -X POST localhost:8090/mode/failing

70 percent of the requests answer 500 and log an ERROR line.

5xx ratio panel; the rule goes pending, then firing once the condition has held for its pending period.

p95 latency above the SLO

curl -X POST localhost:8090/mode/slow

Every request takes 0.7 to 1.5 seconds, so the 95th percentile passes 0.5 s.

p95 panel and the latency rule.

No data

docker compose stop bookshelf loadgen

The up series turns 0 and the request series vanish; the Kibana trace and log counts fall to 0.

The no-data rule; restart with docker compose start bookshelf loadgen.

Error-log spike

curl -X POST localhost:8090/mode/log-errors

Every request answers 200 and logs an ERROR line, so only the log rule reacts.

The error-log rule and the "Error logs" panel.

SLO burn rate

curl -X POST localhost:8090/mode/failing, and keep it running

The 5xx ratio is far above 0.072 in both the 5 minute and the 1 hour window.

The burn rate rule; in Kibana the SLO page.

Return to healthy traffic with curl -X POST localhost:8090/mode/normal. The measured delays between the change and the first notification at the receiver are on the two end-to-end pages. Read the deliveries with docker compose logs --no-log-prefix webhook-receiver (one WEBHOOK line each) or curl -s localhost:8081, which returns the last 50 as JSON.

Stop and clean up

docker compose --profile grafana --profile kibana down -v
docker ps -a

down -v removes the containers, the network and the named volumes (grafana-data, esdata and the log volume), which is what you want after an experiment: Elasticsearch data and the trial licence start from zero on the next start. Without -v the volumes survive, so provisioned files that you changed are not applied to an existing Grafana database as new resources unless their uid is new.

What can go wrong

  • The kibana profile restarts or exits with code 137. Elasticsearch ran out of memory: raise the Docker Desktop memory or lower the load.

  • Kibana answers 503 for a while. It waits for Elasticsearch to be healthy and then migrates saved objects; check docker compose logs kibana and wait.

  • Both profiles started together. Both define the alias otel-gateway, so Bookshelf’s OTLP traffic would go to either one; always start one profile at a time.

  • The Alloy container exits on start. Components marked experimental are refused by default; the lab configuration uses only generally available components.

  • Rules exist but never fire. Check Alerting, Alert rules for the evaluation state and for health errors; a query error is shown on the rule, and the Prometheus data source must have uid prometheus.

  • Webhook deliveries are missing. Read docker compose logs webhook-receiver first; then the contact point or connector test; a request that never arrives usually means a typo in the host name (webhook-receiver, port 8080, paths /grafana and /kibana).

  • Changing .env has no effect on Elasticsearch passwords. The elastic password is set on the first start with an empty esdata volume; run docker compose down -v to reset it.

  • Dashboards that were edited in the UI revert. The provider has allowUiUpdates: false; edit the JSON file instead.

In the books

Hands-on chapters of Grafana books use Docker containers for their data sources in the same way; Salituro’s Learn Grafana 10.x launches its server containers at the start of the dashboard-design chapter and feeds them an InfluxDB data set. The lab here replaces InfluxDB and the older Graphite and Telegraf examples with Prometheus, Loki and Tempo behind Alloy, which is the stack Grafana documents for new installations, and adds the Elastic side that the books treat as a separate Beats and Logstash world.

Where to go next

The Grafana walk-through is Grafana: Bookshelf End to End and the Kibana one is Kibana: Bookshelf End to End. The concepts behind the five alerts are on Alerting Fundamentals, Designing Actionable Alerts and SLIs, SLOs and Error Budgets; the telemetry paths are on Telemetry Collection Pipelines.

The step-by-step guides use this lab: begin with Grafana Guide: First Steps in Grafana or Kibana Guide: First Steps in Kibana and follow the series, which covers the same tasks as the reference pages one screen at a time.