Orchestrate

Report an issue

Something wrong, out of date or unclear? Tell us. Corrections are prioritized over new topics. You don't need to sign in.

0 / 2000

Don't include personal or confidential company details. Reports are reviewed with AI assistance.

Observability on BTP: logs, metrics, traces and alerts for your workloads

Decide where each BTP workload's logs, metrics and traces go, which SAP services carry them, what wakes someone up, and how to check a design is ready.

Updated Nov 27, 2026
Foundational layer · 8 min read

The 60-second version

Observability is what lets a team answer "what is wrong, and where?" about software that is already running, without logging on to it. Applications on SAP Business Technology Platform (BTP) leave three kinds of evidence. Logs are lines of text the app writes as it works. Metrics are numbers counted over time, such as requests per minute or errors. Traces follow one request through every service it touches.

Out of the box, BTP keeps very little of this. A Cloud Foundry app's logs pass through a short buffer, and once it overflows they are gone. So every production workload needs a decision: where do its logs, metrics and traces go, how long are they kept, and who is woken up when the numbers go wrong?

SAP offers services for each part. SAP Cloud Logging stores and searches the evidence. SAP Alert Notification service turns events into messages for people. SAP Cloud ALM gives central operations a high-level view. SAP Audit Log keeps the security record. Your architects decide which of these to use, what to forward to a company-wide tool, and what "healthy" means for each workload.

Why it matters to the business

When an app on BTP fails, the cost is counted in business terms. Picture the fictional company Calder Pumpworks, which makes industrial pumps. Its customer service clerks use an order-exceptions service on BTP to triage blocked sales orders. In this course's example, the AI model behind it starts refusing calls one morning. For fourteen minutes, about two triage requests in three fail. Clerks retry, then give up and work by hand.

Three things decide how much that morning costs:

  • How fast someone knows. With no alert, the first signal is a clerk's complaint an hour later. With an alert tied to a service level objective, the on-call engineer is paged while the problem is still running.
  • How fast they find the cause. If each service logs in its own format with no shared request ID, the team spends the morning matching timestamps. If every request carries one trace ID through every hop, the failing service shows up in minutes.
  • What the evidence itself costs. Logs that hold customer e-mail addresses are personal data, with retention and deletion duties. Logs kept for seven days can't answer an auditor's question about last month.

The money involved is usually small next to an outage: a production log store, an alerting service and some engineering time to instrument the apps. The larger risk is buying the services and switching on none of the parts that make them useful.

How SAP does it

As of 27 November 2026, four SAP services cover observability for workloads you run on BTP:

