Monitoring, Logging, and Observability Questions
Understanding running systems through their signals. Covers metrics, logs, and traces, instrumentation, dashboards, alerting design, and log analysis and correlation for debugging production. Emphasizes designing observability so problems are detectable and diagnosable before users are affected.
A request fails with a timeout. Do you start with logs, metrics, or traces first, and why? Walk through your prioritized first few steps and what you're hoping each one tells you.
Sample Answer
Direct answer
I'd start with metrics, because they answer the cheapest, most important question first: is this an isolated blip or a real, ongoing problem, and is it affecting one endpoint or many? Metrics take seconds to check and tell you where to point traces and logs next, whereas jumping straight into logs on a single failed request risks spending several minutes reading detail for something that turns out to be a one-off retry that already resolved itself.
Prioritized first steps
- Metrics first: check the error rate and latency (p95/p99) for the timing-out endpoint over the last 15 to 30 minutes. This shows whether it's a sustained pattern worth investigating now, or an isolated spike worth a note but not an emergency, and whether it's scoped to one endpoint or spread across the service.
- Traces next, if the metric confirms a real pattern: pull a trace for a recent timed-out request to see which span in the call chain is actually slow or hanging. This shows where the time is going: our own code, a specific downstream dependency, or a shared resource like a connection pool.
- Logs last, once I know where to look: with the specific span and a request ID in hand, pull the logs for that exact request to get the precise error, a timeout waiting on what exactly, instead of searching broadly through every log line mentioning "timeout."
Decision flow
flowchart TD
A[Request times out] --> B[Check metrics first]
B --> C{Isolated to one endpoint or widespread?}
C -->|One endpoint| D[Pull traces for that endpoint]
C -->|Widespread| E[Check shared dependency: DB, network, downstream API]
D --> F[Find the slow span]
E --> F
F --> G[Pull logs for that span's request ID]
G --> H[Read the error detail to confirm root cause]
If forced to pick only one signal
Under real time pressure, say a spike in slow logins and only one tool available before the next status update is due, I'd still pick metrics, not traces or logs, because metrics answer the triage question fastest: is this getting worse, better, or staying flat, and how many users are affected right now. That's what's needed to decide how urgently to escalate, even before the root cause is known. Traces or logs alone can explain one request beautifully while leaving me blind to whether the problem is spreading, which is the wrong trade-off in the first few minutes of an incident.
Trade-offs and pitfalls
- Starting in logs is tempting because it feels like "real investigation," but without a metric to scope the problem first, it's easy to spend the first several minutes reading detail about a request that isn't representative of what's actually happening.
- Traces are only useful if sampling actually captured the failing request; on a low-sample-rate service, the trace for the specific timeout you care about may simply not exist, in which case logs (which usually aren't sampled the same way) become the fallback.
- This ordering (metrics, then traces, then logs) is a good default, not a law: if metrics are known to be unreliable for this specific service, a common gap right after a migration, before dashboards catch up, it's reasonable to start with whichever signal is actually trustworthy.
What's the difference between an SLI, an SLO, and an SLA? Walk through how you'd define each one concretely for a service you've worked on, including how you'd measure the indicator and what time window you'd use.
Sample Answer
Direct answer
An SLI is the measured signal (e.g. the percentage of requests that were fast and successful), an SLO is the internal target for that signal over a time window (e.g. 99.9% of requests succeed under 300ms over a rolling 30 days), and an SLA is the external, often contractual promise built on top of an SLO, usually with margin, and real consequences (service credits, penalties) if it's breached. In short: the SLI measures, the SLO targets, the SLA promises with a business wrapper attached.
Defining each one concretely, for an e-commerce checkout service
| Term | Definition here | Concrete value |
|---|---|---|
| SLI | Percentage of checkout requests that return successfully (2xx) within 300ms | Measured every minute from load-balancer access logs |
| SLO | Internal reliability target for that SLI | 99.9% of checkout requests succeed under 300ms, measured over a rolling 30-day window |
| SLA | External commitment to customers, usually looser than the SLO to leave margin | 99.5% monthly checkout availability, with service credits below that threshold |
Explained for a non-technical stakeholder: the SLO is the bar the engineering team holds itself to internally so problems get caught and fixed before they become customer-visible; the SLA is the, usually more forgiving, bar the business is willing to be held to externally, on paper, with money attached if it's missed. The gap between the two is deliberate headroom, not sloppiness.
Worked example: computing the error budget
The error budget is the amount of allowed failure baked into the SLO. It's what lets a team ship changes at all instead of freezing forever.
error budget=(1−SLO target)For the 99.9% SLO above:
error budget=1−0.999=0.001=0.1%Over the 30-day measurement window (30 days equals 2,592,000 seconds):
0.001×2,592,000s=2,592s≈43.2 minutesSo this service is allowed about 43 minutes of budget-consuming failure (however that failure is defined: downtime, over-300ms responses, and so on) across a 30-day window before the SLO itself is breached. If checkout handles, say, 1,000,000 requests over that same window, the equivalent request-based budget is:
0.001×1,000,000=1,000 requests allowed to violate the SLIBoth framings, time-based and request-based, describe the same budget; which one is more useful depends on whether the SLI is availability-style (was the service up) or ratio-style (what fraction of requests succeeded).
Trade-offs and pitfalls
- Confusing SLO and SLA in conversation causes real problems: teams sometimes design their alerting and release-gating around the SLA (the looser, contractual number) instead of the SLO (the tighter, internal number), which means by the time anyone notices, the team is already close to breaching the external promise with no margin left to react.
- An SLO with no error-budget policy attached is just a number on a dashboard; the value comes from what happens when the budget is nearly exhausted (freeze risky launches, redirect engineering time to reliability work), not from the target itself.
- Picking an SLI that doesn't reflect real user experience (e.g. "server process is running" instead of "requests succeed within an acceptable time") gives a green dashboard while users are still unhappy. The SLI has to be as close to what the user actually experiences as the team can measure.
A service, or a small fleet of them, has grown with inconsistent, mostly unstructured logging: some free text, some ad hoc key-value pairs, no shared schema. How would you design a structured logging approach for it? Cover what a log entry should capture, how you'd keep verbosity manageable on high-traffic endpoints, and how you'd roll the change out without breaking existing tooling or dashboards.
Sample Answer
Design a fixed schema (not a free-for-all), enforce it through a shared logging library rather than convention, control verbosity by sampling low-value log levels on hot paths while always keeping errors, and roll it out by dual-emitting the old and new formats side by side until every dashboard and script that greps the old format has migrated.
Framework
What a log entry should capture. At minimum, every structured log line needs:
timestamp(ISO 8601, UTC),level,service,envcorrelation_id/trace_id(andspan_idif tracing is wired up), so a log line can be tied back to the request it came frommessage(still free text, but now one field among many, not the whole line)- Context relevant to what's being logged:
route,status,duration_msfor a request-handling log;error.type/error.messagefor a failure
Sensitive fields (user identifiers, emails, anything PII) should never be logged raw. Either omit them, or hash/redact them at the point of emission, enforced by the shared logging library so it isn't up to each call site to remember.
Keep field values bounded, not just field names fixed. A stable schema still has a cardinality trap: a field like route should be a small set of route templates (/orders/{id}), not the raw URL with the real ID interpolated in, and free-text fields like stack traces should be capped in length rather than allowed to grow unbounded. Uncontrolled cardinality is what makes a downstream index expensive, so the schema review has to look at value shape, not just field names.
Why this pays off beyond "logs are searchable now." Once every service emits the same fixed fields, three concrete things get easier that were hard with free-text logs: alert rules can key off a stable field (error.type = "TimeoutError") instead of a regex over a message whose wording changes every release; a post-incident timeline can be reconstructed by filtering and sorting on correlation_id and timestamp across services instead of manually eyeballing each service's raw output in turn; and a legacy service that's risky to touch can be instrumented with this schema before any behavioral refactor, giving you a baseline of real production behavior (error rates, latency, call patterns) to diff the refactor against, turning "did the refactor change behavior" from a guess into something you can actually check.
Verbosity on high-traffic endpoints. Logs and metrics are not interchangeable: a hot endpoint doesn't need a log line per request just to know it's up, that's what a request-count metric is for. Reserve full logging for what metrics can't tell you:
- Always log ERROR and WARN at 100%, since those are rare and high-value.
- Sample INFO-level access logs on high-traffic endpoints (a small, fixed percentage), and keep the sample rate configurable per endpoint rather than global.
- Keep DEBUG out of production by default, gated behind a feature flag or short-lived toggle for active investigations.
Rollout without breaking existing tooling. The riskiest part of this kind of change is not the schema, it's cutting over a service whose logs some existing dashboard or on-call script already greps. A safe sequence:
- Introduce the shared logging library and have it emit the new structured fields alongside the existing free-text message, so old tooling that parses the raw message keeps working unchanged.
- Stand up new dashboards/queries against the structured fields in parallel with the old ones, and validate they agree.
- Once consumers (dashboards, alert rules, on-call runbooks) have migrated to the structured fields, deprecate the old free-text-only path.
- Roll out service by service, starting with a low-traffic one, not as a single cutover across the whole fleet.
flowchart LR
A[Service code] --> B[Shared logging library]
B --> C{Migration phase}
C -->|during rollout| D["Emit: old free-text message + new structured fields"]
C -->|after rollout| E[Emit: structured fields only]
D --> F[Log shipper]
E --> F
F --> G["Old dashboards (parse message field)"]
F --> H["New dashboards (query structured fields)"]
Worked example
Take one high-traffic endpoint doing 5,000 requests/sec. Suppose the team sets a per-endpoint logging budget of 200 INFO-level access-log events/sec for it, to keep total ingestion cost bounded. The required sample rate is:
sample rate=5,000 req/sec200 events/sec=0.04=4%Meanwhile, if this endpoint's baseline error rate is 0.3%, that's 0.003×5,000=15 error events/sec, which stays comfortably inside the budget even at 100% logging, so ERROR/WARN can stay unsampled while INFO gets sampled down to 4%. This is the concrete reasoning a strong candidate walks through: log level and sample rate aren't picked in the abstract, they come out of (a) an ingestion budget you've set and (b) the request/error volume you actually have.
Trade-offs and pitfalls
- Sampling INFO logs means a specific request that had no error and wasn't in the sampled 4% has no log trail. That's an acceptable trade for routine traffic, but pair it with always-log-on-error and, ideally, trace-based sampling that always keeps traces for anything flagged interesting (slow, retried, or touching a specific customer), so the rare interesting case isn't lost to the sample.
- A schema that isn't enforced by a shared library drifts fast: one team adds
userId, another addsuser_id, and six months later nothing joins cleanly. Put schema validation in the library, not in a style guide. - Rolling out too fast (cutting the whole fleet to the new format in one release) is the single biggest risk here: any on-call script, saved dashboard, or SIEM rule (a Security Information and Event Management rule: a saved detection query that watches log data for suspicious patterns) that still parses the old free-text line breaks silently until someone notices during an incident, which is the worst possible time to notice. The dual-emit window exists specifically to avoid that.
- Over-redacting can be its own failure mode: hashing or dropping a field that turns out to be needed for debugging (say, an order ID that isn't actually PII) makes incidents harder to resolve. Decide field by field, don't blanket-redact everything that looks user-related.
Implement a small decorator (in Python or a language of your choice) that generates a correlation ID for each incoming HTTP request, attaches it to the request and response headers, and makes it available to any structured logs written while handling that request.
Sample Answer
Wrap the handler so it reads an inbound correlation-id header if present (otherwise generates one), stores it somewhere every log call in that request can reach without threading it through every function signature, and stamps it back onto the response headers before returning. In Python, contextvars.ContextVar is the right tool for the "reach it from anywhere" part, because it's isolated per async task and per thread, unlike a plain module-level global.
Implementation
import contextvars
import functools
import logging
import uuid
_correlation_id: contextvars.ContextVar[str] = contextvars.ContextVar(
"correlation_id", default="-"
)
HEADER_NAME = "X-Correlation-ID"
class _CorrelationIdFilter(logging.Filter):
"""Injects the current request's correlation id into every log record."""
def filter(self, record: logging.LogRecord) -> bool:
record.correlation_id = _correlation_id.get()
return True
def configure_logging() -> logging.Logger:
logger = logging.getLogger("app")
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(
logging.Formatter("%(levelname)s corr=%(correlation_id)s %(message)s")
)
handler.addFilter(_CorrelationIdFilter())
logger.handlers = [handler]
logger.propagate = False
return logger
logger = configure_logging()
def with_correlation_id(handler):
"""Decorator for a request handler with signature handler(request) -> response.
request/response are dict-like objects with a "headers" dict, matching the
shape used by most lightweight Python web frameworks (or an adapter around
a framework's native request/response objects).
"""
@functools.wraps(handler)
def wrapper(request):
incoming = request.get("headers", {}).get(HEADER_NAME)
corr_id = incoming if incoming else str(uuid.uuid4())
token = _correlation_id.set(corr_id)
try:
response = handler(request)
response.setdefault("headers", {})[HEADER_NAME] = corr_id
return response
finally:
_correlation_id.reset(token)
return wrapper
@with_correlation_id
def create_order(request):
logger.info("received request path=%s", request["path"])
logger.info("order validated")
return {"status": 201, "body": {"order_id": "o_1"}}
Key points
_correlation_idis aContextVar, not a plain global: each async task (or thread, for sync frameworks) gets its own isolated value, so concurrent in-flight requests never see each other's correlation id.- The logging filter (
_CorrelationIdFilter) reads the contextvar at log-emit time, which is what makes it "available to any structured log written while handling that request" without changing everylogger.info(...)call site to pass the id explicitly. - If the request already carries
X-Correlation-ID(it came from an upstream service that already started a trace), the decorator reuses it instead of minting a new one, so the id stays consistent across the whole call chain rather than getting reset at every hop. token = _correlation_id.set(...)plus_correlation_id.reset(token)in afinallyblock ensures the value is cleared after the request, which matters in any environment that reuses worker threads or tasks across requests (otherwise a stale correlation id could leak into the next request handled by the same worker).
Demo
Running the module directly (with uuid.uuid4 replaced by a deterministic counter-based generator, uuid.UUID(int=n) for n = 1, 2, 3, ..., purely so this demo's output is reproducible instead of depending on real randomness):
INFO corr=00000000-0000-0000-0000-000000000001 received request path=/orders
INFO corr=00000000-0000-0000-0000-000000000001 order validated
INFO corr=upstream-fixed-id received request path=/orders
INFO corr=upstream-fixed-id order validated
INFO corr=00000000-0000-0000-0000-000000000002 about to fail
demo1 response headers: {'X-Correlation-ID': '00000000-0000-0000-0000-000000000001'}
demo2 response headers: {'X-Correlation-ID': 'upstream-fixed-id'}
demo3: exception propagated as expected
context after all requests (should be default '-'): -
Three cases exercised: (1) no inbound header, a fresh id is generated and both log lines during that request carry it, and it lands on the response; (2) an inbound header (upstream-fixed-id) is present, and it's reused rather than replaced; (3) the handler raises, and the correlation id is still attached to the log line emitted before the exception, and the finally reset means the contextvar is back to its default - afterward, i.e. it didn't leak into whatever runs next on that worker.
Complexity
Per request, the decorator does a constant number of operations: one dict lookup for the inbound header, one ContextVar.set/reset pair, one dict write for the outbound header. That's O(1) time and space overhead per request, independent of how many log lines are emitted inside the handler, since each log call just reads the already-set contextvar rather than redoing any work.
Edge cases
- Missing or empty header: falls through to generating a new UUID, handled by the
if incoming elsecheck (an empty string is falsy, so it's treated the same as missing). - Header already present from upstream: reused as-is rather than overwritten, so a multi-hop call chain keeps one correlation id instead of getting a new one at every service.
- Handler raises an exception: the
try/finallystill resets the contextvar and the correlation id is still attached to any log lines emitted before the exception, so the failure is traceable. - Background work spawned from inside the handler (e.g.
asyncio.create_task(...)or a thread pool submission): a new asyncio Task does inherit the current contextvars snapshot at creation time by default, so logs from a task created directly inside the handler will still carry the id; but work handed off to a separate thread pool or a message queue does not automatically carry it; that has to be passed explicitly (e.g. as a queue message field) and re-set with_correlation_id.set(...)on the receiving side. - Concurrent requests on the same worker: isolated correctly by
ContextVar, unlike a plain module-level variable, which would let concurrent requests clobber each other's id.
What is metric cardinality, and why can high-cardinality labels be dangerous for a metrics backend like Prometheus? What are a few concrete strategies you would use to keep cardinality under control while still preserving useful signal?
Sample Answer
Direct answer
Cardinality is the number of distinct time series a metric produces, which is the metric name multiplied by every unique combination of the label values attached to it. It's dangerous for a backend like Prometheus because each unique series consumes its own memory and disk in the time-series database regardless of how rarely it's queried, so a single label that takes millions of unique values can turn one metric definition into millions of series and exhaust the backend.
Why this happens mechanically
Prometheus and similar time-series databases store each unique series (metric name plus label set) as its own indexed chunk in memory and on disk. Adding a label isn't "one more column," it's a multiplier: a metric with three labels each taking 10 values has up to 1,000 series. Add a fourth label with 100,000 unique values and that multiplies to 100 million.
The classic mistake
The two labels people most often add without realizing the cost are user_id and request_id, because from an application-code perspective they feel like natural dimensions ("I want to see this metric per user"). From the time-series database's perspective, though, they're unbounded, ever-growing label values that are rarely reused, so every request effectively creates a permanent new series that's queried exactly once, if ever.
Strategies to keep cardinality under control while preserving signal
- Push high-cardinality dimensions to logs or traces instead of metrics. A metric answers "how many, how fast, in aggregate," while a log line or trace span is where you attach the specific
user_idorrequest_idfor per-entity debugging. - Use bounded, reusable label values (customer tier, region, status code) instead of unbounded identifiers.
- Pre-aggregate at the instrumentation point, emitting a counter bucketed by tier or cohort rather than by raw ID.
- Enforce it in CI: reject metric definitions with labels that don't come from a small, known enum, before they reach production.
- Monitor cardinality itself as a metric (series count per metric name) and alert on unexpected growth, so a new high-cardinality label gets caught within hours, not after the backend is already under memory pressure.
Worked example
Assume a request-latency histogram with labels method (4 values), status_code (6 values), and endpoint (20 values), where each observation also expands into multiple series per label combination (say 12 latency buckets plus _sum and _count, 14 series total):
Now add user_id as a label, with 100,000 active users:
That's the mechanism: adding one seemingly-reasonable label multiplies series count by its cardinality, turning a perfectly manageable roughly 6,700-series metric into a 672-million-series one, the kind of number that exhausts a Prometheus instance's memory well before it's ever queried usefully.
Trade-offs and pitfalls
- There's a real tension between wanting per-customer visibility and the fact that metrics can't afford per-customer labels at scale. The resolution is almost always to split the concern: aggregated metrics for alerting and dashboards, logs or traces (or a purpose-built analytics store) for per-entity investigation, not forcing one system to do both jobs.
- Hashing or bucketing an identifier reduces cardinality but also destroys the ability to look up a specific entity later. Only do this if coarse cohort visibility is genuinely what's needed, not entity-level debugging.
- Common wrong turn: discovering a cardinality problem in production and reflexively dropping every recently-added label, losing signal that was actually useful (like
status_code), instead of first identifying which specific label is the unbounded one.
Unlock Full Question Bank
Get access to all 13 Monitoring, Logging, and Observability interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.