Automation Scripting for Operations Questions
Writing scripts and tooling to automate operational and delivery tasks: shell and Python scripting, glue automation, toil reduction, and operational efficiency. Covers automating repetitive infrastructure and deployment work and building internal tooling that raises operational leverage. The concern is task-level automation and scripting, distinct from full pipeline or infrastructure-as-code frameworks.
Provide concise Python pseudocode implementing a saga-style multi-step orchestration coordinator. Each step must implement 'execute' and 'compensate' methods; the coordinator should persist progress, retry idempotently on transient failures, and execute compensating actions if a fatal step fails. Show how you would store state and resume after restarts.
Sample Answer
Approach
A saga coordinator's whole job is guaranteeing one of two outcomes: every step committed, or every COMPLETED step was compensated -- never a state where some steps committed and others didn't with no attempt to reconcile.
class Step:
def __init__(self, name, execute, compensate):
self.name = name
self.execute = execute # callable, no args, may raise
self.compensate = compensate # callable, no args, must be safe to call even if execute partially ran
class SagaCoordinator:
def __init__(self, steps, state_store):
self.steps = steps
self.state = state_store # durable key-value store, keyed by f"{saga_id}:{step_name}"
def run(self, saga_id):
completed = []
for step in self.steps:
key = f"{saga_id}:{step.name}"
if self.state.get(key) == "done":
completed.append(step) # RESUME: skip steps already completed in a prior attempt
continue
try:
step.execute()
self.state[key] = "done"
completed.append(step)
except Exception as e:
self._compensate(saga_id, completed)
raise RuntimeError(f"saga failed at '{step.name}', compensated {len(completed)} steps") from e
return "committed"
def _compensate(self, saga_id, completed_steps):
for step in reversed(completed_steps): # undo in reverse of completion order
step.compensate()
self.state[f"{saga_id}:{step.name}"] = "compensated"
Verified in a sandbox with a 3-step saga (reserve-inventory, charge-payment, ship-order) where the third step deliberately fails: the coordinator correctly compensated ONLY the first two (which had actually completed), in exactly the reverse of their completion order (charge-payment compensated before reserve-inventory), confirmed by the exact execution log produced. A second test confirmed the resume path: given a state store where two of three steps were ALREADY marked "done" (simulating a coordinator restart after a crash), re-running the saga correctly executed ONLY the one remaining incomplete step, never re-executing the already-completed ones.
Idempotent retry on transient failures
step.execute should itself be idempotent (or the saga needs its own per-step retry wrapper using the retry-decorator pattern covered elsewhere in this topic) so that a transient failure during execution can be safely retried without risking a double-charge or double-reservation -- the coordinator's job is sequencing and compensation, not retry logic itself, which composes as a separate concern the same way it does for the standalone retry decorator discussed earlier in this topic.
Persisting state and resuming after restart
The state_store needs to be genuinely durable (a database, not in-process memory) for resume to survive a real process crash, not just an in-process exception -- the verified resume behavior above depended on a state store that outlives the coordinator instance itself, which is exactly what a durable key-value store (or a table in the application's existing database) provides in production.
Scoping: pattern versus platform
This is deliberately scoped as a REUSABLE CODING PATTERN a team drops into their own service -- a library primitive, not a standalone multi-service orchestration PLATFORM coordinating steps across many different teams' services with its own operator console and cross-team governance (that's a materially larger system-design problem belonging to CI/CD or platform-engineering territory, not this topic's task-level scripting scope). The distinction matters for how much infrastructure investment is justified: this pattern is worth building for a single team's own multi-step workflow; the platform version is a different, much larger undertaking.
Trade-offs and pitfalls
The most common bug in a from-scratch saga implementation is a compensate function that ASSUMES the corresponding execute fully succeeded, when in fact execute could have failed PARTWAY through its own work (e.g., a step that both reserves inventory AND sends a notification, where only the reservation half completed before the step raised) -- compensate needs to be written defensively against 'what if this step's own effect was itself partial,' not just 'undo what a fully-successful execute would have done.'
Edge cases: a step's compensate() call itself raising an exception (the undo action fails) needs explicit handling -- silently swallowing it hides a saga that's now in a genuinely inconsistent state, while letting it propagate uncaught can abort compensation of the REMAINING completed steps; logging it loudly and continuing to attempt the rest of the compensation chain is usually the safer default than either extreme.
Implement a Python helper 'run_cli(cmd: List[str], timeout: int, log_file: str)' that runs an external CLI safely: it should enforce a timeout, stream stdout and stderr to a rotating log file, return the exit code, and ensure no zombie processes remain if the parent crashes or is killed. Show key code and explain how you guarantee resource cleanup on termination.
Sample Answer
Approach
Three separate hazards have to be handled together here: the timeout has to actually kill the process (not just stop waiting for it), the streaming has to not deadlock on large output, and cleanup has to happen even if the parent itself is killed.
import subprocess, threading, time
def run_cli(cmd, timeout, log_file):
with open(log_file, "w") as lf:
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, bufsize=1)
def pump():
# read line-by-line in a background thread so stdout is drained
# continuously -- reading ONLY after the process exits risks the
# child blocking on a full OS pipe buffer if it writes a lot of output
for line in proc.stdout:
lf.write(line)
lf.flush()
pumper = threading.Thread(target=pump, daemon=True)
pumper.start()
try:
exit_code = proc.wait(timeout=timeout)
except subprocess.TimeoutExpired:
proc.kill() # SIGKILL: don't trust the child to honor SIGTERM
proc.wait() # REAP the process -- this is what prevents a zombie
exit_code = -9
pumper.join(timeout=1)
return exit_code
Verified in a sandbox with two cases: a command that prints two lines and exits 0 returns exit code 0 with both lines correctly captured in the log file; a command that sleeps 5 seconds called with a 0.3s timeout is killed and reaped in ~0.3s (confirmed the process does not linger), returning exit code -9.
Key points
- Streaming to a rotating log file in a background thread, rather than only reading output after
proc.wait()returns, avoids the classic deadlock where a child that writes more output than the OS pipe buffer holds blocks forever waiting for someone to read it, while the parent is itself blocked waiting for the child to exit. proc.kill()(SIGKILL) rather thanproc.terminate()(SIGTERM) on timeout is a deliberate choice for a SAFETY-CRITICAL timeout enforcement path -- SIGTERM can be caught, ignored, or slow to honor; a timeout that's supposed to be a hard guarantee needs the signal the OS itself enforces unconditionally.
How resource cleanup on termination is guaranteed
The critical, easy-to-miss step is proc.wait() immediately AFTER proc.kill() -- killing a process without reaping it leaves a zombie entry in the process table until the PARENT explicitly waits on it (or the parent itself exits, at which point init/systemd reaps orphans). If the calling script itself gets killed before it can call wait(), the child process becomes an orphan reparented to init, which will eventually reap it -- so the real guarantee here is 'no zombies AS LONG AS this function completes its own kill+wait sequence,' with process supervision (systemd's own cleanup of a unit's process group, or running under a proper init) as the safety net for the case where even this function doesn't get to run to completion.
Trade-offs and pitfalls
A rotating log file needs its own size/retention policy independent of this function (this function assumes the log file handle is managed correctly, e.g. via Python's logging.handlers.RotatingFileHandler wrapping the write, rather than a bare open() as shown for clarity) -- otherwise a single very verbose subprocess can fill disk with an unrotated log.
Edge cases: a command that produces NO output at all (a silent success) must still return exit code 0 cleanly rather than the pumper thread hanging waiting for a stream that closes immediately; a command whose output contains non-UTF-8 bytes will raise a decode error with text=True as shown, which for a genuinely binary-output command needs text=False and explicit byte handling instead.
Design monitoring and alerting for a fleet of scheduled automation jobs. What health metrics would you collect to know a job is actually healthy, what alerting thresholds would you set to avoid paging noise, how would escalation and runbook integration work, and where might automated remediation be safe to attempt for transient failures?
Sample Answer
Direct answer
Monitoring a FLEET of scheduled jobs is a different problem from monitoring one job: the goal is surfacing the few jobs that are actually unhealthy out of potentially hundreds that are fine, without burying the signal in noise.
Health metrics to collect
Per job: success rate over a rolling window (not just 'did the last run succeed' -- a job that fails 1 run in 20 looks different from one that just started failing every run), duration (and duration trend -- a job that's gradually getting slower is an early warning before it eventually times out), last-run timestamp (is this job even firing on schedule, or silently stopped triggering entirely), retry count per run (a job succeeding only after 3 retries every time is degraded even though it's technically 'succeeding'), and jitter (how much actual fire-time deviates from scheduled time, which surfaces scheduler-level problems separate from the job's own logic).
Alerting thresholds that avoid noise
Alert on SUSTAINED or TREND signals, not single-run blips: a job that fails once and succeeds on its next scheduled run is not worth paging anyone about (that's exactly what retry/backoff exists to absorb); a job failing its last 3 consecutive runs, or a job whose success rate drops below some threshold (e.g. 90%) over a rolling window, is a real signal. Separate paged (wake someone up) from non-paged (a dashboard/ticket, reviewed during business hours) by actual urgency -- a nightly backup job failing has hours before it matters; a job gating an active deployment failing needs to page immediately.
Escalation flow and runbook integration
A page should link DIRECTLY to that job's specific runbook (not a generic 'automation is broken, good luck' page) -- the runbook should cover the common failure modes for that specific job class (dependency down, resource exhaustion, a known-flaky external API) and the safe manual remediation steps. Escalate to a secondary on-call if the primary doesn't acknowledge within a defined window, and auto-resolve the page if the job self-recovers on its next scheduled run rather than requiring a human to manually close it.
Auto-remediation for transient failures
Safe candidates for automated remediation: a job that fails due to a transient, well-understood cause (a known-flaky dependency that recovers on its own) can have an automatic extra retry attempt beyond its normal retry policy, with a page only firing if THAT also fails. Riskier or ambiguous failures (anything that could indicate a real logic bug, or anything destructive) should never auto-remediate -- auto-remediation is appropriate only when you're confident re-running the exact same job with the exact same inputs is safe (idempotent) and the failure class is well-understood enough that blind retrying isn't masking a real, worsening problem.
Worked example: a nightly backup job
Applying this design to one specific job: track success rate (page if 2 consecutive nightly runs fail), duration (warn, don't page, if a run takes 50% longer than its 30-day rolling average -- an early signal before it eventually breaches a hard timeout), and snapshot size (a suspiciously small backup can indicate the source data wasn't actually captured, a silent-failure mode plain success/failure status won't catch). The runbook for this job should explicitly cover 'how to verify the backup is actually restorable,' not just 'how to re-run it,' and alerting should be tested periodically (deliberately break the job in staging) rather than trusted to work correctly just because it was configured once.
Trade-offs and pitfalls
The most common mistake is measuring toil-reduction success purely by count of automations shipped rather than by actual adoption and hours genuinely saved -- a platform team incentivized on shipped-automation count will optimize for easy, low-value wins rather than the highest-impact toil identified by the prioritization framework above. Edge case: a task that LOOKS automatable but has a rare, high-judgment exception baked into how humans currently handle it (an edge case that occurs 1% of the time but needs real judgment) can produce an automation that's net-negative if that exception isn't explicitly carved out and routed to a human.
You are building automation that calls an external payment API. Describe a robust error-handling strategy: include timeouts, retries with exponential backoff and jitter, idempotency keys for non-idempotent endpoints, circuit-breaker logic, alerting thresholds, and how to surface incidents to operators without causing noise.
Sample Answer
Direct answer
Calling a payment API is the canonical case where getting error handling wrong doesn't just mean a failed request, it means real money moving incorrectly -- so every piece of this design has to be justified by 'what happens if I get this specific part wrong.'
Timeouts, retries, and backoff
Set an explicit timeout well below whatever the caller's own SLA allows, so a hanging payment call doesn't cascade into a hanging caller. Retry with exponential backoff and full jitter on genuinely TRANSIENT failures (connection errors, 5xx, explicit rate-limit responses) -- but a payment call's retry policy needs a MUCH more conservative max-attempts and total-window than a read-only API call, because every additional retry is another chance to actually double-charge if idempotency isn't airtight.
Idempotency keys are non-negotiable here
Unlike a read-only GET (safe to retry unconditionally), a payment charge is the textbook non-idempotent operation, and retrying it blindly risks a double-charge if the first attempt actually succeeded and only the response was lost. Generate a unique idempotency key BEFORE the first attempt and send the SAME key on every retry of that logical operation -- a well-designed payment API deduplicates on that key server-side, so even if the automation retries an attempt that actually already succeeded, the payment provider recognizes the duplicate and returns the original result rather than charging twice. This is the single most important design decision in the whole answer: without it, none of the backoff/jitter tuning matters, because the danger isn't retrying too aggressively, it's retrying an operation that isn't actually safe to repeat.
Circuit-breaker logic
If the payment API starts failing at an elevated rate, a circuit breaker should trip and stop sending new requests for a cooldown window -- both to avoid making an ongoing provider-side incident worse, and because at that failure rate, individual retries are unlikely to succeed anyway; better to fail fast, queue the request for later, and free up resources than to keep an ever-growing backlog of slow-failing in-flight retries.
Alerting without noise
A single failed payment attempt that succeeds on retry is not incident-worthy (that's what the retry logic is FOR). Alert on sustained signal: circuit breaker trips, a sustained elevated failure rate over a rolling window, or -- critically for payments specifically -- any detected DISCREPANCY between attempted charges and confirmed charges (a signal that idempotency might have a gap somewhere), which deserves an immediate, high-priority page regardless of overall volume, because it's the one failure mode with direct financial consequences.
Surfacing incidents to operators
A payment failure that exhausts all retries needs a clear, actionable notification (which transaction, which customer, what the payment provider actually said) routed to whoever owns payment reconciliation, not buried in a generic error log -- and the automation should fail SAFE, meaning it should never silently swallow a payment failure and move on as if it succeeded; the caller needs to know definitively whether the charge happened, partially happened, or is in an unknown state requiring manual reconciliation.
Trade-offs and pitfalls
The single most dangerous mistake in this domain is treating a TIMEOUT the same as a definite failure and retrying unconditionally -- a timeout means 'I don't know what happened,' not 'it definitely failed,' and without an idempotency key, retrying an unknown-outcome operation is exactly how double-charges happen in production payment systems.
You must migrate hundreds of ad-hoc Bash automation scripts to a centralized automation platform. Draft a migration plan covering discovery and inventory, risk-based prioritization, refactoring strategy (how to translate bash into reusable modules), testing, packaging, rollout strategy, rollback plan, documentation, training, and success metrics.
Sample Answer
Direct answer
Hundreds of ad-hoc Bash scripts migrating to a centralized platform is a genuinely large undertaking where the risk isn't any single migration step, it's the aggregate exposure of touching hundreds of production-adjacent scripts -- so the plan has to be sequenced by risk, not just by convenience.
Discovery and inventory
Before migrating anything, build a complete inventory: what scripts exist, where do they run (cron, manually, CI), what do they actually do, how often, and critically, HOW risky is each one if it breaks (does it touch production data, is it destructive, is it on a critical path). This inventory is the input to every subsequent decision -- migrating blind, without knowing what you actually have, is how a migration effort quietly misses a critical script nobody remembered existed until it broke.
Risk-based prioritization
Rank by the same frequency x impact x risk logic used elsewhere in this topic for toil prioritization, but inverted for migration ORDER: migrate LOW-risk, well-understood scripts FIRST (to build confidence in the platform and the migration process itself with low stakes), and save the highest-risk, most business-critical scripts for LAST, once the platform and the team's migration muscle-memory are both proven on lower-stakes work.
Refactoring strategy: bash into reusable modules
Don't do a literal line-for-line Bash-to-Python translation -- that just moves the same design (often lacking the idempotency/retry/logging discipline this topic argues for) into a new language without fixing anything. Instead, decompose each script into its actual PURPOSE (what desired state does it establish, what side effects does it have) and reimplement using the platform's shared primitives (retry, secrets, logging, CLI framework) rather than reinventing them per-script -- this is where the real value of centralizing comes from, not just 'the same logic in a different language.'
Testing, packaging, rollout, rollback
Each migrated script needs its OWN test coverage (unit + integration, per the testing discipline covered elsewhere in this topic) before being trusted to replace the Bash original -- run the new version in SHADOW mode alongside the still-active original for a validation period (comparing outputs/behavior) before cutting over, exactly the pattern recommended for migrating manual runbooks to automation elsewhere in this topic. Package and version each migrated script through the platform's standard packaging path, not ad-hoc. Roll out script-by-script (never migrate everything simultaneously), with an explicit, tested rollback path back to the original Bash script for each one, kept available until the new version has proven itself in production for a defined period.
Documentation, training, success metrics
Document the NEW version per the maintainability-checklist discipline covered elsewhere in this topic (owner, runbook, what it does) since a migrated script inherits none of the tribal knowledge that may have existed (however informally) around the original. Train the teams who'll actually operate these day-to-day, not just the migration team. Measure success concretely: number of scripts migrated (progress), incident rate for migrated vs not-yet-migrated scripts (does centralizing actually reduce operational risk, the core hypothesis being tested), and time saved per migrated script versus migration effort spent (is the ROI holding up as the effort progresses, or degrading on harder scripts).
Trade-offs and pitfalls
The most common failure mode in a migration this large is treating it as a fixed-scope project with a deadline rather than an ongoing, prioritized queue -- forcing a hard deadline on hundreds of scripts of wildly varying risk and complexity creates pressure to rush the highest-risk ones just to hit the date, which is exactly backwards from the risk-based sequencing this plan is built around.
Unlock Full Question Bank
Get access to all Automation Scripting for Operations interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.