Log Analysis and Diagnostic Data Gathering Questions
Extracting signal from existing logs and diagnostic output to find a root cause: parsing and querying log data, correlating traces and metrics during an investigation, and gathering the right diagnostic information (including asking clarifying questions) before drawing conclusions. Covers text-processing and query techniques for locating evidence in logs (structured log parsing, ElasticSearch/SQL-style log queries, log aggregation and retention trade-offs) and reconstructing a timeline from the data on hand. This is the analysis-of-existing-data skill used during troubleshooting and investigation across infrastructure and operations roles: distinct from monitoring and observability, which is about instrumenting a system so telemetry exists in the first place (see the observability topics for that), and distinct from SIEM-based security detection and formal digital-forensics practice (chain of custody, artifact/disk/memory analysis), which have their own dedicated coverage elsewhere in the catalog.
Write (or outline) a Python script that reads a large log file (streaming, may not fit in memory) of timestamped events where each line is: "ISO8601_TIMESTAMP LEVEL message". Implement an approach to identify the top-3 sliding 5-minute windows with the highest error (LEVEL=ERROR) rate and report window start, end, and error count. Explain complexity and streaming constraints.
Sample Answer
Direct answer
Stream the file line by line (never load it whole), keep only ERROR timestamps that fall inside the trailing 5-minute window in a deque (a double-ended queue that supports cheap removal from either end), and every time a new ERROR arrives, record the current window's (count, start, end) into a size-3 min-heap (a small structure that always exposes the smallest of the items it holds). At the end, the heap holds the 3 highest counts seen at any point in the stream.
Structured elaboration
ISO8601 here refers to the standard YYYY-MM-DDTHH:MM:SS timestamp format, so parsing is a direct datetime.fromisoformat() call rather than custom string-splitting.
- Read the file one line at a time (
for line in f), which keeps memory bounded by one line at a time, not the whole file. - Parse each line into
(timestamp, level, message). Skip anything that isn'tLEVEL=ERROR; non-ERROR lines don't affect the window count and can be discarded immediately. - For each ERROR event: append its timestamp to a deque, then pop from the left while the oldest timestamp is more than 5 minutes older than the current one. The deque now holds exactly the ERROR timestamps in the trailing 5-minute window, and its length is the window's error count.
- Push
(count, window_start, window_end)onto a min-heap capped at size 3. If the heap is full and the new count beats the heap's smallest entry, replace it (heapreplace); otherwise it's discarded immediately with no further work. - At the end, sort the heap's 3 entries descending by count for reporting.
Worked example
import heapq
from collections import deque
from datetime import datetime, timedelta
WINDOW = timedelta(minutes=5)
TOP_K = 3
def parse_line(line):
ts_raw, level, *_ = line.split(" ", 2)
return datetime.fromisoformat(ts_raw), level
def top_windows_from_stream(lines):
errors = deque() # ERROR timestamps currently inside the trailing 5-min window
topk = [] # min-heap of (count, window_start, window_end)
for line in lines:
ts, level = parse_line(line)
if level != "ERROR":
continue
errors.append(ts)
cutoff = ts - WINDOW
while errors and errors[0] < cutoff:
errors.popleft()
window = (len(errors), errors[0], ts)
if len(topk) < TOP_K:
heapq.heappush(topk, window)
elif window[0] > topk[0][0]:
heapq.heapreplace(topk, window)
return sorted(topk, key=lambda w: (-w[0], w[1]))
I ran this against a pinned synthetic log with three separate ERROR bursts (three, five, and four ERROR lines respectively, spaced far enough apart to be independent), interspersed with INFO noise:
base = "2026-01-01T00:{:02d}:{:02d}"
synthetic_lines = (
[base.format(m, s) + " ERROR burst-a" for m, s in [(0, 0), (1, 0), (1, 30)]]
+ [base.format(3, 0) + " INFO heartbeat"]
+ [base.format(m, s) + " ERROR burst-b" for m, s in [(10, 0), (10, 45), (11, 30), (12, 15), (13, 0)]]
+ [base.format(15, 0) + " INFO heartbeat"]
+ [base.format(m, s) + " ERROR burst-c" for m, s in [(20, 0), (20, 40), (21, 20), (22, 0)]]
) # bursts of 3, 5, and 4 ERROR lines respectively
results = top_windows_from_stream(synthetic_lines)
for count, start, end in results:
print(f"{count} errors [{start.isoformat()} -> {end.isoformat()}]")
Output:
5 errors [2026-01-01T00:10:00 -> 2026-01-01T00:13:00]
4 errors [2026-01-01T00:10:00 -> 2026-01-01T00:12:15]
4 errors [2026-01-01T00:20:00 -> 2026-01-01T00:22:00]
I cross-checked the top-1 count independently with a brute-force O(n^2) scan (for every ERROR timestamp, count ERRORs within 5 minutes before it, ignoring the streaming algorithm entirely) and it also found 5 as the maximum, confirming the streaming result is correct.
Complexity and streaming constraints
- Time:
O(n log k)wherenis the number of lines andk=3. Each line doesO(1)amortized deque work (each timestamp is pushed and popped from the deque at most once across the whole run) plus at most oneO(log k)heap operation, andk=3makes that heap cost negligible in practice. - Space:
O(m + k)wheremis the number of ERROR events that can exist inside any single 5-minute window (bounded by your event rate, not file size) andk=3for the heap. The file's total size never appears in the memory bound, which is exactly the streaming constraint the question asks about: memory scales with event density, not with file size. - Streaming constraint: the algorithm makes exactly one forward pass, never seeking backward, so it works unchanged whether the input is a local file, a piped stream, or a network socket.
Trade-offs & pitfalls
- This assumes timestamps arrive in non-decreasing order (true for a single process's own log file). Out-of-order lines (common when merging logs from multiple hosts) break the deque's "oldest is always at the front" invariant; you'd need a small out-of-order buffer or an external sort-by-timestamp pass first.
- The top-3 windows found this way can overlap heavily, as in the example above where windows 1 and 2 are both anchored in the same burst. If the interviewer wants 3 distinct, non-overlapping worst periods, add a step that discards any candidate window overlapping an already-selected one (a small non-maximum-suppression pass) before taking the top 3.
- Malformed lines (wrong field count, unparsable timestamp) should be counted and logged, not silently dropped, or you risk under-reporting error bursts without anyone noticing the pipeline is quietly losing data.
Write an ElasticSearch DSL query or SQL (pick one and state it) that finds users who experienced more than five HTTP 500 responses within any 10-minute window in the last 24 hours. Assume an index/table 'http_logs' with fields: timestamp (UTC), user_id, status_code, endpoint. Provide the query and explain assumptions about timestamp normalization and log completeness.
Sample Answer
Direct answer
I'll write this in SQL. Self-join http_logs to itself on matching user_id, keep only pairs where the second row's timestamp falls within 10 minutes after the first, group by user and window-start, and keep groups with more than 5 matches. That directly implements "more than five 500s in any 10-minute window" without assuming the windows are aligned to clock boundaries (00:00, 00:10, and so on); a genuinely sliding window has to consider every possible 10-minute span, not just fixed buckets.
Approach
import sqlite3
from datetime import datetime, timedelta, timezone
conn = sqlite3.connect(":memory:")
conn.execute("""
CREATE TABLE http_logs (
timestamp TEXT,
user_id INTEGER,
status_code INTEGER,
endpoint TEXT
)
""")
now = datetime(2025, 6, 1, 12, 0, 0, tzinfo=timezone.utc)
def ts(minutes_ago, seconds=0):
return (now - timedelta(minutes=minutes_ago, seconds=-seconds)).strftime("%Y-%m-%d %H:%M:%S")
rows = []
# user 42: six 500s inside one 10-minute window (0..9 min ago) -> should trip
for i, m in enumerate([9, 7, 6, 4, 2, 0]):
rows.append((ts(m), 42, 500, "/checkout"))
# user 99: five 500s spread across 40 minutes -> should NOT trip
for m in [40, 30, 20, 10, 0]:
rows.append((ts(m), 99, 500, "/search"))
# user 7: five 500s inside 10 minutes -> exactly 5, "more than five" excludes it
for m in [8, 6, 4, 2, 0]:
rows.append((ts(m), 7, 500, "/login"))
conn.executemany(
"INSERT INTO http_logs (timestamp, user_id, status_code, endpoint) VALUES (?, ?, ?, ?)",
rows,
)
conn.commit()
query = """
SELECT DISTINCT user_id
FROM (
SELECT a.user_id, a.timestamp AS window_start, COUNT(*) AS error_count
FROM http_logs a
JOIN http_logs b
ON b.user_id = a.user_id
AND b.status_code = 500
AND b.timestamp >= a.timestamp
AND b.timestamp < datetime(a.timestamp, '+10 minutes')
WHERE a.status_code = 500
AND a.timestamp >= datetime(?, '-1 day')
GROUP BY a.user_id, a.timestamp
HAVING COUNT(*) > 5
)
ORDER BY user_id
"""
cursor = conn.execute(query, (now.strftime("%Y-%m-%d %H:%M:%S"),))
print("users with >5 HTTP 500s in any 10-minute window (last 24h):")
for (user_id,) in cursor.fetchall():
print(f" user_id={user_id}")
Worked example (executed output)
users with >5 HTTP 500s in any 10-minute window (last 24h):
user_id=42
Three synthetic users test the boundary explicitly: user 42 has six 500s inside a 10-minute span (correctly flagged), user 7 has exactly five inside 10 minutes (correctly excluded, since the question asks for more than five), and user 99 has five 500s spread across 40 minutes (correctly excluded, since no single 10-minute window contains more than five of them).
Key points
- The self-join with
b.timestamp >= a.timestamp AND b.timestamp < datetime(a.timestamp, '+10 minutes')treats every error event as a candidate window start and counts how many errors (including itself) fall in the next 10 minutes from there; if any such window has more than 5, that user is flagged. DISTINCTin the outer query collapses potentially many qualifying window-starts for the same user down to one row per user, since the question asks which users tripped the threshold, not how many times.- An engine with native window-frame support (PostgreSQL, for example) can express the same sliding-window count more concisely with
COUNT(*) OVER (PARTITION BY user_id ORDER BY timestamp RANGE BETWEEN INTERVAL '10 minutes' PRECEDING AND CURRENT ROW). That is valid, idiomatic Postgres syntax, shown here for comparison only; it was not executed in this environment, so the self-join version above is the one to trust as verified.
Trade-offs & pitfalls
Timestamp normalization: this assumes timestamp is stored consistently in UTC (or at least a single consistent timezone) across all rows; comparing timestamps with mixed offsets would silently produce wrong window boundaries. Log completeness: if http_logs has gaps (a service that failed to log some requests, or a period logs were dropped entirely), this query can only see what's actually in the table and would undercount, never overcount, a user's true error rate. Performance: the self-join is quadratic in the worst case (http_logs rows for one user squared) without an index; in production you'd want an index on (user_id, status_code, timestamp) so both the initial filter and the join lookup are efficient rather than full scans.
Coding task in Python: build a memory-efficient utility that reads multiple large newline-delimited JSON log files and extracts, in chronological order, all events that have a given request_id between two timestamps. The function signature should be extract_events(file_paths, request_id, start_ts, end_ts) and must stream files without loading them entirely into memory. Describe edge cases you would handle in production.
Sample Answer
Direct answer
Stream each file line by line rather than reading it into memory, filter to the matching request_id and timestamp range as you go, and merge the per-file streams with a k-way merge, using a min-heap (a small structure that always exposes the smallest of the items it holds) keyed by timestamp, so the combined output comes out globally chronological without ever holding more than one buffered record per file at once.
Approach
import json
import heapq
from datetime import datetime
def _parse_ts(raw):
return datetime.fromisoformat(raw.replace("Z", "+00:00"))
def _file_matches(path, request_id, start_ts, end_ts):
"""Stream one file line by line. Assumes each file is internally
time-ordered (true of an append-only log file), so this generator
yields matching events in ascending timestamp order for THIS file.
Never holds more than the current line in memory.
"""
with open(path, "r") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
rec = json.loads(line)
except json.JSONDecodeError:
continue
if rec.get("request_id") != request_id:
continue
raw_ts = rec.get("ts")
if raw_ts is None:
continue
try:
event_ts = _parse_ts(raw_ts)
except ValueError:
continue
if start_ts <= event_ts <= end_ts:
rec["_ts_parsed"] = event_ts
yield rec
def extract_events(file_paths, request_id, start_ts, end_ts):
"""Yield events with the given request_id whose timestamp falls in
[start_ts, end_ts], in chronological order, across multiple large
NDJSON log files, without loading any file fully into memory.
Each file is scanned by its own generator (bounded to one open line
at a time); a min-heap does a k-way merge across those generators so
only one buffered record per file is held at once, not all matches.
Memory is O(number of files), not O(file size) or O(match count).
"""
heap = []
iterators = [iter(_file_matches(p, request_id, start_ts, end_ts)) for p in file_paths]
for idx, it in enumerate(iterators):
first = next(it, None)
if first is not None:
heapq.heappush(heap, (first["_ts_parsed"], idx, first))
while heap:
ts, idx, rec = heapq.heappop(heap)
del rec["_ts_parsed"]
yield rec
nxt = next(iterators[idx], None)
if nxt is not None:
heapq.heappush(heap, (nxt["_ts_parsed"], idx, nxt))
if __name__ == "__main__":
import os
file_a = "/tmp/loganalysis_b1_s13_a.ndjson"
file_b = "/tmp/loganalysis_b1_s13_b.ndjson"
# file_a and file_b are each individually time-ordered, as a real
# per-host or per-service log file would be, even though the SET of
# files is not globally ordered relative to each other.
with open(file_a, "w") as f:
f.write(json.dumps({"ts": "2025-01-01T00:00:01Z", "request_id": "req-1", "service": "C", "msg": "too_early"}) + "\n")
f.write(json.dumps({"ts": "2025-01-01T00:00:02Z", "request_id": "req-1", "service": "A", "msg": "start"}) + "\n")
f.write(json.dumps({"ts": "2025-01-01T00:00:09Z", "request_id": "req-2", "service": "A", "msg": "other_request"}) + "\n")
f.write("not valid json\n")
f.write(json.dumps({"ts": "2025-01-01T00:00:20Z", "request_id": "req-1", "service": "A", "msg": "too_late"}) + "\n")
with open(file_b, "w") as f:
f.write(json.dumps({"ts": "2025-01-01T00:00:05Z", "request_id": "req-1", "service": "B", "msg": "middle"}) + "\n")
start = _parse_ts("2025-01-01T00:00:02Z")
end = _parse_ts("2025-01-01T00:00:10Z")
for rec in extract_events([file_a, file_b], "req-1", start, end):
print(rec)
os.remove(file_a)
os.remove(file_b)
Worked example (executed output)
{'ts': '2025-01-01T00:00:02Z', 'request_id': 'req-1', 'service': 'A', 'msg': 'start'}
{'ts': '2025-01-01T00:00:05Z', 'request_id': 'req-1', 'service': 'B', 'msg': 'middle'}
file_a and file_b are individually time-ordered (as a real append-only log file would be), but the two files are not ordered relative to each other, and file_a even has an out-of-range line, a wrong-request-id line, and a malformed line mixed in. The output above still comes out correctly filtered and in chronological order across both files.
Key points
- Memory usage is
O(number of files), notO(file size)orO(number of matches): at any moment, the heap holds at most one buffered record per file, since each file is its own generator that only produces its next matching record when asked. - The k-way merge relies on one precondition worth stating explicitly: each individual file must already be time-ordered internally. That's a safe assumption for a normal append-only application log, but it would need to be checked (or the approach would need to change) for a log source that writes out of order within a single file.
extract_eventsis itself a generator (ityields rather than returning a list), so a caller can start consuming matching events immediately and stop early if it only needs the first few, rather than waiting for the entire multi-file scan to finish.
Complexity
Let N be the total number of matching events across all files and k be the number of files. Each heap push/pop is O(log k), and there are O(N) of them (one per yielded event, plus refills), so total time is O(N log k). Space is O(k) for the heap itself, plus the fixed per-line buffer each open file uses while being read, which is independent of file size.
Edge cases
- Malformed JSON lines: skipped rather than raising, so one corrupt line doesn't abort the entire scan (shown above:
file_a's "not valid json" line is silently passed over). - A file with no matches at all: its generator is simply exhausted immediately and it drops out of the heap; the merge continues correctly with the remaining files.
- Ties on identical timestamps across files: the heap comparison falls through to the file index as a tiebreaker, so results are still deterministic (files earlier in the input list sort first on an exact tie) rather than raising a comparison error on the underlying dict.
- A file that isn't actually time-ordered internally: this breaks the merge's chronological guarantee silently (each file's own stream would emit an out-of-order record without the heap detecting it), which is worth flagging explicitly rather than assuming away.
Trade-offs & pitfalls
A simpler alternative, collect every match into a list and sort once at the end, is easier to write and is fine when you expect a bounded, small number of matches for one request_id (usually true; a single request rarely touches millions of log lines). The heap-based merge shown here is the more defensible answer for a "must stream, must not load fully into memory" prompt because it doesn't rely on that assumption: it stays memory-bounded even in the pathological case where one request_id matches a huge number of events, which the simpler collect-and-sort approach would not.
You receive application logs as JSON lines with fields like ts (ISO8601), level, user_id, action, latency_ms (example shown as text: ts=2024-03-10T14:12:05Z level=info user_id=123 action=login latency_ms=42). Provide:
- A jq command (or short Python snippet) to compute counts of 'login' actions per minute
- A method to compute p95 latency for 'search' actions
- A filter to output events where user_id is missing
Explain assumptions about timezone handling and malformed JSON.
Sample Answer
Direct answer
jq is a command-line JSON processor: it reads JSON (here, one JSON object per line, sometimes called NDJSON) and lets you filter, project, and reshape it with a small query language, similar in spirit to how you'd use SQL SELECT/WHERE but for JSON text streams. The three asks below split naturally: two are jq one-liners, and the p95 latency computation is clearer in a few lines of Python since jq has no built-in percentile function.
Structured elaboration
#!/bin/bash
set -e
cat > /tmp/loganalysis_b1_s4_log.jsonl <<'EOF'
{"ts":"2024-03-10T14:12:05Z","level":"info","user_id":123,"action":"login","latency_ms":42}
{"ts":"2024-03-10T14:12:20Z","level":"info","user_id":124,"action":"login","latency_ms":55}
{"ts":"2024-03-10T14:13:01Z","level":"info","user_id":125,"action":"login","latency_ms":39}
{"ts":"2024-03-10T14:12:10Z","level":"info","action":"login","latency_ms":48}
{"ts":"2024-03-10T14:12:12Z","level":"info","user_id":126,"action":"search","latency_ms":100}
{"ts":"2024-03-10T14:12:40Z","level":"info","user_id":127,"action":"search","latency_ms":220}
{"ts":"2024-03-10T14:13:05Z","level":"info","user_id":128,"action":"search","latency_ms":180}
{"ts":"2024-03-10T14:13:30Z","level":"info","user_id":129,"action":"search","latency_ms":300}
{"ts":"2024-03-10T14:13:45Z","level":"info","user_id":130,"action":"search","latency_ms":150}
EOF
echo "1) login counts per minute:"
jq -r 'select(.action=="login") | .ts[0:16]' /tmp/loganalysis_b1_s4_log.jsonl | sort | uniq -c
echo ""
echo "3) events missing user_id:"
jq -c 'select(has("user_id") | not)' /tmp/loganalysis_b1_s4_log.jsonl
The p95 computation below embeds the same nine records directly (rather than reading the file the bash snippet above writes), so it can be copied and run on its own, independent of the bash block:
import json
import math
# Same nine records as the bash heredoc above, embedded directly here so this
# snippet runs on its own without needing that bash block to have run first.
SAMPLE_LINES = [
'{"ts":"2024-03-10T14:12:05Z","level":"info","user_id":123,"action":"login","latency_ms":42}',
'{"ts":"2024-03-10T14:12:20Z","level":"info","user_id":124,"action":"login","latency_ms":55}',
'{"ts":"2024-03-10T14:13:01Z","level":"info","user_id":125,"action":"login","latency_ms":39}',
'{"ts":"2024-03-10T14:12:10Z","level":"info","action":"login","latency_ms":48}',
'{"ts":"2024-03-10T14:12:12Z","level":"info","user_id":126,"action":"search","latency_ms":100}',
'{"ts":"2024-03-10T14:12:40Z","level":"info","user_id":127,"action":"search","latency_ms":220}',
'{"ts":"2024-03-10T14:13:05Z","level":"info","user_id":128,"action":"search","latency_ms":180}',
'{"ts":"2024-03-10T14:13:30Z","level":"info","user_id":129,"action":"search","latency_ms":300}',
'{"ts":"2024-03-10T14:13:45Z","level":"info","user_id":130,"action":"search","latency_ms":150}',
]
def p95_latency(lines, action):
latencies = []
for line in lines:
line = line.strip()
if not line:
continue
try:
rec = json.loads(line)
except json.JSONDecodeError:
continue
if rec.get("action") == action and "latency_ms" in rec:
latencies.append(rec["latency_ms"])
if not latencies:
return None
latencies.sort()
idx = math.ceil(0.95 * len(latencies)) - 1
idx = max(0, min(idx, len(latencies) - 1))
return latencies[idx]
p95 = p95_latency(SAMPLE_LINES, "search")
print(f"p95 latency for search: {p95}ms")
Worked example (executed output)
1) login counts per minute:
3 2024-03-10T14:12
1 2024-03-10T14:13
3) events missing user_id:
{"ts":"2024-03-10T14:12:10Z","level":"info","action":"login","latency_ms":48}
p95 latency for search: 300ms
Key points
- Per-minute counts: truncating the ISO 8601 timestamp string to its first 16 characters (
ts[0:16]) collapses"2024-03-10T14:12:05Z"to"2024-03-10T14:12", a minute bucket, thensort | uniq -ccounts occurrences per bucket. This only works because the timestamps are already zero-padded and lexicographically sortable, which ISO 8601 guarantees by design. - p95 latency: p95 means "95% of requests were faster than this value." With n samples sorted ascending, the nearest-rank method used here takes the value at index
ceil(0.95 * n) - 1. It is a common, simple choice for ad hoc analysis; a statistics library's percentile function may use linear interpolation between ranks instead, which gives a slightly different number on small samples, so don't be surprised if two tools disagree by a few milliseconds on the same data. - Missing user_id:
select(has("user_id") | not)filters to objects where the key is absent entirely. That's different fromselect(.user_id == null), which would also match a key that exists but was explicitly set tonull. Decide which case you actually mean; production logs sometimes have both.
Trade-offs & pitfalls
The assumption doing the most work here is that every ts is UTC and already zero-padded, so a plain string prefix and a plain string sort behave correctly. If timestamps come from multiple sources with mixed timezones (a local offset instead of Z), string-prefix bucketing silently groups events into the wrong minute; normalize to UTC with a real datetime parser first in that case, don't trust the string. Malformed JSON lines are another common trap: a bare jq filter without a try/? guard aborts the whole run on the first bad line, whereas the Python snippet here explicitly skips lines that fail json.loads so one corrupt line doesn't take down the whole aggregation.
Write a Python 3 script that reads a newline-delimited log file where each line is a JSON object with keys: "timestamp" (ISO 8601), "service", "level", "message". The script should output per-minute error counts (level == "ERROR") for a given service over the last 60 minutes, printing lines like: 2025-03-12 14:05 3. The log may be out-of-order and can be large (~10GB): prioritize streaming and bounded memory.
Sample Answer
Direct answer
Stream the file line by line and keep only a small dict of per-minute counters, never the raw lines, so memory stays bounded regardless of file size. Because the file can be out of order, the true 60-minute window boundary (which minute is "now") isn't known until you've seen the latest timestamp, so prune the counters dict opportunistically as later, larger timestamps arrive, rather than needing a full second pass over the file.
Approach
import json
from datetime import datetime, timedelta, timezone
WINDOW_MINUTES = 60
def _parse_ts(raw):
if raw.endswith("Z"):
raw = raw[:-1] + "+00:00"
dt = datetime.fromisoformat(raw)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
def per_minute_error_counts(path, service):
"""Stream a large NDJSON log file and return per-minute ERROR counts
for `service` over the last WINDOW_MINUTES relative to the latest
timestamp seen, as a dense list of (minute, count) tuples (one entry
per minute, zero-filled).
The file may be out of order. Rather than buffering every distinct
minute seen across the whole file, the counts dict is pruned WHILE
streaming: every time a new maximum timestamp arrives, anything
older than (new_max - WINDOW_MINUTES) is dropped. Memory therefore
stays close to O(WINDOW_MINUTES) even over a ~10GB file, at the cost
of one bookkeeping check per line rather than a second pass.
"""
counts = {}
newest = None
with open(path, "r") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
rec = json.loads(line)
except json.JSONDecodeError:
continue
if rec.get("service") != service:
continue
raw_ts = rec.get("timestamp")
if not raw_ts:
continue
try:
ts = _parse_ts(raw_ts)
except ValueError:
continue
if newest is None or ts > newest:
newest = ts
cutoff = newest - timedelta(minutes=WINDOW_MINUTES - 1)
for bucket in [b for b in counts if b < cutoff.replace(second=0, microsecond=0)]:
del counts[bucket]
if rec.get("level") == "ERROR":
bucket = ts.replace(second=0, microsecond=0)
counts[bucket] = counts.get(bucket, 0) + 1
if newest is None:
return []
window_start = (newest - timedelta(minutes=WINDOW_MINUTES - 1)).replace(second=0, microsecond=0)
result = []
cur = window_start
end = newest.replace(second=0, microsecond=0)
while cur <= end:
result.append((cur.strftime("%Y-%m-%d %H:%M"), counts.get(cur, 0)))
cur += timedelta(minutes=1)
return result
if __name__ == "__main__":
import os
path = "/tmp/loganalysis_b1_s18.ndjson"
lines = [
{"timestamp": "2025-03-12T14:05:10Z", "service": "checkout", "level": "ERROR", "message": "timeout"},
{"timestamp": "2025-03-12T13:00:00Z", "service": "checkout", "level": "ERROR", "message": "too old, outside 60min window"},
{"timestamp": "2025-03-12T14:05:40Z", "service": "checkout", "level": "ERROR", "message": "timeout"},
{"timestamp": "2025-03-12T14:59:59Z", "service": "checkout", "level": "ERROR", "message": "latest event, defines the window end"},
{"timestamp": "2025-03-12T14:05:20Z", "service": "checkout", "level": "INFO", "message": "not an error"},
{"timestamp": "2025-03-12T14:07:00Z", "service": "checkout", "level": "ERROR", "message": "timeout"},
{"timestamp": "2025-03-12T14:07:05Z", "service": "auth", "level": "ERROR", "message": "different service"},
]
with open(path, "w") as f:
for rec in lines:
f.write(json.dumps(rec) + "\n")
for bucket, cnt in per_minute_error_counts(path, "checkout"):
if cnt:
print(f"{bucket} {cnt}")
os.remove(path)
Worked example (executed output)
2025-03-12 14:05 2
2025-03-12 14:07 1
2025-03-12 14:59 1
The synthetic input above is deliberately out of order and mixes services and levels: a 13:00 entry (an hour before the latest timestamp, correctly excluded from the 60-minute window), an INFO-level entry at 14:05 (correctly excluded, not an ERROR), and an entry from a different service, auth (correctly excluded). The three surviving lines match exactly what the question's example output format specifies: YYYY-MM-DD HH:MM count.
Key points
- Memory stays close to
O(WINDOW_MINUTES), notO(distinct minutes in the whole file): every time a new maximum timestamp arrives, the code immediately drops any bucket older thannew_max - 60 minutes, rather than waiting until the end of the file to filter. Over a ~10 GB file that could span far more than an hour of wall-clock time, this keeps the counters dict small throughout the scan instead of growing with every minute the file happens to contain. - The underlying function returns a dense per-minute series (one entry per minute of the 60-minute window, zero-filled where there were no errors), which is more useful than a sparse series if you intend to plot it; the driver code above only prints non-zero minutes to match the requested output format, but the zero-filled minutes are still available from the function's return value.
- Out-of-order tolerance comes from tracking the running maximum timestamp seen so far, not from assuming the file's line order matches timestamp order at all.
Complexity
Time is O(n) for n lines in the file, one pass, no sorting. Space is bounded by the number of distinct minute buckets retained at any point, which the opportunistic pruning keeps close to the 60-minute window rather than proportional to the file's total time span.
Edge cases
- No matching lines at all (wrong service, or no ERROR-level entries): the function returns an empty list rather than guessing a window relative to wall-clock "now," since there's no timestamp evidence in the file to anchor a window to.
- All events in the same single minute: the loop still correctly walks the full 60-minute range and reports that one minute's count alongside 59 zero counts in the dense series.
- A timestamp that fails to parse: skipped rather than raised, so one malformed line doesn't abort processing of a 10 GB file.
Trade-offs & pitfalls
The main design decision worth defending is anchoring "last 60 minutes" to the latest timestamp actually seen in the file, rather than to wall-clock now(). For a file being analyzed after the fact (which is the realistic scenario for "you're handed a log file and asked to find the error pattern"), the data's own latest timestamp is the meaningful reference point; anchoring to now() instead would silently produce an empty or wrong window whenever the file isn't from the current moment, which is the common case during an investigation. The trade-off of opportunistic pruning versus a simpler two-pass approach (scan once for the max timestamp, then scan again to aggregate) is one pass of I/O saved at the cost of slightly more bookkeeping per line; for a 10 GB file, halving the required I/O is worth that complexity.
Unlock Full Question Bank
Get access to all 28 Log Analysis and Diagnostic Data Gathering interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.