Service What it does Who uses it
SAP Cloud Logging Stores and searches logs, metrics and traces from Cloud Foundry, Kyma and other runtimes, on OpenSearch, with dashboards and notifications (SAP's plans page) The team that owns the app
SAP Alert Notification service Turns events from BTP services and your own apps into messages by e-mail, Slack or another alerting tool (product page) On-call engineers
SAP Cloud ALM Central health, exception and business process monitoring; collects data from Java and Node.js apps with OpenTelemetry-based libraries (Expert Portal) Central operations and support
SAP Audit Log Keeps the security record of who did what in your accounts, 90 days by default at no extra cost (BTP documentation) Security and audit

Three facts shape every design. SAP Cloud Logging is instance-based: you create and pay for instances, and the smallest plan is for evaluation only. It accepts the open standard OpenTelemetry, so the same instrumentation can send to another tool later. And SAP Cloud ALM's collection libraries cover Java and Node.js; the Expert Portal page lists none for Python, so Python apps need another route.

What to watch, and where it goes

A decision guide your architect can fill in per workload:

Evidence Question it answers SAP home Forward to a company-wide tool?
Application logs What did the app do, and what went wrong? SAP Cloud Logging Usually errors and warnings only, to control volume
Metrics Is it healthy right now? Is it getting slower? SAP Cloud Logging; SAP Cloud ALM for central health Yes, the few that define each service level objective
Traces Which hop of this request was slow or failed? SAP Cloud Logging Rarely: traces are for the owning team
Alerts Who must act, and how soon? SAP Alert Notification service Yes, into the on-call tool the company already uses
Audit records Who changed what, and when? SAP Audit Log Yes, into the security team's monitoring, before the 90 days run out

A service level objective (SLO) is the written promise behind an alert, for example "99% of triage requests succeed". It turns "the app feels slow" into a number someone owns.

Questions to ask

  1. For each production workload, where do its logs go, and how long are they kept?
  2. Which plan is each SAP Cloud Logging instance on? Is any production data on the evaluation plan?
  3. What is each workload's service level objective, and which alert fires when it is at risk?
  4. Where does an alert go at 3 a.m.? A team channel or on-call tool, or someone's personal mailbox?
  5. Can one request be followed through every service it touches, by one ID?
  6. Do any logs hold personal data, such as customer contact details? Who approved that, and how long is it kept?
  7. Who renews the certificates the apps use to send data, and what happens on the day they expire?
  8. When is the audit log exported, and does it leave BTP before the 90-day default retention ends?

Common misconceptions

  • "BTP keeps our logs." Cloud Foundry streams logs through a buffer meant for watching, not keeping. Without a log store they are lost.
  • "More logs make us safer." Unfiltered debug logs cost money, slow searches, and often carry personal data. Collect what answers a question.
  • "An alert on every error is thorough." It trains people to ignore alerts. Alert on the service level objective being at risk.
  • "SAP Cloud ALM watches everything we build." Its libraries cover Java and Node.js apps. Python apps and third-party tools need their own path.
  • "The audit log is just another log." It is a security record with its own service, categories and retention. Treat it separately.

Key terms

All course terms, A to Z, in the glossary

  • Observability: the ability to tell what is wrong inside running software from the evidence it emits.
  • Log, metric, trace: a line of text about an event; a number counted over time; the path of one request through several services.
  • Service level objective (SLO): a measurable target for a service, such as "99% of requests succeed over 30 days".
  • Error budget: the failures an SLO allows; at 99%, one request in a hundred.
  • SAP Cloud Logging: SAP's instance-based service that stores and searches logs, metrics and traces from BTP workloads.
  • OpenTelemetry: the open standard for producing and sending logs, metrics and traces, supported by SAP Cloud Logging.
  • SAP Alert Notification service: the BTP service that turns events into messages for people and tools.

Check yourself

Pick one answer for each question. The explanation appears after you choose.

1A Cloud Foundry app on BTP has no log store configured. What happens to its logs?

Answer: A. Cloud Foundry streams logs through a buffer meant for watching, not keeping. Every production workload needs a decision about where its logs go. The 90-day figure belongs to SAP Audit Log, which holds security records, not application logs.

2Why does an alert work better when it is tied to a service level objective?

Answer: C. An SLO such as "99% of requests succeed" says how many failures are acceptable. Alerting when that budget is being used up fast wakes people for real problems and keeps quiet about isolated errors.

3Calder's team can't tell which of three services made a triage request fail. What would help most?

Answer: B. A shared trace ID joins the evidence from each hop, so the failing service shows up in minutes. Longer retention, a different runtime or more forwarding don't connect the hops.

4A leader asks whether SAP Cloud ALM will monitor all of Calder's BTP apps. What is the careful answer?

Answer: A. SAP's Expert Portal lists OpenTelemetry-based libraries for Java and Node.js on Cloud Foundry and Kyma, and none for Python. Python workloads can still send OpenTelemetry data to SAP Cloud Logging.

5Which finding should a leader treat as a compliance risk rather than a tuning issue?

Answer: B. Customer contact details in logs are personal data, with retention and deletion duties. Masking them before logging is cheaper than managing them afterwards.

6A production SAP Cloud Logging instance runs on the dev plan. Why does that matter?

Answer: C. SAP's plans page says the dev plan must not be used in production because it lacks replication and auto-scaling and has limited throughput. Plans can't be changed in place, so moving means running a new instance beside the old one.
Deep layer · 40 min read

Mental model

Treat observability as plumbing with a contract at each end. At the source, each workload promises to emit evidence in an agreed shape: structured logs, a few named metrics, and traces that pass the request's ID on. At the destination, each signal has an agreed home, a retention period and an owner. In between, the platform carries the data, and something has to keep the pipes open: certificates, bindings and rate limits.

Most observability failures are not missing tools. They are a broken contract somewhere along the pipe: a service that starts its own trace instead of continuing the caller's, a log line in plain text that nothing can parse, a certificate that expires on a Saturday, an alert that goes to someone who has left. The design work is to write the contract down and check it, the same way the earlier Unit 21 topics check accounts, credentials and connections.

How it works

Three signals and one ID

Each signal answers a different question, and one field connects them:

Signal Shape Answers Volume
Log A timestamped record with a level and a message, ideally JSON with named fields What happened in this request, in this service? High: one or more lines per request
Metric A number with a name and labels, aggregated over time How many, how fast, how full, right now and over weeks? Low: fixed per time interval
Trace A tree of spans, each a timed step with a parent Which step of this request was slow or failed? Medium: often sampled

The connecting field is the trace ID. The W3C Trace Context Recommendation defines how it travels between services: an HTTP header named traceparent with four dash-separated parts, a version (2 hex characters), the trace ID (32), the caller's span ID (16) and flags (2). When every service reads that header, continues the trace, and writes the trace ID into its own log lines, a single search returns the whole story of one request.

How evidence leaves each BTP runtime

flowchart LR
  subgraph CF[Cloud Foundry]
    A[App writes stdout] --> L[Loggregator buffer]
    A2[App with OTel SDK] --> O1[OTLP gRPC + mTLS]
  end
  subgraph KY[Kyma]
    P[Pods] --> T[Telemetry module<br/>Log/Trace/MetricPipeline]
  end
  L -->|syslog drain via binding| CLS[(SAP Cloud Logging)]
  O1 --> CLS
  T -->|OTLP| CLS
  A2 -.Java/Node.js libraries.-> ALM[SAP Cloud ALM]
  CLS --> N[Notifications]
  ANS[SAP Alert Notification] --> ON[On-call channel]
  N --> ANS
  • Cloud Foundry. Apps must write logs to standard output or standard error; Loggregator, the platform's logging component, streams them with the router's request logs. The Cloud Foundry documentation calls this best effort: a slow reader can lose lines. Binding the app to an SAP Cloud Logging instance adds a syslog drain, so the lines are shipped and kept. For traces and custom metrics, the app uses an OpenTelemetry SDK and sends OTLP to the instance's endpoint.
  • Kyma. The Telemetry module runs OpenTelemetry Collector components in the cluster. You declare a LogPipeline, TracePipeline and MetricPipeline, each with an output to a backend (Kyma documentation). The module is vendor-neutral; SAP's guide integrates it with SAP Cloud Logging, and it recommends a central backend outside the cluster for production. Audit logs are out of its scope.
  • ABAP environment. System metrics such as runtime errors and client certificate expiry go to SAP Cloud ALM or SAP Focused Run health monitoring (BTP documentation).

What SAP Cloud Logging does with the data

As of 27 November 2026, per SAP's documentation on GitHub:

  • One OTLP endpoint takes logs, metrics and traces, over gRPC only. Apps that speak OTLP over HTTP need an OpenTelemetry Collector in between to convert (ingestion page). The endpoint is switched off until you set ingest_otlp.enabled on the instance.
  • Mutual TLS only. Each binding or service key carries a client certificate, valid 90 days by default (the binding parameter certValidityDays sets 1 to 180). When it expires, ingestion stops. Deleting a binding doesn't revoke its certificate; rotating the instance's root certificate does, and can invalidate every binding.
  • Retention is set per instance with retention_period: 1 to 90 days, default 7, applied to new indices only (configuration parameters). When the disk fills at maximum scale, the oldest indices are deleted regardless.
  • Plans can't be changed in place. dev is for evaluation only (7.5 GiB, no replication or auto-scaling). standard scales 75 to 375 GiB of net storage and large 750 GiB to 3.75 TiB, both replicated (plans). Pricing is on SAP Discovery Center and SAP's capacity unit estimator.
  • Limits that bite (shipping FAQ): requests over 4 MiB are refused with HTTP 413; an index takes 1,000 fields, about 500 in practice; Loggregator drops its whole queue once it holds more than 10,000 signals; an overloaded instance answers with retryable errors, so senders need retries with exponential backoff.
  • Dashboards are OpenSearch Dashboards. Sign-in goes through SAP Cloud Identity Services, by SAML 2.0 or OpenID Connect, which SAP lists as a prerequisite.

From signal to alert: burn rates

An alert on "any error" pages too often; an alert on "error rate above 5% for an hour" pages too late. Google's Site Reliability Workbook uses the burn rate: how fast a service is using its error budget, relative to the SLO. A burn rate of 1 uses the budget exactly over the SLO period; 14.4 uses 2% of a 30-day budget in one hour. Its starting recommendation pages when both a long and a short window exceed the threshold (14.4 over 1 hour and 5 minutes, or 6 over 6 hours and 30 minutes) and opens a ticket at 1 over 3 days and 6 hours. The short window, about one twelfth of the long one, lets the alert clear soon after the problem stops.

Build it yourself: Calder's observability check

You will write Calder's observability design as data, check it against twelve rules, generate two hours of telemetry for one of its workloads, find the incident hidden in it, and follow one failed request through two services. Then you will fix the design and see what changes. Everything runs on your computer with no account; one optional step uses the real OpenTelemetry SDK.

flowchart LR
  I[--init / --fixed] --> J[calder_observability.json]
  J --> C[--check<br/>rules O01-O12]
  J --> S[--simulate<br/>seed 42]
  S --> T[telemetry/spans.jsonl<br/>telemetry/logs.jsonl]
  T --> A[--analyze<br/>RED, burn rate, joins]
  T --> R[--trace worst]
  C --> W[--write]
  W --> M[calder_observability_readiness.md]

Before you start: complete Set up your computer for this course and Set up for Unit 21. This walkthrough doesn't repeat their steps. It reuses Calder's workloads W01 to W08 from BTP runtimes compared and the subaccounts from the BTP account model.

What you need

  • Python 3 and your orchestrate-course folder with its .venv.
  • No account for Steps 1 to 7 and 9. Step 8 installs two free libraries from PyPI.
  • About 45 minutes. Everything is free.

Step 1: Open the course folder and turn on the virtual environment

  1. Open VS Code, choose File > Open Folder, and open orchestrate-course.

  2. Open a terminal: Terminal > New Terminal.

  3. If the prompt doesn't start with (.venv), turn it on:

    • Windows (PowerShell):

      .venv\Scripts\Activate.ps1
    • macOS / Linux:

      source .venv/bin/activate
  4. The unit21 folder exists from the setup topic. If it doesn't, create it with mkdir unit21.

Step 2: Create the script

  1. In VS Code, create a new file unit21/observability_lab.py.
  2. Paste this code and save. It uses only Python's built-in modules.
"""Calder's observability lab for BTP workloads (course lab, built-in modules only).

Steps:
  --init        write the draft design unit21/calder_observability.json
  --fixed       write the reviewed design (same file)
  --check       check the design against rules O01-O12
  --simulate    write two hours of telemetry (seed 42) into unit21/telemetry/
  --analyze     compute RED numbers, the SLO page alert and trace coverage
  --trace ID    print one trace with its log lines ("worst" = slowest failed request)
  --write       write unit21/calder_observability_readiness.md

All names, numbers, rules and dates are course values for the fictional
Calder Pumpworks. Nothing here talks to SAP BTP.
"""
import argparse
import json
import random
import re
import sys
from datetime import date, datetime, timedelta, timezone
from pathlib import Path

HERE = Path(__file__).resolve().parent
MODEL = HERE / "calder_observability.json"
TEL = HERE / "telemetry"
REPORT = HERE / "calder_observability_readiness.md"
AS_OF = date(2026, 11, 27)

SLO_TARGET = 0.99          # 99% of order-exception requests succeed (course value)
PAGE_BURN = 14.4           # SRE workbook starting value for 1 h / 5 min
START = datetime(2026, 11, 26, 14, 0, tzinfo=timezone.utc)   # 08:00 in Rockford
INCIDENT = (START + timedelta(minutes=98), START + timedelta(minutes=112))  # 15:38-15:51 UTC


def workloads(fixed):
    """The production workloads in the observability design."""
    w = [
        {"id": "W01", "name": "order-exc-api", "runtime": "cloud-foundry",
         "subaccount": "calder-ai-prod", "owner": "00100288",
         "log_target": "cls-ai-prod", "log_format": "json", "trace_propagation": True,
         "masks_personal_data": fixed,
         "alerts": [{"name": "order-exc availability burn", "slo": "99% of requests succeed",
                     "route": "ans-ai-prod", "runbook": "runbooks/order-exc.md"}]},
        {"id": "W02", "name": "distributor-order-status", "runtime": "cloud-foundry",
         "subaccount": "calder-ext-prod", "owner": "00100292",
         "log_target": "cls-ext-prod", "log_format": "json", "trace_propagation": True,
         "masks_personal_data": True,
         "alerts": [{"name": "portal availability burn", "slo": "99.5% of requests succeed",
                     "route": "ans-ext-prod", "runbook": "runbooks/portal.md"}]},
        {"id": "W03", "name": "calder-ai-gw", "runtime": "cloud-foundry",
         "subaccount": "calder-ai-prod", "owner": "00100288",
         "log_target": "cls-ai-prod", "log_format": "json" if fixed else "text",
         "trace_propagation": fixed, "masks_personal_data": True,
         "alerts": [{"name": "gateway upstream 429 rate", "slo": "upstream errors under 2%",
                     "route": "ans-ai-prod", "runbook": "runbooks/ai-gateway.md"}]},
        {"id": "W04", "name": "mes-event-listener", "runtime": "kyma",
         "subaccount": "calder-ext-prod", "owner": "00100292",
         "log_target": "cls-ext-prod", "log_format": "json", "trace_propagation": True,
         "masks_personal_data": True,
         "kyma_pipelines": ["LogPipeline", "TracePipeline", "MetricPipeline"] if fixed
         else ["LogPipeline"],
         "alerts": [{"name": "MES events not processed", "slo": "events processed within 5 min",
                     "route": "ans-ext-prod" if fixed else "email:integration.dev@calder-pumpworks.example",
                     "runbook": "runbooks/mes-listener.md"}]},
        {"id": "W07", "name": "notification-coding-batch", "runtime": "cloud-foundry",
         "subaccount": "calder-ai-prod", "owner": "00100288",
         "log_target": "cls-ai-prod", "log_format": "json", "trace_propagation": True,
         "masks_personal_data": True,
         "alerts": [{"name": "nightly batch did not finish", "slo": "done by 06:00 Rockford",
                     "route": "ans-ai-prod", "runbook": "runbooks/coding-batch.md"}] if fixed else []},
    ]
    return w


def design(fixed):
    return {
        "as_of": AS_OF.isoformat(),
        "version": "reviewed" if fixed else "draft",
        "logging_instances": [
            {"name": "cls-ai-prod", "subaccount": "calder-ai-prod",
             "plan": "standard" if fixed else "dev", "retention_days": 30 if fixed else 7,
             "otlp_enabled": True, "dashboard_sign_in": "ias-saml",
             "otlp_cert_expires": "2027-02-24" if fixed else "2026-12-05"},
            {"name": "cls-ext-prod", "subaccount": "calder-ext-prod", "plan": "standard",
             "retention_days": 30, "otlp_enabled": True, "dashboard_sign_in": "ias-saml",
             "otlp_cert_expires": "2027-02-10"},
        ],
        "alert_routes": [
            {"name": "ans-ai-prod", "service": "alert-notification", "subaccount": "calder-ai-prod",
             "channel": "on-call team channel ai-platform"},
            {"name": "ans-ext-prod", "service": "alert-notification", "subaccount": "calder-ext-prod",
             "channel": "on-call team channel apps-team"},
        ],
        "audit_log": {"export_to": "central SIEM", "export_interval_days": 7 if fixed else 90},
        "workloads": workloads(fixed),
    }


# ---------------------------------------------------------------- rules

def check(model):
    """Return a list of (rule, subject, verdict, message)."""
    out = []
    inst = {i["name"]: i for i in model["logging_instances"]}
    routes = {r["name"] for r in model["alert_routes"]}
    as_of = date.fromisoformat(model["as_of"])

    def add(rule, subject, ok, msg, warn=False):
        out.append((rule, subject, "OK" if ok else ("WARN" if warn else "FAIL"), msg))

    for w in model["workloads"]:
        s = w["id"]
        add("O01", s, w.get("log_target") in inst,
            f"logs to {w.get('log_target')}" if w.get("log_target") in inst
            else "no central log store: cf logs keeps only a small buffer")
        add("O02", s, w["log_format"] == "json",
            "structured JSON logs with trace_id" if w["log_format"] == "json"
            else "plain-text logs: no trace_id field to join on")
        add("O03", s, w["trace_propagation"],
            "passes W3C traceparent on" if w["trace_propagation"]
            else "starts a new trace: calls through it can't be followed end to end")
        alerts = w.get("alerts", [])
        good = [a for a in alerts if a.get("slo") and a.get("runbook")]
        add("O08", s, bool(good),
            f"{len(good)} alert(s) with SLO and runbook" if good
            else "no alert: a failure here is found by its users")
        for a in alerts:
            add("O09", s, a["route"] in routes,
                f"'{a['name']}' routes to {a['route']}" if a["route"] in routes
                else f"'{a['name']}' goes to {a['route']}, a personal mailbox")
        add("O10", s, w["masks_personal_data"],
            "personal data masked before logging" if w["masks_personal_data"]
            else "logs customer contact e-mails")
        if w["runtime"] == "kyma":
            need = {"LogPipeline", "TracePipeline", "MetricPipeline"}
            have = set(w.get("kyma_pipelines", []))
            add("O12", s, need <= have,
                "Telemetry module ships logs, traces and metrics" if need <= have
                else "missing " + ", ".join(sorted(need - have)), warn=True)

    for i in model["logging_instances"]:
        s = i["name"]
        add("O04", s, i["plan"] in ("standard", "large"),
            f"plan {i['plan']}" if i["plan"] in ("standard", "large")
            else f"plan {i['plan']} is for evaluation only: no replication or scaling")
        r = i["retention_days"]
        add("O05", s, 30 <= r <= 90,
            f"retention {r} days" if 30 <= r <= 90
            else f"retention {r} days: below the course minimum of 30")
        days = (date.fromisoformat(i["otlp_cert_expires"]) - as_of).days
        add("O06", s, days >= 14,
            f"OTLP client certificate valid {days} more days" if days >= 14
            else f"OTLP client certificate expires in {days} days: ingestion stops then",
            warn=days >= 0)
        add("O07", s, i["dashboard_sign_in"].startswith("ias"),
            "dashboards sign in through Identity Authentication"
            if i["dashboard_sign_in"].startswith("ias") else "no single sign-on for dashboards")

    days = model["audit_log"]["export_interval_days"]
    add("O11", "audit-log", days <= 30,
        f"exported every {days} days" if days <= 30
        else f"exported every {days} days: the default 90-day retention can lose records first")
    return sorted(out, key=lambda x: (x[0], x[1]))


def print_check(model):
    rows = check(model)
    for rule, subj, verdict, msg in rows:
        print(f"{rule}  {subj:<14} {verdict:<5} {msg}")
    counts = {v: sum(1 for r in rows if r[2] == v) for v in ("OK", "WARN", "FAIL")}
    print(f"\n{counts['OK']} OK, {counts['WARN']} WARN, {counts['FAIL']} FAIL")
    return rows, counts


# ---------------------------------------------------------------- simulation

ORDERS = {"1000002": ("Hallam Fluid Systems", "orders@hallam-fluid.example", "credit"),
          "1000003": ("Brennock Water Utility", "purchasing@brennock-water.example", "sales"),
          "1000004": ("Brennock Water Utility", "purchasing@brennock-water.example", "planning"),
          "1000005": ("Hallam Fluid Systems", "orders@hallam-fluid.example", "pricing"),
          "1000006": ("Brennock Water Utility", "purchasing@brennock-water.example", "billing"),
          "1000007": ("Brennock Water Utility", "purchasing@brennock-water.example", "sales")}


def ts(t):
    return t.isoformat(timespec="milliseconds").replace("+00:00", "Z")


def simulate(model):
    rng = random.Random(42)        # traffic, latencies and failures
    ids = random.Random(43)        # trace and span IDs, so both designs see the same traffic
    w = {x["id"]: x for x in model["workloads"]}
    w01, w03 = w["W01"], w["W03"]
    spans, logs = [], []
    hexid = lambda n: "".join(ids.choice("0123456789abcdef") for _ in range(n))
    t = START
    end = START + timedelta(hours=2)
    while True:
        t += timedelta(seconds=rng.uniform(6, 18))
        if t >= end:
            break
        order = rng.choice(sorted(ORDERS))
        trace = hexid(32)
        root, s4, gw_client = hexid(16), hexid(16), hexid(16)
        s4_ms = rng.randint(180, 420)
        in_incident = INCIDENT[0] <= t < INCIDENT[1]
        attempts, status = [], 200
        for attempt in (1, 2):
            fail = in_incident and rng.random() < 0.85
            attempts.append((rng.randint(900, 2200) if not fail else rng.randint(60, 140), fail))
            if not fail:
                break
        gw_status = 429 if all(f for _, f in attempts) else 200
        gw_ms = sum(ms for ms, _ in attempts) + (500 if len(attempts) == 2 else 0) + 30
        status = 503 if gw_status == 429 else 200
        total = s4_ms + gw_ms + 40
        t_s4 = t + timedelta(milliseconds=20)
        t_gw = t_s4 + timedelta(milliseconds=s4_ms + 10)
        spans.append({"trace_id": trace, "span_id": root, "parent_id": None,
                      "service": "order-exc-api", "name": "POST /exceptions/triage",
                      "start": ts(t), "duration_ms": total, "status": status,
                      "attrs": {"order": order}})
        spans.append({"trace_id": trace, "span_id": s4, "parent_id": root,
                      "service": "order-exc-api", "name": "GET A_SalesOrder via S4_ODATA",
                      "start": ts(t_s4), "duration_ms": s4_ms, "status": 200,
                      "attrs": {"destination": "S4_ODATA", "connector": "SCC-RK-P"}})
        spans.append({"trace_id": trace, "span_id": gw_client, "parent_id": root,
                      "service": "order-exc-api", "name": "POST calder-ai-gw /v1/chat",
                      "start": ts(t_gw), "duration_ms": gw_ms, "status": gw_status, "attrs": {}})
        # the gateway's own server span: same trace only if it reads traceparent
        own_trace, gw_root = hexid(32), hexid(16)
        gw_trace = trace if w03["trace_propagation"] else own_trace
        spans.append({"trace_id": gw_trace, "span_id": gw_root,
                      "parent_id": gw_client if w03["trace_propagation"] else None,
                      "service": "calder-ai-gw", "name": "POST /v1/chat",
                      "start": ts(t_gw + timedelta(milliseconds=5)), "duration_ms": gw_ms - 10,
                      "status": gw_status, "attrs": {"attempts": len(attempts)}})
        tu = t_gw + timedelta(milliseconds=10)
        for n, (ms, fail) in enumerate(attempts, 1):
            spans.append({"trace_id": gw_trace, "span_id": hexid(16), "parent_id": gw_root,
                          "service": "calder-ai-gw", "name": f"generative AI hub call (try {n})",
                          "start": ts(tu), "duration_ms": ms, "status": 429 if fail else 200,
                          "attrs": {}})
            tu += timedelta(milliseconds=ms + 500)
        # log lines
        cust, mail, owner = ORDERS[order]
        contact = "" if w01["masks_personal_data"] else f" contact={mail}"
        done = t + timedelta(milliseconds=total)
        if status == 200:
            logs.append({"time": ts(done), "service": "order-exc-api", "level": "INFO",
                         "trace_id": trace, "msg": f"triaged order {order} owner={owner}{contact}"})
        else:
            logs.append({"time": ts(done), "service": "order-exc-api", "level": "ERROR",
                         "trace_id": trace,
                         "msg": f"gateway answered 429 for order {order}, returned 503{contact}"})
        tu = t_gw + timedelta(milliseconds=10)
        for n, (ms, fail) in enumerate(attempts, 1):
            tu += timedelta(milliseconds=ms)
            if fail:
                line = f"upstream 429 on try {n}"
                if w03["log_format"] == "json":
                    logs.append({"time": ts(tu), "service": "calder-ai-gw", "level": "WARN",
                                 "trace_id": gw_trace, "msg": line})
                else:
                    logs.append({"time": ts(tu), "service": "calder-ai-gw", "level": "WARN",
                                 "trace_id": None, "msg": f"{ts(tu)} WARN {line}"})
            tu += timedelta(milliseconds=500)
    logs.sort(key=lambda x: x["time"])
    TEL.mkdir(exist_ok=True)
    for name, rows in (("spans.jsonl", spans), ("logs.jsonl", logs)):
        with open(TEL / name, "w", encoding="utf-8") as f:
            for r in rows:
                f.write(json.dumps(r) + "\n")
    print(f"Wrote {len(spans)} spans and {len(logs)} log lines to {TEL.relative_to(HERE.parent)}")
    print(f"Design version: {model['version']}. Window {ts(START)} to {ts(end)}.")


# ---------------------------------------------------------------- analysis

def load(name):
    with open(TEL / name, encoding="utf-8") as f:
        return [json.loads(line) for line in f]


def p95(values):
    v = sorted(values)
    return v[max(0, int(round(0.95 * len(v))) - 1)] if v else 0


def parse(t):
    return datetime.fromisoformat(t.replace("Z", "+00:00"))


def analyze():
    spans, logs = load("spans.jsonl"), load("logs.jsonl")
    servers = [s for s in spans if s["parent_id"] is None or s["name"] == "POST /v1/chat"]
    print("RED numbers per service (server spans, two hours)")
    print(f"{'service':<16}{'requests':>9}{'errors':>8}{'error %':>9}{'p95 ms':>8}")
    for svc in ("order-exc-api", "calder-ai-gw"):
        rows = [s for s in servers if s["service"] == svc]
        err = [s for s in rows if s["status"] >= 500 or s["status"] == 429]
        print(f"{svc:<16}{len(rows):>9}{len(err):>8}{100 * len(err) / len(rows):>8.1f}%"
              f"{p95([s['duration_ms'] for s in rows]):>8}")

    roots = sorted([s for s in spans if s["service"] == "order-exc-api" and s["parent_id"] is None],
                   key=lambda s: s["start"])
    ev = [(parse(s["start"]), s["status"] >= 500) for s in roots]
    budget = 1 - SLO_TARGET
    print(f"\nSLO: {SLO_TARGET:.0%} of order-exception requests succeed. "
          f"Page when the 1 h and 5 min error rates both exceed {PAGE_BURN} x {budget:.0%} "
          f"= {PAGE_BURN * budget:.1%}.")
    fired = resolved = None
    minute = START + timedelta(hours=1)
    end = START + timedelta(hours=2)
    while minute <= end:
        def rate(win):
            sel = [e for t, e in ev if minute - win < t <= minute]
            return (sum(sel) / len(sel)) if sel else 0.0
        long_r, short_r = rate(timedelta(hours=1)), rate(timedelta(minutes=5))
        firing = long_r > PAGE_BURN * budget and short_r > PAGE_BURN * budget
        if firing and not fired:
            fired = (minute, long_r, short_r)
        if fired and not firing and not resolved:
            resolved = (minute, long_r, short_r)
        minute += timedelta(minutes=1)
    local = lambda t: (t - timedelta(hours=6)).strftime("%H:%M")
    print(f"Incident window (built in): {local(INCIDENT[0])} to {local(INCIDENT[1])} Rockford time")
    if fired:
        print(f"Page fires at {local(fired[0])} (1 h {fired[1]:.1%}, 5 min {fired[2]:.1%}, "
              f"burn rate {fired[1] / budget:.1f})")
    else:
        print("Page does not fire")
    if resolved:
        print(f"Page resolves at {local(resolved[0])} (5 min {resolved[2]:.1%})")
    failed = sum(e for _, e in ev)
    print(f"Failed requests in the two hours: {failed} of {len(ev)} "
          f"(the {SLO_TARGET:.0%} target allows {len(ev) * budget:.0f})")

    by_trace = {}
    for s in spans:
        by_trace.setdefault(s["trace_id"], set()).add(s["service"])
    joined = sum(1 for r in roots if "calder-ai-gw" in by_trace[r["trace_id"]])
    print(f"\nTraces that reach the gateway: {joined} of {len(roots)}")
    for svc in ("order-exc-api", "calder-ai-gw"):
        rows = [l for l in logs if l["service"] == svc]
        with_id = sum(1 for l in rows if l.get("trace_id"))
        print(f"Log lines with trace_id, {svc}: {with_id} of {len(rows)}")
    mail = re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+")
    pii = sum(1 for l in logs if mail.search(l["msg"]))
    print(f"Log lines with an e-mail address: {pii}")
    worst = max((r for r in roots if r["status"] >= 500), key=lambda r: r["duration_ms"], default=None)
    if worst:
        print(f"\nSlowest failed request: trace {worst['trace_id']} ({worst['duration_ms']} ms)")


def trace(trace_id):
    spans, logs = load("spans.jsonl"), load("logs.jsonl")
    if trace_id == "worst":
        roots = [s for s in spans if s["parent_id"] is None and s["service"] == "order-exc-api"
                 and s["status"] >= 500]
        if not roots:
            sys.exit("No failed request in this run.")
        trace_id = max(roots, key=lambda r: r["duration_ms"])["trace_id"]
    mine = [s for s in spans if s["trace_id"] == trace_id]
    if not mine:
        sys.exit(f"No spans for trace {trace_id}.")
    kids = {}
    for s in mine:
        kids.setdefault(s["parent_id"], []).append(s)
    print(f"Trace {trace_id}")

    def show(parent, depth):
        for s in sorted(kids.get(parent, []), key=lambda x: x["start"]):
            print(f"{'  ' * depth}{s['service']:<14} {s['name']:<34} "
                  f"{s['duration_ms']:>6} ms  status {s['status']}")
            show(s["span_id"], depth + 1)
    show(None, 0)
    ids = {s["span_id"] for s in mine}
    orphans = [s for s in mine if s["parent_id"] and s["parent_id"] not in ids]
    for s in orphans:
        show(s["parent_id"], 0)
    print("Log lines:")
    for l in sorted(logs, key=lambda x: x["time"]):
        if l.get("trace_id") == trace_id:
            print(f"  {l['time']} {l['service']:<14} {l['level']:<5} {l['msg']}")
    gw = [s for s in mine if s["service"] == "calder-ai-gw"]
    if not gw:
        print("  (no gateway spans in this trace: the gateway started its own trace)")


def write_report(model):
    rows = check(model)
    lines = [f"# Calder observability readiness ({model['version']} design, {model['as_of']})", "",
             "Course document for the fictional Calder Pumpworks. Rules O01-O12 are course rules.", "",
             "| Rule | Subject | Verdict | Finding |", "| --- | --- | --- | --- |"]
    lines += [f"| {r} | {s} | {v} | {m} |" for r, s, v, m in rows]
    lines += ["", "## Owners", ""]
    lines += [f"- {w['id']} {w['name']}: {w['owner']}" for w in model["workloads"]]
    REPORT.write_text("\n".join(lines) + "\n", encoding="utf-8")
    print(f"Wrote {REPORT.relative_to(HERE.parent)} ({len(rows)} findings)")


def main():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
    g = p.add_mutually_exclusive_group(required=True)
    g.add_argument("--init", action="store_true")
    g.add_argument("--fixed", action="store_true")
    g.add_argument("--check", action="store_true")
    g.add_argument("--simulate", action="store_true")
    g.add_argument("--analyze", action="store_true")
    g.add_argument("--trace", metavar="ID")
    g.add_argument("--write", action="store_true")
    p.add_argument("--model", default=str(MODEL))
    a = p.parse_args()
    path = Path(a.model)
    if a.init or a.fixed:
        path.write_text(json.dumps(design(a.fixed), indent=2) + "\n", encoding="utf-8")
        print(f"Wrote {path.name} ({'reviewed' if a.fixed else 'draft'} design)")
        return
    if a.analyze:
        return analyze()
    if a.trace:
        return trace(a.trace)
    if not path.exists():
        sys.exit(f"{path.name} not found. Run with --init first.")
    model = json.loads(path.read_text(encoding="utf-8"))
    if a.check:
        _, counts = print_check(model)
        sys.exit(2 if counts["FAIL"] else 0)
    if a.simulate:
        return simulate(model)
    if a.write:
        return write_report(model)


if __name__ == "__main__":
    main()

Step 3: Write the draft design and check it

  1. Write Calder's draft observability design. This is the design a partner proposed for the five production workloads:

    python unit21/observability_lab.py --init
  2. Check it:

    python unit21/observability_lab.py --check
  3. You should see 39 lines ending like this:

    O09  W04            FAIL  'MES events not processed' goes to email:integration.dev@calder-pumpworks.example, a personal mailbox
    O10  W01            FAIL  logs customer contact e-mails
    ...
    O11  audit-log      FAIL  exported every 90 days: the default 90-day retention can lose records first
    O12  W04            WARN  missing MetricPipeline, TracePipeline
    
    29 OK, 2 WARN, 8 FAIL

    The script exits with code 2 because something failed, so a pipeline could stop on it. The eight failures: the AI gateway (W03) logs plain text and starts its own trace; the AI log store cls-ai-prod is on the dev plan with 7 days of retention; the nightly batch (W07) has no alert; the MES listener's alert goes to a personal mailbox; the order-exceptions API (W01) logs customer e-mails; and the audit log is exported only every 90 days. The two warnings: cls-ai-prod's OTLP certificate expires in 8 days, and the Kyma workload ships logs but no traces or metrics.

Step 4: Generate two hours of telemetry

  1. Generate the telemetry for the order-exceptions API (W01) and the AI gateway (W03) between 08:00 and 10:00 Rockford time on Thursday 26 November 2026:

    python unit21/observability_lab.py --simulate
  2. You should see:

    Wrote 3002 spans and 692 log lines to unit21/telemetry
    Design version: draft. Window 2026-11-26T14:00:00.000Z to 2026-11-26T16:00:00.000Z.

    On Windows the folder shows as unit21\telemetry.

  3. Open unit21/telemetry/spans.jsonl in VS Code. Each line is one span: its trace ID, its own ID, its parent's ID, the service, the step's name, start time, duration and HTTP status. Each triage request reads the sales order through the destination S4_ODATA and the Cloud Connector SCC-RK-P, then asks the AI gateway, which calls the generative AI hub.

The simulation hides one incident: from 09:38 to 09:52 the generative AI hub refuses most calls with HTTP 429 (too many requests). The gateway retries once, then gives up, and W01 answers the clerk with 503. Times are stored in UTC, six hours ahead of Rockford.

Step 5: Find the incident

  1. Run the analysis:

    python unit21/observability_lab.py --analyze
  2. You should see:

    RED numbers per service (server spans, two hours)
    service          requests  errors  error %  p95 ms
    order-exc-api         589      46     7.8%    2482
    calder-ai-gw          589      46     7.8%    2133
    
    SLO: 99% of order-exception requests succeed. Page when the 1 h and 5 min error rates both exceed 14.4 x 1% = 14.4%.
    Incident window (built in): 09:38 to 09:52 Rockford time
    Page fires at 09:51 (1 h 14.5%, 5 min 73.9%, burn rate 14.5)
    Page resolves at 09:56 (5 min 13.6%)
    Failed requests in the two hours: 46 of 589 (the 99% target allows 6)
    
    Traces that reach the gateway: 0 of 589
    Log lines with trace_id, order-exc-api: 589 of 589
    Log lines with trace_id, calder-ai-gw: 0 of 103
    Log lines with an e-mail address: 589
    
    Slowest failed request: trace 11d274891d1565998c4fb14d45864576 (1205 ms)

Read it in three parts:

  • The alert. The 5-minute window is above 14.4% from the first minutes of the incident, but the 1-hour window crosses only at 09:51, thirteen minutes in. That is the price of the 1-hour window: it protects against short blips. The workbook's 6-hour and 30-minute page would not fire here at all, because this lab assumes nothing before 08:00 and the 6-hour window can't be filled. The page clears five minutes after the errors stop, thanks to the short window.
  • The error budget. At 99%, these 589 requests allow 6 failures. Fourteen minutes used 46, nearly eight times what the whole two hours allowed.
  • The joins. No trace reaches the gateway, and none of the gateway's 103 warnings carries a trace ID. The draft gateway starts a new trace for every call and logs plain text, so its evidence can't be tied to W01's requests. Every W01 log line also holds a customer's e-mail address.

Step 6: Follow one failed request

  1. Print the slowest failed request with its log lines:

    python unit21/observability_lab.py --trace worst
  2. You should see:

    Trace 11d274891d1565998c4fb14d45864576
    order-exc-api  POST /exceptions/triage              1205 ms  status 503
      order-exc-api  GET A_SalesOrder via S4_ODATA         413 ms  status 200
      order-exc-api  POST calder-ai-gw /v1/chat            752 ms  status 429
    Log lines:
      2026-11-26T15:49:21.279Z order-exc-api  ERROR gateway answered 429 for order 1000005, returned 503 contact=orders@hallam-fluid.example
      (no gateway spans in this trace: the gateway started its own trace)

    The trace stops at W01's call to the gateway. You can see that the gateway answered 429, but not why, or whether it retried.

Step 7: Fix the design and compare

  1. Write the reviewed design, which fixes all ten findings:

    python unit21/observability_lab.py --fixed
    python unit21/observability_lab.py --check

    The last line reads 40 OK, 0 WARN, 0 FAIL and the exit code is 0. W08 is not in it yet; you add it in the exercise.

  2. Simulate and analyze again:

    python unit21/observability_lab.py --simulate
    python unit21/observability_lab.py --analyze
    python unit21/observability_lab.py --trace worst
  3. The traffic and the incident are identical, so the RED numbers and the alert times don't change. What changes:

    Traces that reach the gateway: 589 of 589
    Log lines with trace_id, order-exc-api: 589 of 589
    Log lines with trace_id, calder-ai-gw: 103 of 103
    Log lines with an e-mail address: 0

    and the trace now shows the cause:

    Trace 11d274891d1565998c4fb14d45864576
    order-exc-api  POST /exceptions/triage              1205 ms  status 503
      order-exc-api  GET A_SalesOrder via S4_ODATA         413 ms  status 200
      order-exc-api  POST calder-ai-gw /v1/chat            752 ms  status 429
        calder-ai-gw   POST /v1/chat                         742 ms  status 429
          calder-ai-gw   generative AI hub call (try 1)        129 ms  status 429
          calder-ai-gw   generative AI hub call (try 2)         93 ms  status 429
    Log lines:
      2026-11-26T15:49:20.656Z calder-ai-gw   WARN  upstream 429 on try 1
      2026-11-26T15:49:21.249Z calder-ai-gw   WARN  upstream 429 on try 2
      2026-11-26T15:49:21.279Z order-exc-api  ERROR gateway answered 429 for order 1000005, returned 503

    Observability didn't prevent the incident; the model provider still refused calls. It turned "the AI is broken" into "the generative AI hub rate-limited the gateway twice, from 09:38", which points at quota and retry settings rather than at the app.

Step 8 (optional): See trace propagation with the real OpenTelemetry SDK

The simulation fakes the trace IDs. This step shows the real mechanism: the OpenTelemetry SDK writes a traceparent header on the way out, and the receiving service continues the same trace. Spans stay in memory and are printed; nothing is sent anywhere.

  1. Add these lines to requirements.txt:

    opentelemetry-api==1.45.2
    opentelemetry-sdk==1.45.2
  2. Install them:

    pip install -r requirements.txt
  3. Create unit21/otel_hello.py with this code:

"""Two services, one trace: the OpenTelemetry SDK passing W3C traceparent (course lab).

Runs on your computer only. Spans are kept in memory and printed; nothing is sent anywhere.
"""
from opentelemetry import trace
from opentelemetry.propagate import extract, inject
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter


def provider(service, exporter):
    p = TracerProvider(resource=Resource.create({"service.name": service}))
    p.add_span_processor(SimpleSpanProcessor(exporter))
    return p


exporter = InMemorySpanExporter()
api = provider("order-exc-api", exporter).get_tracer("calder.lab")
gateway = provider("calder-ai-gw", exporter).get_tracer("calder.lab")


def gateway_handles(headers):
    """The gateway reads traceparent from the incoming headers and continues the trace."""
    ctx = extract(headers)
    with gateway.start_as_current_span("POST /v1/chat", context=ctx, kind=trace.SpanKind.SERVER):
        with gateway.start_as_current_span("generative AI hub call"):
            pass


with api.start_as_current_span("POST /exceptions/triage", kind=trace.SpanKind.SERVER) as root:
    root.set_attribute("calder.order", "1000002")
    with api.start_as_current_span("GET A_SalesOrder via S4_ODATA", kind=trace.SpanKind.CLIENT):
        pass
    with api.start_as_current_span("POST calder-ai-gw /v1/chat", kind=trace.SpanKind.CLIENT):
        headers = {}
        inject(headers)          # writes the W3C traceparent header for the outgoing call
        print("Outgoing header:", "traceparent:", headers["traceparent"])
        gateway_handles(headers)

print()
for s in sorted(exporter.get_finished_spans(), key=lambda s: s.start_time):
    parent = format(s.parent.span_id, "016x") if s.parent else "-" * 16
    print(f"{s.resource.attributes['service.name']:<14} {s.name:<32} "
          f"trace {format(s.context.trace_id, '032x')}  span {format(s.context.span_id, '016x')}  "
          f"parent {parent}")
ids = {s.context.trace_id for s in exporter.get_finished_spans()}
print(f"\n{len(exporter.get_finished_spans())} spans, {len(ids)} trace ID{'s' if len(ids) > 1 else ''}")
  1. Run it:

    python unit21/otel_hello.py
  2. You should see output shaped like this. The IDs are random and differ on every run; what matters is that all five spans share one trace ID, and that the gateway's server span has the client span as its parent:

    Outgoing header: traceparent: 00-51489e780fdc4a245b8c17b4564f9eef-52593372daa6576c-03
    
    order-exc-api  POST /exceptions/triage          trace 51489e780fdc4a245b8c17b4564f9eef  span be64b82e0f064d47  parent ----------------
    order-exc-api  GET A_SalesOrder via S4_ODATA    trace 51489e780fdc4a245b8c17b4564f9eef  span 879dad40409b2f75  parent be64b82e0f064d47
    order-exc-api  POST calder-ai-gw /v1/chat       trace 51489e780fdc4a245b8c17b4564f9eef  span 52593372daa6576c  parent be64b82e0f064d47
    calder-ai-gw   POST /v1/chat                    trace 51489e780fdc4a245b8c17b4564f9eef  span ee8f2b53734a1998  parent 52593372daa6576c
    calder-ai-gw   generative AI hub call           trace 51489e780fdc4a245b8c17b4564f9eef  span 0f0053020957e13c  parent ee8f2b53734a1998
    
    5 spans, 1 trace ID

    The header's second part is the trace ID and its third part is the client span's ID, as the W3C format defines. The last part holds the flags: the W3C Recommendation defines only the lowest bit, "sampled"; this SDK version writes 03.

  3. To see the draft gateway's mistake, change ctx = extract(headers) to ctx = extract({}) in gateway_handles, so the gateway ignores the header. Run again: the last line reads 5 spans, 2 trace IDs. Change it back afterwards.

Step 9: Write the readiness document

  1. With the reviewed design in place, write the document:

    python unit21/observability_lab.py --write
  2. You should see Wrote unit21/calder_observability_readiness.md (40 findings). Open it: a table of every rule, subject and verdict, plus the owner of each workload. It is the operations readiness checklist for Calder's design review.

  3. Save your work with Git:

    git add unit21/observability_lab.py unit21/otel_hello.py unit21/calder_observability.json unit21/calder_observability_readiness.md requirements.txt
    git commit -m "Unit 21: observability design and readiness check"

    The generated unit21/telemetry/ folder can be recreated any time; leave it out of Git.

Sketch: the same design on a real subaccount

# Sketch: create a production instance with OTLP on and 30 days of retention
cf create-service cloud-logging standard cls-ai-prod -c '{"retention_period": 30, "ingest_otlp": {"enabled": true}}'
# Ship a Cloud Foundry app's stdout and router logs by binding it
cf bind-service order-exc-api cls-ai-prod
# Sketch: Kyma Telemetry module, logs from the MES listener's namespace to the same kind of instance
apiVersion: telemetry.kyma-project.io/v1beta1
kind: LogPipeline
metadata:
  name: sap-cloud-logging
spec:
  input:
    runtime:
      enabled: true
  output:
    otlp:
      endpoint:
        valueFrom:
          secretKeyRef: {name: sap-cloud-logging, namespace: sap-cloud-logging-integration, key: ingest-otlp-endpoint}
      tls:
        cert:
          valueFrom:
            secretKeyRef: {name: sap-cloud-logging, namespace: sap-cloud-logging-integration, key: ingest-otlp-cert}
        key:
          valueFrom:
            secretKeyRef: {name: sap-cloud-logging, namespace: sap-cloud-logging-integration, key: ingest-otlp-key}

The cf commands follow SAP's Cloud Logging guide, and the pipeline follows SAP's Kyma integration guide; a TracePipeline and MetricPipeline take the same output. The secret comes from a service binding created with the SAP BTP service operator, which also rotates it, as described in services, instances and bindings.

How the code works

Part of the script What it does
workloads() and design() Build the draft or reviewed design: five workloads, two Cloud Logging instances, two alert routes and the audit log export
check() Applies rules O01 to O12 to each workload, instance and the audit log; returns OK, WARN or FAIL with a reason
simulate() Generates two hours of triage requests with seed 42 (traffic) and seed 43 (IDs), writes spans and logs as JSONL; reads the design to decide whether the gateway continues the trace, how it logs, and whether W01 masks e-mails
analyze() Computes RED numbers from server spans, evaluates the 1-hour and 5-minute burn-rate page minute by minute, and counts trace joins and e-mail addresses in logs
trace() Rebuilds one trace as a tree from parent IDs and prints the log lines with the same trace ID
write_report() Writes the readiness checklist as a Markdown table
otel_hello.py Uses the OpenTelemetry SDK: two tracer providers stand for two services, inject writes traceparent, extract continues the trace

If something goes wrong

What you see What it means What to do
python: command not found or 'python' is not recognized Python isn't on your PATH, or the venv is off Turn on the venv (Step 1). On macOS/Linux try python3.
calder_observability.json not found --check, --simulate or --write ran before a design existed Run --init or --fixed first
FileNotFoundError for spans.jsonl --analyze or --trace ran before --simulate Run --simulate first
Your numbers differ from the sample The script was changed, or another Python edited the seeds Paste the script again; the output depends only on the code
ModuleNotFoundError: No module named 'opentelemetry' Step 8's libraries aren't installed in this venv Run pip install -r requirements.txt with the venv on
pip times out or reports a proxy error Your network blocks PyPI Ask IT for the proxy settings, or skip Step 8; Steps 1 to 7 and 9 need no network
No failed request in this run. The design or the incident window was edited Run --init and --simulate again

The SAP way

What SAP provides, as of 27 November 2026:

  • SAP Cloud Logging for the store. Created from the Service Marketplace, the cf CLI, the btp CLI or the SAP BTP service operator. Cloud Foundry apps ship by binding (logs into logs-cfsyslog-*, resource metrics into metrics-otel-v1-*); OpenTelemetry data lands in logs-otel-v1-*, metrics-otel-v1-* and otel-v1-apm-span-*. One instance can be shared across spaces, or across Cloud Foundry orgs through a user-provided service. SAP's What's New lists OpenSearch 2.19.6 and, on 12 November 2026, OpenTelemetry dashboards that now include logs without a trace ID.
  • Instrumentation helpers. For Java, an OpenTelemetry agent extension shipped with the SAP Java buildpack finds Cloud Logging bindings and configures the exporters; for Node.js, an exporter package does the same and is compatible with CAP. Python apps use the standard OpenTelemetry SDK with the gRPC exporter and the binding's certificate.
  • Kyma Telemetry module for clusters, with LogPipeline, TracePipeline and MetricPipeline and an SAP Cloud Logging integration guide.
  • SAP Alert Notification service for routing events. As of 27 November 2026, its product page describes subscriptions with conditions, a producer API for your own apps' events, a consumer API, and delivery by e-mail, Slack, SAP Solution Manager, SAP Focused Run or another alert management system. It is sold in blocks of 1,000 API calls a month. BTP's documentation says it receives MTA deployment events from its space without setup.
  • SAP Cloud ALM for central operations. Its data collection is OpenTelemetry-based, with libraries for Java and Node.js or CAP on Cloud Foundry and Kyma. Health Monitoring for SAP BTP Cloud Foundry covers custom Java apps with its OpenTelemetry extension and can show Alert Notification events such as application crashes. Its Configuration and Security Analysis app checks Cloud Logging instances against SAP's security recommendations.
  • SAP Audit Log for the security record: 90 days by default at no extra cost; the premium plan lets your own apps write audit records and lets you set retention. Retrieval is by API and the SAP Audit Log Viewer.
  • Licensing. Cloud Logging is priced by plan and consumption (Discovery Center and the estimator); Alert Notification by API-call blocks; Audit Log's premium plan by volume. BTP commercial models and cost control covers how these add up.

Build vs. SAP

Need SAP services Company-wide tool (via OpenTelemetry) Both
BTP-only landscape, small team Cloud Logging + Alert Notification Overkill
Company already runs a central observability platform Keep Cloud Logging for app teams' deep dives Forward SLO metrics, errors and alerts Usually the answer
Central SAP operations across S/4HANA, ECC and BTP Cloud ALM or Focused Run Feed from them
Python or third-party workloads Cloud Logging via OTLP Same OTLP, other endpoint Cloud ALM sees them only through events
Security record Audit Log, exported The security team's monitoring Always both: export before 90 days
Kubernetes-native teams on Kyma Telemetry module to Cloud Logging Telemetry module to their backend A second pipeline per signal

Because the protocol is OpenTelemetry, the instrumentation is the same in every column. The choice is about where the data lands, who reads it, and what it costs.

Architecture view

Where it sits. Calder's production workloads from BTP runtimes compared, their evidence, and where it goes:

flowchart LR
  subgraph AI[calder-ai-prod]
    W01[W01 order-exc-api] --> W03[W03 calder-ai-gw]
    W07[W07 coding batch]
    C1[(cls-ai-prod)]
  end
  subgraph EXT[calder-ext-prod]
    W02[W02 distributor portal]
    W04[W04 MES listener, Kyma]
    C2[(cls-ext-prod)]
  end
  W01 & W03 & W07 -->|OTLP + drain| C1
  W02 & W04 -->|OTLP + drain| C2
  C1 & C2 -->|notifications| ANS[Alert Notification]
  ANS --> OC[On-call channels]
  W01 -->|S4_ODATA via SCC-RK-P| S4P[S/4HANA S4P]
  AUD[Audit Log] -->|weekly export| SIEM[Security monitoring]

Non-functional requirements that decide the design:

Requirement Typical target (course values) What breaks if it's missed
Time to page on an SLO breach Within 15 minutes of a fast burn Users report the outage before the team knows
Trace coverage Every hop of a request continues the caller's trace Causes are found by matching timestamps
Log retention 30 days in production, within SAP's 1 to 90 Last month's question can't be answered
Certificate lead time Renew at least 14 days before expiry Ingestion stops silently on the expiry date
Log volume per app instance Below the platform's rate limit; info level in production Lines dropped ("messages lost", "exceeded log rate limit")
Personal data in logs None, or masked Logs become a store of customer data with its own duties
Audit export At least every 30 days Records age out after 90 days

Integration and identity. Evidence travels on the workloads' own credentials: each binding to SAP Cloud Logging is one more client certificate in the register from services, instances and bindings. People reading dashboards sign in through SAP Cloud Identity Services, with groups mapped as in the BTP security model. The trace ID crosses the BTP boundary in the traceparent header; inside S/4HANA, the request is found by its own correlation IDs, so the app should log the S/4HANA response's identifiers too.

The decision to record (short ADR form from the design-doc topic):

  • Context: five production workloads on Cloud Foundry and Kyma in two subaccounts; Python and CAP apps; a company-wide on-call tool; no central observability platform; eight failing rules in the draft.
  • Options: (1) Cloud ALM only, (2) one SAP Cloud Logging instance per production subaccount with Alert Notification routing to on-call channels, OpenTelemetry instrumentation in every workload, (3) a third-party observability platform for everything.
  • Decision: option 2. standard plan, 30 days of retention, OTLP on, dashboards through Identity Authentication; every service continues the W3C trace; JSON logs with masking; one SLO-based page per workload; audit log exported weekly.
  • Consequences: cls-ai-prod is recreated on standard (plans can't change in place) and the old one deleted after 7 days; the gateway (W03) gets OpenTelemetry middleware; certificates join the rotation calendar; Cloud ALM is fed by Alert Notification events for crashes, since its libraries don't cover the Python workloads; if Calder later buys a central platform, the same OTLP data is forwarded and nothing is re-instrumented.

What a design review will ask:

  1. For each workload, what is the SLO, what pages, and who receives it?
  2. Can you show one failed request end to end, across every service, by one ID?
  3. What happens to evidence on the day an OTLP client certificate expires, and who renews it?
  4. Which logs can hold personal data, and how is that prevented?
  5. What does the log store cost at peak month-end volume, and what is dropped first when it fills?

Production concerns

  • Security and authorizations. Dashboard access is access to whatever the logs contain: map it to groups, keep production read access narrow, and follow SAP's critical recommendation to set up sign-in through Identity Authentication. Never log tokens, keys or full request bodies.
  • Evaluation. Test the alerting, not just the app: replay a known bad hour (as in Step 5) after every change to alert rules, and check that the page fires and clears when it should.
  • Cost. Volume drives cost. Set production log levels to info, drop health-check noise at the source or in the Kyma pipeline, sample traces when volume grows, and size the plan with SAP's estimator for month-end peaks, not an average day.
  • Operations. Write a runbook for every page. Put certificate expiry dates in the same calendar as other credentials. Watch the log store's own health: its usage dashboards show when ingestion is throttled.
  • Clean core. Observability of side-by-side apps needs nothing inside S/4HANA. Monitoring S/4HANA itself is Cloud ALM's or Focused Run's job; don't build custom logging into the core to feed BTP dashboards.

Where AI fits

AI changes three things for BTP observability:

  • Agents are workloads with extra failure modes. A call can succeed and still give a wrong answer, and costs move with tokens. Observability for AI systems covers AI-specific spans, quality signals and SAP's orchestration response fields; the generative AI hub's batch and observability topic covers labels and usage on SAP's side. The platform plumbing in this topic carries their data the same way.
  • Prompts and answers in logs are personal data risks. An AI gateway that logs full prompts copies customer data into the log store. Log identifiers, token counts and outcomes, and keep content capture off unless policy allows it.
  • AI can help read the evidence. A model can summarize a trace or draft an incident note from log lines. Treat log content as untrusted input when a model reads it: a customer note in a log line can carry instructions, as prompt injection explains.

As far as this run could find, SAP's Cloud Logging and Alert Notification pages describe no AI features as of 27 November 2026.

Pitfalls

  • Relying on cf logs. It is for watching a live app. Without a drain, logs are gone.
  • Production on the dev plan. No replication, no scaling, and no in-place upgrade: moving later means a second instance.
  • Keeping the default 7-day retention. It is a default, not a decision.
  • A gateway that drops traceparent. One hop that starts its own trace breaks every trace through it.
  • Plain-text logs. Nothing can filter or join on a field that doesn't exist.
  • Alerts to a person. People change jobs and go on holiday; alerts go to a channel or an on-call tool.
  • Forgotten certificates. OTLP client certificates last 90 days by default, and ingestion stops without warning when they expire.
  • Sending HTTP OTLP to a gRPC-only endpoint. Use the gRPC exporter, or put an OpenTelemetry Collector in front.

Exercise

Calder adds W08, the casting porosity image check on Kyma (from BTP runtimes compared), and its security team adds a rule: production workloads log at info or warn, never debug.

  1. Run python unit21/observability_lab.py --fixed so you start from the reviewed design.

  2. Open unit21/calder_observability.json and add "log_level": "info" to each of the five workloads.

  3. Add W08 to the workloads list:

    {"id": "W08", "name": "porosity-image-check", "runtime": "kyma",
     "subaccount": "calder-ai-prod", "owner": "00100288",
     "log_target": "cls-ai-prod", "log_format": "json", "trace_propagation": true,
     "masks_personal_data": true, "log_level": "debug",
     "kyma_pipelines": ["LogPipeline", "TracePipeline", "MetricPipeline"],
     "alerts": [{"name": "porosity check backlog", "slo": "images checked within 10 min",
                 "route": "ans-ai-prod", "runbook": "runbooks/porosity-check.md"}]}
  4. In check(), just above the line if w["runtime"] == "kyma":, add rule O13 at the same indentation:

            add("O13", s, w.get("log_level") in ("info", "warn"),
                f"production log level {w.get('log_level')}" if w.get("log_level") in ("info", "warn")
                else f"log level {w.get('log_level')}: debug output floods the log store")
  5. Run python unit21/observability_lab.py --check. You should see seven OK lines for W08 under O01 to O12, then O13 W08 FAIL log level debug: debug output floods the log store and 52 OK, 0 WARN, 1 FAIL.

  6. Change W08's log_level to info and check again.

  7. Run --write and commit the updated design and readiness document.

Done when --check prints 53 OK, 0 WARN, 0 FAIL and calder_observability_readiness.md lists W08 with its owner. The file feeds the CI/CD topic and the resilience topic.

Check yourself

Pick one answer for each question. The explanation appears after you choose.

1Calder's AI gateway reads no traceparent header and starts a new trace for every call. What does the analysis show?

Answer: C. Each service continues a trace only by reading the caller's traceparent. The draft gateway's spans and logs exist but sit in separate traces, so "Traces that reach the gateway" is 0 of 589. Counts and alerts are unchanged because they come from W01's own spans.

2Why did the page fire at 09:51 when the errors began at 09:38?

Answer: D. The page needs both windows above 14.4 times the 1% budget. The 5-minute window was far above it within minutes, but the 1-hour window only crossed when enough failures had built up. That delay is the trade-off that keeps short blips from paging.

3A Python app on Cloud Foundry sends OTLP over HTTP to SAP Cloud Logging and nothing arrives. What is the likely fix?

Answer: A. SAP's documentation says the OTLP endpoint accepts gRPC only and uses mutual TLS. HTTP variants need an OpenTelemetry Collector to convert them. Plan size and retention don't affect which protocol is accepted.

4Logs from cls-ai-prod stop arriving one morning with no change to the apps. What should you check first?

Answer: C. The certificates last 90 days by default, and SAP's FAQ lists expiry first when data is missing entirely. Rule O06 warns 14 days ahead so this doesn't happen on a weekend.

5Why does Calder recreate cls-ai-prod instead of switching it from dev to standard?

Answer: A. The plans page states that updating service plans isn't supported and suggests a side-by-side transition. That is why choosing the production plan at the start saves a migration.

6Which part of the design does the Kyma Telemetry module not cover?

Answer: C. The Telemetry module's documentation says audit logs are out of scope. It handles application logs, traces and metrics, can filter with OTTL, and is vendor-neutral, so it can feed any OTLP backend.

7Calder's W01 and W03 are Python apps. How should central operations in SAP Cloud ALM learn when they crash?

Answer: C. SAP's Expert Portal lists Cloud ALM libraries for Java and Node.js only. Its BTP health monitoring can show Alert Notification events such as app crashes, so the Python apps reach it that way, while their detailed telemetry goes to SAP Cloud Logging over OpenTelemetry.

8What should an AI gateway write to its logs about each model call?

Answer: B. Prompts often carry customer data, which turns the log store into a store of personal data. Identifiers and counts are enough to join with the provider's side and to explain cost and failures.
NextCI/CD and transport management on BTP: one release flow for a hybrid landscapeDesign how BTP changes are built, promoted from dev to test to production and released with S/4HANA transports, using pipelines and the transport service.

Sources

  • Service Plans (SAP Cloud Logging documentation, SAP-docs on GitHub, read 2026-11-27) — plans can't be updated, run instances side by side to migrate; dev for evaluation only (7.5 GiB, no auto-scaling or replication); standard 75 to 375 GiB, large 750 GiB to 3.75 TiB net storage, replicated and auto-scaling; oldest indices deleted when the disk watermark is exceeded at maximum scale; pricing via Discovery Center and the capacity unit estimator
  • Configuration Parameters (SAP Cloud Logging documentation) — retention_period 1 to 90 days, default 7, overruled by size-based curation, affects only new indices; ingest.enabled default true; ingest_otlp.enabled default false; min and max data nodes and ingest instances 2 to 10; oidc and saml for dashboard sign-in; rotate_root_ca can invalidate bindings
  • Ingest via OpenTelemetry API Endpoint (SAP Cloud Logging documentation) — one OTLP endpoint for logs, metrics and traces, gRPC only (other protocols through an OpenTelemetry Collector); mTLS only; client certificates valid 90 days by default, certValidityDays 1 to 180; deleting a binding doesn't revoke its certificate; Java agent extension and Node.js exporter read the bindings; index patterns logs-otel-v1-*, metrics-otel-v1-*, otel-v1-apm-span-*
  • Shipping Data, FAQ (SAP Cloud Logging documentation) — expired client certificates stop ingestion; Loggregator drops its whole queue above 10,000 signals ("messages lost for application"); log rate limit; back pressure and retries with exponential backoff; 4 MiB request limit (HTTP 413); 1,000 fields per index, about 500 usable
  • Telemetry Module (Kyma project documentation, kyma-project/telemetry-manager, read 2026-11-27) — collects logs, traces and metrics with LogPipeline, TracePipeline and MetricPipeline resources based on the OpenTelemetry Collector; vendor-neutral OTLP output, optimized for SAP Cloud Logging; central backend outside the cluster recommended for production; filtering with OTTL; audit logs out of scope
  • Audit Logging in the Cloud Foundry Environment (SAP BTP documentation, SAP-docs on GitHub) — SAP Audit Log stores audit records written by BTP services, 90 days by default at no extra cost; premium plan to write your own apps' audit data and set retention; categories audit.data-access, audit.data-modification, audit.security-events, audit.configuration
  • SAP Alert Notification service for SAP BTP (sap.com product page, read 2026-11-27) — notifications about BTP services and custom apps; subscriptions with conditions; producer API for custom alerts, consumer API to pull alerts; delivery by email, Slack, SAP Solution Manager, SAP Focused Run or another alert management system; base plan in blocks of 1,000 API calls a month
  • Data Collection Infrastructure (SAP Cloud ALM Expert Portal, support.sap.com, read 2026-11-27) — based on OpenTelemetry with SAP extensions; instrumentation libraries for Java and Node.js or CAP; BTP Cloud Foundry and Kyma; data feeds Health Monitoring, Real User Monitoring, Exception Monitoring, Business Process Monitoring and Job and Automation Monitoring; no Python library listed
  • Chapter 5: Alerting on SLOs (The Site Reliability Workbook, Google) — burn rate is how fast the service consumes its error budget relative to the SLO; page at 14.4 over 1 hour with a 5-minute short window (2% of a 30-day budget), page at 6 over 6 hours and 30 minutes, ticket at 1 over 3 days and 6 hours; short window about 1/12 of the long one; starting numbers, not fixed
  • Trace Context (W3C Recommendation, 23 November 2021) — traceparent header version-trace-id-parent-id-trace-flags (2, 32, 16 and 2 lowercase hex characters); sampled is the only flag defined in version 00; tracestate carries vendor-specific data

Sign in to track your progress

We'll email you a one-time sign-in link. No password needed.

or

Tell us a little about you

Optional, every field. It helps us pitch answers to your questions at the right level and decide which topics to write next. It is never shown publicly, and you can change or clear it anytime from the account menu.

SAP areas you work in