Live SSH Log Triage and Centralized Logging Architecture

Medium · System Design · Software Engineer · Onsite

Prompt

An online backend service is actively returning errors in production. Right now, your sole debugging foothold is an SSH terminal on a live server whose on-disk log files are tens of gigabytes in size.

  1. Immediate Live-Host Triage: Explain how you would rapidly isolate the failure window and root-cause error patterns without degrading the running host, including the concrete shell pipelines, search strategies, and safety precautions you would apply.
  2. Fleet-Wide Centralized Logging: Assuming similar incidents will happen again across many machines, design an end-to-end centralized log collection, indexing, and query platform, and walk through the primary architectural trade-offs involved.

Scope & Expectations

  • Safe, fast SSH investigation: Check host-level resource exhaustion first, avoid full-file sequential scans or disk-filling temporary files, and narrow huge logs by time window and normalized error signatures.
  • Decoupled ingestion pipeline: Ensure log collection, buffering, multi-line stack-trace folding, and secret/PII scrubbing never block or crash application traffic, even during log storms.
  • Storage & indexing economics: Justify write-time vs. read-time indexing choices, partitioning, compression, and hot-vs.-cold retention tiers against realistic ingest-to-query ratios.
  • Operational resilience: Cover backpressure, noisy-neighbor isolation, query scan guardrails, and meta-monitoring when parts of the logging pipeline fail.

