Setting a USDC Runway Alarm: Alerting Before Your Prepaid Balance Hits Zero Mid-Job
Build a polling script that monitors your prepaid USDC balance and sends alerts at custom thresholds to Slack, email, or a webhook. This guide covers balance retrieval, alert logic, scheduling, and tuning for overnight batch workloads.
Why monitor your USDC balance
Prepaid API credits can run out at any time—especially during long-running batch jobs. If your balance hits zero mid-job, requests fail until you top up, causing delays and data gaps. A simple polling script that watches your balance and fires alerts at thresholds you choose keeps you ahead of outages.
This guide shows how to build such a script using the aggregator's API to check your remaining USDC credit and send alerts via Slack, email, or a generic webhook. The approach is language-agnostic; we'll outline the logic and key considerations.
How balance information is exposed
Your prepaid balance is tied to your API key. The aggregator provides a way to query your current credit—likely via a dedicated endpoint. Check the API documentation for the exact path and authentication method. Typically, you'll make a GET request with your API key in the header.
The response will include your remaining balance in USDC. You may also see usage details, but for alerting, you only need the balance figure.
Designing your alert thresholds
Choose thresholds based on your spending velocity and top-up latency. Common patterns:
- Warning: Balance below a comfortable buffer (e.g., enough for several hours of typical usage).
- Critical: Balance low enough that you must act soon (e.g., enough for one more batch run).
- Emergency: Balance near zero—immediate action required.
For overnight batch workloads, consider that no one may be watching. Set thresholds higher than you would for interactive use. For example, if a batch run consumes a predictable amount, set a threshold just above that amount so you can top up before the next run starts.
Building the polling script
The script's core loop:
- Fetch current balance from the aggregator API.
- Compare against your defined thresholds.
- If the balance crosses a threshold, send an alert.
- Avoid duplicate alerts: track the last alerted threshold or use a cooldown period.
- Sleep for a configured interval, then repeat.
Fetching the balance
Use your preferred HTTP client. Example in Python:
import requests
API_KEY = "your_api_key"
BALANCE_URL = "https://api.example.com/v1/account/balance" # Replace with actual endpoint
def get_balance():
headers = {"Authorization": f"Bearer {API_KEY}"}
resp = requests.get(BALANCE_URL, headers=headers)
resp.raise_for_status()
data = resp.json()
return float(data["balance_usdc"])
Defining thresholds and alert state
THRESHOLDS = [5.0, 2.0, 0.5] # USDC amounts
last_alerted = None # Track which threshold was last triggered
Sending alerts
Implement a function per channel. For Slack, use an incoming webhook:
def send_slack(message):
webhook_url = "https://hooks.slack.com/services/..."
requests.post(webhook_url, json={"text": message})
For email, use an SMTP library or a transactional email API. For a generic webhook, POST a JSON payload to your endpoint.
Main loop logic
import time
while True:
balance = get_balance()
for threshold in sorted(THRESHOLDS, reverse=True):
if balance < threshold:
if last_alerted != threshold:
send_slack(f"ALERT: USDC balance is {balance:.2f}, below threshold {threshold}")
last_alerted = threshold
break
else:
# Balance is above all thresholds; reset alert state if needed
if balance > max(THRESHOLDS):
last_alerted = None
time.sleep(300) # Poll every 5 minutes
Adjust the sleep interval based on your needs. For overnight batches, polling every 10–15 minutes is usually sufficient.
Tuning for overnight batch workloads
Overnight jobs often run unattended, so alerts must reach someone who can act. Consider these tips:
- Set higher thresholds to account for the fact that you might not see alerts until morning.
- Use multiple channels: Send critical alerts to both Slack and email, or trigger a PagerDuty-style escalation.
- Include context in alerts: current balance, threshold crossed, and a link to top up.
- Test your alerts during the day to ensure they work.
- Monitor the monitor: Ensure your script itself is running (e.g., via a cron job with error reporting).
Scheduling and deployment
Run the script as a long-running process (e.g., systemd service) or schedule it via cron. If using cron, the script can run once per interval and exit; you'll need to persist alert state between runs (e.g., write to a file).
For simplicity, a long-running process with an internal loop is often easier. Deploy it on a small server or container that stays up.
Handling API errors and rate limits
Your polling script should gracefully handle network errors and API rate limits. Implement retries with exponential backoff. If the balance endpoint returns an error, log it and continue—don't let a transient failure crash the script.
Also, be mindful of the aggregator's rate limits. Polling every few minutes is typically fine, but check the documentation.
Next steps
Once your alerting is in place, you can focus on optimizing your top-up strategy. Since the aggregator uses USDC on Base with no KYC, you can top up quickly when needed. Consider automating top-ups based on the same thresholds—but that's a topic for another guide.