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.
In Python 3, implement a small CLI skeleton using argparse with subcommands backup and restore. Requirements: global --verbose and --dry-run flags, backup --path PATH must validate that PATH exists, restore --version VERSION must accept a version string. The submission should focus on argument parsing, validation, help text, and exit codes (0 success, 1 runtime error, 2 for usage). You do not need to implement real backup logic, only the CLI structure and validation.
Sample Answer
Approach
For a backup/restore CLI, argparse subparsers give you isolated flag namespaces per command plus free -h text, which is exactly what a multi-command tool needs.
import argparse, os, sys
def build_parser():
p = argparse.ArgumentParser(prog="backuptool")
p.add_argument("--verbose", action="store_true")
p.add_argument("--dry-run", action="store_true")
sub = p.add_subparsers(dest="command", required=True)
backup = sub.add_parser("backup")
backup.add_argument("--path", required=True)
restore = sub.add_parser("restore")
restore.add_argument("--version", required=True)
return p
def main(argv=None):
parser = build_parser()
args = parser.parse_args(argv)
try:
if args.command == "backup":
if not os.path.exists(args.path):
print(f"error: path does not exist: {args.path}", file=sys.stderr)
return 2 # usage error: bad input, nothing was attempted
if args.dry_run:
print(f"[dry-run] would back up {args.path}")
return 0
# ... real backup logic would go here ...
return 0
elif args.command == "restore":
if not args.version.strip():
print("error: --version must be non-empty", file=sys.stderr)
return 2
if args.dry_run:
print(f"[dry-run] would restore version {args.version}")
return 0
# ... real restore logic would go here ...
return 0
except Exception as e:
print(f"runtime error: {e}", file=sys.stderr)
return 1 # the operation was attempted and failed
if __name__ == "__main__":
sys.exit(main())
Key points
add_subparsers(dest="command", required=True)makesargparseitself reject an invocation with no subcommand (exit code 2, argparse's own usage-error convention), rather than the script having to check forNonemanually.--pathexistence is validated explicitly and returns 2 (usage error, nothing attempted) rather than 1 -- the caller typed a bad path, the tool never touched anything.- The runtime
try/exceptaround actual command dispatch is what earns exit code 1: something was ATTEMPTED and failed, as opposed to a bad invocation. --dry-runreturns before any state-mutating call, and is checked identically in both subcommands so the pattern generalizes -- the same shape applies whether the tool grows adeploy --targetsubcommand or arun/plan/applytriad; the CLI skeleton doesn't change, only what's inside the dry-run branch does.
Complexity
Argument parsing itself is O(number of flags) with argparse's built-in machinery; not a meaningful cost. The design cost that matters is keeping validation (usage errors) and execution (runtime errors) cleanly separated so the two failure classes map to two different exit codes consistently across every subcommand.
Edge cases
restore --version "" (empty string passes required=True since the flag was technically supplied) must be checked explicitly, which the code above does. Unknown subcommands and missing required flags are handled by argparse itself, exiting 2 automatically. A --path that exists but isn't readable (permissions) should also surface as a runtime error (1), not a silent failure -- worth calling out even though it's not in the original spec, because it's the kind of edge case that ships broken in a first draft.
Edge cases: an empty --path/--version argument passed as a whitespace-only string technically satisfies required=True and needs its own explicit check (the code above already handles this for --version); a --path that exists but isn't readable due to permissions should surface as a runtime error (exit 1), not crash with an uncaught PermissionError traceback.
Trade-offs and pitfalls
A hand-rolled argparse skeleton like this trades a little boilerplate for full control over exit-code semantics; a higher-level framework (click, typer) would reduce the boilerplate at the cost of the framework choosing some of those conventions for you, which matters if the team needs exit codes to match an existing internal standard rather than the framework's own defaults.
Describe safe retry strategies for operational automation that interacts with flaky remote services (APIs, package registries, databases). Explain exponential backoff, constant backoff, full jitter vs equal jitter, max-attempt limits, retry windows, idempotency concerns when retrying side-effecting operations, and when to circuit-break instead of retrying. Include examples of mistakes that can cause cascading failures.
Sample Answer
The goal of a retry strategy is to survive genuinely transient failures without making things worse -- either by hammering an already-struggling service or by silently corrupting state through an unsafe retry.
The backoff/jitter vocabulary
- Constant backoff: wait the same fixed interval between every attempt. Simple, but if many clients fail at once (a deploy, a brief network blip) they all retry in lockstep and re-create the exact spike that caused the failure.
- Exponential backoff: each retry waits roughly
base * 2^attempt. Spreads load out over time, but without jitter, many clients that failed at the same moment still retry at the same computed delays -- lockstep survives, it's just spaced out further. - Full jitter:
delay = random(0, base * 2^attempt)-- the whole computed ceiling is randomized down to zero. This is what actually breaks the synchronization: two clients that failed simultaneously now retry at genuinely different, unpredictable times. - Equal jitter:
delay = base*2^attempt/2 + random(0, base*2^attempt/2)-- keeps a guaranteed minimum wait while still spreading. Useful when you want a floor on how soon anyone retries (protects a service that's still overloaded) at the cost of slightly less spread than full jitter.
Bounding the retry
max-attempt limits cap total attempts so a truly broken dependency fails loudly instead of retrying forever. retry windows cap total elapsed time rather than attempt count, which matters more when backoff grows large (5 attempts at exponential backoff could span minutes; you may want to give up on wall-clock time instead). Both should exist together: attempts to bound retry density, a window to bound retry duration.
Idempotency is the real gate
Retrying is only safe if re-running the operation doesn't double its effect. A GET is naturally safe to retry. A POST that charges a card or inserts a row is not, unless the operation itself is made idempotent (an idempotency key the server deduplicates on, a conditional write, an upsert instead of an insert). The rule of thumb: never blindly retry a side-effecting operation without first asking 'if the first attempt actually succeeded and only the response was lost, what happens when I resend it?'
When to circuit-break instead
Retrying assumes the failure is transient and isolated to this one call. A circuit breaker exists for the case where the failure is systemic -- the downstream service is down or overloaded, and every caller retrying it is making the outage worse. Once a failure rate crosses a threshold, the breaker trips: stop calling the dependency for a cooldown window (return a fast failure instead), then send a small number of probe requests to see if it's recovered before fully closing the circuit again.
A mistake that causes cascading failures
The classic one: constant or unjittered exponential backoff at scale. A downstream dependency has a brief blip; hundreds of clients all fail at the same moment and all retry at the same computed intervals, turning a brief blip into a sustained self-inflicted DDoS on the dependency just as it's trying to recover. This is exactly why full jitter exists -- without it, adding retries can make an outage longer, not shorter.
Trade-offs and pitfalls
A subtler pitfall than the cascading-failure mistake above: setting max-attempt limits too high relative to a caller's own timeout budget means the caller gives up (times out) before the retry loop itself has exhausted its attempts, so the retries never actually get a chance to help -- the retry policy and the caller's own timeout need to be sized together, not chosen independently. Edge case: a dependency that returns a MIX of retryable and non-retryable errors across a single call (e.g., a batch API where some sub-results succeeded and others failed) needs per-item, not per-call, retry logic.
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.
Describe recommended approaches to package and distribute automation tooling so other teams can consume it safely: compare publishing a pip package (wheel), shipping a static Go binary, or distributing a Docker container. Discuss artifact repositories, semantic versioning, documentation, and installability on minimal OS images.
Sample Answer
Direct answer
The three options trade artifact simplicity for runtime dependency management, and the right choice usually depends on who's consuming the tool and what environments they run in.
Comparison
- pip package (wheel): Best when consumers are already Python environments (other services, CI jobs, developer machines with a Python toolchain). Lowest friction for Python-native consumers, but requires them to manage a compatible Python version and a virtual environment -- friction for anyone NOT already in a Python-heavy workflow.
- Static Go binary: Best for cross-team distribution where you can't assume a specific runtime is installed -- a single binary with no dependencies just works, which matters enormously for a tool that needs to run on minimal container images or across heterogeneous developer machines.
- Docker container: Best when the tool has non-trivial dependencies beyond its own code (system libraries, specific tool versions) that would otherwise need documenting and manually installing -- the container bundles the whole environment, at the cost of requiring Docker itself to be available and usually being the heaviest option to distribute and run for a simple CLI invocation.
Artifact repositories, versioning, documentation
Whichever format, publish to a proper artifact repository (a private PyPI index, an internal container registry, a binary artifact store) rather than ad-hoc file shares -- this is what gives you a queryable history of every version ever shipped and lets consumers pin exact versions. Use semantic versioning (MAJOR.MINOR.PATCH) so consumers can reason about upgrade risk from the version number alone: a MINOR bump should never break their existing usage, a MAJOR bump signals 'read the changelog before upgrading.' Documentation should live alongside the artifact (a README in the package, not a separate wiki page that drifts out of sync) and always include a minimal working example, not just a flag reference.
Installability on minimal OS images
A wheel needs a matching Python version and its dependencies resolved, which can fail silently-ish on a minimal image missing system libraries a dependency needs (common with anything using C extensions). A static Go binary sidesteps this entirely -- copy it in, run it, no runtime to match. A container sidesteps it differently -- the image carries its own complete environment -- at the cost of needing a container runtime present and typically being much larger to pull.
Combined pip + Docker distribution
Worth naming the two aren't mutually exclusive: publishing BOTH a pip package (for Python-native consumers who want to import it as a library, not just run it as a CLI) and a Docker image (for consumers who just want to run the tool without any Python setup at all) is common and reasonable for tools that serve both audiences. Making that work well requires the same version number to map cleanly across both artifact types, pinned dependencies baked into the image at build time (not resolved fresh on every container start, which breaks reproducibility), and a CI build step that produces both artifacts from the same tagged commit so they can never drift apart into 'the wheel and the image are technically different versions.'
Trade-offs and pitfalls
The most common mistake is picking based on what's easiest to build rather than what's easiest for CONSUMERS to install -- a wheel is trivial to build but pushes real dependency-resolution risk onto every consumer's environment; a container is heavier to build and distribute but removes almost all of that risk from the consumer's side.
Design a robust backup automation workflow for a production database from first principles. What does the schedule and retention story need to look like, how do you actually verify a backup is restorable rather than just assuming it is, and how would you automate periodic test restores and surface backup health to the teams who depend on it? Be explicit about the recovery time objective (RTO) you're designing for and how encryption and off-site replication fit in.
Sample Answer
Direct answer
A backup you haven't verified restorable isn't a backup, it's an unverified assumption -- so the design has to treat restore-verification as a first-class, automated, recurring part of the workflow, not a manual step someone remembers to do occasionally.
Schedule and retention
Combine full backups on a longer cadence (weekly, say) with incremental backups more frequently (daily or more), which bounds both storage cost and restore time -- a full-only strategy at high frequency wastes storage on largely-redundant data; an incremental-only strategy with no periodic full backup makes restore slow and fragile (a long chain of incrementals all has to apply cleanly). Retention should reflect actual recovery needs, not just 'keep everything forever': recent backups at high density (every day for the last 2 weeks), tapering to lower density further back (weekly for the last quarter, monthly beyond that) -- driven by how far back a real recovery need has historically reached, not an arbitrary round number.
Verifying restorability, not just backup success
A checksum on the backup file confirms it wasn't corrupted in transit/storage, but it does NOT confirm the backup can actually be restored into a working database -- schema incompatibilities, a corrupted-but-checksum-valid dump, or a restore procedure that's silently broken are all real failure modes a checksum alone misses. The only real verification is periodically and automatically RESTORING the backup into an isolated environment and running a basic health check against it (can you query it, does row count roughly match expectations) -- scheduled the same way the backup itself is scheduled, not as a manual quarterly fire-drill. Automating this: after each (or a sampled subset of) backup runs, spin up a throwaway restore target, restore into it, run the health check, tear it down, and record pass/fail as a first-class metric alongside the backup job's own success rate.
RTO, encryption, and off-site replication
The recovery time objective (RTO) -- how long a real recovery is allowed to take -- should drive concrete design choices, not just be a number in a doc: if RTO is tight, favor more frequent full backups (shorter restore chains) and pre-warmed restore infrastructure over cheaper-but-slower cold storage. Encrypt backups at rest (and in transit to off-site storage) using keys managed separately from the backup storage itself, so a compromise of the storage location alone doesn't also compromise the ability to decrypt what's there. Off-site (or cross-region) replication protects against a failure mode local backups can't: the whole primary region/site becoming unavailable at once.
Surfacing backup health
Don't bury backup/restore-test results in a log file nobody reads -- surface success rate, last-verified-restorable timestamp, and current RTO-vs-actual-restore-time as a dashboard visible to both the SRE team and the product teams who depend on the data, and alert distinctly on 'backup failed' versus the arguably scarier 'backup succeeded but the periodic restore-test failed' -- the second one means you have backups that LOOK fine and aren't, which is worse than an obviously-broken backup because nobody's watching for it.
At larger scale
The same design extends in two directions worth naming: at petabyte scale, the mechanics change (chunked parallel upload/download rather than a single-stream dump, streaming rather than a full point-in-time snapshot where a snapshot would be prohibitively slow to take, explicit throttling so the backup doesn't saturate the network link other production traffic needs) but the underlying verification discipline doesn't. At multi-region scale, replication has to account for bandwidth-constrained cross-region transfer and should include periodic FULL restoration drills (not just spot-checks) specifically because the RTO/RPO trade-offs (how much data can you afford to lose, how long can recovery take) get materially harder to hit the further data has to travel and the larger it is.
Unlock Full Question Bank
Get access to all 29 Automation Scripting for Operations interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.