Interview Prep/Python for DevOps/Automation scripting & CLI design

A script reads a 15 GB access log to count 5xx errors per endpoint, and the box runs out of memory. How do you fix it?

BeginnerScenarioAutomation scripting & CLI design
Answer

Situation read → It almost certainly does f.read() or readlines(), loading the whole file.

What I'd do →

  1. Iterate the file object line by line (for line in f) and update a Counter.
  2. Use gzip.open(path, "rt") for compressed rotations instead of decompressing to disk.
  3. Precompile the regex, or use line.split() if the format is fixed.
  4. Open with errors="replace" so a single bad byte does not kill the run.
codes = Counter()
with open(path, encoding="utf-8", errors="replace") as f:
    for line in f:
        parts = line.split()
        if len(parts) > 8 and parts[8].startswith("5"):
            codes[parts[6]] += 1

Why → Streaming keeps memory constant regardless of file size.

Interview tip → Mention that for recurring analysis the right fix is to ship logs to a system built for it (Loki, CloudWatch Logs Insights, Athena).

All Python for DevOps questions Roadmap: Python for automation

More on Automation scripting & CLI design