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…"
}
Read the error
codeis what to branch on;messageis for people;data.retryablesays whether sending the same request again can succeed;data.detailscarries what the code needs;requestId(also theX-Request-Idheader) is what support asks for. In the SDKs:err.code,err.status,err.message,err.retryable,err.details,err.retryAfter(seconds, fromRetry-After) anderr.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_audioFix the request: the message names the field. 401 invalid_token,key_expired,key_revokedCheck VOCALSTACK_API_KEY; use the replacement key, or create one.402 insufficient_creditThe account's credit is out, or does not cover what the transcription costs: details.balance(dollars),plan,topUpUrl, andrequiredwhen 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.minimumSecondsonGET /v1/billing)). Add credit; nothing was charged.402 usage_cap_reachedThe 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), andrequiredwhen a file's cost would pass it. Adding credit does not lift it: wait forresetsAt, raise the cap in the dashboard, or use another key. The account's other keys keep working.402 quota_exceededA 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 waitsqueued, withjob.queue, until one of the account's transcriptions ends, then starts by itself.403 forbidden,key_from_browser,suspendedA 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_requiredThe 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.maxTranscriptionSecondsonGET /v1/billing), the same for a file, a link and a live transcription. A longer file or link, or amaxDurationSabove it, is400 invalid_options; a live transcription is given it asmaxDurationSwhen it starts, counting every stretch between its pauses, and ends by itself when it is used up. Both carrydetails.metric(max_transcription_seconds) andlimit. Start a new transcription, or move to a plan with a longer limit.404, 409 not_found,conflict,invalid_stateNo such thing, a clash (a link code taken, another device sending a transcription's audio), or not now ( stopon a live transcription that is not paused;starton one that has already been stopped; a second subscription checkout while one is active).409 payment_method_requiredAuto 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_offA 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_invalidThe 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_reachedThe 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.languageslists them,details.refusedthe ones asked for that could not be added. Retrying does not help.400 range_too_longA usage report covers at most 92 days: ask for a shorter range. 429 rate_limitedWait Retry-Afterseconds. Retried for you. Withdetails.metric: "creates_per_hour"it is the plan's creation rate (new transcriptions an hour), not a burst limit:Retry-AfterandresetsAtsay when; a wait over 60 s is not retried for you.503 unavailableThe service is waking (its database was asleep). Send it again after Retry-After. Retried for you when it is safe.Retry what can be retried
The SDKs retry a
429 rate_limitedand a503 unavailableafterRetry-After, twice by default (maxRetrieson the client,max_retriesin Python), but a503only for a call that is safe to send twice:GET,HEAD,DELETE, or any call carrying anIdempotency-Key. A create without one is not retried, because the first attempt may have worked. Every rate-limited response carriesRateLimit-Limit,RateLimit-RemainingandRateLimit-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/billingshows 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).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,limitup to 200), its history (500 by default, up to 1,000) and the billing lists. A page with more after it carriesnextCursor; send it back ascursorfor 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 is400 invalid_options. In the SDKs,list()reads every page for you, andlistPage({ cursor })(TypeScript),list_page(cursor=)(Python) orlistPage(cursor: …)(PHP) reads one.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 (withIdempotent-Replayed: true) instead of creating a second thing; the same key with a different body is422 idempotency_key_reused, and a repeat while the first is still running is409 conflict. Keys are per account. In the SDKs:{ idempotencyKey }as the call options (TypeScript),idempotency_key=(Python),idempotencyKey:(PHP).Sockets
A refused WebSocket upgrade carries the same envelope over HTTP:
401 invalid_token,410 session_expired(a realtime session'sexpiresAtpassed 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 afterRetry-After),503 engine_unavailablewithRetry-Afteron 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 ascapacity_exceeded, and asengine_unavailablewhen the machine started warming up and then went quiet. On an open socket, anerrorframe carriescode,messageandretryable;slow_consumermeans 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 neithersession.donenor anerrorframe is reported by the SDKs asengine_losttoo, except a restart close (1012: the server restarting for a deploy, or a proxy blip), which the SDKs reconnect on with the samestreamUrl(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 samestreamUrlfor about 75 seconds, as long as each try is answered "try again"; a refusal for good isengine_lostat 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 withengine_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 reasonrestart, 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 astreamUrlconnected twice at once: the second socket is closed, create a new realtime session for it.
TypeScript SDK
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
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
<?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']), '