Prompt
How do I add retries and alerting to an API-based workflow?
Latest observation
To add retries and alerting to an API-based workflow, you usually want three things:
- Retry transient failures safely
- Detect when the workflow is really broken
- Notify humans or systems when intervention is needed
Here’s a practical way to do it.
1) Add retries for transient failures
Retry only when the failure is likely temporary, such as:
- network timeouts
- connection resets
- HTTP
429rate limit - HTTP
503/502/504 - occasional downstream service errors
Avoid retrying blindly on:
- validation errors (
400) - auth failures (
401/403) - not found (
404) unless your workflow expects eventual consistency - non-idempotent operations unless you have safeguards
Good retry pattern
Use:
- exponential backoff
- jitter to avoid retry storms
- a max retry limit
- a timeout per request
- a dead-letter / failure path after max retries
Example backoff delays:
- 1s
- 2s
- 4s
- 8s
- 16s
Add random jitter so many workflows don’t retry at the same time.
Idempotency matters
If the API action can be repeated, make it idempotent:
- use idempotency keys
- store request IDs
- ensure duplicate calls don’t create duplicate side effects
This is critical if a retry happens after a timeout but the server actually processed the request.
2) Put retries in the right place
Retries can be implemented in a few layers:
Client-side
Your app retries the API call directly.
Good for:
- simple workflows
- quick fixes
- internal services
Workflow orchestrator
Use a tool like:
- AWS Step Functions
- Temporal
- Airflow
- Azure Durable Functions
- Google Workflows
- n8n / Make / Zapier with error handling
Good for:
- multi-step workflows
- pause/resume behavior
- retries plus branching
- auditability
Queue-based processing
Put the task on a queue and let workers retry.
Good for:
- background jobs
- high scale
- decoupling
Common pattern:
- enqueue task
- worker processes task
- on failure, retry with delay
- after max attempts, move to dead-letter queue
3) Add alerting for repeated or unrecoverable failures
Retries handle temporary issues. Alerting handles problems humans need to know about.
Trigger alerts when:
- max retries exceeded
- error rate crosses a threshold
- a workflow step fails consistently
- latency rises beyond an SLA
- a critical dependency is unavailable
- dead-letter queue starts growing
Alerting channels
Common options:
- Slack / Teams
- PagerDuty / Opsgenie
- SMS for critical issues
- dashboard + incident management system
Alert on symptoms, not every failure
Don’t page someone for every single retry. Instead, alert on patterns like:
- 5 consecutive failures
-
10% failure rate in 5 minutes
- queue backlog above threshold
-
50 items in dead-letter queue
- no successful runs for 15 minutes
This reduces noise.
4) Use observability so alerts are actionable
Add:
- structured logs with request IDs / correlation IDs
- metrics:
- success rate
- retry count
- failure count
- latency
- queue depth
- traces for multi-step workflows
This helps you answer:
- what failed?
- where did it fail?
- how many retries happened?
- is it one customer or everyone?
5) Example workflow design
A strong pattern:
- Call API
- If transient error:
- retry with exponential backoff + jitter
- If still failing after max attempts:
- mark job failed
- send to dead-letter / failure queue
- emit alert
- If permanent error:
- fail fast
- alert if needed
- Log all attempts with a correlation ID
6) Pseudocode example
import random
import time
import requests
def call_api_with_retry(url, payload, max_retries=5):
base_delay = 1
for attempt in range(max_retries + 1):
try:
response = requests.post(url, json=payload, timeout=10)
if response.status_code in [429, 500, 502, 503, 504]:
raise Exception(f"Transient error: {response.status_code}")
response.raise_for_status()
return response.json()
except Exception as e:
if attempt == max_retries:
send_alert(f"API workflow failed after {max_retries} retries: {e}")
raise
delay = base_delay * (2 ** attempt)
jitter = random.uniform(0, 0.5 * delay)
time.sleep(delay + jitter)
7) Alerting example logic
You might alert when:
retry_count > 3for a single job, orfailure_rate > 5%over 10 minutes, ordead_letter_queue_size > 0
Example alert rule:
- If 3 out of 5 workflow runs fail in 10 minutes, page the on-call.
- If a single job fails after all retries, create a ticket and send Slack notification.
8) Recommended best practices
- Retry only transient errors
- Use exponential backoff + jitter
- Set hard limits on retries
- Use idempotency keys
- Separate transient vs permanent failures
- Alert on sustained failure patterns, not every error
- Log all attempts with correlation IDs
- Send exhausted failures to a dead-letter queue or failure store
- Test failure scenarios deliberately
9) If you’re using a platform
If you tell me your stack, I can give more specific setup instructions. For example:
- AWS: Step Functions + CloudWatch alarms + SNS/PagerDuty
- GCP: Workflows + Cloud Monitoring alerts
- Azure: Durable Functions + Monitor alerts
- Python service:
tenacityfor retries + Prometheus/Grafana + Slack/PagerDuty - Node.js:
p-retryor custom retry middleware + alerting via Sentry/PagerDuty
If you want, I can also provide:
- a Python example
- a Node.js example
- an AWS architecture
- or a step-by-step implementation plan for your specific workflow.