Watch your balance and spending
Sessions are charged while they run, and a forgotten session keeps spending. This guide shows how to keep spending under control from a script.
What you can read
Data | Where |
|---|---|
Available balance | GET /accounts/balance (balance, micro-USD). It already includes what running sessions have used |
Cost of each running session so far | charge_amount in GET /sessions |
How long each session runs | duration, seconds |
Prices of each session | base_price, storage_price, traffic_price, fixed at start |
When your balance falls to $0.01, all your sessions are stopped and their data is gone. OctaSpace warns you when the balance will last less than about an hour. See Pricing and billing.
Check before a long job
Estimate the cost and compare it with the balance before you start:
import { OctaClient, formatUsd } from '@octaspace/sdk'
const client = new OctaClient({ apiKey: process.env.OCTA_API_KEY })
const hours = 12
const diskGb = 100
const machine = (await client.compute.list()).find((m) => m.node_number === '7KQ4-M2XD-4')
const estimate = hours * (machine.base_price + machine.storage_price * diskGb)
const { balance } = await client.accounts.balance()
if (balance < estimate * 1.2) {
throw new Error(`Need about ${formatUsd(estimate)}, have ${formatUsd(balance)}`)
}Traffic is not in the estimate: add a margin if your job downloads or uploads a lot.
Stop sessions over a limit
A watchdog run from cron every few minutes:
#!/usr/bin/env bash
# stop any session that has cost more than $5 or runs longer than 24 hours
set -euo pipefail
MAX_COST=5000000 # micro-USD
MAX_SECONDS=$((24*3600))
octa sessions -o json \
| jq -r --argjson c "$MAX_COST" --argjson s "$MAX_SECONDS" \
'.[] | select(.charge_amount > $c or .duration > $s) | .uuid' \
| xargs -r octa sessions stop*/5 * * * * OCTA_API_URL=https://api.octa.space /usr/local/bin/octa-watchdog.shAlert on a low balance
b, err := client.Accounts.Balance(ctx)
if err != nil {
return err
}
if b.Balance < 5_000_000 { // $5
notify(fmt.Sprintf("OctaSpace balance is low: %s", b.Balance))
}To know how long the balance lasts, add up the hourly rate of your running sessions:
const sessions = await client.sessions.list()
const perHour = sessions.reduce((sum, s) => sum + (s.base_price ?? 0), 0)
const { balance } = await client.accounts.balance()
console.log('Hours left at the current rate:', perHour ? (balance / perHour).toFixed(1) : 'n/a')This counts the base price only; storage and traffic make it a bit shorter.
Always clean up
In scripts that start sessions, stop them even when something fails:
UUID=$(octa compute start --node "$NODE" --image "$IMAGE" --wait -o json | jq -r .uuid)
trap 'octa sessions stop "$UUID"' EXIT
# ... run the job ...const { uuid } = await client.compute.start(params)
try {
await client.sessions.waitReady(uuid)
// ... run the job ...
} finally {
await client.sessions.stop(uuid)
}Stopping is safe to repeat, so a cleanup that runs twice does no harm.