Step-by-step walkthrough

  1. Clarify the incident and set safe ground rules

    This question has two halves: triaging a live outage over SSH with huge local log files (spend ~15 minutes here) and designing a centralized logging platform so future incidents take seconds instead of ad-hoc shell scripts (spend ~25–30 minutes here).

    Before typing any command, clarify the setup with the interviewer. Here are the concrete assumptions we will use:

    • Symptom: Users started seeing HTTP 5xx (server error) responses from one backend service roughly 20 minutes ago.
    • Topology: A fleet of identical Linux hosts behind a load balancer; you have SSH and sudo access.
    • Log layout: Plain-text lines starting with an ISO 8601 UTC timestamp (2026-11-27T14:03:12Z), log level, logger name, message, and req_id=.... Multi-line stack traces appear on continuation lines that do not start with a timestamp. Today's active app.log is 40 GB; prior days are rotated into gzip-compressed .gz files.
    • Live traffic: The host is still serving production requests, so clumsy commands can make the outage worse.

    Work toward four goals in strict order:

    1. Mitigate first if a safe fix is obvious (roll back the deploy or config push from 20 minutes ago, or drain a single sick host from the load balancer). Restoring user traffic beats finishing root-cause analysis.
    2. Pin down the exact start minute and check what changed right before it.
    3. Isolate the new error signature (not merely the loudest old error) and verify whether one host or the entire fleet is affected.
    4. Capture evidence for the postmortem timeline before restarting processes wipes in-memory state.

    Live-host safety rules: Stick to read-only commands, never write large temporary files onto a partition that might already be full, lower your CPU/disk priority, and never copy raw logs containing personal data (PII) or secrets to an unencrypted laptop.

  2. Triage host health first before touching 40 GB of logs

    Many "application bugs" are actually a server that ran out of disk space, memory, or network sockets. Check host vitals first—these commands finish in under 5 seconds and require reading zero gigabytes of application logs:

    • Inodes: Filesystem metadata slots (one per file); millions of tiny temp files can exhaust all inodes and block writes even when df -h shows gigabytes of free disk space.
    • OOM killer (Out-Of-Memory killer): A Linux kernel safeguard that forcibly kills a process (SIGKILL) when host RAM runs out—a crash that never appears inside the victim application's own log file.
    • File descriptors (fd): Integer handles the OS assigns to each open file or network socket; hitting the per-process limit (~1,024 or ~65,536) triggers immediate "Too many open files" failures.
    uptime                              # 1m/5m/15m load averages: is CPU or disk I/O saturated?
    df -h && df -i                      # free disk bytes (-h) AND free inodes (-i)
    free -m                             # free/available RAM and swap pressure
    sudo dmesg -T | tail -n 50          # kernel ring buffer: OOM kills, disk or NIC errors
    systemctl status myapp              # process uptime, exit code, recent crash-loop restarts
    ss -s                               # TCP socket summary: connection backlog or TIME_WAIT storms
    pid=$(pgrep -o myapp)
    sudo ls /proc/"$pid"/fd | wc -l     # open file descriptors right now...
    grep 'open files' /proc/"$pid"/limits   # ...compared against the process soft/hard limit
    top -b -n 1 | head -n 20            # top CPU and memory consumers right now
    ls -lh --time-style=full-iso /var/log/myapp/   # log sizes and last-modified timestamps
    sudo lsof +L1                       # deleted files still held open by a live process
    

    Run the same 10-second check on two healthy-looking peers and check recent change history (ls -lt /opt/myapp/releases/, config push logs, last reboot):

    Is it ONLY this host?  --> Local cause: full disk, bad hardware, wedged process, stale local config.
    Is it EVERY host?      --> Shared cause: bad deploy, feature-flag/config push, overloaded DB or API.
    
  3. Narrow before scanning: fast, low-impact log commands

    Scanning 40 GB sequentially is bottlenecked by disk throughput: even on a fast NVMe SSD at 500 MB/s, reading 40,000 MB takes ~80 seconds per pass and steals disk I/O from live requests. Never open the whole file in vim (which tries to load or scan it) or pipe 40 GB into sort (which writes multi-gigabyte temporary files to /tmp and can fill the root disk).

    Use tools that seek directly to the end of the file or stop early:

    • tail -n 2000 app.log or tail -F app.log (-F follows the file name across log rotation, when app.log is renamed to app.log.1 and a fresh app.log is created): shows what is failing right now.
    • tac app.log | LC_ALL=C grep -m 1 -F ' ERROR ' (GNU Linux; tail -r on macOS): reads blocks backward from the end and stops at the single most recent error (-m 1).
    • less -n app.log (-n disables line counting so less does not scan all 40 GB up front), then press G to jump to EOF and ?ERROR to search backward.

    When you do scan a slice, make each pass cheap and polite:

    • LC_ALL=C grep -F 'literal': LC_ALL=C compares raw single bytes instead of decoding UTF-8 locales, and -F uses fast fixed-string search instead of a regular-expression state machine.
    • Prefix heavy scans with nice -n 19 ionice -c3 to yield CPU (nice) and disk (ionice idle class) priority to production traffic. Note one real-world Linux detail: ionice only enforces disk priorities when the block scheduler is bfq or mq-deadline; NVMe SSDs often default to none (check /sys/block/<dev>/queue/scheduler), where reading fewer bytes is your only real protection.
    • Gzipped rotations (app.log.1.gz) cannot be seeked into the middle—reading one requires zcat / zgrep from byte 0 of that file—which is why rotating logs hourly instead of daily makes incident triage far cheaper.
  4. Slice the exact time window with byte-offset binary search

    Because log lines are written chronologically, timestamps in app.log are sorted (up to millisecond jitter across threads). That means we can run binary search on raw byte offsets—jumping to the middle byte of the 40 GB file, advancing to the next complete timestamped record, comparing its timestamp against our target, and cutting the search range in half:

    40 GB file = ~40,000,000,000 bytes  -->  log2(40 * 10^9) ≈ 36 disk seeks per boundary!
    
    Byte offset:  0                                mid = 20 GB                              40 GB
                  |-------------------------------------|-------------------------------------|
                  1. f.seek(mid - 1); f.readline()   --> discard partial tail of current line
                  2. Read lines until TIMESTAMP      --> skip stack-trace continuation lines
                  3. Compare "2026-11-27T11:42:09" < "2026-11-27T14:00:00"
                     --> Target is in the RIGHT half! Set lo = mid + 1 and repeat.
    

    Instead of scanning 40 GB (~80 s), two binary searches (start and end) take ~72 tiny seeks (< 50 ms) and copy only the [14:00, 14:30) window (~0.8 GB, 1/48th of the day) to a separate scratch mount:

    import os
    import re
    import sys
    
    # Match ISO 8601 timestamps at the start of a log record: YYYY-MM-DDTHH:MM:SS
    TIMESTAMP_RE = re.compile(rb"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}")
    
    
    def normalize_ts(when: str) -> bytes:
        """Normalize 'YYYY-MM-DDTHH:MM' or 'YYYY-MM-DDTHH:MM:SSZ' to 19-byte 'YYYY-MM-DDTHH:MM:SS'."""
        if len(when) == 16:
            when = when + ":00"
        return when[:19].encode("ascii")
    
    
    def record_at_or_after(f, pos: int):
        """Return (byte_offset, 19_byte_ts) of the first timestamped record starting at >= pos."""
        if pos == 0:
            f.seek(0)
        else:
            # Seek 1 byte earlier so if pos is already at byte 0 of a line, readline()
            # consumes only the preceding '\n' instead of skipping that valid line.
            f.seek(pos - 1)
            f.readline()
    
        while True:
            offset = f.tell()
            line = f.readline()
            if not line:
                return offset, None  # Reached EOF without another timestamped record
            if TIMESTAMP_RE.match(line):
                return offset, line[:19]
    
    
    def find_offset(f, size: int, when: str) -> int:
        """Binary-search the smallest byte offset whose record timestamp is >= when."""
        target = normalize_ts(when)
        lo, hi = 0, size
        while lo < hi:
            mid = (lo + hi) // 2
            _, ts = record_at_or_after(f, mid)
            if ts is None or ts >= target:
                hi = mid
            else:
                lo = mid + 1
        offset, _ = record_at_or_after(f, lo)
        return offset
    
    
    def copy_window(path: str, start: str, end: str, out) -> None:
        """Copy whole multi-line log records in [start, end) to binary stream out."""
        with open(path, "rb") as f:
            size = os.fstat(f.fileno()).st_size
            start_byte = find_offset(f, size, start)
            end_byte = find_offset(f, size, end)
            f.seek(start_byte)
            remaining = max(0, end_byte - start_byte)
            while remaining > 0:
                chunk = f.read(min(remaining, 1 << 20))  # Copy in 1 MiB chunks
                if not chunk:
                    break
                out.write(chunk)
                remaining -= len(chunk)
    
    
    if __name__ == "__main__":
        # Usage: python3 log_window.py app.log 2026-11-27T14:00 2026-11-27T14:30 > /mnt/scratch/window.log
        copy_window(sys.argv[1], sys.argv[2], sys.argv[3], sys.stdout.buffer)
    

    Why normalizing to 19 bytes (normalize_ts) matters: if line[:19] is b"2026-11-27T14:00:00" and a caller passes "2026-11-27T14:00:00Z" (20 bytes) without slicing, raw byte comparison treats the 19-byte string as strictly smaller than the 20-byte target and skips valid 14:00:00 records. Also pad your search window by 1 minute on each side (13:59 to 14:31) so lines flushed slightly out of order across threads are not missed, and write window.log onto a partition with plenty of free space (/mnt/scratch).

    If Python is unavailable, a single awk pass exits immediately once timestamps pass b and keeps stack-trace lines attached to their parent record via the keep flag:

    awk -v a="2026-11-27T14:00:00" -v b="2026-11-27T14:30:00" '
      /^[0-9]{4}-[0-9]{2}-[0-9]{2}T/ {
        ts = substr($0, 1, 19)
        if (ts >= b) exit
        keep = (ts >= a)
      }
      keep' app.log > /mnt/scratch/window.log
    
  5. Pinpoint what changed: histograms, normalized signatures, and request traces

    Once you have /mnt/scratch/window.log (~0.8 GB), every query runs in 1–2 seconds.

    1. Build a per-minute error histogram (zero sorting needed). Because window.log is already ordered by time, slicing the 16-character minute prefix (YYYY-MM-DDTHH:MM) and piping into uniq -c counts errors per minute in one streaming pass:

    LC_ALL=C grep -F ' ERROR ' /mnt/scratch/window.log | cut -c1-16 | uniq -c
    #   35 2026-11-27T14:00
    #   49 2026-11-27T14:01
    #   41 2026-11-27T14:02
    #  512 2026-11-27T14:03   <-- 12x jump from ~42/min baseline right at 14:03!
    #  527 2026-11-27T14:04
    

    2. Normalize variable IDs into signatures and diff against a healthy window. Raw error lines look unique because of req_ids and latencies. Scrub numbers and IDs with sed, then compare against an earlier healthy slice (before.log, say 13:00–13:30) so noisy old errors don't distract you:

    # Group and rank top error templates during the incident:
    LC_ALL=C grep -F ' ERROR ' /mnt/scratch/window.log \
      | cut -d' ' -f4- \
      | sed -E 's/req_id=[^ ]+/req_id=?/g; s/[0-9]+/N/g' \
      | sort | uniq -c | sort -rn | head -n 15
    # 12768 c.e.PaymentClient - Timeout calling payments after N ms req_id=?
    #   830 c.e.Cache - miss storm on key user:N req_id=?
    
    # Show signatures that ONLY appear during the incident (absent in healthy before.log):
    sig() { LC_ALL=C grep -F ' ERROR ' "$1" | cut -d' ' -f4- | sed -E 's/req_id=[^ ]+/req_id=?/g; s/[0-9]+/N/g' | sort -u; }
    comm -13 <(sig /mnt/scratch/before.log) <(sig /mnt/scratch/window.log)
    

    3. Inspect one full stack trace, one end-to-end req_id, and peer hosts.

    # First matching error plus 30 lines of stack trace:
    grep -n -m 1 -A 30 -F 'Timeout calling payments' /mnt/scratch/window.log
    
    # Every log line (INFO, WARN, ERROR) for a single failing request:
    LC_ALL=C grep -F 'req_id=8f14e45f' /mnt/scratch/window.log
    
    # Fleet-wide check across peers, reading ONLY the last 2 GiB (~75 min) per host:
    for h in app-01 app-02 app-03; do
      ssh "$h" "tail -c 2G /var/log/myapp/app.log | LC_ALL=C nice -n 19 grep -c -F 'Timeout calling payments'" \
        | sed "s/^/$h /" &
    done
    wait
    

    (Tip for JSON logs: always pre-filter with fixed-string grep -F '"level":"error"' before piping to jq, because parsing JSON on every INFO line is 10–20x slower than byte substring matching.)

    Here the diagnosis is immediate: errors jumped 12x at 14:03 across every host with Timeout calling payments, 60 seconds after a config push lowered the payment timeout. You roll back the config, watch the per-minute histogram drop back to ~42/min, and transition to Part 2: designing a central logging system so nobody ever needs multi-host SSH loops again.

  6. Central logging platform: requirements and back-of-the-envelope numbers

    Functional requirements

    • Collect logs automatically from every host/container, folding multi-line stack traces into one event.
    • Interactive search by time range, service, host, level, trace_id/req_id, and free-text tokens.
    • Time-series aggregations (errors/min by service) powering dashboards and automated paging alerts, plus live tail.
    • Tiered retention (fast hot SSD tier + cheap long-term archive), per-service access control (RBAC), secret/PII redaction, and audit logging of searches.

    Non-functional requirements

    • Ingestion freshness: p95 < 30 s from log write to searchable.
    • Query latency: p95 < 5 s for 1-hour service queries; p95 < 30 s for 24-hour needle searches across the fleet.
    • Zero application impact: A logging outage or slowdown must never block or crash application threads.
    • Fault & storm isolation: Hours-long platform maintenance loses zero logs; a 10x error storm in one runaway service neither drops other services' logs nor stalls queries.

    Back-of-the-envelope capacity math (assuming a 2,000-host fleet; our 40 GB/day service is a heavy outlier, averaging 1 GB/day across all hosts):

    Raw ingest volume       2,000 hosts * 1 GB/day          = 2 TB/day raw
    Ingest throughput       2,000,000 MB / 86,400 s         = ~23 MB/s avg, ~70 MB/s at 3x peak
    Event rate (~250 B/ln)  2 * 10^12 B / 250 B             = 8B lines/day (~93k/s avg, ~280k/s peak)
    Compressed size (~8x)   2 TB / 8 (columnar + zstd)      = ~250 GB/day on disk
    Hot SSD tier (14 days)  14 days * 250 GB * 2 replicas   = ~7 TB SSD across the store cluster
    Cold archive (1 year)   365 days * 250 GB               = ~91 TB in object storage (S3/GCS)
    Kafka buffer (3 days)   3 days * 2 TB * 3 replicas      = 18 TB raw (~2.5 TB with zstd batching)
    Local agent buffer      10 GB disk cap per host         = ~10 days avg, ~6 hours for a 40 GB/day host
    Read load               ~1–2 interactive queries/s normally, 10/s during incidents + ~17 alert evals/s
    

    Key takeaway from the numbers: writes outnumber reads by ~100,000 to 1 (93,000 lines/s ingested vs. < 20 queries/s). Optimizing write-time indexing cost and compression is the single biggest architectural lever.

  7. API, structured log schema, and storage layout

    Decoupled write contract: Applications never make network calls to the logging service; they write structured JSON lines (ndjson) to stdout or local rotated files, and a local host agent tails those files asynchronously:

    Structured log event
      ts            UTC event timestamp from the app (ms precision, used for time-range queries)
      observed_ts   UTC timestamp when the agent read the line (measures clock skew & ingest lag)
      service, env, host, pod, version    (injected reliably by the agent, never trusted to ad-hoc text)
      level         DEBUG | INFO | WARN | ERROR | FATAL
      trace_id, span_id, req_id           (correlates one user request across microservices)
      message       log body + attached multi-line stack trace
      attrs         Map<String, String> for arbitrary key-value context (user_tier, endpoint, latency_ms)
    

    Read and alerting APIs (every endpoint requires a bounded [start, end) window and enforces a maximum byte-scan budget, returning partial: true with a cursor rather than running runaway scans):

    POST /v1/logs/search     {start, end, filters: {service, level, host}, text, limit, cursor}
                             -> {records: [...], next_cursor, scanned_bytes, partial: false}
    POST /v1/logs/aggregate  {start, end, filters, group_by: ["service", "level"], interval: "1m"}
                             -> {series: [...]}
    GET  /v1/logs/tail?service=checkout&level=ERROR     (Server-Sent Events stream)
    POST /v1/alerts          {query, threshold: "count > 500 in 5m", notify: "pager:checkout"}
    

    Hot-store table layout using a columnar store (a database such as ClickHouse that stores each column's values contiguously on disk rather than whole rows together, giving ~8–10x compression on repetitive log strings and fast scans of only queried columns):

    CREATE TABLE logs (
      ts          DateTime64(3),
      observed_ts DateTime64(3),
      service     LowCardinality(String),
      level       LowCardinality(String),
      host        LowCardinality(String),
      trace_id    String,
      message     String,
      attrs       Map(String, String),
      INDEX msg_tokens message  TYPE tokenbf_v1(32768, 3, 0) GRANULARITY 4,
      INDEX by_trace   trace_id TYPE bloom_filter            GRANULARITY 4
    ) ENGINE = MergeTree
    PARTITION BY toDate(ts)
    ORDER BY (service, level, ts)
    TTL toDate(ts) + INTERVAL 14 DAY;
    

    Why each clause is chosen:

    • PARTITION BY toDate(ts): Queries for today touch only today's partition, and expiring 14-day-old data drops whole daily directories instantaneously without expensive row-by-row deletes.
    • ORDER BY (service, level, ts): Incident queries almost always filter by service, level, and ts—sorting physically by those three columns puts "checkout ERRORs in the last hour" into one contiguous sequential disk read.
    • Bloom filter skip indexes (tokenbf_v1, bloom_filter): A Bloom filter is a compact bit array computed from hashed tokens that answers "could token X appear in this block of 32,768 rows?" with zero false negatives. Here 32 KiB (32,768 bytes = 262,144 bits) with k = 3 hash functions over 4 * 8,192 = 32,768 rows keeps the false-positive rate (1 - e^(-3 * 50000 / 262144))^3 ≈ 8.3% even at 50,000 distinct tokens per block—letting needle searches skip ~92% of blocks without paying for a massive full-text index.
  8. High-level architecture and end-to-end log flow

      Every production host / Kubernetes node
      +-------------------------------------------------------------------+
      | [ App ] --stdout/file--> /var/log/app.log (24h local rotation)    |
      |                                |                                  |
      |                   [ Agent: Vector / Fluent Bit ]                  |
      |                   checkpoint (inode, offset), fold stack traces,  |
      |                   redact secrets/PII, 10 GB disk buffer           |
      +--------------------------------|----------------------------------+
                                       | zstd-compressed batches
                                       v
                [ Kafka: logs topic ] (partitioned by service + host, 3-day retention)
                       |                                        \
                       v                                         \--> [ Archiver ]
         [ Indexer workers ] (batch 100k rows or 5 s)                    | Parquet + zstd (1 yr)
                       |                                                 v
                       v                                        [ Object Storage (S3/GCS) ]
         [ Columnar Log Store: 14d hot SSD, 2 replicas ]                 ^
                       ^                                                 | cold batch SQL / rehydrate
                       |                                                 |
                [ Query Service ] (RBAC, scan budgets, query cache, audit log) <-- UI / CLI / API
                       |
                       +--> [ Alert Evaluator (1m rollups) ] --> Pager / Slack
                       +--> [ Canary Meta-Monitor ] (1 synthetic line/min -> alert if lag > 60s)
    

    End-to-end life of a log line:

    1. The app appends a line to local disk in microseconds—zero network wait.
    2. Within ~1 s, the host agent tails the bytes, folds any stack trace, scrubs secret patterns (Bearer ..., SSNs, API keys) before data leaves the box, attaches service/host metadata, and ships a zstd-compressed batch to Kafka (a distributed append-only message log that decouples producers from consumers).
    3. Indexer workers read large batches (100,000 rows or every 5 s, because columnar engines thrive on large bulk inserts rather than tiny single-row writes) and insert into the hot store; lines become searchable in 10–30 s.
    4. Independently, an archiver consumer writes hourly Parquet files to object storage for cheap 1-year compliance and historical queries.
  9. Deep dive 1: choosing the storage and indexing engine

    The hardest architectural choice at 2 TB/day is how much indexing work to pay at write time versus read time:

    Dimension Full-text inverted index (Elasticsearch / OpenSearch) Labels only + chunk scan (Grafana Loki style) Columnar store + Bloom skip indexes (ClickHouse style)
    How it works Builds an inverted index (a dictionary mapping every unique word to every log ID containing it) on write Indexes only small (service, env) labels; stores compressed text chunks in object storage Stores typed columns sorted by (service, level, ts) plus per-block Bloom filters
    Write CPU & RAM High (tokenizing & indexing 280k lines/s at peak) Very low Low to medium
    On-disk footprint Largest (inverted index + stored document source) Smallest (cheap object storage) Small (~8x columnar compression)
    "checkout ERRORs, last 1h" Fast Fast (narrows by service label, scans 1h) Fastest (one tiny contiguous range)
    "Rare string across all services, 24h" Fastest (direct posting-list lookup) Slow (must decompress & scan up to 2 TB) Fast (~8% of blocks read via Bloom filter)
    "Errors/min grouped by service" Moderate Moderate (must parse log lines) Fastest (scans only service, level, ts columns)

    Why columnar + Bloom skip indexes wins here:

    • Scoped incident queries read almost nothing: All services generate 2 TB / 24 ≈ 83.3 GB/hour. If checkout is 10% of traffic (8.3 GB/hour) and 1% of its lines are ERROR, sorting by (service, level, ts) narrows "checkout ERRORs in the last hour" to ~83 MB of raw logs (~10 MB compressed on SSD)—returning in well under 1 second.
    • 24-hour needle searches still meet the < 30 s SLA: Scanning all 2 TB of raw text across 20 nodes at 1 GB/s decompressed per node would take 2,000 GB / 20 GB/s = 100 s (too slow!). With a tokenbf_v1 Bloom filter skipping ~92% of blocks for a rare token or trace_id, the cluster reads < 10% of blocks and finishes in < 10 seconds.
    • Critical schema rule—avoid high-cardinality keys: A high-cardinality field has millions of distinct values (req_id, user_id, raw URLs with IDs). Never put high-cardinality fields into index labels or the ORDER BY prefix, and keep random IDs in attrs/trace_id rather than packed into message (otherwise millions of unique IDs fill every bit of the message Bloom filter and degrade its skip rate).

    When to flip this decision: At < 100 GB/day where engineers run arbitrary regex/phrase searches across everything, OpenSearch is great; if budget is ultra-tight and queries always specify service, Loki-style object storage is cheapest.

  10. Deep dive 2: lossless, bounded ingestion under log storms

    During an outage, a broken retry loop can make one service emit 10x–50x its normal log volume—the exact moment you cannot afford to lose other services' logs or crash hosts.

    Host agent reliability & safety

    • Checkpointing across restarts and rotation: The agent persists (file_inode, byte_offset) on disk after every Kafka ACK. Prefer rename-and-reopen rotation (rename app.log -> app.log.1, create a new app.log with a new inode, signal the app to reopen—zero lost bytes; the agent finishes draining the old inode before switching) over copytruncate (copy file then truncate to length 0, which loses lines written during the copy). If copytruncate is unavoidable, the agent detects file_size < checkpoint_offset and resets its offset to 0.
    • Strict cgroup limits: Cap the agent at 0.5 CPU cores, 200 MB RAM, and a 10 GB local disk ring buffer so the logging agent itself can never trigger an OOM or fill the disk.

    Delivery guarantees and storm isolation

    • At-least-once delivery + deterministic IDs: Retrying timed-out Kafka or indexer batches means occasional duplicate writes (at-least-once). Deriving a deterministic record_id = hash(host, inode, byte_offset) lets queries or background merges deduplicate cleanly without paying for heavyweight distributed transactions (exactly-once).
    • Tiered load shedding per service: Enforce per-service token-bucket quotas (e.g., 5x normal rate). When a service exceeds its quota, drop DEBUG and INFO first, preserve WARN/ERROR/FATAL, collapse identical bursts ("repeated 12,000 times in 10s"), and emit a logs_dropped_total{service, level} metric so data loss is explicit, never silent.
    • Partition isolation: Route noisy services to dedicated Kafka partitions and indexer consumer groups so one runaway service's lag never delays ERROR ingestion for the rest of the company.
    • Event time vs. arrival time: Index by application event time ts so buffered logs from a recovered host land at their real incident minute, clamp wild future timestamps (ts > observed_ts + 5m) caused by skewed clocks, and alert when observed_ts - ts exceeds 60 s.
  11. Scaling, failure modes, and key trade-offs summary

    Scaling & incident stampede protection

    • Scale ingestion horizontally by adding Kafka partitions and stateless indexer workers; scale the hot store by sharding rows across replica pairs.
    • Isolate query compute from ingest compute: When 50 engineers open dashboards during a Sev-1 outage, route queries to read replicas (or dedicated compute nodes) and enforce per-query scan caps, timeouts (30 s), and per-user concurrency limits so heavy searches never stall fresh log ingestion. Cache closed historical 1-minute rollup buckets (< now - 2m) for dashboards and alerts.

    Failure modes and mitigations

    Failure scenario Impact if unhandled How the architecture survives
    Columnar log store down / upgrading Fresh logs cannot be indexed Kafka buffers 3 days of compressed logs; indexers replay from committed offsets upon recovery
    Kafka cluster unreachable Agents cannot ship batches Agents spool to their 10 GB local disk buffer + 24h local log files, retrying with exponential backoff and jitter
    Runaway service logs 50x volume Noisy neighbor starves cluster Per-service agent/indexer quotas shed DEBUG/INFO, isolate Kafka partitions, and increment visible drop metrics
    Logging pipeline silently stalls Engineers search empty results and think "zero errors!" Meta-monitoring canary: a probe logs 1 synthetic heartbeat per minute per region and pages if a search fails to find it within 60 s
    Region-wide network outage Central logging UI unreachable Run logging control plane in an isolated failure domain, and fall back to Part 1's SSH + binary-search playbook on local 24h files

    Summary of key trade-offs

    Design choice Selected approach Alternative Why it fits this problem
    Locating time window over SSH Byte-offset binary search (~36 seeks) Full-file grep (40 GB read) Milliseconds and near-zero disk I/O vs. ~80 s per scan on a live host
    Isolating root-cause errors Normalized signature diff vs. healthy hour Inspecting raw top-count errors Highlights newly introduced failures instead of noisy baseline chatter
    Application-to-platform link Async local file + host agent Direct synchronous network logging App latency and availability have zero dependency on logging health
    Ingestion buffer Kafka (3-day retention) Direct agent -> database writes Absorbs spikes, survives store downtime, feeds both hot store and cold archive
    Hot storage engine Columnar + Bloom skip indexes Full-text inverted index / label-only Handles 2 TB/day cheap writes + fast rollups while keeping rare-token scans < 10 s
    Retention strategy 14d SSD hot + 1y S3 Parquet cold 1 year all-hot SSD Cuts SSD storage bill ~25x while keeping recent incidents sub-second

Intuition & how it works

Imagine debugging a jammed factory assembly line when all you have is a terminal in a noisy machine room and a 100,000-page paper logbook printed in chronological order. You wouldn't sit down on page 1 and read every line while the conveyor belt is still sparking: first you glance at the wall gauges (CPU, memory, free disk space, and inodes—filesystem metadata slots that run out if millions of tiny files accumulate) because a blown fuse explains the jam in five seconds. Next, because every page is stamped with a clock time, you use binary search (opening the book to the middle byte, checking the timestamp, and repeatedly halving the remaining section) to jump straight to 14:00 in ~36 flips instead of reading 40 gigabytes, copy out a small 30-minute booklet onto a scratch pad, and compare normalized error signatures (log templates with request IDs and numbers replaced by placeholders) against a healthy earlier hour to spot what suddenly changed. To make the next outage painless, a centralized logging platform puts a lightweight host agent on each server to tail local files asynchronously into Kafka (a durable, distributed message buffer) and bulk-load them into a columnar store (a database that stores each column together on disk for ~8x compression and fast time-series counts) equipped with Bloom filter skip indexes (compact bit-array summaries per block of rows that let searches skip ~92% of blocks that definitely do not contain a rare token or trace_id).

Why do the obvious approaches fail? On a live host, running grep or sort across the full 40 GB file takes ~80 seconds of heavy disk I/O per pass—stealing throughput from production requests and risking filling a nearly full disk with temporary sort files—while reading the most frequent raw ERROR often wastes 20 minutes on a harmless warning that has fired 40 times a minute for months. On the platform side, having application code send logs directly over the network means a logging slowdown blocks live user traffic, and building a full-text inverted index (a textbook-style word-to-document map for every single word and unique ID) at 2 TB/day burns huge CPU, RAM, and SSD budgets on data nobody ever queries.

Let's trace a concrete incident on a 40 GB app.log when HTTP 5xx errors spike around 14:03:

1. 10-second host check (`df -h`, `df -i`, `free -m`, `dmesg -T`):
   Disk is 54% full, zero OOM kills, and 3 peer hosts show the same 5xx rate -> shared cause, check logs.

2. Byte-offset binary search (`log_window.py app.log 2026-11-27T14:00 2026-11-27T14:30`):
   40 GB file -> 36 seeks find byte offset for 14:00:00, 36 seeks find 14:30:00 (< 0.1 s total).
   Copies only the 800 MB window to /mnt/scratch/window.log.

3. Per-minute histogram (`LC_ALL=C grep -F ' ERROR ' window.log | cut -c1-16 | uniq -c`):
   14:00 -> 35 errors, 14:01 -> 49, 14:02 -> 41, 14:03 -> 512 (12x jump right at 14:03!).

4. Signature diff against healthy 13:00 slice (`sed` scrub IDs/numbers + `comm -13`):
   Old noisy error (42/min): "Cache miss on user:N" (present in 13:00 too -> ignore).
   Brand-new error (473/min): "PaymentClient - Timeout calling payments after N ms" -> started 60s
   after a 14:02 config push lowered payment timeout -> roll back config, 5xx drops immediately!

Key trade-offs

  • Mitigate first vs. root-cause first. Rolling back a suspect deploy or draining one bad host restores user traffic quickly, whereas restarting processes can wipe useful in-memory state. Capture 30 seconds of cheap evidence (top, open socket summary, last few thousand log lines, exact timestamp) and then mitigate immediately rather than making users wait for a full root-cause proof.
  • Byte-offset binary search vs. sequential awk/grep scan. Binary search locates a time window in ~36 seeks per boundary without touching 98% of a 40 GB file, at the cost of requiring monotonically ordered timestamps at the start of records. A streaming awk pass works even on messy formats and exits early at the end timestamp, but still reads every byte up to the window. Either way, slice once into a small file and run all exploratory queries against that slice.
  • Analyzing on the host vs. copying slices off-box. Running commands locally avoids network transfers and keeps PII (Personally Identifiable Information) inside production boundaries, but shares CPU and disk I/O with live requests (mitigated with nice -n 19 and ionice -c3, noting that ionice is a no-op when an NVMe disk uses the none scheduler). Copying a scrubbed slice to an isolated bastion protects production I/O so long as security policies allow it.
  • Structured JSON logs vs. plain-text lines. One-JSON-object-per-line (ndjson) makes field extraction (service, latency_ms, trace_id) unambiguous and eliminates fragile regex parsers, at the cost of ~20–40% larger raw byte size before compression and needing jq (ideally pre-filtered by grep -F) for human reading over SSH.
  • Columnar + skip indexes vs. full-text inverted index vs. label-only chunks. An inverted index (OpenSearch/Elasticsearch) gives the fastest arbitrary phrase search across everything but costs the most CPU and SSD at 2 TB/day; label-only object storage (Loki) is the cheapest to run but brute-force-scans compressed chunks whenever queries lack narrow labels; a columnar store sorted by (service, level, ts) with Bloom skip indexes balances cheap bulk writes, sub-second error-rate rollups, and < 10 s rare-token needle searches.
  • Kafka ingestion buffer vs. direct database writes. Putting Kafka between agents and indexers adds a cluster to operate, but absorbs traffic bursts, lets indexers write efficient 100k-row batches, survives multi-hour store maintenance without losing logs, and fans the same stream out to a cheap 1-year Parquet archive.
  • Completeness vs. stability under a 10x log storm. Enforcing per-service rate quotas that drop DEBUG/INFO first while preserving WARN/ERROR means a misbehaving service loses low-severity breadcrumbs during a flood, in exchange for guaranteeing that no single noisy neighbor can blind or crash logging for the rest of the company—provided every dropped line increments a visible metric.

Common mistakes

  • Opening a 40 GB file in vim/less (without -n) or piping it straight into sort: Editors that scan line counts freeze or consume gigabytes of RAM, and sort spills huge temporary files to /tmp that can tip a stressed disk to 100% full.
  • Skipping the 10-second host check: Hunting inside application logs when the root cause is a full disk, exhausted inodes (df -i), exhausted file descriptors, or kernel OOM kills (dmesg -T) wastes critical minutes because a dead or disk-blocked process often cannot write the fatal error to app.log at all.
  • Chasing the highest-volume raw error instead of diffing against a healthy baseline: Production logs almost always contain pre-existing noisy errors; always normalize IDs/numbers and compare signatures before vs. during the incident.
  • Truncating timestamps inconsistently or splitting multi-line stack traces: Comparing a 19-byte slice (YYYY-MM-DDTHH:MM:SS) against an un-sliced ...Z argument misses exact boundary seconds, and line-by-line grep without -A or timestamp-aware record grouping detaches Java/Python stack traces from their header line.
  • Having applications ship logs synchronously over the network: Any slowdown, DNS blip, or outage in the central logging service then backs up application threads and causes a production outage.
  • Indexing high-cardinality fields (req_id, user_id, raw URLs) in labels or sort prefixes: Millions of unique values explode index metadata and stream counts, and stuffing raw UUIDs into message saturates token Bloom filters so they stop skipping blocks.
  • Forgetting query limits and meta-monitoring: Without per-query byte-scan caps, one engineer running a 30-day wildcard regex during an outage stalls everyone else's searches; without a synthetic canary log (a 1-per-minute heartbeat verified end-to-end by an automated search), a broken ingestion pipeline looks identical to "zero errors in production."

Follow-up questions

  • If the disk is 100% full because of the active log file and the service is failing, what exact commands free space safely? First confirm what owns the space (du -xh --max-depth=1 /var/log | sort -h and sudo lsof +L1 for deleted files still held open). Truncate the active log file in place (sudo truncate -s 0 /var/log/myapp/app.log or : > app.log) rather than running rm app.log, because rm unlinks the filename while the running process still holds the open file descriptor, freeing zero bytes on disk! If someone already ran rm and lsof +L1 shows PID 4321 holding deleted descriptor 7, reclaim space immediately via : > /proc/4321/fd/7 (or restart the process once safe), then add hourly size-capped rotation (maxsize 1G) and an 80% disk alert.
  • How do you trace a single failed user request end-to-end across two dozen microservices? Generate a globally unique trace_id (such as the W3C traceparent header) at the API gateway/load balancer, propagate it automatically through every HTTP/gRPC client and async queue header, and inject trace_id into every structured log record via thread/async context. In the central columnar store, the bloom_filter skip index on trace_id lets a query WHERE ts BETWEEN t1 AND t2 AND trace_id = '8f14e45f...' skip almost every data block across all 24+ services and reconstruct the cross-service timeline in seconds.
  • How do you prevent secrets and PII from reaching centralized logs, and how do you remediate a leak if one slips through? Enforce defense in depth: ban logging raw request bodies in code review/linters, wrap sensitive struct fields in redacted types (SecretString that prints "[REDACTED]"), and run fast regex/key-name scrubbers inside the host agent so tokens, passwords, credit cards, and emails are masked before leaving the host. If PII still slips into the store, restrict query access by service via RBAC, log every search in an immutable audit trail, mask or delete affected partitions asynchronously in the hot store and Parquet archive, and switch future user correlation to non-reversible pseudonymous IDs.

Follow-up questions

Similar questions

More Box interview questions

All 9 Box questions →