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.
Explain the differences between these automation approaches: one-off fixes, ad-hoc scripts, Infrastructure as Code (IaC) modules, and platform self-service. For each, provide pros/cons, expected maintenance burden, discoverability, and one concrete scenario where it is the right choice for an SRE team.
Sample Answer
The idea in plain words
These four options are four levels of investment in the same goal, getting a task done without repeating manual effort. A one-off fix is a manual, single-use action. An ad-hoc script is a small program someone writes to do one job and keeps for convenience. Infrastructure as Code (IaC) means describing infrastructure in version-controlled files that a tool applies, so the setup is reviewable and repeatable; a module is a reusable, parameterised piece of that description (parameterised means it takes inputs, such as a service name or a size, so one description serves many cases). Platform self-service is an interface (a portal, a command or an API) through which other teams get a capability on their own without filing a request to the SRE team, within guardrails (limits built into it, such as defaults, quotas and forbidden options). Moving up the ladder lowers the cost of each future use and raises the cost of building and of owning the result. The right rung depends on how often the need recurs, how many people have it, how risky it is, and who will keep the thing alive.
Comparison
| Option | Pros | Cons | Maintenance burden | Discoverability |
|---|---|---|---|---|
| One-off fix | Fastest. No design cost. Leaves nothing to maintain | Not repeatable. Knowledge is lost unless written down. Easy to make a typo in production | None after the fix, but each recurrence costs full manual effort | None. It lives in a chat thread, a shell history or someone's memory |
| Ad-hoc script | Cheap to write. Captures the steps so the second run is faster and consistent | Often untested, hard-coded to one environment, depends on its author | Low at first, then grows silently as APIs and environments drift. Usually unowned | Poor. Stored in a home directory or a personal repository |
| IaC module | Reviewable, versioned, testable, repeatable. Good for standardising how things are built | Needs design for parameters, upgrades and state (the tool's own record of what it has built, which must be stored safely and kept in step with reality). Slower to build. Operators need the tooling | Moderate and real: provider upgrades (the tool's connectors to the cloud services it manages change over time), breaking changes, consumers pinned to old versions (teams who stay on an old release so a new one cannot break them, which leaves you supporting several versions) | Good if published in a module registry (a searchable catalogue of modules and their versions) or repository with docs and examples |
| Platform self-service | Removes the request queue. Enforces guardrails and defaults. Scales across teams | Highest build cost. Needs a product mindset, support and documentation. Wrong abstractions are hard to undo | Highest. It is a product with users, an on-call rotation (someone reachable out of hours when it breaks) and a roadmap | Highest when it is a catalogue or portal with search, but only if users hear about it |
One scenario where each is right (assumptions, not real data)
- One-off fix. A single malformed cache key is serving stale data for one customer. Delete the key, record what you did in the incident notes, and move on. Building anything here costs more than it saves. If the same key corrupts a third time, the fix becomes a candidate for the next rung.
- Ad-hoc script. A one-time migration must rename the tags on 3,000 storage objects. Write a script with a dry-run mode that prints what it would change, run it, keep it in the team repository with a one-line note, and delete it when the migration closes.
- IaC module. Every new service needs the same alert rules, dashboards and service-account setup. Assume about 10 new services per year, each taking 6 hours by hand: 60 hours per year. A module costing 40 hours to build and 12 hours per year to maintain saves 60 - 12 = 48 hours per year, so it pays back in 40 / 48 = 0.83 years (10 months), and it also makes every service look the same, which helps on-call. What a module looks like to the team using it (an illustrative call in generic syntax, not a specific tool):
module "service_baseline" {
source = "registry/service-baseline" # where the shared module lives
version = "1.3.0" # the release this service uses
name = "checkout" # parameters: the only things that vary
tier = "critical"
}
# The module itself creates the alert rules, the dashboard and the
# service account, so the caller never repeats those 6 hours of steps.
- Platform self-service. Developers ask the SRE team for a database read replica. Assume 150 requests per year at 45 minutes each, which is 150 x 45 = 6,750 minutes = 112.5 hours per year. A self-service flow costing 120 hours to build and 30 hours per year to maintain saves 112.5 - 30 = 82.5 hours per year if it handles every request, so break-even is 120 / 82.5 = 1.45 years (about 17 months). If it handles only 80% of requests (some need special sizing), the saving is 0.8 x 112.5 = 90 hours, net 90 - 30 = 60 hours per year, and break-even stretches to 120 / 60 = 2.0 years. The requesters also stop waiting in a queue, which this arithmetic does not count. What it looks like to a developer (an illustrative request form, not a specific product):
Request: database read replica
source database : orders-primary (pick from the databases you own)
size : small | medium (large needs a ticket)
environment : staging | production
[Submit] -> guardrails check quota and ownership, then builds it
Deciding which rung
- Ask how often the need recurs and for how many people. A one-time need stays on the first two rungs.
- Ask what a mistake costs. A risky change on production (deleting data, changing network rules) deserves a dry-run and review, which pushes you toward a script with safeguards or a module.
- Ask whether the same shape of request comes from many teams. If so, a module or self-service removes you as the bottleneck.
- Ask who will own it. A rung with no owner decays. An unowned platform feature is worse than an honest runbook (written step-by-step instructions that a person follows).
- Do the break-even arithmetic with maintenance included, as in the scenarios above.
A practical promotion rule: the first time you do something manually, fine; the second time, write the commands down; the third time, script it with a dry-run (a mode that prints what the script would change without changing it). Three is a convention, not a law, with a reason behind it: one occurrence might be a one-off, two might be coincidence, and by the third you have seen the steps three times and know which parts vary between runs, which tells you what to parameterise; when other teams ask for it repeatedly or it must be consistent across services, make it a module; when the requests keep arriving and the shape is stable, offer it as self-service.
Judgment
The four rungs are not equally common. Most recurring work stops at rung two or three, and self-service is justified only when volume is high and the request has a stable shape.
For an SRE team I would recommend starting most recurring work at the script rung with a dry-run and a named owner, graduating to modules for anything that defines how services are built, and building self-service only for the one or two request types with high volume and a stable shape. What would flip it: if the work is regulated or irreversible, I would put approval and audit around even the lowest rung; if demand is below the break-even, I would leave it manual and documented.
Common mistakes
- Building a self-service portal for a request that arrives six times a year.
- Leaving an ad-hoc script in a personal directory after it has become a team dependency.
- Counting only build time and forgetting upgrades and support.
- Publishing a module with no examples or version policy, so no one finds or trusts it.
- Skipping the dry-run on the script rung because the task "is simple".
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.
What separates safe automation from unsafe automation when it acts on production? What controls would you insist on before letting it run unattended, and why?
Sample Answer
The idea in plain words
Automation acts at machine speed, on many targets, usually with nobody watching. A person who is about to do something odd tends to pause, notice and ask. A program does not unless you build that in. So the difference between safe and unsafe automation is not how clever the code is. It is whether a mistake in the code, the input or the environment stays small, is noticed quickly, can be undone, and can be traced afterwards. Unsafe automation has wide permissions, acts on everything at once, gives no preview and leaves no record. Safe automation limits what it can touch, shows what it intends to do before doing it, starts small, stops itself when results look wrong, and writes down what it did.
The controls I would insist on before it runs unattended
Unattended means no person is watching each run. A few words used below: a selector is the rule that picks which targets the automation acts on (here, which volumes to delete), and a tag filter is a selector that matches resources by the labels (tags) attached to them. Eight controls, each paired with the failure it addresses:
| # | Control | What it means | Failure it addresses |
|---|---|---|---|
| 1 | Dry-run | A mode that computes and prints the planned actions without performing them | A wrong selector or bad input is seen before it does damage |
| 2 | Least privilege | The automation's identity (its service account, the login a program uses instead of a person) holds only the permissions its job needs, scoped to the resources it manages | A bug or stolen credential cannot reach beyond its job |
| 3 | Staged rollout | Apply to a small slice first, check health (an automated probe that says whether the affected service still works), then widen in steps | A defect hits 1% of targets instead of all |
| 4 | Rate limits | A ceiling on actions per minute and per run | A runaway loop cannot finish its damage before someone reacts |
| 5 | Approval gate | A human approves actions above a stated size or risk | The unusual large action gets a second pair of eyes |
| 6 | Audit log | An append-only record (entries can be added but never edited or deleted) of who or what acted, on which target, when, with before and after state | Investigation, accountability and compliance |
| 7 | Circuit breaker and kill switch | An automatic stop when errors or alerts exceed a threshold, plus a manual off switch with a known owner | Failure that grows while nobody is looking |
| 8 | Undo path and idempotency | A way to restore (a snapshot, which is a point-in-time copy; a soft delete, which hides data for a while instead of erasing it; or a previous version) and a design where repeating a run is harmless | Mistakes that are discovered late, and retries that duplicate effects |
Why these and not others: each one bounds one dimension of risk. Least privilege bounds what is reachable, staging and rate limits bound how much happens before feedback, dry-run and approval bound intent, the breaker bounds duration, the log bounds ignorance, and the undo path bounds permanence.
Worked example (assumed numbers)
Automation: a cleanup job that deletes storage volumes it believes are unused, from a fleet of 2,000 volumes.
Unsafe design. It runs with administrator rights across all accounts, selects by a tag filter, deletes immediately and logs only "done". Assume the tag filter has a bug and matches every volume, and the job deletes 50 volumes per minute. Time to delete the whole fleet = 2,000 / 50 = 40 minutes. Nobody is paged, because nothing in the job reports a problem, and there is no snapshot.
Safe design, with the same bug. The over-broad selector still matches "every volume the job can see". What changes is how much the job can see, and what the controls do with the result.
- Least privilege first. The job's credentials only list and delete volumes carrying its own marker tag, in the accounts it was assigned. Of the 2,000 volumes in the fleet, 214 carry that tag, so the buggy selector can return at most 214, not 2,000. This is a limit the bug in the selector cannot cross, and it is why the number below is 214 and not 2,000.
- Dry-run. A normal night finds around 20 candidates (assumed). Tonight the plan lists 214, and the size guard (a limit on how large a plan may be before a person must approve it) is set at 5% of the fleet, which is 2,000 x 0.05 = 100 volumes. 214 / 2,000 = 10.7%, which is above the limit, so the run stops and asks for approval. The reviewer sees volumes attached to running databases in the list and rejects it. An illustrative dry-run output and guard setting:
DRY RUN job=volume-cleanup version=1.4.2
candidates: 214 of 2,000 volumes in the fleet (10.7%)
size guard: max_unattended_deletes=100 (5% of fleet)
RESULT: REFUSED, 214 > 100, approval required. Nothing was deleted.
volume-cleanup:
max_unattended_deletes: 100 # 5% of a 2,000 volume fleet
first_stage: 20 # 1% of the fleet
max_actions_per_minute: 10
require_snapshot_before_delete: true
- Suppose the guard had been set looser and the run continued. Staged rollout deletes the first 20 volumes (1% of the fleet) and waits for a health check. A volume attached to a live service raises an alert, and the circuit breaker halts the job. Damage is at most 20 of 2,000 volumes, which is 1%, instead of 100%.
- Before each deletion the job takes a snapshot, so the 20 can be restored.
- The audit log shows exactly which 20 volumes were touched, when, and under which version of the job.
The guard rule and the 1% first stage here are an illustration. They cover one kind of mistake, an over-broad selection. A real process would also handle other failures, and they are not equally urgent for a first version. The two I would not ship without are a lock (a marker that lets only one copy of the job run at a time, so two instances cannot delete the same things or fight each other) and a named owner who is paged when the breaker trips. The rest can follow in order of how often they happen: a job that hangs midway (give it a time limit so it is killed and alerts), a log store that is unavailable (refuse to act if the action cannot be recorded first), and credentials rotated mid-run (fail safely and alert rather than retry forever).
Judgment
I would not let it run unattended until: the dry-run and a size guard exist; the credentials are scoped to the resources it owns; the first run in each new environment goes through the staged path; the breaker and the kill switch have been exercised on purpose in a test; and someone is named as owner and on-call for it. I would allow routine, small, reversible actions to proceed without approval, and keep the human gate for large or irreversible ones. The reason is that a gate on everything gets approved without reading, which adds delay and no safety.
What would flip it: if the action is irreversible and high-impact (dropping a production database), I would not run it unattended at all, whatever controls surround it.
Common mistakes
- Having a dry-run flag that is not the default, so people forget it.
- Giving the job a broad administrator role "to make it work".
- Logging success only, so partial failures are invisible.
- Testing the happy path but never the breaker or the kill switch.
- Staging by percentage when the first slice happens to be the most critical targets. Choose the first slice to be low-risk.
How do you validate automation that modifies stateful resources such as databases, load balancer configuration or schema before trusting it in production? How would you test its behavior under partial failure and dependency outages?
Sample Answer
The idea in plain words
Automation that changes stateful resources (a database, a load balancer's pool of servers, a schema) is dangerous because a mistake persists: restarting a stateless web server is undone by the next restart, but a deleted row or a dropped backend stays gone. Trust is earned in layers: design the automation so repeats and crashes are safe, test it on a disposable copy of production-shaped data, deliberately break its dependencies and watch that it stops instead of guessing, then release it in small steps. The central rule for partial failure is that "I could not find out" must never be treated as "the answer is bad".
Validation ladder, in order
- Design properties checked in review
- Idempotent: running it twice leaves the same end state as running once.
- Preconditions: it checks the state it expects before every change and refuses if reality differs (compare-and-set: change only if the value is still what you read).
- Small, bounded steps: a cap on how many resources it may change per run and a floor such as "never fewer than 4 healthy backends".
- Resumable: if it crashes between step 2 and 3, a rerun detects where it stopped.
- Single writer: a lock or lease (a lock that expires) so two copies cannot act at once, with a fencing token (a number that increases each time the lock is granted, rejected by the target if stale).
- Timeouts and bounded retries with backoff (waiting longer after each failed attempt, for example 1 second, then 2, then 4). A timeout is ambiguous: the write may or may not have happened, so the next step is to read the state, not to repeat blindly.
- Reversible changes: for schemas, use expand then contract (add the new column, write to both, migrate, switch reads, drop the old one later), so each step is backward compatible.
- Plan or dry-run output against production, reviewed by a person who owns the resource.
- Execution on a restored backup or clone of production shape. Restoring the backup is itself a test of your recovery. Measure what matters on production-sized data: how long locks are held, how many rows change.
- Fault injection (deliberately causing a failure to see how the automation reacts) in a test environment (below).
- Production canary (a first, small slice of real production, run before everything else): one pool or one shard, with limits, and a person watching.
Which properties matter when, with a trace
Three properties belong in every stateful automation: idempotent, preconditions (compare-and-set) and small bounded steps with a floor. The others each answer one specific hazard, so add them when the hazard exists: resumable when a run has several steps that can stop halfway; a single writer (lease plus fencing token) when two copies could ever run at once; bounded retries with backoff when a dependency can be slow; expand then contract when the change is to a schema.
Compare-and-set with a concrete value: an order row reads pending, the automation plans to set it to archived, but another process sets it to paid first. The automation's update says "set archived where status is still pending", so it changes 0 rows and stops instead of overwriting paid.
Fencing token with concrete numbers: copy A holds the lock with token 32, then stalls (a long pause in the process or the virtual machine) and its lease expires. Copy B is granted the lock with token 33 and writes. When A wakes up it still believes it holds the lock and writes with token 32. Without the token the stale write would land after B's. The target remembers the highest token it has accepted (33) and rejects 32.
import sqlite3
# Compare-and-set: change a row only if it still has the value that was read.
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, status TEXT)")
db.execute("INSERT INTO orders VALUES (7, 'pending')")
seen = db.execute("SELECT status FROM orders WHERE id = 7").fetchone()[0]
db.execute("UPDATE orders SET status = 'paid' WHERE id = 7") # another process acts first
changed = db.execute(
"UPDATE orders SET status = 'archived' WHERE id = 7 AND status = ?", (seen,)
).rowcount
print("automation read:", seen, "| rows it changed:", changed)
print("final status:", db.execute("SELECT status FROM orders WHERE id = 7").fetchone()[0])
# Fencing token: the target remembers the highest token it has accepted.
class Target:
def __init__(self):
self.highest = 0
def write(self, token, value):
if token < self.highest:
return f"rejected {value!r}: token {token} < highest seen {self.highest}"
self.highest = token
return f"accepted {value!r}: token {token}"
target = Target()
print("copy A (token 32) writes:", target.write(32, "drain backend 3"))
print("lease expires, copy B gets token 33")
print("copy B (token 33) writes:", target.write(33, "drain backend 3"))
print("copy A wakes up late (token 32):", target.write(32, "drain backend 5"))
Output:
automation read: pending | rows it changed: 0
final status: paid
copy A (token 32) writes: accepted 'drain backend 3': token 32
lease expires, copy B gets token 33
copy B (token 33) writes: accepted 'drain backend 3': token 33
copy A wakes up late (token 32): rejected 'drain backend 5': token 32 < highest seen 33
Reading the output: the first two lines show the conditional update changing 0 rows, so the row keeps the value paid. The last four lines show token 32 accepted when it was the newest, token 33 accepted next, and the late write with 32 rejected because 32 is below the highest seen, 33.
Expand then contract on a concrete column: renaming users.fullname to users.display_name. A one-step rename breaks every running copy of the old code that still reads fullname. Instead: (1) add display_name as an optional column, which old code ignores; (2) deploy code that writes both columns; (3) copy existing values across in small batches; (4) switch reads to display_name; (5) after a quiet period, stop writing fullname and drop it in a later release. At every step both the previous and the next version of the code work against the schema, so a rollback at any step is safe.
Partial failure and dependency outages: what to test
| Fault | What the automation must do |
|---|---|
| Crash between two steps | On restart, detect the half-done state and finish or roll back; never repeat the first step blindly |
| Timeout on a write | Read back the state before retrying |
| Metrics or health source unreachable | Treat as unknown, take no destructive action, alert |
| Target API slow or rate limited | Back off; do not queue unbounded work |
| Two instances run together | The lock or lease rejects the second; a stale holder is rejected by its fencing token (a counter the lock issues, which the target refuses if it is older than the last one seen) |
| Input list unexpectedly empty or huge | Refuse and alert (limits on both ends) |
| Dependency returns stale data | Check data age; refuse if older than a threshold |
Fault-injection experiment: network partition between the automation and its health data
Scenario (assumed): automation removes a backend from a load balancer pool when its health check fails. The pool has 6 backends. The automation reads health from a metrics API at 192.0.2.10 port 9090. That address sits in the range 192.0.2.0/24, which RFC 5737 sets aside for documentation examples, so it can never be a real host; in a real test, use the address of your own metrics API.
Steady-state hypothesis (a measurable statement of what normal looks like and what you expect to stay true while the fault is active): at least 4 of 6 backends in the pool, error rate within 0.5 percentage points of baseline, and zero removal actions that the automation was not entitled to take.
Experiment, run first in staging, then on one low-risk production pool:
sudo iptables -A OUTPUT -p tcp -d 192.0.2.10 --dport 9090 -j DROP
sudo systemd-run --on-active=10m iptables -D OUTPUT -p tcp -d 192.0.2.10 --dport 9090 -j DROP
Flags: iptables edits the Linux firewall; -A OUTPUT appends a rule to the OUTPUT chain, the list of firewall rules checked in order for packets leaving this host (run it on the host where the automation runs, so traffic from it to the metrics API is dropped); -p tcp matches TCP; -d 192.0.2.10 matches that destination; --dport 9090 matches the destination port; -j DROP silently discards matching packets, which looks like a partition (timeouts) rather than a refused connection. The second command uses systemd-run --on-active=10m to schedule the identical rule with -D (delete) after 10 minutes, so the partition heals itself even if your session is lost.
Procedure and expected behaviour, as a timeline (minutes from start):
- 0:00 steady state; 6 healthy backends.
- 2:00 partition begins. The last good health read is at 2:00.
- 3:00 backend 3 genuinely fails (stop its service by hand).
- 3:30 the automation's staleness limit of 90 seconds is exceeded. Expected: it logs "health data stale", raises an alert, and takes no removal action. It does not drain backend 3 yet, because it cannot know.
- 12:00 the partition heals (10 minutes after the rule was added at 2:00).
- 12:30 first fresh read. Expected: it removes backend 3 exactly once; 5 healthy remain.
Failure the experiment is built to expose: an automation that treats missing data as unhealthy would, at 3:30, try to drain all 6 backends. The floor of 4 healthy would stop it after 2 removals (6 minus 2 = 4), but removing 2 healthy servers still hurts, which is why the floor is the second defence and "unknown means hold" is the first.
Abort criteria (stop the experiment and heal the partition at once, by running the delete command manually): error rate more than 1 percentage point above baseline for 2 minutes, healthy backends below 4, or any removal action during the partition. A removal during the partition also means the hypothesis failed, whatever the user-facing impact.
Pass means: the hypothesis held in staging and in the canary pool, the alert fired, and exactly one removal happened after healing. Repeat the experiment after any change to the automation's decision logic.
Judgment
I would not trust the automation in production until it passes: dry-run review, a restored-copy run, the partition experiment, and one canary pool. What would slow me down: irreversible actions without a backup, no way to read state back, or a source of truth that the automation itself cannot verify.
Mistakes
- Testing only the success path.
- Retrying a timed-out write without reading state.
- Floors and caps that exist in the design but are never exercised by a test.
- Experiments with no abort condition or no scheduled heal.
Running the code
Python 3.12, standard library only: save the program as cas_fencing.py and run python cas_fencing.py.
You deployed a script that halved a manual deployment task but occasionally leaves partial deployments in inconsistent states. Outline a concrete iterative plan to harden the automation: detection, rollback strategies, idempotency, verification checkpoints, staged runs, and team adoption steps. Be specific about monitoring and safeguards you'd add.
Sample Answer
The idea in plain words
A deployment script that is right 117 times out of 120 is worse than it looks, because the other 3 runs leave a partial deployment: some hosts or steps are on the new version and some are not, and nobody is told. Hardening it means making four things true: a half-finished run announces itself (detection), a rerun cannot make things worse (idempotency, meaning running the same step twice gives the same end state as running it once), a bad run can be undone (rollback), and a new run proves what it did (verification checkpoints). Then you widen the blast radius (the number of users or hosts a mistake can hurt) in stages, and you earn trust from the team before asking them to rely on it.
Assumed scenario
These inputs are assumptions chosen to make the arithmetic followable. The script deploys one service to 12 hosts in five steps: copy the artifact, stop the service, switch a current symlink (a filesystem entry that points at another directory, so repointing it changes which release is live in one step) to the new release directory, run a database migration on one host, start the service. Before automation the task took 40 minutes by hand; the script takes 20. In a month there are 120 runs and 3 leave a partial state, each costing 45 minutes of cleanup.
The cleanup hours are small. The real cost is the window when production is inconsistent and unnoticed, which is why detection comes first.
The plan, in the order I would do it
Iteration 1: make failure visible (week 1). Do not change behaviour yet.
- Give every run a run ID and write a record per step (
started,succeeded,failed) to a durable place, not only to the terminal. - Emit metrics:
deploy_runs_totallabelled by outcome, andhosts_on_target_versionagainsthosts_total. - Add a reconciler (a small job that compares desired and actual state): 10 minutes after any run ends, check every host's reported version against the target. If any host differs, page the deploy owner. This catches partial states from any cause, including causes you have not found yet.
- Read the three failed runs' logs to find the cause. Typical causes are a timeout on one host, a lost SSH session (the remote-login connection used to run commands on a host), or a migration that ran but whose result was never recorded.
Iteration 2: idempotency and resume (weeks 2 to 3). Rewrite each step as "ensure this state" instead of "do this action":
| Step | Action form (unsafe to rerun) | Ensure form (safe to rerun) |
|---|---|---|
| Copy | cp artifact /releases/ | Copy to a temp name, check the checksum, rename into place only if absent |
| Switch | Edit config in place | Atomically repoint the current symlink to the release directory |
| Migration | Run script | Check a migrations table first, apply only versions not yet recorded |
| Start | Start process | Start only if not running with the target version |
With that, "resume" is just "run again": the script skips what is already true. Add a lock so two runs cannot overlap on the same service, and a --dry-run flag that prints the plan without touching anything.
Iteration 3: verification checkpoints and rollback (weeks 3 to 4). After each host, run a health check (the process answers a real request and reports the target version) before moving on. If it fails, stop. Rollback is different for each step:
-
Code and config: repoint the symlink to the previous release directory, which is kept on disk for exactly this reason. This is fast and needs no rebuild.
-
Database migration: a code rollback does not undo a schema change. Require migrations to be backward compatible (the old code runs against the new schema), so a code rollback does not break against the new schema in the common case, and treat a destructive migration as a separate, manually approved change.
What the difference looks like, using a column rename as the example:
Schema change What the old code does against it Verdict Rename emailtocontact_emailin placeSELECT emailfails because the column no longer existsDestructive: a code rollback now breaks Add contact_email, keepemail, write both columnsOld code still reads emailand ignores the new columnBackward compatible: a code rollback is safe Drop emailOld code that still reads it fails Destructive: do it in a later, separately approved release, once no running code reads emailThe compatible route takes more steps (add the column, deploy, copy the data, switch reads, drop later), which is the price of being able to roll back at every step.
-
If rollback itself fails, the script stops and pages a human with the run ID and per-host state; it does not keep trying.
Iteration 4: staged runs (week 5). Deploy to 1 host first (1 of 12 is 8.3 percent of the fleet), wait for the health check and an error-rate comparison, then 3 more hosts (4 of 12, 33 percent), then the remaining 8. A bad release now hurts 1 host before it hurts 12. The halt rule is written down in advance: stop if any health check fails, or if the 5xx error rate (the share of responses with HTTP status codes 500 to 599, which mean the server failed) on updated hosts is more than, say, double that of the old hosts (a threshold to tune from your own baseline).
Iteration 5: adoption (weeks 5 to 8). Teams trust automation that is boring and visible, so:
- Publish a one-page runbook: what the script does, how to read its state, how to stop it, and who owns it.
- Run the new version in dry-run alongside manual deploys for two weeks and compare the plan with what the human did.
- Keep a manual path documented and tested, and measure the metrics below so you can show the data, not opinions.
Monitoring and safeguards, listed
- Partial-state alert: any host not on the target version 10 minutes after a run ends.
- Run-outcome ratio: partial plus failed runs divided by total runs, tracked weekly. Target in this scenario: below 0.5 percent, a figure you pick with the team.
- Time in inconsistent state: minutes from first failure to full recovery. This is the number that matters to users.
- Kill switch: one flag that makes the script refuse to start, usable by anyone on call.
- Audit record: run ID, who triggered it, the commit deployed, and per-host results.
Judgment
I would do iterations 1 and 2 before anything else. Detection tells you whether the plan is working, and idempotency removes a common source of partial states, because a rerun of a half-finished action is one of the usual ways a run ends in a mixed state; the logs read in iteration 1 show how large that share is here. Staging (iteration 4) is the point where you stop hoping and start limiting damage. What would change the plan: if the partial states were all caused by one flaky dependency, fixing that dependency beats all five iterations; if the migration step is the real hazard, spend the effort there.
Common mistakes
- Adding retries without idempotency, which turns a partial deployment into a duplicated one.
- Treating "script exited 0" as proof of success instead of checking host state.
- Rollback steps that have never been run, so the first test is during an incident.
- Declaring the project done when the metric improves for two weeks; 3 failures in 120 runs is rare enough that a quiet fortnight is weak evidence.
That is every published Automation and Toil Reduction question for Cloud Engineer so far. Browse the other topics in this category, or practice this one interactively.