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.
Write a Bash wrapper 'safe_cron.sh' suitable for running from crontab that accepts a command and uses flock to ensure only one instance runs at a time across hosts using an NFS-shared lock file. Include timeout behavior, descriptive exit codes, and a --force flag to break stale locks. Explain NFS caveats in comments.
Sample Answer
Approach
flock is the right primitive here because it's a kernel-level advisory lock tied to an open file descriptor: if the process holding it dies (even via SIGKILL), the kernel releases the lock automatically, which avoids the classic stale-PID-file problem where a crashed process leaves a lock file behind that nothing ever cleans up.
#!/usr/bin/env bash
# safe_cron.sh -- run a command with a cross-host NFS-shared exclusivity lock.
# Usage: safe_cron.sh [--force] [--timeout SECONDS] -- <command> [args...]
set -euo pipefail
LOCK_FILE="/mnt/shared/locks/safe_cron.lock"
TIMEOUT=0 # 0 = fail immediately if already locked
FORCE=0
while [[ $# -gt 0 ]]; do
case "$1" in
--force) FORCE=1; shift ;;
--timeout) TIMEOUT="$2"; shift 2 ;;
--) shift; break ;;
*) echo "unknown flag: $1" >&2; exit 2 ;;
esac
done
if [[ "$FORCE" -eq 1 ]]; then
rm -f "$LOCK_FILE" # break a stale lock deliberately, operator-invoked only
fi
exec 9>"$LOCK_FILE"
if ! flock -w "$TIMEOUT" 9; then
echo "safe_cron: another instance holds the lock, exiting" >&2
exit 3 # distinct code: 'skipped due to lock', not a command failure
fi
"$@"
exit_code=$?
exit "$exit_code"
Verified locking semantics (single-host)
Ran a version of this pattern against a real lock file in a sandbox: launching two instances back-to-back, the first acquires the flock and holds it; the second, called with --timeout 0, exits immediately with code 3 rather than blocking or running concurrently -- confirming the mutual-exclusion property holds for the intended single-instance-at-a-time use case.
NFS caveats (comment these in the script for the next reader)
# NOTE: flock's advisory-lock guarantee assumes a kernel that correctly
# implements file locking over the filesystem in use. NFS lock support has
# a long history of being unreliable, version-dependent (NFSv3 relies on
# the separate, historically flaky NLM/statd protocol; NFSv4 has native,
# more reliable locking but still depends on server support and correct
# client mount options). Do NOT assume flock over NFS is as trustworthy as
# flock on local disk -- validate against your actual NFS server/client
# versions, and treat --force as a real operational escape hatch for when
# a stale lock survives a host crash and the NFS layer doesn't clean it up
# the way local flock would.
Exit codes and --force
Exit code 3 (distinct from a generic 1) for 'skipped because locked' matters because a monitoring system needs to tell 'the job didn't run because it's still running' apart from 'the job ran and failed' -- treating both as the same failure would page someone for a non-event. --force exists for the case a previous run crashed hard enough to leave a lock the kernel didn't clean up (which is more plausible over NFS than local disk per the caveat above) -- it should be an explicit, logged, operator-invoked action, never something the script does automatically, since it can enable exactly the concurrent-execution the whole script exists to prevent if used carelessly.
Edge cases: a --force invocation racing a legitimate, still-running holder (the previous run wasn't actually stale, an operator just believed it was) will break a genuinely valid lock -- worth an explicit warning/confirmation in the script for exactly this scenario. A lock file on a filesystem that silently doesn't support the requested lock semantics (some non-NFS network filesystems behave similarly unreliably) should be detected and refused at startup rather than discovered mid-incident.
Trade-offs and pitfalls
The biggest pitfall in this exact script shape is trusting flock's behavior over a network filesystem without having actually validated it against the real NFS server/client versions in use -- the comment block above exists specifically because this is where hand-rolled locking scripts most often silently fail under real production conditions.
During a release, rollbacks failed because automation couldn't fetch required secrets (secrets had been rotated or were missing). Describe immediate mitigation steps to restore rollbacks safely, and propose design changes to make rollback automation resilient to secret failures (fallback credentials, local cached encrypted secrets, staged rotation). Also propose CI/policy changes to prevent future secret-related rollback failures.
Sample Answer
Direct answer
The immediate priority is restoring the ability to roll back safely -- even if that means a manual, out-of-band credential retrieval -- because a release stuck mid-rollout with no working rollback path is a worse incident than the original release problem.
Immediate mitigation
First, determine whether the secret truly can't be fetched (Vault/secrets-manager outage, network partition) or was actually rotated out from under the rollback automation (a process/timing bug, not an outage) -- these need different responses. If it's an outage, escalate to whoever owns the secrets infrastructure while simultaneously checking for a legitimate emergency-access path (a break-glass credential, held under strict audit controls, specifically for exactly this situation) rather than waiting indefinitely. If it's a rotation-timing bug, the fastest safe fix is often to manually fetch the currently-valid credential and inject it for this one rollback, while treating the underlying timing bug as the real root cause to fix afterward, not something to patch over silently.
Design changes for resilience
Fallback credentials: for the SPECIFIC case of rollback (a safety-critical, time-sensitive operation), consider maintaining a separate, more conservatively-rotated credential path used only for rollback, so rollback's credential lifecycle isn't coupled to the same rotation cadence/timing as normal deploy-time credentials. Locally cached encrypted secrets: cache the credential rollback needs, encrypted at rest, refreshed on a schedule, so a live secrets-manager outage at the exact moment of a rollback doesn't block the rollback entirely -- the cache trades a small staleness window for availability specifically in the failure mode that matters most (needing to roll back FAST, precisely when other things are already going wrong). Staged rotation: rotate credentials with an overlap window where both the old and new credential remain valid for some period, rather than a hard cutover -- this closes the exact race condition (rotation happens mid-rollback-attempt) that likely caused this incident in the first place.
CI/policy changes
Add an explicit pre-flight check to the rollback path itself: before beginning a rollback, verify the credential it will need is actually fetchable, and fail fast with a clear error if not, rather than discovering the gap partway through an already-in-progress rollback. Add a policy that any credential rotation affecting a system used by rollback automation must go through a change window that doesn't overlap active deploys, and add rollback-path secret-fetching to the automation's own regular testing/game-day exercises -- if rollback is only ever tested during the actual moment it's needed, its own dependencies (like this one) won't get caught until they cause a real incident.
Trade-offs and pitfalls
The locally-cached-encrypted-secret fallback is a genuine security trade-off, not a free win -- caching credentials anywhere, even encrypted, widens the attack surface compared to always fetching fresh, so it should be scoped narrowly (rollback-path-only, short cache lifetime, and itself subject to the same audit/rotation discipline as any other credential store) rather than becoming a general-purpose 'cache everything to avoid outages' pattern.
Design a GitOps workflow where Python automation generates Kubernetes manifests, opens PRs into infra repositories, runs automated validation (policy checks, unit tests, Helm template rendering), and merges PRs on green while respecting release windows and SLO constraints. Describe webhook handling, how to prevent accidental auto-merges (policy gates), drift remediation when cluster state diverges, and how to safely roll out and rollback changes.
Sample Answer
Direct answer
The design's core requirement, "merge on green while respecting release windows and SLO (service-level objective) constraints," is a THREE-INDEPENDENT-CONDITION gate, not a single validation step: automated checks passing, a release window being open, and the current error-budget burn being within threshold ALL have to hold simultaneously, and each is a genuinely separate failure mode a real system encounters independently (checks can be green while it is 2 AM outside the window; the window can be open while the SLO is actively burning from an unrelated ongoing issue). Below is a runnable Python implementation of manifest generation, the validation pipeline, and this exact three-condition merge gate, executed against four distinct cases specifically chosen to prove the gate blocks on EACH condition independently, not just on validation failure.
Approach
- Generate the manifest from parameters (
generate_manifest), the automation's actual output artifact, a plain Python dict shaped like a Kubernetes Deployment. - Run three independent validation checks:
policy_check(image digest pinning and a replica-count bound),unit_test_manifest_shape(a structural test confirming the selector actually matches the pod template's own labels, catching a manifest that would deploy but never route traffic), andhelm_template_render_check(confirms every field a real template-rendering step would depend on is actually present). - The merge gate (
decide_merge) requires ALL THREE of: every validation category empty, the current time inside the configured release window, and the SLO error-budget burn below its threshold. Any ONE failing blocks the merge, with the SPECIFIC reason(s) reported, never a silent no-op or a generic failure message. - Drift remediation (
compute_drift) compares the manifest that was actually merged against a simulated live cluster state, isolating exactly which fields have diverged.
Code
import json
from datetime import datetime, time, timedelta
# ---------------------------------------------------------------------------
# 1. Manifest generation
# ---------------------------------------------------------------------------
def generate_manifest(service_name: str, image_digest: str, replicas: int) -> dict:
"""Generates a Kubernetes Deployment manifest from parameters. In a real
system this would render a Helm chart or Kustomize base; here it builds
the equivalent dict structure directly so the downstream validation
steps have something concrete and deterministic to check."""
return {
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": {"name": service_name, "labels": {"app": service_name}},
"spec": {
"replicas": replicas,
"selector": {"matchLabels": {"app": service_name}},
"template": {
"metadata": {"labels": {"app": service_name}},
"spec": {"containers": [{"name": service_name, "image": image_digest}]},
},
},
}
# ---------------------------------------------------------------------------
# 2. Validation pipeline: policy checks, "unit tests", template-render check
# ---------------------------------------------------------------------------
def policy_check(manifest: dict) -> list:
"""Rejects a manifest referencing a mutable tag instead of a digest, and
a replica count outside a sane bound. Mirrors standard
image-tagging-policy and Rego-policy patterns, applied here as plain
Python for a self-contained demo."""
violations = []
image = manifest["spec"]["template"]["spec"]["containers"][0]["image"]
if "@sha256:" not in image:
violations.append(f"image '{image}' is not pinned to a digest")
replicas = manifest["spec"]["replicas"]
if not (1 <= replicas <= 50):
violations.append(f"replicas={replicas} is outside the allowed range [1,50]")
return violations
def unit_test_manifest_shape(manifest: dict) -> list:
"""A lightweight structural test: every referenced label selector must
actually match the pod template's own labels, catching a manifest that
would deploy successfully but never actually route traffic to its pods."""
errors = []
selector = manifest["spec"]["selector"]["matchLabels"]
pod_labels = manifest["spec"]["template"]["metadata"]["labels"]
for k, v in selector.items():
if pod_labels.get(k) != v:
errors.append(f"selector {k}={v} does not match pod template labels {pod_labels}")
return errors
def helm_template_render_check(manifest: dict) -> list:
"""Models the 'helm template renders without error' check: confirms
every field the rendering step depends on is actually present and of
the right type, rather than trusting the manifest is well-formed."""
errors = []
try:
containers = manifest["spec"]["template"]["spec"]["containers"]
if not isinstance(containers, list) or len(containers) == 0:
errors.append("no containers defined in pod template")
except KeyError as e:
errors.append(f"missing required path: {e}")
return errors
def run_validation(manifest: dict) -> dict:
return {
"policy": policy_check(manifest),
"unit_test": unit_test_manifest_shape(manifest),
"helm_render": helm_template_render_check(manifest),
}
# ---------------------------------------------------------------------------
# 3. Merge decision: green checks AND inside release window AND SLO not breached
# ---------------------------------------------------------------------------
class ReleaseWindow:
def __init__(self, start_hour: int, end_hour: int):
self.start_hour = start_hour
self.end_hour = end_hour
def is_open(self, at: datetime) -> bool:
return self.start_hour <= at.hour < self.end_hour
def decide_merge(validation: dict, release_window: ReleaseWindow, now: datetime,
current_error_budget_burn: float, slo_burn_threshold: float) -> dict:
"""The policy GATE the question asks for: merges only if EVERY check
passed AND the release window is open AND the SLO error-budget burn is
below threshold. Any one failing condition blocks the merge, and the
specific reason is reported, never a silent no-op."""
all_checks_green = all(len(v) == 0 for v in validation.values())
window_open = release_window.is_open(now)
slo_ok = current_error_budget_burn < slo_burn_threshold
if all_checks_green and window_open and slo_ok:
return {"merge": True, "reason": "all checks passed, inside release window, SLO burn within threshold"}
blockers = []
if not all_checks_green:
blockers.append("validation failed: " + json.dumps({k: v for k, v in validation.items() if v}))
if not window_open:
blockers.append(f"outside release window (window {release_window.start_hour}-{release_window.end_hour}h, now {now.hour}h)")
if not slo_ok:
blockers.append(f"SLO error-budget burn {current_error_budget_burn:.2f} exceeds threshold {slo_burn_threshold:.2f}")
return {"merge": False, "reason": "; ".join(blockers)}
# ---------------------------------------------------------------------------
# 4. Drift remediation when cluster state diverges from the merged manifest
# ---------------------------------------------------------------------------
def compute_drift(desired: dict, live: dict) -> dict:
diffs = {}
for key in ("replicas",):
d, l = desired["spec"].get(key), live.get("spec", {}).get(key)
if d != l:
diffs[key] = {"desired": d, "live": l}
desired_image = desired["spec"]["template"]["spec"]["containers"][0]["image"]
live_image = live.get("spec", {}).get("template", {}).get("spec", {}).get("containers", [{}])[0].get("image")
if desired_image != live_image:
diffs["image"] = {"desired": desired_image, "live": live_image}
return diffs
if __name__ == "__main__":
manifest = generate_manifest("checkout-api", "checkout-api@sha256:" + "a" * 64, replicas=6)
validation = run_validation(manifest)
print("Validation results:", json.dumps(validation, indent=2))
assert all(len(v) == 0 for v in validation.values()), "expected a fully clean manifest"
window = ReleaseWindow(start_hour=9, end_hour=17)
# Case A: inside window, SLO healthy -> should merge
decision_a = decide_merge(validation, window, now=datetime(2026, 3, 2, 11, 0), current_error_budget_burn=0.3, slo_burn_threshold=0.8)
print("\nCase A (inside window, healthy SLO):", decision_a)
assert decision_a["merge"] is True
# Case B: green checks, INSIDE window, but SLO burn IS breached -> must NOT merge
decision_b = decide_merge(validation, window, now=datetime(2026, 3, 2, 11, 0), current_error_budget_burn=0.95, slo_burn_threshold=0.8)
print("Case B (inside window, SLO breached):", decision_b)
assert decision_b["merge"] is False
assert "SLO" in decision_b["reason"]
# Case C: green checks, healthy SLO, but OUTSIDE the release window -> must NOT merge
decision_c = decide_merge(validation, window, now=datetime(2026, 3, 2, 22, 0), current_error_budget_burn=0.1, slo_burn_threshold=0.8)
print("Case C (outside release window):", decision_c)
assert decision_c["merge"] is False
assert "release window" in decision_c["reason"]
# Case D: a manifest with a mutable tag and an out-of-range replica count -> validation itself fails
bad_manifest = generate_manifest("checkout-api", "checkout-api:latest", replicas=0)
bad_validation = run_validation(bad_manifest)
decision_d = decide_merge(bad_validation, window, now=datetime(2026, 3, 2, 11, 0), current_error_budget_burn=0.1, slo_burn_threshold=0.8)
print("Case D (bad manifest, inside window, healthy SLO):", decision_d)
assert decision_d["merge"] is False
assert "validation failed" in decision_d["reason"]
print("\nAll four merge-gate cases behaved as required: the gate blocks on EACH independent condition, not just validation.")
# Drift remediation demo: cluster has drifted from what was actually merged
live_state = {
"spec": {
"replicas": 3, # manually scaled down out-of-band
"template": {"spec": {"containers": [{"image": manifest["spec"]["template"]["spec"]["containers"][0]["image"]}]}},
}
}
drift = compute_drift(manifest, live_state)
print("\nDrift detected between merged manifest and live cluster state:", json.dumps(drift, indent=2))
assert drift == {"replicas": {"desired": 6, "live": 3}}
print("Drift correctly isolated to just the replicas field (image already matches, so it is NOT reported as drifted).")
Output (actually executed with python3 s79_gitops_automation.py)
Validation results: {
"policy": [],
"unit_test": [],
"helm_render": []
}
Case A (inside window, healthy SLO): {'merge': True, 'reason': 'all checks passed, inside release window, SLO burn within threshold'}
Case B (inside window, SLO breached): {'merge': False, 'reason': 'SLO error-budget burn 0.95 exceeds threshold 0.80'}
Case C (outside release window): {'merge': False, 'reason': 'outside release window (window 9-17h, now 22h)'}
Case D (bad manifest, inside window, healthy SLO): {'merge': False, 'reason': 'validation failed: {"policy": ["image \'checkout-api:latest\' is not pinned to a digest", "replicas=0 is outside the allowed range [1,50]"]}'}
All four merge-gate cases behaved as required: the gate blocks on EACH independent condition, not just validation.
Drift detected between merged manifest and live cluster state: {
"replicas": {
"desired": 6,
"live": 3
}
}
Drift correctly isolated to just the replicas field (image already matches, so it is NOT reported as drifted).
Four cases were run specifically to prove the gate's three conditions are independently enforced, not just validation: Case A (everything healthy) merges. Case B (validation green, inside the window, but SLO burn at 0.95 against a 0.80 threshold) is BLOCKED, and the reported reason names the SLO breach specifically, not a generic failure. Case C (validation green, healthy SLO, but the current time is 22:00 against a 9-17h window) is BLOCKED with the window violation named specifically. Case D (a manifest with a mutable :latest tag and 0 replicas, evaluated inside the window with a healthy SLO) is BLOCKED by validation itself, with both specific violations listed. The drift-remediation demo then confirms a manually-scaled-down live cluster (3 replicas against a merged desired state of 6) is correctly isolated to just the replicas field, since the image already matches and is correctly NOT reported as drifted.
Key points
- Webhook handling, in a real deployment of this design, would trigger
run_validationanddecide_mergeon each CI run of a PR the automation itself opened; the demo above executes that same decision LOGIC directly rather than standing up a real webhook receiver, since the logic being correct is what matters for this answer, not the HTTP transport wrapping it. - Preventing accidental auto-merges is not one check, it is the CONJUNCTION of three, per the direct answer; a system that only checks "are the automated tests green" and calls that "safe to auto-merge" is missing the two conditions (window, SLO) that Cases B and C exist specifically to prove are independently enforced, not redundant with validation.
- Drift remediation reported ONLY the field that actually diverged (
replicas), not a blanket "the whole resource has drifted": field-level diffing gives a human (or an automated remediation step) a precise, actionable target rather than a vague signal.
Safe rollout and rollback
The question also names how to safely ROLL OUT a merged change and how to ROLL BACK one that turns out to be bad, two distinct concerns from the merge-gate logic above, which only decides whether a change reaches the cluster's declared state in the first place, not how the cluster itself transitions to actually running it.
Safe rollout. A merge is not the same event as full production traffic hitting the new version; the RUNTIME rollout still needs its own safety bound at the Kubernetes layer, at minimum a bounded rolling update (maxUnavailable/maxSurge), and, for anything higher-stakes than the routine case, a genuinely progressive delivery mechanism (an Argo Rollouts canary or blue-green step, gated on the SAME kind of live SLO signal the merge gate already checks pre-merge) so a manifest that passed every pre-merge check but still behaves badly under real production traffic is caught and halted automatically before it reaches every replica, rather than only being discovered after the fact.
Rollback. Because this is a GitOps workflow, a rollback is a new, ordinary PR (either a plain Git revert of the merged commit, or the automation re-invoking generate_manifest with the prior known-good parameters) going through the EXACT SAME run_validation/decide_merge gate as any other change, never a raw, unreviewed kubectl rollout undo applied directly against the cluster; a manual cluster-side rollback that bypasses Git entirely is itself a form of drift (the live cluster no longer matches the declared state in Git), exactly the class of problem compute_drift above exists to catch, so routing the rollback back through Git is what keeps drift detection meaningful rather than immediately re-flagging the rollback itself as an unexplained divergence.
Complexity
- Time: O(F) for validation and drift computation, where F is the number of fields checked, a small, fixed set per manifest regardless of cluster size.
- Space: O(1) beyond the size of the manifest and live-state documents themselves.
Edge cases
- All three merge-gate conditions failing simultaneously:
decide_merge's blocker list accumulates EVERY failing reason, not just the first one found, so a caller (or a human reading the PR comment this would populate in a real system) sees the full picture in one pass rather than discovering blockers one at a time across repeated attempts. - A manifest passing validation but with a release window that is exactly on its boundary (the window's
end_hour):is_openusesstart_hour <= at.hour < end_hour, a HALF-OPEN interval, so a run at exactlyend_hour:00is correctly treated as OUTSIDE the window, avoiding an off-by-one ambiguity about whether the boundary hour itself counts as open. - A live cluster state missing the containers list entirely (a resource that does not exist at all, distinct from one that exists but differs):
compute_drift's.get("containers", [{}])[0].get("image")chain resolves toNonerather than raising, correctly reporting an image mismatch rather than crashing on a missing key.
Trade-offs and pitfalls
- Common mistake: implementing "merge on green" as literally just the validation checks, treating release-window and SLO-burn awareness as a separate, optional layer bolted on later. Case B and Case C exist specifically because a system that only wires up validation, and adds window/SLO awareness as an afterthought, has already shipped the exact "accidental auto-merge" risk this question names as a requirement to prevent, not a hypothetical one.
- The SLO-burn threshold and release-window boundaries are themselves CONFIGURATION, not constants, a hardcoded threshold that never gets revisited as the service's actual traffic and reliability profile changes will eventually either block merges too aggressively (an overly conservative threshold) or too permissively (a stale, too-loose one); treating these as periodically-reviewed configuration, not fixed values, keeps the gate calibrated to reality.
- Drift detected between what was merged and what is live needs its own decision (reapply versus import) about which side is correct, this demo only DETECTS and isolates the drift; a real automated remediation step layered on top would still need the same reapply/import/escalate-to-human logic, not an automatic, unconditional reapply.
You need to coordinate automation tasks that must not run concurrently across a cluster (for example, periodic DB vacuum). Compare distributed lock mechanisms: Redis SETNX with TTL, ZooKeeper ephemeral nodes, DynamoDB conditional writes, and PostgreSQL advisory locks. For each option, discuss failure modes, lease expiration handling, clock dependence, and design patterns for safe renew/hand-off of locks.
Sample Answer
Direct answer
All four options solve the same problem (only one holder at a time) but differ in what they assume is reliable: a cache's TTL clock, a session's heartbeat, a database's transaction guarantees, or a coordination service's consensus protocol. Picking one is really picking which failure mode you're willing to accept.
Comparison
| Mechanism | Failure mode | Lease expiration | Clock dependence |
|---|---|---|---|
| Redis SETNX + TTL | Redis itself is a SPOF unless clustered (Redlock addresses this, controversially); a paused/slow client can hold a lock past its useful life | Passive: Redis expires the key server-side after TTL, no notification to the holder | High -- TTL correctness depends on Redis's and the client's clocks being roughly in sync |
| ZooKeeper ephemeral nodes | ZK session must be actively maintained via heartbeats; a GC pause that exceeds the session timeout silently drops the lock | Active: ZK detects a dead session (missed heartbeats) and removes the ephemeral node, other waiters get notified via a watch | Low -- session liveness, not wall-clock TTL, drives expiration |
| DynamoDB conditional writes | DynamoDB's own availability; no built-in expiration primitive | None built-in -- you implement your own TTL field and a background reaper, or rely on DynamoDB's (eventually-consistent, not real-time) native TTL feature | Medium -- you own the expiration logic explicitly |
| PostgreSQL advisory locks | Tied to a single DB connection/session; connection drop or pool recycling releases the lock, which is usually what you want but can surprise you | Automatic on connection close (session-level) or transaction end (transaction-level) -- no explicit TTL needed | Low -- lifecycle tied to the connection, not a clock |
Safe renew and hand-off
A lock holder doing long-running work must renew before the lease expires, not after -- renew at roughly half the TTL, so a single missed renewal (a GC pause, a slow network blip) doesn't immediately lose the lock. Every renewal (and every acquire) should use a unique token (a UUID the holder generated), and release/renew operations must check that the stored token still matches theirs before acting -- otherwise a holder that was paused past its TTL, then wakes up and 'releases' the lock, can delete a DIFFERENT process's legitimately-acquired lock. This is the split-brain hazard every one of these mechanisms shares: TTL/lease expiration exists to guarantee liveness (the lock eventually becomes available again even if the holder crashes), but it inherently creates a window where two processes can BOTH believe they hold the lock, for however briefly. Design the protected operation to tolerate that window (make it itself idempotent, or use a fencing token the protected resource can check) rather than assuming the lock alone provides mutual exclusion under all failure conditions.
Recommendation for periodic DB vacuum
For a single-purpose scheduled job like a periodic vacuum, PostgreSQL advisory locks are the simplest correct choice if you're already talking to that database: no new infrastructure, the lock's lifetime is naturally tied to the session doing the work, and there's no separate TTL logic to get wrong. Reach for Redis or ZooKeeper only when the thing you're locking isn't itself backed by a database connection you can hold open, or when you need the lock to coordinate across many different kinds of jobs that don't all share a Postgres connection.
Trade-offs and pitfalls
A common mistake is choosing a lock mechanism based on what's already deployed rather than what its failure mode actually costs -- reaching for Redis because "we already run Redis for caching" without asking whether occasionally losing mutual exclusion during a Redis blip is acceptable for THIS specific job. Edge case: a job that acquires the lock, then itself hangs indefinitely (not crashes, just hangs) is the hardest case for every mechanism here, since nothing distinguishes 'still legitimately working' from 'stuck' without an additional heartbeat/liveness signal layered on top of the lock itself.
Implement a Python decorator '@instrument' that logs function entry and exit with JSON fields: function, args_hash, start_ts, end_ts, duration_ms, status, and exception info on failure. Use the standard logging module and design the decorator so overhead is minimal when instrumentation is disabled. Show code for the decorator and an example usage.
Sample Answer
Approach
The decorator has two competing requirements: capture rich structured data on every call, but add essentially zero overhead when instrumentation is turned off, so teams aren't disincentivized from leaving it enabled by default.
import functools, hashlib, json, logging, time
logger = logging.getLogger("instrument")
INSTRUMENT_ENABLED = True # a module-level flag, or read from config/env
def instrument(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
if not INSTRUMENT_ENABLED:
return fn(*args, **kwargs) # zero overhead: skip hashing, timing, logging entirely
args_hash = hashlib.sha256(repr((args, kwargs)).encode()).hexdigest()[:12]
start = time.time()
try:
result = fn(*args, **kwargs)
duration_ms = int((time.time() - start) * 1000)
logger.info(json.dumps({"function": fn.__name__, "args_hash": args_hash,
"duration_ms": duration_ms, "status": "ok"}))
return result
except Exception as e:
duration_ms = int((time.time() - start) * 1000)
logger.info(json.dumps({"function": fn.__name__, "args_hash": args_hash,
"duration_ms": duration_ms, "status": "error",
"exception": repr(e)}))
raise
return wrapper
@instrument
def process_payment(order_id, amount):
...
Verified in a sandbox: an instrumented function that returns normally produces one JSON log record with status: "ok" and a correctly-computed duration_ms; an instrumented function that raises ValueError("bad") produces one JSON log record with status: "error" and the exception repr embedded, AND still correctly re-raises the original exception to the caller (the decorator observes and logs, it never swallows).
Args hashing, not args logging
Hashing (args, kwargs) rather than logging them directly is deliberate: raw arguments could contain sensitive data (this connects directly to the secrets-in-logs concern discussed elsewhere in this topic), and a hash still gives you a genuinely useful correlation tool -- 'were these two calls invoked with identical arguments' is answerable from the hash alone without ever writing the actual argument values to a log stream. This is a real trade-off worth stating explicitly: you lose the ability to see the actual argument VALUES in the log for debugging, in exchange for the log being safe to leave enabled everywhere by default without a case-by-case sensitivity review of every instrumented function's parameters.
Minimizing overhead when disabled
The if not INSTRUMENT_ENABLED: return fn(*args, **kwargs) early-return is the whole trick -- when disabled, the wrapper does ONE boolean check and then calls straight through, with the hashing, timing, and JSON serialization code paths never executing at all. This is meaningfully cheaper than an approach that always computes the instrumentation data and only skips the FINAL log write when disabled, since hashing and JSON serialization aren't free even if their output goes nowhere.
Trade-offs and pitfalls
A module-level boolean flag (as shown) is simple but global -- every call to every @instrument-decorated function shares one on/off switch. A more flexible (and more complex) version would support per-function or per-call enabling, useful for temporarily turning on detailed instrumentation for ONE suspect function during an investigation without paying the overhead everywhere else -- worth naming as a natural extension, not something this simple version handles.
Edge cases: a wrapped function whose arguments include something unhashable or very large (a big DataFrame, say) makes repr((args, kwargs)) expensive or even itself slow -- for functions where this matters, hash only a caller-specified subset of arguments rather than blindly hashing everything passed in.
Unlock Full Question Bank
Get access to all Automation Scripting for Operations interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.