SD·194F
Security, Observability and AI Integration at L5/L6
The three cross-cutting backend topics at design and production depth: ladders for each; security from the attacker's side — why password hashing must be slow (1.8 million SHA-256 guesses per second per core versus about 6 for PBKDF2 with 600,000 iterations), a JWT verifier that accepts a forged alg=none admin token and the fix, injection, SSRF and authorisation flaws, threat modelling and secure-by-default design, and security operations; observability from first principles — why percentiles can't be averaged (a 279 ms "average p99" against a true 55 ms, with the real problem visible only at p99.9), histogram bucket error, cardinality, sampling, SLOs and the diagnostic method; and AI integration as an unreliable, expensive, attackable dependency — schema-validated output with bounded retries and a safe fallback, the model proposing while the application decides, prompt injection, cost and latency budgets, and evaluation.
Start here: what L5/L6 security, observability and AI integration look like
These three topics share a pattern: anyone can switch on the tool (a scanner, a dashboard, an LLM API) at L2, but the value appears at L4–L6, where you understand the failure modes well enough to design around them. Security at depth means thinking like an attacker; observability at depth means knowing what your telemetry costs and what it can't show; AI integration at depth means treating a model as an unreliable, expensive, attackable dependency.
One example from observability: the label that costs 341 MB
Metrics systems store one time series per unique combination of labels. Adding user_id as a label to a request-latency histogram feels harmless. The lab measured what it does in a single process with the standard Prometheus client:
| Distinct user IDs | Time series | Memory in the app | Size of one scrape | Time to render it |
|---|---|---|---|---|
| 10 | ~180 | ~0 MB | 0.01 MB | 1 ms |
| 1,000 | ~18,000 | 3.4 MB | 1.1 MB | 105 ms |
| 10,000 | ~180,000 | 33.9 MB | 11.2 MB | 1.1 s |
| 100,000 | ~1,800,000 | 341 MB | 113 MB | 11.2 s |
Each histogram creates about 18 series per label value (one per bucket, plus sum, count and creation time). At 100,000 users, one service's metrics would overwhelm both the app and the monitoring system. The L5 rule: high-cardinality identifiers go in traces and logs, not metric labels.
One example from security: comparing secrets
Comparing a submitted token with == stops at the first differing byte, so in principle the time taken leaks how much of the guess was right. In the lab's Python measurement the difference between 0 and 63 correct leading bytes was only about 1.5 nanoseconds (33.4 vs 34.9 ns), but attackers average thousands of measurements; hmac.compare_digest takes the same time regardless. Using it costs 30 ns and removes the question.
How deep to go in security, observability and AI integration
Volume 17 defines six mastery levels; for this chapter's topics they look like this:
| Level | You can… |
|---|---|
| L1 | name core threats, the observability signals and LLM integration patterns |
| L2 | apply secure defaults, instrument a service, and call a model API safely |
| L3 | explain attacks and defences, telemetry internals and costs, model failure modes |
| L4 | investigate incidents and abuse from telemetry; debug quality and cost problems in AI features |
| L5 | design secure, observable, AI-integrated systems with explicit risk and cost trade-offs |
| L6 | run security, observability and AI platforms across an organisation |
The ladders
| Level | Security | Observability | AI integration |
|---|---|---|---|
| L1 | Knows CIA triad, authn vs authz, common attack names | Knows logs, metrics, traces | Knows what LLMs, embeddings and RAG are |
| L2 | Uses framework security correctly: parameterised queries, output encoding, password hashing libraries, OAuth/OIDC libraries, secrets managers | Emits structured logs, RED metrics, traces with OpenTelemetry; builds dashboards | Calls a model API, writes prompts, parses structured output, uses an SDK |
| L3 | Explains attacks mechanically (injection, XSS, CSRF, SSRF, deserialisation, token flaws), cryptographic primitives and their properties, OAuth flows, TLS | Explains metric types, histograms and quantile estimation, cardinality, sampling, context propagation, storage engines' trade-offs | Explains tokens and context windows, sampling parameters, embeddings and similarity, why models hallucinate, tool calling mechanics |
| L4 | Finds vulnerabilities in code review and testing; investigates incidents from logs; reads CVEs and judges exposure | Diagnoses novel problems by slicing telemetry by dimensions; finds the trace that explains the metric | Diagnoses bad outputs (retrieval misses, prompt issues, context overflow), latency and cost spikes, injection attempts |
| L5 | Threat-models designs; designs authorisation models, tenant isolation, key management, secure defaults | Designs SLOs, alerting strategy, telemetry pipelines, sampling, cost controls | Designs LLM features: when to use one, architecture (RAG, tools, workflows), guardrails, evaluation, fallbacks |
| L6 | Runs security: vulnerability management, incident response, audits, secrets rotation, supply chain | Runs observability: on-call quality, telemetry cost, retention, migrations between vendors | Runs AI features: evaluation in CI and production, model upgrades, cost per request, safety incidents |
Security from the attacker's side
L3 security knowledge is mechanical: you can explain exactly how each attack works, so you can see it in code that doesn't look like the textbook example.
Why password hashing must be slow
When a password database leaks (and assume it will), attackers guess passwords offline, as fast as their hardware allows. The defence is a hash designed to be expensive per guess: a salt (unique per user, defeating precomputed tables) plus a deliberately slow, ideally memory-hard function. Measured on one core:
# How many password guesses per second does an attacker get per CPU core, by hashing scheme?
schemes = {
"SHA-256 (unsalted, fast)": lambda: hashlib.sha256(pw).digest(),
"PBKDF2-SHA256, 600k iterations": lambda: hashlib.pbkdf2_hmac("sha256", pw, salt, 600_000),
"scrypt n=2^15 r=8 p=1 (32 MiB)": lambda: hashlib.scrypt(pw, salt=salt, n=2**15, r=8, p=1, maxmem=64 * 2**20),
}
SHA-256 (unsalted, fast) 1,849,592.2 guesses/s/core 10^10 guesses: 0.0626 core-days
PBKDF2-SHA256, 600k iterations 5.9 guesses/s/core 10^10 guesses: 19,651.7392 core-days
scrypt n=2^15 r=8 p=1 (32 MiB) 7.7 guesses/s/core 10^10 guesses: 15,068.8561 core-days
A 300,000× difference per guess, and that's Python on a CPU; GPUs compute fast hashes like SHA-256 at billions per second, while memory-hard functions (scrypt, Argon2id, the current first choice per OWASP) resist GPU and ASIC parallelism because each guess needs tens of megabytes of memory. L5 decisions: Argon2id (or bcrypt/scrypt where unavailable) with parameters tuned so a login costs tens to hundreds of milliseconds on your servers; rate-limit login attempts; and better still, reduce the value of passwords with MFA, passkeys (WebAuthn) and SSO.
Tokens: trust nothing the attacker sends
JSON Web Tokens carry their own header, including the algorithm. A verifier that lets the token choose the algorithm lets the attacker choose it:
def verify_naive(token): # BUG: lets the attacker choose the algorithm
h, p, s = token.split(".")
alg = json.loads(unb64(h))["alg"]
if alg == "none": return json.loads(unb64(p))
expected = b64(hmac.new(KEY, f"{h}.{p}".encode(), hashlib.sha256).digest())
if not hmac.compare_digest(s, expected): raise ValueError("bad signature")
return json.loads(unb64(p))
def verify_strict(token, allowed=("HS256",)): # FIX: the server decides the algorithm; constant-time compare
h, p, s = token.split(".")
if json.loads(unb64(h)).get("alg") not in allowed: raise ValueError("algorithm not allowed")
expected = b64(hmac.new(KEY, f"{h}.{p}".encode(), hashlib.sha256).digest())
if not hmac.compare_digest(s, expected): raise ValueError("bad signature")
return json.loads(unb64(p))
naive legit token → accepted, role=subscriber
naive forged alg=none admin token → accepted, role=admin
strict legit token → accepted, role=subscriber
strict forged alg=none admin token → rejected (algorithm not allowed)
The same class of bug produced real vulnerabilities in JWT libraries (accepting none; RS256/HS256 confusion where the public key was used as an HMAC secret). The general L3 principle: the server decides algorithms, issuers, audiences and key ids from its own configuration; tokens are untrusted input until verified; also verify exp, nbf, iss, aud. The L5 principle: use a maintained library configured strictly, rather than writing verification yourself (this demo exists to show why).
The attack catalogue at L3
| Attack | Mechanism | Defence (primary) |
|---|---|---|
| SQL/command/LDAP injection | Untrusted input concatenated into an interpreter's code | Parameterised queries / APIs that separate code and data; allow-lists |
| XSS | Untrusted data rendered as HTML/JS in a victim's browser | Context-aware output encoding (framework defaults), CSP, avoid innerHTML/dangerouslySetInnerHTML |
| CSRF | Browser sends cookies with cross-site requests | SameSite cookies, CSRF tokens, checking Origin |
| SSRF | Server fetches attacker-chosen URLs, reaching internal services or cloud metadata | Allow-list destinations, block link-local/private ranges after DNS resolution, IMDSv2 |
| Broken object-level authorisation | API trusts the id in the request | Check ownership on every object access; tests per endpoint |
| Insecure deserialisation | Deserialiser instantiates attacker-chosen types | Don't deserialise untrusted native formats; use data-only formats with schemas |
| Path traversal | ../ in file paths |
Canonicalise and check against a base directory |
| Secrets in code/logs | Credentials leak through repositories and logs | Secret managers, scanning, log redaction |
| Supply chain | Malicious or compromised dependencies, build systems | Pinning, provenance, review of new dependencies, least-privilege CI |
| Prompt injection (LLM features) | Instructions hidden in data the model reads | See AI integration below |
Security at L5 and L6
- Threat modelling (STRIDE, attack trees, or simply "what can go wrong?") at design time, recorded and revisited; abuse cases next to use cases.
- Authorisation design: a model chosen deliberately (RBAC, ABAC, ReBAC as in Google Zanzibar and its open-source descendants such as OpenFGA and SpiceDB), enforced in one place, testable, auditable; tenant isolation by design (tenant id in every query, row-level security in Postgres as a backstop).
- Secure defaults: deny by default, least privilege, short-lived credentials, encryption everywhere, safe framework settings that require effort to weaken.
- Key management: KMS-held keys, envelope encryption, rotation, separation of duties for key administrators.
- L6 operations: vulnerability management with SLAs by severity and exposure (not every CVE matters equally: is the vulnerable code reachable?); security incident response (contain, eradicate, recover, notify per law: India's CERT-In requires reporting certain incidents within 6 hours; DPDP breach notification); audit logging that attackers can't erase; penetration tests and bug bounties; security champions in teams.
Observability from first principles
Observability is the ability to answer new questions about your system's behaviour from its outputs, without shipping new code. Monitoring answers known questions (is the error rate high?); observability lets you ask why, for this customer, on this endpoint, since this deploy.
Percentiles don't average
A fleet of three pods, one of which has GC trouble on 5% of its requests:
# Percentiles don't average: three pods' p99s vs the true fleet p99, and histogram bucket resolution
pods = {
"pod-a (healthy)": [random.lognormvariate(3.0, 0.4) for _ in range(9000)], # ms
"pod-b (healthy)": [random.lognormvariate(3.0, 0.4) for _ in range(9000)],
"pod-c (GC issue)": [random.lognormvariate(3.0, 0.4) if random.random() > 0.05 else random.uniform(400, 900) for _ in range(1000)],
}
pod-a (healthy) n= 9000 p99= 50.7 ms
pod-b (healthy) n= 9000 p99= 53.0 ms
pod-c (GC issue) n= 1000 p99= 732.8 ms
average of pod p99s = 278.8 ms (meaningless)
true fleet p99 (all samples) = 54.7 ms
true fleet p99.9 = 679.1 ms (the GC problem appears only here)
fleet p99 from histogram = 71.9 ms (interpolated inside the 50–100 ms bucket)
Three lessons:
- Averaging percentiles is meaningless (279 ms describes nothing); quantiles must be computed from the combined distribution. Hence histograms (mergeable bucket counts) rather than pre-computed per-instance percentiles: sum the buckets across pods, then estimate the quantile.
- Fleet-level percentiles hide bad instances: pod-c's problem affects 0.26% of fleet requests, below p99. Slice by instance (or zone, version, customer) and look at higher percentiles when users on one pod are suffering.
- Histogram estimates are only as precise as the buckets: Prometheus's
histogram_quantileinterpolates linearly inside a bucket, so the estimate (72 ms) can be far from the truth (55 ms) when buckets are wide. Choose buckets around your SLO thresholds, or use native/exponential histograms (Prometheus native histograms, OpenTelemetry exponential histograms) that keep relative error bounded.
The rest of L3
- Metric types: counters (monotonic; you graph rates), gauges (current values), histograms (bucketed distributions), summaries (client-side quantiles, not mergeable).
- Cardinality: every unique label combination is a separate time series. A
user_idlabel on a request metric with a million users creates a million series per metric and endpoint: memory, cost and query time explode. High-cardinality detail belongs in traces and logs (or in wide events stored in column stores built for it), not metric labels. - Traces: spans with parent ids and a trace id propagated across processes (W3C
traceparent); sampling head-based (decide at the start: cheap, may miss rare errors) or tail-based (decide after the trace completes, keeping errors and slow traces: needs a collector tier that buffers traces). - Logs: structured (JSON), with trace ids, at deliberate levels; logs are the most expensive signal per byte at scale.
- OpenTelemetry: the vendor-neutral standard for instrumentation APIs, SDKs, the collector and the OTLP protocol; instrument once, send anywhere.
Observability at L4–L6
- L4 method: start from the symptom users feel (SLO burn), then slice by every dimension available (endpoint, status, version, zone, pod, customer tier) until the difference appears; then jump to exemplar traces from the bad slice; then to logs for that trace. "What changed?" (deploys, flags, config, traffic mix, dependencies) is the first question.
- L5 design: SLOs on user journeys with error budgets; alerts on symptoms (burn rate) with runbooks, not on every cause; telemetry pipeline with a collector for sampling, redaction and routing; retention and resolution per signal; dashboards per journey and per service.
- L6 operations: alert quality (every page actionable; track pages per on-call shift); telemetry cost (often a significant share of infrastructure spend: sampling, cardinality budgets, tiered retention); vendor migrations (OpenTelemetry makes them possible); observability for the observability system (who alerts when the alerting pipeline is down?).
AI integration at L5/L6
For a backend engineer, an LLM is a dependency with unusual properties: non-deterministic, slow (seconds), expensive per call, sometimes wrong in fluent ways, and steerable by text that may come from attackers. L5/L6 integration treats it like any other unreliable dependency, plus those extras.
Validated output, bounded retries, safe fallback
class SkipIntent(BaseModel): # the contract the rest of the system relies on
action: str = Field(pattern="^(skip|unskip|none)$")
dates: list[date] = Field(max_length=10)
confidence: float = Field(ge=0, le=1)
def parse_intent(user_text, max_attempts=3):
errors = []
for attempt in range(1, max_attempts + 1):
raw = call_model(user_text + (f"\nPrevious output was invalid: {errors[-1]}" if errors else ""))
try:
intent = SkipIntent.model_validate(json.loads(raw))
print(f"attempt {attempt}: valid → {intent.model_dump(mode='json')}")
return intent
except (json.JSONDecodeError, ValidationError) as e:
errors.append(type(e).__name__); print(f"attempt {attempt}: rejected ({type(e).__name__})")
return SkipIntent(action="none", dates=[], confidence=0.0) # safe fallback: do nothing, show the normal UI
attempt 1: rejected (JSONDecodeError)
attempt 2: rejected (ValidationError)
attempt 3: valid → {'action': 'skip', 'dates': ['2026-11-06', '2026-11-13'], 'confidence': 0.86}
confirm with user: skip ['2026-11-06', '2026-11-13']
cost per request ≈ $0.0070; at 20,000 requests/day ≈ $4,212/month
(The model is a stub returning a malformed, an invalid, then a valid reply, to exercise each path.) The pattern: a schema is the contract; provider features for structured outputs or constrained decoding make malformed JSON rare but don't guarantee semantic validity (an action that's well-formed but not allowed), so validate anyway; retries are bounded; the fallback is safe (do nothing, fall back to the normal UI); and the model proposes, the application decides: the skip executes through the same API, with the user's authorisation and a confirmation step, because it changes billing.
The L5/L6 concerns
- When not to use an LLM: if a form, a rule, a regex or a classic classifier solves it reliably, use that; LLMs earn their cost where language is genuinely open-ended.
- Prompt injection: any text the model reads (user messages, retrieved documents, web pages, tool results, emails) can contain instructions. There's no complete defence at the model level; design so that a fully compromised model can't do damage: least-privilege tools, the user's own permissions for every action, confirmation for consequential actions, no secrets in prompts, output treated as untrusted (encode it before rendering; never execute it), and separation of untrusted content from instructions.
- Data: what personal data goes to which provider, under what terms and in which region; retention; logging prompts with PII controls.
- Latency: stream responses; set timeouts; parallelise independent calls; use smaller/faster models for classification and routing; cache.
- Cost: tokens in and out per request × requests (above: about $4,200 a month at 20,000 requests/day with illustrative prices); prompt caching for long static prefixes; budgets per user and per tenant; alerts on spend anomalies.
- Evaluation: a test set of real inputs with expected outcomes, run in CI on every prompt or model change (an offline eval), plus production monitoring of outcomes (acceptance rates, corrections, complaints). Model upgrades are deploys: canary them with evals.
- Observability: trace each call (model, prompt version, tokens, latency, retries, validation failures, tool calls).
- Resilience: provider outages and rate limits happen; degrade gracefully (the app works without the assistant), and consider a secondary provider or model for critical paths.
Volume 14 (ch. 159–180) covers LLM application engineering in depth; chapter 196 covers the AI specialisation's own L5/L6 targets.
Lab: the costs you can't see on a dashboard
Setup. Python 3.13 on the lab machine with prometheus_client and tracemalloc (Experiment 1), and hmac with time.perf_counter_ns (Experiment 2).
Experiment 1: metric cardinality
One Histogram("req_seconds", labelnames=["route", "user_id"]) with default buckets; one observation per distinct user_id; memory measured with tracemalloc, then one exposition rendered with generate_latest:
Distinct user_id |
Series (≈ 18 per value) | App memory | Scrape size | Render time |
|---|---|---|---|---|
| 10 | ~180 | 0.0 MB | 0.01 MB | 1 ms |
| 1,000 | ~18,000 | 3.4 MB | 1.10 MB | 105 ms |
| 10,000 | ~180,000 | 33.9 MB | 11.16 MB | 1,123 ms |
| 100,000 | ~1,800,000 | 341.0 MB | 113.37 MB | 11,192 ms |
Everything grew linearly with distinct values, and that's one process; a fleet multiplies it, and the time-series database pays again for each series (memory for the index, storage, query cost). Many hosted services bill per active series. Rules for L5 designs: label values must come from small, bounded sets (route templates, status classes, plan, region); put request-level identifiers in traces (with exemplars linking metrics to example traces) and logs; enforce limits with relabelling and per-tenant series caps.
Experiment 2: early-exit comparison
A 64-byte secret compared against guesses whose first k bytes are correct (median of 7 runs × 200,000 comparisons):
| Correct leading bytes | 0 | 16 | 32 | 48 | 63 |
|---|---|---|---|---|---|
== |
33.4 ns | 34.2 ns | 34.8 ns | 34.6 ns | 34.9 ns |
hmac.compare_digest |
62.9 ns | 62.5 ns | 63.0 ns | 64.7 ns | 60.8 ns |
== (an optimised memcmp) leaked about 1.5 ns across the full range, roughly monotonic; compare_digest showed only noise. A 1.5 ns signal is far below network jitter for a single request, but timing attacks work statistically (many requests, nearby attackers, slower comparisons in other languages or for longer values), and published attacks have recovered secrets from smaller signals. The L5 lesson is about classes of bugs: use constant-time comparison for every secret (tokens, MACs, API keys) by policy, and don't spend time arguing about whether a particular leak is exploitable.
Try it yourself
- Add a
user_tierlabel (3 values) instead ofuser_idand recompute; then recorduser_idas a trace attribute with an exemplar. - Run a Prometheus server against an app exposing 100,000 series and measure its memory.
- Write a Semgrep or lint rule that flags
==comparisons on variables named*token*,*secret*or*signature*. - Repeat Experiment 2 in a compiled language with a byte-by-byte loop and compare the leak per byte.
Revision sheet: security, observability and AI integration at L5/L6
Key ideas
- Security from the attacker's side: threat modelling (STRIDE, attack trees), trust boundaries, authN/authZ (BOLA), injection, SSRF, deserialisation, supply chain, secrets; classes of bugs removed by design (parameterised queries, constant-time compare, safe defaults).
- Observability from first principles: metrics (aggregates, low cardinality), logs (events), traces (causality), profiles; SLIs/SLOs and burn-rate alerts; sampling; cardinality and cost control.
- AI integration at L5/L6: models as unreliable dependencies: evals, guardrails, prompt-injection containment, cost and latency budgets, fallbacks, versioning and drift monitoring.
- L6: running security programmes, observability platforms and AI platforms across teams with governance.
Numbers to remember
- Lab: a histogram with 100,000
user_idvalues → ~1.8 M series, 341 MB in-process, 113 MB scrape, 11 s to render. - Lab:
==leaked ~1.5 ns across 63 matching bytes;compare_digestwas flat. - Histogram with default buckets ≈ 18 series per label combination.
Pitfalls
- Unbounded label values (IDs, URLs with parameters, error messages).
- Dashboards without SLOs; alerts on causes instead of symptoms.
- Security reviews that check tools ran but never model attackers.
- Shipping LLM features without evals, budgets or injection controls.
- Arguing exploitability instead of removing bug classes.
Glossary
- Cardinality: number of distinct series a metric produces.
- Exemplar: a sample trace ID attached to a metric observation.
- STRIDE: spoofing, tampering, repudiation, information disclosure, denial of service, elevation of privilege.
- Timing attack: inferring secrets from how long operations take.
- Burn rate: speed of error-budget consumption relative to the SLO.