Automation and Toil Reduction Questions
Deciding what manual, repetitive work is worth automating and proving it paid off. Covers identifying and inventorying toil, scoring and prioritizing automation candidates, break-even and ROI arithmetic including maintenance cost, choosing an automation approach (robotic process automation, scripts, no-code tools, rules engines, ML-assisted triage, self-service) and migrating legacy spreadsheet or macro processes, when not to automate, safeguards and governance for automation that touches production or business-critical processes (dry-run, approvals, audit trail, ownership, rollout and rollback), finding opportunities through ticket data or process-discovery analysis, measuring automation health and impact (including diagnosing regressions and attributing impact), cataloguing existing automations, making the business case to leadership, and managing the people side (adoption, reskilling, stakeholder concerns). Applies to operations, data and business-process work alike. Excludes writing the automation itself (scripts, infrastructure-as-code, pipelines, orchestrator internals), the definition of toil as reliability doctrine, and incident response mechanics.
A team runs a manual 30-minute backup verification every morning to ensure backups are restorable. Outline an end-to-end automation plan to remove this daily toil. Cover success criteria, scheduling, verification artifacts, alerting on failures, rollback or fail-open behavior if automation fails, and how you would measure and present reduction in toil.
Sample Answer
The idea in plain words
Toil is manual, repetitive work that follows a rule, grows with the service and leaves nothing lasting behind; a 30-minute check done by hand every morning is a clear example. The manual task exists to answer one question every morning: "if we lost the database today, could we get it back?" A backup is only useful if it can be restored (restored means turned back into a working copy of the data), so the check must restore and inspect, not merely confirm that a backup file was written. Automating it means a scheduled job that restores the latest backup into a throwaway environment, runs defined checks, stores a report, and alerts a human when something is wrong or when no result arrives. The plan below follows the order of the questions asked: success criteria, scheduling, verification artifacts, alerting, failure behaviour, and how to measure and show the toil reduction.
Two terms used below. RPO (recovery point objective) is how much data loss the business accepts, expressed as time, for example 24 hours means the newest usable backup must be less than 24 hours old. RTO (recovery time objective) is how long a restore is allowed to take. The numbers here are assumptions for the example: RPO 24 hours, RTO 4 hours.
1. Success criteria
A run is a pass only if every one of these holds, and each is measurable:
- The newest backup is younger than the RPO (24 hours).
- The restore completes without error into an isolated scratch environment (a temporary, separate copy of the infrastructure that is thrown away afterwards).
- The restore finishes within the RTO budget (4 hours). A restore that takes 5 hours is a failure even if the data is perfect.
- Integrity checks pass: the backup file's checksum (a short fingerprint computed from the file's bytes; if one byte changes, the fingerprint changes) matches the one recorded when it was written, and row counts or object counts for chosen tables fall within an expected band against the source. For example, if the orders table had 1,250,000 rows when the backup was taken, the restored copy should have 1,250,000, and a count outside, say, 1% of that fails the check.
- An application-level check passes: a small set of read queries returns expected results, for example the latest order is present and a key table is non-empty.
Start by making the automation at least as thorough as the human check. If the person only looked at a job status page, the automation should do more than that, but first write down what the manual check really covers, so that nothing it caught is dropped.
2. Scheduling
Trigger the verification when the backup job finishes (an event or a dependency in the scheduler), with a time-based fallback. Assume backups finish by 03:00 and verification starts at 04:00. A typical restore takes about 1.5 hours (assumed), so the report usually lands around 05:30. The hard limit is the RTO: start plus 4 hours is 08:00, and a run still going then is stopped and counted as a failure. A "started" heartbeat (a small signal the job sends when it begins) is expected by 04:15. Do not simply start at a fixed time and hope the backup is done: a verifier that tests yesterday's backup and reports green hides that today's failed. Run the restore in an isolated environment with no route to production, cap its cost and run time, and tear it down afterwards. Keep a weekly deeper test, for example a full restore of the largest database, in addition to the daily lighter one, if the daily one samples.
3. Verification artifacts
Each run writes one report, kept for a retention period that fits the audit need, for example 13 months:
- run identifier, start and end time, backup identifier and its timestamp,
- checksum expected and observed, restore duration, restored size,
- each check with pass or fail and the value observed,
- link to the logs and the scratch environment's teardown confirmation.
A short machine-readable summary (a JSON file) feeds the dashboard; the full logs are linked from it. This replaces a person's recollection with evidence anyone can open. An illustrative summary (invented values):
{
"run_id": "2026-10-29-0400",
"backup_id": "orders-2026-10-29-0230",
"backup_age_hours": 1.5,
"restore_minutes": 95,
"checksum_match": true,
"checks": [
{"name": "orders_row_count", "expected": 1250000, "observed": 1249870, "pass": true},
{"name": "latest_order_present", "pass": true}
],
"result": "pass"
}
4. Alerting
- Failed check or restore: a high-priority ticket during business hours (a ticket is a tracked work item that someone picks up in working hours); a page (an automatic call or message to the on-call person's phone, even at night) if it is the second consecutive failure or if the newest usable backup is older than the RPO.
- No report by 08:30 (a dead-man's switch, meaning an alert that fires when an expected signal does not arrive): the verifier itself has failed to run. The time is the latest legitimate finish, 08:00, plus a 30-minute margin, so a slow but valid 3.5-hour restore does not trip it. A missing "started" heartbeat at 04:15 raises the same alert early. This is the most important alert, because silence otherwise looks like success.
- Slow restore trend: a ticket, not a page, when restore time exceeds 75% of the RTO budget (3 hours of 4, so a run still going at 07:00).
5. Rollback and fail-open behaviour if the automation fails
The verifier only reads backups and writes to a scratch area, so a failure of the verifier cannot damage the backups or production: the backups keep running regardless (that is the fail-open part, the verification being a monitor and not a gate). What must not happen is a failure that looks like a pass. So: no result is treated as a failure, never as a green; a crashed verifier alerts through the dead-man's switch; and on such a day a person runs the old manual check as the fallback. For the rollout, run the automation in parallel with the manual check for 10 working days and compare results; only stop the manual check after the two agree. Keep the manual procedure written down and rehearse it once a quarter.
6. Measuring and presenting the toil reduction
Assumptions: the manual check takes 30 minutes on each of 260 working days per year; the automation costs 24 hours to build; the parallel run costs 10 days x 0.5 hours = 5 hours of manual checking; maintenance is 12 hours per year; and 15 failures per year need a person for 20 minutes each.
| Item | Hours per year |
|---|---|
| Manual toil removed: 260 x 0.5 | 130 |
| Maintenance | 12 |
| Human time on automation exceptions: 15 x 20 / 60 | 5 |
| Net saved per year: 130 - 12 - 5 | 113 |
Upfront cost = 24 + 5 = 29 hours. Payback = 29 / 113 = 0.26 years, about 13 weeks of operation (0.2566 x 52 = 13.3).
If the team actually checked on 365 days, the saving would be larger; the 260 figure is a stated assumption. Present: a before and after table of hours, the payback date, and outcome measures that matter more than hours: share of days with a verified restore (target 100%), time from a backup failure to detection (hours before, minutes after), and restore duration against the RTO. Report what the freed hours were used for, and report the maintenance honestly.
Judgment
I would build it, because the check is daily, rule-based and read-only with respect to production, so the harm is low and the payback is about a quarter. I would keep a human fallback and a quarterly manual rehearsal. What would flip it: if restores need manual steps that cannot be scripted (for example hardware media loaded by hand), I would automate the status and age checks first and keep the restore test as a weekly manual drill.
Common mistakes
- Verifying that the backup job reported success instead of restoring.
- No dead-man's switch, so a dead verifier looks like green.
- Restoring into an environment connected to production.
- Counting the build time but not maintenance and exception handling.
- Retiring the manual procedure so completely that nobody remembers how to do it.
Draft a controlled rollout plan for automation that modifies production infrastructure (for example, automated scaling rules). The plan should include testing stages, rollout percentages, automated health checks, rollback criteria, runbook readiness, and stakeholder notifications and approvals.
Sample Answer
The idea in plain words
Automation that modifies production infrastructure, such as a scaling rule that adds or removes servers, can fail by doing the wrong thing at full speed everywhere. A controlled rollout limits the harm by exposing the change to a small, chosen slice first (this slice is the blast radius, the amount that can be damaged), watching agreed health signals for long enough to see problems, and promoting to the next slice only when pre-agreed numbers say so. Each stage needs a rollback trigger written as a number, and a rollback that has been practised.
The plan
Stage 0: offline checks
- Review the rule and its limits: minimum and maximum instance counts per group, maximum change per step (for example no more than 10 percent of a group removed per 10 minutes), cooldown (a pause after each action so metrics can settle). A group here means one autoscaling group: a set of servers that the rule resizes together.
- Replay a week of historical load through the rule in a simulator or a test harness and count how many scale actions it would take and how often it oscillates (flaps: scaling out then in repeatedly, usually because the out and in thresholds are too close).
- Unit tests for the arithmetic, and a test that the rule refuses to scale below the minimum.
Stage 1: synthetic load in a test environment
Apply the rule and push load that ramps up, spikes and falls. Confirm scale-out latency is within what traffic needs, scale-in does not remove capacity during a dip that is followed by a peak, and the limits hold.
Stage 2: shadow (recommend-only) in production
The rule runs against live metrics but only logs what it would do. Run for a full weekly traffic cycle. Compare its decisions with what the current rule did.
Stage 3 to 6: staged enablement
Enable on a growing slice of groups, chosen from low-risk to high-risk. Between stages a bake time (the minimum time to watch before promoting) must cover at least one daily traffic peak.
Why the unit is a group and not a share of traffic: a scaling rule does not act on requests, it decides how many servers a group should have. A group cannot run a rule for 5 percent of its requests, so the smallest honest slice is one whole group. A traffic percentage fits a change to request-handling code, where a router can send 5 percent of requests to the new version. Groups also give a built-in comparison: at the same hour, enabled groups can be compared with groups that are not enabled yet.
Automated health checks at every stage
Compare each enabled group with its own baseline (that group's normal readings from previous weeks at the same time of day) or with groups not yet enabled:
- error rate: roll back if it exceeds baseline by more than 0.5 percentage points for 5 minutes
- 99th percentile latency (the value 99 percent of requests are faster than): roll back if above 1.25 times baseline for 10 minutes
- flapping: roll back if more than 4 scale actions in an hour for one group
- capacity floor: stop if healthy instances fall below the minimum, or utilisation (the share of capacity in use, such as CPU busy percent) stays above 85 percent for 10 minutes
- cost guard: stop if instance count exceeds 1.5 times the forecast for the group (the instance count the capacity plan, or the same hour in previous weeks, says the group needs)
These thresholds are illustrations; tune them from your own baselines.
What a trip looks like, for one group with assumed baselines: error rate 0.4 percent, 99th percentile latency 240 ms, minimum 12 instances, forecast 20 instances.
| Check | Trigger value for this group | Reading that trips it |
|---|---|---|
| Error rate | 0.4 + 0.5 = 0.9 percent (0.5 percentage points is added to the baseline, not 50 percent of it) | 1.1 percent for 5 minutes in a row |
| p99 latency | 1.25 x 240 = 300 ms | 310 ms for 10 minutes |
| Flapping | More than 4 scale actions in an hour | The 5th action in the same hour |
| Capacity floor | Fewer than 12 healthy instances | 11 healthy |
| Cost guard | 1.5 x 20 = 30 instances | 31 instances |
A reading of 0.8 percent errors does not trip the first check (0.8 is below 0.9), which is why the latency and flapping checks exist alongside it. When the 1.1 percent reading holds for 5 minutes, the flag switches the rule off for that group, capacity is pinned at the last known good number (here 20 instances), and the on-call person is paged. Alert on the health checks and, where safe, let them switch the rule off automatically, because a person may not be watching.
Runbook readiness
Before stage 3, the runbook (a step-by-step document for responders) says: how to disable the rule (a feature flag, meaning a configuration switch that turns the rule on or off without redeploying code, tested), how to pin capacity manually to a known good number, who is on call, what each alert means, and how to reach the owner. A person who did not write the rule must perform the rollback in a drill and time it; target under 5 minutes.
Stakeholders, notifications and approvals
- Approval: the owning service team approves each stage promotion; the platform owner approves the plan; for services with customer commitments the service owner confirms the stage dates.
- Notify before each stage in the channel the on-call teams watch (what changes, when, the rollback switch, who to contact), and after each stage with the result.
- Record the change in the change system so it appears in an incident timeline.
Worked example (all numbers are assumed)
A fleet (the whole set of servers a team runs) of 200 instances in 10 groups of 20. Stages 0 and 1 touch no production instances. Plan:
| Stage | Scope | Instances | Share of fleet | Bake time |
|---|---|---|---|---|
| 0 | Offline review, replay, unit tests | 0 | 0% | 2 days |
| 1 | Synthetic load in a test environment | 0 | 0% | 3 days |
| 2 | Shadow, all groups | 0 changed | 0% | 7 days |
| 3 | 1 low-risk group | 20 | 20 / 200 = 10% | 3 days |
| 4 | 3 groups | 60 | 60 / 200 = 30% | 3 days |
| 5 | 6 groups | 120 | 120 / 200 = 60% | 3 days |
| 6 | All 10 groups | 200 | 100% | 7 days watch |
Elapsed time from the start of shadow mode to the end of the final watch: 7 + 3 + 3 + 3 + 7 = 23 days. Including stages 0 and 1, the whole plan takes 2 + 3 + 23 = 28 days. If stage 3 trips the latency trigger on day 2, the rule is switched off for that group, only 20 of 200 instances (10 percent of the fleet) were ever exposed, and the rest never ran the new rule. Without staging, the same defect would have hit all 200 at once.
Promotion rule: a stage is promoted only after its full bake time with no trigger, covering at least one daily peak. Do not promote on a Friday afternoon, or immediately before a freeze (a period in which only emergency changes are allowed), because the person who must watch the next stage may not be there.
Failure modes
- A healthy-looking stage on a quiet day: bake times and peak coverage exist for this.
- A metric outage: if health data is missing, treat that as "unknown" and hold, not as "healthy".
- A correct rule, a provider that cannot supply capacity: the rollback keeps the old minimum capacity.
- A rollback that also fails: keep manual pinning as a second path.
Design a monitoring rule and alert to detect regressions in an automated remediation system (for example, automated restarts or rollbacks). Explain the signals, sample thresholds, how you'd reduce alert noise, and what context the alert should include to help on-call diagnose quickly.
Sample Answer
The idea in plain words
An automated remediation system is a piece of software that reacts to a problem (for example restarting a crashed service or rolling back a bad release) without a person. It can fail in three different ways, and a monitoring rule has to catch all three: it can stop working (no action when one is needed), it can work badly (acts, but the problem does not go away), or it can work too much (acts in a loop or on far too many targets, which is how automation turns a small fault into an outage). A regression means the system used to do its job and now does not. The alert should therefore watch outcomes, not just activity: "it ran" is not "it fixed anything".
Signals to collect
Have the automation emit one structured event per attempt with these fields: automation name and version, target (host, pod, service), action, trigger (which alert fired it), start and end time, and a verification result (did the health check pass within the verification window, a fixed period such as 5 minutes after the action).
| Signal | What it catches | Sample alert threshold (illustrative) |
|---|---|---|
| Verified success rate = verified successes / attempts | Fixes that no longer fix | Below 90 percent over 1 hour, with at least 10 attempts |
| Repeat rate on the same target | A restart loop that is masking a real fault | More than 3 actions on one target in 30 minutes |
| Action volume against the same hour's trailing baseline | A runaway trigger, or a flood from a real incident | Above 3 times the trailing 7-day median (the middle value of this same hour's action counts over the previous seven days) for that hour, and at least 20 actions |
| Concurrent targets touched | Blast radius (how much of the fleet is affected at once) | More than 10 percent of a tier acted on in 15 minutes |
| Guard trips and aborts (safety checks that refused to act) | A circuit breaker (a switch that automatically stops all automated actions once failures or action counts cross a limit) working, or a dependency broken | Any trip of the global circuit breaker; abort share above 20 percent |
| Heartbeat (a regular "I evaluated and I am alive" record; its absence is the alert): evaluations completed | A silent, dead automation | No evaluation recorded for 15 minutes |
| Time to verify (action end to healthy) | Slowing remediation | 95th percentile (the time that 95 percent of verifications beat, so only the slowest 5 percent are longer) above 2 times the 7-day baseline |
These numbers are starting points to tune against your own history, not universal values.
Reducing alert noise
-
Minimum volume gate. A rate on a handful of attempts is dominated by chance. The question this arithmetic answers is: how often would a perfectly healthy automation look bad purely by luck? Assume it succeeds 95 percent of the time and treat each attempt as an independent coin that fails with probability 5 percent (real failures often cluster, for example when a shared dependency is down, so real false-page rates are higher than this). The wider the gap between the baseline and the alert line, the fewer attempts are needed, so use a rule that pages when success falls below 80 percent, a 15-point margin that keeps the sums short; the table's 90 percent line has only a 5-point margin and is treated after this. With only 8 attempts, a "below 80 percent" reading means 2 or more failures (6 of 8 is 75 percent; 7 of 8 is 87.5 percent), and the chance of that happening to a healthy automation is one minus the chance of 0 failures minus the chance of exactly 1 failure: 1−0.958−8×0.05×0.957. Step by step: 0.958=0.6634, 0.957=0.6983, 8×0.05×0.6983=0.2793, so the chance is 1−0.6634−0.2793=0.0573, about 5.7 percent per window. With 10 attempts the same 80 percent line means 3 or more failures, and the chance is about 1−0.5987−0.3151−0.0746≈0.012 (terms: no failures 0.9510, one failure 10×0.05×0.959, two failures 45×0.052×0.958), about 1.2 percent. A minimum of 10 attempts therefore cuts false pages from this cause by roughly a factor of five, at the price of not alerting on very low-volume automations (cover those with a daily ticket instead).
The table's 90 percent line sits closer to the 95 percent baseline, so it is twitchier. Below 90 percent with 10 attempts means 2 or more failures (8 of 10 is 80 percent, 9 of 10 is exactly 90 and does not page). By the same method, a healthy automation shows 2 or more failures in 10 attempts about 8.6 percent of the time, and 3 or more in 20 attempts (17 of 20 is 85 percent) about 7.5 percent of the time. That is why the table's rule needs the next item as well: requiring two consecutive windows, assumed independent, gives roughly 0.0862≈0.0074, under 1 percent.
-
A "for" duration or two consecutive windows, so one bad quarter-hour does not page. A "for" duration is a setting that makes the condition hold continuously for a set time (say 15 minutes) before the alert fires.
-
Alert on the automation, not on each target. One alert per automation per window, with the list of affected targets inside it, instead of 40 pages.
-
Inhibit (suppress the lower-value alert while a related, more important one is active) while a declared incident covers the same service, because remediation volume is expected to spike then. Keep a lower-severity record so it is still reviewed afterwards.
-
Tiered routing. Page a person only for loops, runaway volume and a dead automation (fast harm). Send a ticket for a slow slide in success rate (slow harm).
-
Review alert precision monthly: of the pages sent, how many led to a human action? Retire or retune the rest.
What the alert must contain so on-call can act in minutes
- Which automation and version, and when it last changed (a deploy of the automation itself is the first suspect).
- The numbers: success rate, attempts, baseline for comparison, and the window.
- The three most common failure reasons from the event field, and a sample of affected targets with links.
- Whether the circuit breaker or kill switch (a manual off switch for the automation) is armed, and the exact command or link to pause the automation.
- What else changed nearby: deploys to the target service, config changes, dependency incidents.
- Runbook link and owning team, plus the audit-log query for the last actions taken.
Checked against the table, the example alert below fires for two reasons: success is 13 of 21, which is 61.9 percent (rounded to 62), under the 90 percent line with more than the 10-attempt minimum; and 4 targets crossed the "more than 3 actions in 30 minutes" repeat rule. An example alert body, with made-up values: "restart-hung-worker v14: verified success 62 percent (13 of 21) over 60 min, baseline 96 percent. Top failure: health check timeout (6). 4 targets restarted more than 3 times in 30 min. v14 deployed 47 minutes ago. Pause: automation-ctl pause restart-hung-worker. Runbook and last 20 actions linked."
Recommendation and failure modes
I would page on loop, volume and heartbeat rules (fast-acting harm) and ticket on the success rate, and I would make the first action in the runbook "pause the automation" because a paused automation returns the system to the manual state everyone already knows how to run. The monitoring itself can fail: if the events pipeline is down, success rate looks fine because nothing arrives, which is why the heartbeat rule exists. It should be evaluated from a source independent of the automation's own logging.
Common mistakes
- Alerting on "number of remediations" alone, which rises in a real incident and punishes the automation for working.
- Counting an action as a success because the command exited cleanly, instead of verifying health afterwards.
- Thresholds with no minimum sample size, producing pages from three bad attempts.
- An alert that says only "regression detected" with no version, no baseline and no pause instruction.
Compare trade-offs between implementing automation as ad-hoc scripts in a repo, packaging as a CLI tool, or exposing as a hosted API service. Discuss discoverability, testability, security and RBAC, versioning, operational overhead, and give examples of when each option is preferable.
Sample Answer
The idea in plain words
The same automation (say, "drain a node pool before maintenance") can live in three forms. An ad-hoc script is a file in a repository that someone runs by hand. A CLI (command-line interface) tool is the same logic packaged with a name, arguments, help text and releases. A hosted API (application programming interface) service runs the logic on a server and other people or programs call it over the network. The form decides who can run it, with whose permissions, how changes reach users, and who gets paged when it breaks. My recommendation: start as a script with discipline, promote to a CLI when several people depend on it, and put it behind an API only when you need central control of who may do what, or callers that are not humans at a terminal.
Trade-offs, axis by axis
| Axis | Script in a repo | Packaged CLI | Hosted API service |
|---|---|---|---|
| Discoverability | Poor: people must know the path; a README helps | Good: one name on the path, --help, shell completion, a listing in the team's docs | Good if there is a catalogue or generated API documentation; callers need a client or a UI |
| Testability | Hard when logic is mixed with I/O; usually only run-and-see | Good: arguments parse to a plan, --dry-run shows the plan, unit tests on the core | Good for the contract (request in, effect out) but needs integration tests with real dependencies |
| Security and RBAC (role-based access control) | None of its own: it runs with the caller's credentials, so every user needs direct production access | Same as a script unless it calls an API; credentials still sit on each machine | Strongest: the service authenticates the caller, checks a role per action, holds one service identity, writes an audit log |
| Versioning | A git commit; users run whatever they last pulled, so versions drift | Semantic versions (MAJOR.MINOR.PATCH, major means breaking change); users can lag behind | One deployed version on the server; callers pin an API version so changes do not break them |
| Operational overhead | Almost none | Packaging, a release process, supporting old versions | Highest: deploy, monitor, patch, on-call, capacity, an extra failure point during incidents |
Terms in the table. A node pool is a group of identical machines in a cluster that run the workloads; to drain one is to move work off it before maintenance. A principal is any identity that can be granted permission, a person or a program. A service identity is an account created for a program rather than a person, with its own permissions. An audit log is an append-only record of who did what and when. Shell completion lets a user press Tab to finish a command or argument. To pin an API version is for a caller to ask explicitly for, say, version 1, so a later change on the server does not alter its behaviour. Rate limits cap how many calls one caller may make in a period.
The same action in the three forms
The action is "restart the stuck consumers owned by one team" (a consumer is a program that reads messages from a queue). As a script, it is one line in a file in the repository, run by whoever knows it exists (illustrative):
kubectl rollout restart deployment/orders-consumer
As a CLI, the same logic has a name, arguments and a dry-run mode. This small tool takes the team name, prints a plan, and changes nothing under --dry-run:
import argparse
def positive_int(text):
value = int(text)
if value < 1:
raise argparse.ArgumentTypeError("must be at least 1")
return value
CONSUMERS = {"orders": "team-payments", "invoices": "team-payments", "emails": "team-growth"}
parser = argparse.ArgumentParser(prog="consumerctl", description="Restart stuck queue consumers.")
sub = parser.add_subparsers(dest="command", required=True)
restart = sub.add_parser("restart", help="restart consumers owned by a team")
restart.add_argument("--team", required=True)
restart.add_argument("--dry-run", action="store_true", help="print the plan, change nothing")
restart.add_argument("--max-targets", type=positive_int, default=5)
args = parser.parse_args()
targets = [name for name, owner in CONSUMERS.items() if owner == args.team][: args.max_targets]
prefix = "DRY RUN: would restart" if args.dry_run else "restarting"
for name in targets:
print(f"{prefix} consumer {name}")
print(f"{len(targets)} target(s), limit {args.max_targets}")
Run as python consumerctl.py restart --team team-payments --dry-run --max-targets 2, it prints:
DRY RUN: would restart consumer orders
DRY RUN: would restart consumer invoices
2 target(s), limit 2
--max-targets caps how many consumers one run may touch (a value below 1 is rejected, because a negative number would otherwise slice names off the end of the list instead of limiting it), and --dry-run lets an engineer see the plan before any change. As a hosted API, the call is a request over the network (an illustrative request and response; the host and fields are hypothetical):
POST /v1/consumers/orders/restart
Authorization: Bearer <the engineer's token>
{"reason": "lag growing since 02:10"}
202 Accepted
{"status": "accepted", "audit_id": "a-1042", "requested_by": "engineer-7"}
The server checks that this engineer may restart this team's consumers, performs the restart with its own service identity, and records the audit_id in the audit log.
When each is preferable
- Script: one or two owners, a one-off or rarely used task, a migration that will be deleted next month. Add a README, a
--dry-run, and keep it in code review like anything else. - CLI: a task used by many engineers, run from terminals, with arguments and safety flags (
--dry-run,--yesconfirmations,--max-targets). Example: a tool to rotate a cache cluster, used by the on-call rotation. - Hosted API: callers are other systems (a deployment pipeline, a chatbot, a self-service portal), the action needs approval or an audit trail, or credentials must not leave a controlled host. Example: a service that grants temporary database access after a manager approves.
Worked example: the credentials count
Assume 12 on-call engineers need to restart stuck consumers in production.
- As a script or CLI: each of 12 engineers holds production write permission directly. Principals with direct write access = 12.
- As an API: the service holds one service identity with write permission; engineers hold only "may call restart on team-owned consumers". Principals with direct write access = 1, and each call is logged with the engineer's identity.
The overhead trade: assume the CLI costs 1 hour a month to release and support, and the service costs 6 hours a month (patching, alerts, on-call). The extra 5 hours a month, 60 hours a year, is the price of cutting 12 holders of production write to 1 and getting an audit log. The 1 and 6 hours are assumptions; to estimate them for your own team, count the releases of a comparable internal tool in the last year x the hours each took, and the pages and patches of a comparable service x the hours each took. A usable rule: move to the API when more people hold production write than the audit or security policy allows, when an approval or audit trail is required, or when the callers are programs. For a team of 3 with low-risk actions that price is not worth it (3 holders instead of 1 does not justify 60 hours a year); for 12 people touching production data it usually is.
Practical design
Put the logic in a library with no I/O mixed in. A thin CLI and, later, a thin API both call that library, so promotion does not mean a rewrite and one test suite covers both. Make every form idempotent (running it twice gives the same end state), because people will run things twice.
Failure modes and mistakes
- The script that "everyone uses" with no owner and no tests: the most common state of automation.
- A hosted service built first for a task that three people run monthly, now needing a pager.
- CLI versions that drift: an old client calls a changed API. Fix with a minimum-version check and deprecation warnings.
- Treating the API as secure because it is hosted: it needs authorization per action and rate limits, not only login.
- No offline fallback: if the service is down during an incident, the CLI is useless. Keep a documented, audited break-glass path (an emergency route with extra logging, used only when the normal path is down).
Running the code
Python 3.12, standard library only. Save the program as consumerctl.py and run the command shown above.
You inherit hundreds of ad-hoc automation scripts across multiple repos with poor testing and no clear owners. Propose a step-by-step migration plan to inventory, prioritize, refactor, test, and centralize critical automations into maintainable artifacts while keeping services operational. Include risks and rollback strategies.
Sample Answer
The idea in plain words
You cannot safely fix what you cannot see, and you cannot afford to fix everything. So the plan is: find every script, sort by what each can damage and how often it runs, retire what nobody uses, fix only the small critical set to a proper standard, and leave the rest labelled and owned. Every change to a script that runs in production is made so it can be reversed: the new version runs next to the old one before it replaces it.
Assumed starting point
These numbers are assumptions to make the plan concrete. 300 scripts across 25 repositories. Some run from cron on servers, some from CI pipelines, some are run by hand. Two engineers can give this work 60 percent of their time.
Step 1: Inventory (weeks 1 to 3)
Collect from every place a script can be triggered, not just the repositories: scheduler and cron tables on servers, CI job definitions, ticket and chat history ("run this script"), and the credentials list (a service account with production access is evidence of a script that uses it). For each, record: location, trigger, what it touches, last run (from logs over 90 days), and a best-guess owner. A spreadsheet is enough. Do not change anything yet.
Step 2: Prioritise with two questions
Sort each script by how bad is it if it misbehaves (blast radius) and how often does it run (exposure):
| Group | Rule | Assumed count | Action |
|---|---|---|---|
| Dead | No run in 90 days and no scheduled trigger | 120 | Quarantine, then archive |
| Critical | Runs at least weekly and writes to production | 40 | Refactor, test, centralise |
| Other live | The remainder | 300 - 120 - 40 = 140 | Label and assign owner; fix when touched |
Step 3: Retire the dead, safely
Do not delete. Disable the trigger and leave a tripwire: a stub that records "someone tried to run this" and who. Wait 60 days. Anything nobody asks for moves to an archive branch, still recoverable. If someone does ask, the tripwire has told you the script was not dead, and you re-enable it and reclassify. This is cheap and removes 120 of the 300 from the problem.
Step 4: Rebuild the critical 40 one at a time
For each critical script, in order of blast radius:
- Characterise before changing. Write tests that capture what the script currently does on known inputs (including its odd behaviour). A test that pins down existing behaviour is called a characterisation test; it tells you when a refactor changed something.
- Refactor into a shared library and a thin script. Pull duplicated logic (authentication, retry, logging) into one tested module, add a
--dry-runthat prints the plan, structured logging, and a named owner in the catalog. - Shadow run. Run the new version in dry-run next to the old one for a defined period (for example, two scheduled cycles) and compare the intended actions. Differences are either bugs in the new version or surprises in the old one; both are findings.
- Cut over with a switch. A single flag selects old or new. Start with the new one on a low-risk subset (one environment, one customer segment), then expand.
- Rollback. Flip the flag back. Keep the old script runnable for a defined window (say 30 days after full cutover), then archive it.
The two safety nets, as code
A tripwire stub replaces a disabled script. It does none of the script's work: it records who called what and when, and tells the inventory owner. A characterisation test pins what a legacy function does today, quirks included, so a refactor that changes behaviour fails loudly. The program below shows both; the second function is a refactor that quietly drops a quirk.
def tripwire(script, args, user, when):
entry = f"TRIPWIRE script={script} args={args} user={user} at={when}"
# a real stub appends this line to a shared log, alerts the inventory owner,
# and exits non-zero without doing the script's work
return entry
print(tripwire("purge_old_exports.sh", ["--all"], "alice", "2026-03-02T09:14:00Z"))
# Characterisation test: pins what the legacy function does today, quirks included.
def legacy_backup_name(host, day):
return host.lower().split(".")[0] + "-" + day + ".tar"
def refactored_backup_name(host, day):
return host.lower() + "-" + day + ".tar"
def characterise(fn):
assert fn("DB1", "0301") == "db1-0301.tar"
assert fn("db1.prod", "0301") == "db1-0301.tar", "dotted host names lose their suffix"
for name, fn in [("legacy", legacy_backup_name), ("refactored", refactored_backup_name)]:
try:
characterise(fn)
print(name, "passes the pinned behaviour")
except AssertionError as err:
print(name, "FAILS:", err)
Output:
TRIPWIRE script=purge_old_exports.sh args=['--all'] user=alice at=2026-03-02T09:14:00Z
legacy passes the pinned behaviour
refactored FAILS: dotted host names lose their suffix
Reading the output: the first line is the record the stub leaves behind (script, arguments, user, time), which turns "nobody uses this" into evidence. The pinned check expects db1.prod to produce db1-0301.tar, a quirk of the legacy code that cuts a host name at its first dot. The legacy function passes it. The refactored function keeps the dotted name, so the test fails and names the behaviour that changed. Whether that quirk is a bug to keep or fix is then a decision somebody makes on purpose, not a surprise found in production.
Effort estimate, with arithmetic
Assume 3 engineer-days per critical script (tests, refactor, shadow run, cutover):
40×3=120 engineer-daysTwo engineers at 60 percent give 2×0.6=1.2 engineer-days of work per working day.
1.2120=100 working days=20 weeks(at 5 working days per week). So the critical set is a programme of about 20 weeks, not a sprint, and that figure moves with the per-script estimate. Review it after the first 5 scripts, using actual days rather than the assumption.
Step 5: Keep the system operational
- Change one script at a time, never a batch.
- Avoid cutovers in busy periods or while an incident is open.
- Keep the old and new on-call instructions in the runbook during overlap.
- Report progress with a simple burn-down: critical scripts done, in shadow, remaining.
Risks and rollback
| Risk | Mitigation |
|---|---|
| A "dead" script runs yearly (year-end report) | Check for calendar triggers and ask finance and ops; extend the tripwire to cover a full year for suspects |
| Refactor changes behaviour somebody depends on | Characterisation tests and shadow run |
| Hidden dependency: another script calls this one | Grep for callers and track invocations in logs during the tripwire period |
| The project stalls and leaves two parallel versions | Time-box the overlap and publish the end date |
| Credentials shared among scripts | Issue each rebuilt script its own identity and revoke the shared one only after all users have moved |
Judgment
I would not try to bring all 300 scripts up to a standard. Retiring 120 and rebuilding the 40 that matter removes most of the risk for a fraction of the effort, and the 140 that remain get an owner and a label, which is the minimum for them to be found and fixed on touch. What would flip this: if the tripwire shows a "dead" script is used, or if one script causes repeated incidents, move it up regardless of its group.
Common mistakes
- Starting with a rewrite in a new framework, before the inventory.
- Deleting unused scripts on a guess.
- Refactoring without tests, so nobody can tell if behaviour changed.
- No named owner, so the improvements decay.
Running the code
Python 3.12, standard library only: save the program as safety_nets.py and run python safety_nets.py.
Unlock Full Question Bank
Get access to all 30 Automation and Toil Reduction interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.