Guide · async

Errors, retries and limits

One error envelope everywhere; what to retry (429, 503 unavailable) and how to make a retry safe (Idempotency-Key); credit, plan limits and the 402s.

Every failed call answers with the same JSON envelope, and the SDKs turn it into one error type (VocalStackError; VocalStackException in PHP) with the same fields. Most errors are final; a few say "try again", and the SDKs already do that for you where it is safe.

{
  "defined": true,
  "code": "insufficient_credit",
  "status": 402,
  "message": "this transcription would cost $0.05 and the account has $0.04 of credit; add credit to continue",
  "data": {
    "retryable": false,
    "details": {
      "balance": 0.04,
      "required": 0.05,
      "currency": "usd",
      "plan": "payg",
      "topUpUrl": "https://…"
    }
  },
  "requestId": "01J…"
}
  1. Read the error

    code is what to branch on; message is for people; data.retryable says whether sending the same request again can succeed; data.details carries what the code needs; requestId (also the X-Request-Id header) is what support asks for. In the SDKs: err.code, err.status, err.message, err.retryable, err.details, err.retryAfter (seconds, from Retry-After) and err.headers; in PHP, $e->errorCode, $e->status, $e->getMessage(), $e->retryable, $e->details, $e->retryAfter() and $e->headers.

    Status and code What to do
    400, 422 invalid_options, invalid_body, invalid_audio Fix the request: the message names the field.
    401 invalid_token, key_expired, key_revoked Check VOCALSTACK_API_KEY; use the replacement key, or create one.
    402 insufficient_credit The account's credit is out, or does not cover what the transcription costs: details.balance (dollars), plan, topUpUrl, and required when the cost was known up front (a file of known length, or the plan's minimum for a new transcription: every transcription is billed at least the plan's minimum (rates.minimumSeconds on GET /v1/billing)). Add credit; nothing was charged.
    402 usage_cap_reached The API key reached the usage cap set for it when it was made (in total, or per month, week or day, UTC): details.apiKeyId, cap, period, used, resetsAt (null for a lifetime cap), and required when a file's cost would pass it. Adding credit does not lift it: wait for resetsAt, raise the cap in the dashboard, or use another key. The account's other keys keep working.
    402 quota_exceeded A live transcription or realtime session would pass the plan's transcriptions at once: details.metric (concurrent_transcriptions), limit, used (the live transcriptions and realtime sessions running), resetsAt (null: it frees up as they end), plan, topUpUrl. A file or link transcription is never refused for it: it is created and its job waits queued, with job.queue, until one of the account's transcriptions ends, then starts by itself.
    403 forbidden, key_from_browser, suspended A missing scope (the message names it), a key sent from a web page (keep it on your server), or a suspension. Retrying never helps.
    403 terms_acceptance_required The account has not accepted the current Terms of Service and Privacy Policy: someone signs in to the Dashboard and accepts them (an organisation's keys work once one of its owners or admins has). Until then API keys and paid work are refused; cancelling, refunds and account deletion still work.
    400, 409 over the plan's transcription length A plan has one maximum length for a transcription (limits.maxTranscriptionSeconds on GET /v1/billing), the same for a file, a link and a live transcription. A longer file or link, or a maxDurationS above it, is 400 invalid_options; a live transcription is given it as maxDurationS when it starts, counting every stretch between its pauses, and ends by itself when it is used up. Both carry details.metric (max_transcription_seconds) and limit. Start a new transcription, or move to a plan with a longer limit.
    404, 409 not_found, conflict, invalid_state No such thing, a clash (a link code taken, another device sending a transcription's audio), or not now (stop on a live transcription that is not paused; start on one that has already been stopped; a second subscription checkout while one is active).
    409 payment_method_required Auto top-up (PUT /v1/billing/auto-top-up) and the customer portal need a saved payment method: make a payment (POST /v1/billing/checkouts) or add a card (POST /v1/billing/payment-methods/manage) first.
    409 payment_method_in_use, billing_details_required, auto_top_up_off A card that pays the subscription cannot be removed (add another and make it the default first); an invoice needs a billing name and address (PUT /v1/billing/details); auto top-up is off, so there is nothing to run now.
    404 promo_code_invalid The promo code does not exist, has expired, is used up, was redeemed by this account already, or gives nothing for this purchase.
    409 language_limit_reached The transcription already has 10 languages, besides the one it was spoken in: every language it was translated into or read aloud in, live or afterwards. A language it already has always works, in any voice: details.languages lists them, details.refused the ones asked for that could not be added. Retrying does not help.
    400 range_too_long A usage report covers at most 92 days: ask for a shorter range.
    429 rate_limited Wait Retry-After seconds. Retried for you. With details.metric: "creates_per_hour" it is the plan's creation rate (new transcriptions an hour), not a burst limit: Retry-After and resetsAt say when; a wait over 60 s is not retried for you.
    503 unavailable The service is waking (its database was asleep). Send it again after Retry-After. Retried for you when it is safe.
  2. Retry what can be retried

    The SDKs retry a 429 rate_limited and a 503 unavailable after Retry-After, twice by default (maxRetries on the client, max_retries in Python), but a 503 only for a call that is safe to send twice: GET, HEAD, DELETE, or any call carrying an Idempotency-Key. A create without one is not retried, because the first attempt may have worked. Every rate-limited response carries RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset (all but the health check, the reference, the language list, the realtime capabilities and the plan list): slow down before the 429. GET /v1/billing shows the plan, its rates per hour of audio and the minimum a transcription is billed, the credit balance, whether a new file (canStart) or live transcription (canStartLive) would start now, and the limits (transcriptions at once, new transcriptions an hour, requests a minute, the largest file, the longest live transcription).

  3. Read long lists a page at a time

    The lists that grow with an account answer a page at a time: GET /v1/transcriptions, a transcription's corrections (100 a page by default, limit up to 200), its history (500 by default, up to 1,000) and the billing lists. A page with more after it carries nextCursor; send it back as cursor for the next page, and stop at the page that has none. A cursor marks the last item you were given, not a position, so an item added or changed while you page is never repeated and never pushes another off a page; a cursor the list did not give out is 400 invalid_options. In the SDKs, list() reads every page for you, and listPage({ cursor }) (TypeScript), list_page(cursor=) (Python) or listPage(cursor: …) (PHP) reads one.

  4. Make creates safe to retry

    Send Idempotency-Key: <a fresh UUID> with a create (POST /v1/broadcasts, POST /v1/transcriptions, POST /v1/transcriptions/live, starting a live transcription…). Repeated within 24 hours with the same key and the same body, it returns the first answer (with Idempotent-Replayed: true) instead of creating a second thing; the same key with a different body is 422 idempotency_key_reused, and a repeat while the first is still running is 409 conflict. Keys are per account. In the SDKs: { idempotencyKey } as the call options (TypeScript), idempotency_key= (Python), idempotencyKey: (PHP).

  5. Sockets

    A refused WebSocket upgrade carries the same envelope over HTTP: 401 invalid_token, 410 session_expired (a realtime session's expiresAt passed before its first connect, or its time to reconnect after a restart close or a lost server ran out: create a new one), 503 unavailable (retry after Retry-After), 503 engine_unavailable with Retry-After on a reconnect that comes while the server the stream was on has only just gone quiet (try again). A fleet with every machine busy can instead hang the connect or answer a bare 503 with no envelope: the SDKs report that as capacity_exceeded, and as engine_unavailable when the machine started warming up and then went quiet. On an open socket, an error frame carries code, message and retryable; slow_consumer means you read too slowly and were closed (commits are never dropped, drafts are); engine_lost (retryable) means the engine transcribing the stream stopped mid-stream and no other could carry it on: the socket closes with 1011 right after, what was committed before stays. A socket that closes with neither session.done nor an error frame is reported by the SDKs as engine_lost too, except a restart close (1012: the server restarting for a deploy, or a proxy blip), which the SDKs reconnect on with the same streamUrl (up to three tries in a row) and the session goes on, and a socket that drops with no close frame at all (the server it was on died), which the SDKs open again with the same streamUrl for about 75 seconds, as long as each try is answered "try again"; a refusal for good is engine_lost at once, and a try that gets no answer at all is made again up to three more times, within about 13 seconds, before the session ends with engine_lost. Otherwise there is no resume: create a new session. A subscribe or events socket closed with 4004 fell behind (it read frames more slowly than they were sent): reconnect and read the current state again (Listen). The other close codes of those sockets and of the account socket (WS /v1/events), each with what to do: 4001, too many sockets open for the API key, the account or a listener's network (the close reason says which), or on the account socket one more than a user may hold: do not reconnect at once; 4002, open too long (a socket with no key after 6 hours, the account socket after a day): reconnect, the account socket when the user next uses that screen; 4003, access changed (the share link, key or access it was opened with was revoked): do not reconnect with the same credentials; 1008, too many client messages, or on subscribe a language the link does not allow or the transcription's 11th: send fewer, or do not ask for it again; 1009, a client message too big (over 16 KB): do not send it again; 1012 with reason restart, the server is restarting: reconnect at once and carry on as after any reconnect, no lines are lost. A realtime socket closed with 1008 was a streamUrl connected twice at once: the second socket is closed, create a new realtime session for it.

TypeScript SDK

errors.ts

import { VocalStack, VocalStackError } from '@vocalstack/js-sdk';

// 429s, and 503s on calls that are safe to repeat, are retried after Retry-After.
const vs = new VocalStack({ baseUrl: 'https://api.vocalstack.com', apiKey: process.env.VOCALSTACK_API_KEY, maxRetries: 4 });

try {
  // The key makes this create safe to retry: a repeat returns the first broadcast.
  const broadcast = await vs.broadcasts.create({ name: 'Town hall' }, { idempotencyKey: crypto.randomUUID() });
  console.log(broadcast.shareUrl);
} catch (err) {
  if (!(err instanceof VocalStackError)) throw err;
  switch (err.code) {
    case 'insufficient_credit':
    case 'quota_exceeded': {
      const d = err.details as { metric?: string; balance?: number; required?: number; topUpUrl?: string } | undefined;
      console.error(err.message, d?.metric ?? '', d?.balance ?? '', d?.required ?? '', d?.topUpUrl ?? '');
      break;
    }
    case 'rate_limited':
    case 'unavailable':
      console.error(`still ${err.code} after the retries; try again in ${err.retryAfter ?? 1} s`);
      break;
    default:
      console.error(err.status, err.code, err.message, err.headers?.get('x-request-id') ?? '');
  }
}

const billing = await vs.billing.get();
console.log(billing.plan?.name, `${billing.balance} of credit`, `${billing.limits?.concurrentTranscriptions ?? '∞'} at once`);

Python SDK

errors.py

import asyncio
import os
import uuid

from vocalstack import VocalStack, VocalStackError


async def main() -> None:
    # 429s, and 503s on calls that are safe to repeat, are retried after Retry-After.
    async with VocalStack("https://api.vocalstack.com", api_key=os.environ["VOCALSTACK_API_KEY"], max_retries=4) as vs:
        try:
            # The key makes this create safe to retry: a repeat returns the first broadcast.
            broadcast = await vs.broadcasts.create(name="Town hall", idempotency_key=str(uuid.uuid4()))
            print(broadcast.share_url)
        except VocalStackError as e:
            if e.code in ("insufficient_credit", "quota_exceeded"):
                print(e.message, e.details)
            elif e.code in ("rate_limited", "unavailable"):
                print(f"still {e.code} after the retries; try again in {e.retry_after or 1} s")
            else:
                print(e.status, e.code, e.message)

        billing = await vs.billing.get()
        print(billing.plan, f"${billing.balance} of credit", billing.limits)


asyncio.run(main())

PHP SDK

errors.php

<?php
require 'vendor/autoload.php';

use VocalStack\VocalStack;
use VocalStack\VocalStackException;

// 429s, and 503s on calls that are safe to repeat, are retried after Retry-After.
$vs = new VocalStack(apiKey: getenv('VOCALSTACK_API_KEY'), baseUrl: 'https://api.vocalstack.com', maxRetries: 4);

try {
    // The key makes this create safe to retry: a repeat returns the first broadcast.
    $broadcast = $vs->broadcasts->create(['name' => 'Town hall'], idempotencyKey: bin2hex(random_bytes(16)));
    echo $broadcast['shareUrl'], "\n";
} catch (VocalStackException $e) {
    if (in_array($e->errorCode, ['insufficient_credit', 'quota_exceeded'], true)) {
        echo $e->getMessage(), ' ', json_encode($e->details), "\n";
    } elseif (in_array($e->errorCode, ['rate_limited', 'unavailable'], true)) {
        echo "still {$e->errorCode} after the retries; try again in ", $e->retryAfter() ?? 1, " s\n";
    } else {
        echo $e->status, ' ', $e->errorCode, ' ', $e->getMessage(), "\n";
    }
}

$billing = $vs->billing->get();
echo json_encode($billing['plan']), ' 
  

, $billing['balance'], ' of credit ', json_encode($billing['limits']), "\n";

HTTP + WebSocket

errors.sh

#!/usr/bin/env bash
# curl and jq, no SDK: a create with an Idempotency-Key, retried on 429 and 503.
set -euo pipefail
API=https://api.vocalstack.com
AUTH="Authorization: Bearer $VOCALSTACK_API_KEY"
KEY=$(uuidgen) # the same key on every attempt: a repeat returns the first answer

for attempt in 1 2 3 4 5; do
  HEADERS=$(mktemp)
  STATUS=$(curl -sS -o body.json -D "$HEADERS" -w '%{http_code}' "$API/v1/broadcasts" \
    -H "$AUTH" -H "Content-Type: application/json" -H "Idempotency-Key: $KEY" \
    -d '{"name":"Town hall"}')
  case $STATUS in
    2??) jq -r .shareUrl body.json; exit 0 ;;
    429|503)
      WAIT=$(awk 'tolower($1)=="retry-after:"{print $2+0}' "$HEADERS")
      echo "$STATUS $(jq -r .code body.json): retrying in ${WAIT:-2} s" >&2
      sleep "${WAIT:-2}" ;;
    *)
      jq -r '"\(.status) \(.code): \(.message) (request \(.requestId))"' body.json >&2
      jq '.data.details' body.json >&2
      exit 1 ;;
  esac
done
exit 1