HaltState AI: Idempotency Keys
Idempotency keys solve the process discontinuity problem - when your script exits before an approval arrives, then needs to resume later.
How It Works
- First call with key
"my-operation-2026-01-05"→ ReturnsApprovalPending - Human approves in dashboard
- Retry with same key
"my-operation-2026-01-05"→ Guard block executes with Permit
Key Construction Best Practices
from datetime import date, datetime
# Daily operations - include date
op_key = f"nightly-cleanup-{date.today().isoformat()}"
# Specific resources - include identifier
op_key = f"delete-user-{user_id}"
# Unique operations - include timestamp
op_key = f"deploy-{datetime.now().strftime('%Y%m%d_%H%M%S')}"
# Combination for complex operations
op_key = f"transfer-{sender_id}-{recipient_id}-{amount}-{date.today()}"
Why This Matters
- Scripts can die and restart safely - State lives in HaltState, not process memory
- No duplicate approval requests - Same key = same approval
- Works with cron/schedulers - Natural retry pattern
- Audit trail preserved - Every attempt is logged
The Exit-and-Retry Pattern
This is the standard pattern for scheduled tasks:
#!/usr/bin/env python3
"""Runs via cron every hour"""
from haltstate import HaltStateClient, ApprovalPending, ActionDenied
from datetime import date
import sys
client = HaltStateClient(tenant_id="...", api_key="hs_...")
# Same key each run today - finds existing approval if approved
op_key = f"maintenance-{date.today().isoformat()}"
try:
with client.guard("system.maintenance", params={}, idempotency_key=op_key):
run_maintenance()
print("Done!")
except ApprovalPending:
print("Pending approval - will retry next cron run")
sys.exit(0) # Clean exit
except ActionDenied as e:
print(f"Denied: {e}")
sys.exit(1)
Cron config:
0 * * * * /opt/scripts/maintenance.py