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 →
- Iterate the file object line by line (
for line in f) and update aCounter. - Use
gzip.open(path, "rt")for compressed rotations instead of decompressing to disk. - Precompile the regex, or use
line.split()if the format is fixed. - 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).
More on Automation scripting & CLI design
Your team has a 300-line Bash script that parses JSON with `jq`, loops over AWS accounts and retries with `sleep`. It breaks every month. Do you rewrite it in Python?BeginnerA colleague's script deletes files older than 30 days from `/var/log/app`. You are asked to review it before it goes into cron. What do you look for?IntermediateYou need a script that ops engineers run from laptops and that CI runs nightly. How do you design its interface?IntermediateYou must run the same Python automation on 40 servers that have Python 3.6, 3.9 and 3.12. What do you do?IntermediateA cron job that runs a Python script fails silently. Nobody noticed for two weeks. How do you make sure that never happens again?IntermediateProduct wants a Slack notification whenever a deploy finishes. You have 30 minutes. What do you build?Beginner