Safe automation and rate limiting
When a retry becomes a second change
A test VM creation request times out after the service accepted it. The client cannot infer whether a resource was created. Retrying with a new request ID could create a second VM. An idempotency token, where supported, links repeated attempts for the same intent. Persist it with the original scope and parameters; do not reuse it for a different change. Check the provider's token lifetime, scope and conflict rules. A correlation ID is not automatically an idempotency key.
Read operations are generally easier to repeat, but may be metered or sensitive. Some writes are conditionally safe with generation or revision preconditions; others are not safe to repeat automatically. Reconcile ambiguous outcomes by checking operation status or intended resource identity. Never interpret an eventual-consistency miss as proof of absence. A bounded reconciliation process may finish as unknown and require human review.
Throttle handling and retry budgets
Rate limits constrain requests per time window; quotas constrain other quantities such as resources or concurrency. A 429 can indicate throttling, and service-specific errors may indicate conflicting operations. Check documented error codes rather than classifying every failure by HTTP status alone. Authentication/authorization and invalid request errors normally require correction, not a rapid loop.
Use a deadline, maximum attempts (including the first call), capped exponential backoff and jitter; respect documented Retry-After values. Coordinate SDK retries with application retries, because nested budgets multiply. Example: two wrapper attempts with three SDK attempts each can issue up to six requests; a 4-second server delay cannot be squeezed into a 3-second remaining deadline. Queue bounded work and limit concurrency per appropriate scope. No fixed provider rate is assumed.
A fictional allowance of 60 calls/minute and 15 calls/minute reserved for other work leaves 45 calls/minute. With 90 pages and no retries, the quota-based lower bound is two minutes at the assumed sustained rate. Real limits may use bursts, separate read/write counters or dynamic throttling. Additional retries and polls consume the same budget only if the specific API counts them there.
Dry-run and approval are different
A local dry run renders a proposed change without network access. Provider dry-run semantics vary: EC2 RunInstances supports DryRun and returns DryRunOperation when permissions are sufficient, or UnauthorizedOperation when not. This checks permissions, not future capacity, price or runtime success. Azure ARM deployment previews such as what-if apply to supported deployment workflows; they are not a universal az flag. Google Cloud validation or preview support is service-specific; do not assume gcloud has a universal dry-run mode.
Before execution, bind approval to the exact plan digest, resource scope, allowed operations, expected revision, expiration and cost ceiling. Validate resource ownership and tenant isolation. Re-read state if the plan becomes stale and require a new approval when necessary. A successful preview does not grant authorization. For this course all decisions are local and no actual mutation is permitted.
Partial failure and compensating changes
Suppose a three-step job creates a test disk, attaches it, then verifies a filesystem. Attachment succeeds but verification fails. Record the outcome of every step with an operation ID and revision. Stop further changes and inspect the known state. Compensating actions are new changes, not time travel: detaching or deleting a disk may lose data or break another workload. Do not compensate based on a guessed name or when the outcome is unknown. Require ownership, approval, dependency checks, current revision, recoverability and an explicit compensation plan; otherwise hold and escalate.
A durable journal of step intent and outcome helps recover after a crash. Separate a rejected request from an accepted but unknown operation. Redact secrets and preserve enough evidence to investigate. Do not delete all resources as a generic cleanup strategy.
Offline retry and compensation gate
The next Python 3 example is a deterministic policy model, not an actual HTTP client. It assumes a maximum of three attempts, virtual integer seconds and a simple backoff sequence of 1, 2 seconds before retries. It does not sleep, implement random jitter, authenticate, or perform rollback. The caller supplies safe_repeat only after checking documented idempotency conditions. Real code must calculate remaining time from a monotonic deadline, include request timeouts, validate trusted Retry-After values and account for SDK attempts. A successful response still needs verification.
def decision(status, safe_repeat, attempt, remaining, retry_after=0): # attempt includes the initial call; remaining is virtual seconds. if (type(attempt) is not int or attempt not in (1, 2, 3) or type(remaining) is not int or remaining < 0 or type(retry_after) is not int or retry_after < 0 or type(safe_repeat) is not bool): return "invalid", 0 if status == "ok": return "verify", 0 if status in ("denied", "invalid"): return "stop", 0 if status not in ("throttle", "timeout", "unavailable"): return "reconcile", 0 if not safe_repeat: return "reconcile", 0 delay = max(2 ** (attempt - 1), retry_after) if attempt == 3 or delay >= remaining: return "reconcile", 0 return "retry", delay
def rollback_gate(owned, approved, revision_matches, state_known): # Exact booleans only; an unknown value is never approval. return "reviewed-compensation" if all( x is True for x in (owned, approved, revision_matches, state_known) ) else "hold"
print(decision("throttle", True, 1, 10, 4))print(decision("timeout", False, 1, 10))print(rollback_gate(True, True, False, True))Expected output:
('retry', 4)('reconcile', 0)holdThe first response honors a four-second server delay within ten seconds. The second may have created something, so it requires reconciliation. The third refuses compensation when the revision changed. Try remaining=4 with retry_after=4, attempt=3, a denied request, malformed input and a compensation gate with an unknown owner. All must stop retrying or hold. The model's reviewed-compensation result indicates review eligibility only, never automatic permission to execute.
Release checklist and troubleshooting
Before deploying a real automation adapter, test empty and repeated cursors, malformed and partial responses, throttle and timeouts, non-idempotent writes, conflicting revisions and expired approval. Pin client versions and explicitly test retry configuration. Use scoped short-lived identity, allowlisted operations, independent policy enforcement, time and spend limits, structured redacted outputs, and a manual stop switch. If status cannot be established, preserve the journal and escalate to the responsible owner rather than looping forever. Review the selected provider's exact API documentation for pagination, retries, operation status and preview behavior; the V58 evidence register records official excerpts and recheck requirements.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Safe automation and rate limiting — knowledge check
Choose the best answer for each offline scenario.
A non-idempotent create timed out. What next?
Two wrapper attempts each allow three SDK attempts. Maximum requests?
A four-second Retry-After equals remaining time. What does the local model do?
What does EC2 RunInstances DryRunOperation establish?
A resource revision changed after approval. What happens to compensation?