Going to Production
Keep your key safe, handle errors and limits, and ship with confidence
Before you launch, make sure your API key stays private, your code handles errors and limits properly, and your API credit can't run dry unnoticed.
Keep your key on the server
Call Voice213 from your backend, never from browser or mobile app code. A key shipped to a client can be extracted and used to spend your API credit. The API also refuses cross-origin requests from other websites' browser code, so a front-end call fails with a CORS error anyway. Live transcription in a browser has a pattern of its own, below.
The usual pattern is a small endpoint on your server that your front end calls:
import express from "express";
import Voice213, { APIError } from "@voice213/sdk";
const app = express();
app.use(express.json());
const voice213 = new Voice213(); // reads VOICE213_API_KEY
app.post("/api/speak", async (req, res) => {
// Authenticate your own user here, and validate what they send
try {
// inline: the WAV comes back in the response, and nothing is stored
const speech = await voice213.textToSpeech.create({
text: String(req.body.text ?? "").slice(0, 3000),
model: "voice213-lite",
voice: "nariman",
inline: true,
});
res.type(speech.contentType).send(Buffer.from(await speech.bytes()));
} catch (error) {
// An APIError carries Voice213's status; no answer at all is a 502 here
res.status(error instanceof APIError ? error.status : 502).json({ error: error.message });
}
});
app.listen(8080);from fastapi import FastAPI, HTTPException, Response
from voice213 import APIError, AsyncVoice213
app = FastAPI()
client = AsyncVoice213() # reads VOICE213_API_KEY
@app.post("/api/speak")
async def speak(payload: dict):
# Authenticate your own user here, and validate what they send
try:
# inline=True: the WAV comes back in the response, and nothing is stored
speech = await client.text_to_speech.create(
str(payload.get("text", ""))[:3000], model="voice213-lite", voice="nariman", inline=True
)
except APIError as error:
raise HTTPException(error.status_code, error.message)
return Response(await speech.read(), media_type="audio/wav")Put your own authentication and rate limiting in front of an endpoint like this. Otherwise anyone who finds it can spend your API credit through it.
Live transcription in a browser
KhasbhaSTT LIVE is the one case where a browser connects to Voice213 itself, and the key still stays on your server. Your server creates a live token and hands the browser only the socket's url, which carries the token:
import express from "express";
import Voice213, { APIError } from "@voice213/sdk";
const app = express();
const voice213 = new Voice213(); // reads VOICE213_API_KEY
app.post("/api/live-token", async (req, res) => {
// Authenticate your own user here, and decide how long they may talk
try {
// origin: other websites can't use the token. maxSeconds: 10 minutes at most
const token = await voice213.speechToText.live.createToken({
language: "ar",
dialect: "algerian",
maxSeconds: 600,
origin: "https://shop.example",
});
// The socket's address with its single-use token: never the key
res.json({ url: token.url });
} catch (error) {
res.status(error instanceof APIError ? error.status : 502).json({ error: error.message });
}
});
app.listen(8080);from fastapi import FastAPI, HTTPException
from voice213 import APIError, AsyncVoice213
app = FastAPI()
client = AsyncVoice213() # reads VOICE213_API_KEY
@app.post("/api/live-token")
async def live_token():
# Authenticate your own user here, and decide how long they may talk
try:
# origin: other websites can't use the token. max_seconds: 10 minutes at most
token = await client.speech_to_text.live.create_token(
language="ar", dialect="algerian", max_seconds=600, origin="https://shop.example"
)
except APIError as error:
raise HTTPException(error.status_code, error.message)
# The socket's address with its single-use token: never the key
return {"url": token.url}- Set
originto your site's exact origin, such ashttps://shop.example: the socket then only opens from pages on that origin, so other websites can't use your tokens. - Create one token per session, when your user starts to talk: a token opens one session, within two minutes.
- Cap each session with
maxSeconds(up to 3,600), so a microphone left on can't run for an hour on your credit. - Put your own authentication and rate limiting in front of this endpoint too: every session it opens is paid from your API credit.
In the page, LiveSession from the JavaScript SDK opens that url and streams the microphone as 16 kHz PCM: see KhasbhaSTT LIVE for the page.
Protect your key
Give each app or server its own key: an account can have up to 10, and you can then switch one off without stopping the others. They share your limits, so more keys never mean more requests. The API Keys page shows when each key last made a request that counts toward your limits (a voice-over, a transcription or a live token: see What counts), and Usage breaks down your calls day by day.
If the key may have leaked, switch it off on the API Keys page right away: requests that use it are refused at once. Then delete it, create a new one, and deploy the new key.
Handle errors and retry safely
Every error response is JSON with a readable message in error:
{ "error": "Rate limit exceeded: RPM limit exceeded", "limit": 600 }When your API credit runs out, error holds the code INSUFFICIENT_CREDIT and message the explanation, with the amounts:
{
"error": "INSUFFICIENT_CREDIT",
"message": "Not enough API credit. Top up your balance in the developer workspace.",
"required": 3.6,
"balance": 0.12,
"currency": "DZD"
}Retry only the errors that can succeed on a second attempt:
| Status | Retry? | What to do |
|---|---|---|
400 | No | Fix the request. The message says what's wrong. |
401 | No | Check the API key, and that it's sent as Authorization: Bearer <key> or in x-api-key. |
402 | After a top-up, or once running requests end | Top up your API credit, then retry. If your other running voice-overs, transcriptions and live sessions have set the rest of it aside, you can also retry once they end. |
403 | No | The account is deactivated or suspended, or its API access is switched off (API_ACCESS_BLOCKED). Contact support. |
410 | No | The endpoint was removed from the API: remove the call. See Removed endpoints. |
413 | No | Send less: a JSON body up to 25 MB, a file for POST /stt up to 100 MB (FILE_TOO_LARGE). Compress or split long recordings. |
429 | Yes | Wait for the minute (or the day) to pass, or for one of your 20 running requests to end. For SESSION_LIMIT, wait for one of your 5 live sessions to end. See Rate Limits. |
500, 502 | Yes | Retry with exponential backoff. |
503 | Later | The API's paid requests or speech to text are paused (TOOL_DISABLED), or the API is down for maintenance. For MODEL_DISABLED, switch to another model instead. See Paused models and maintenance. |
Voice213 charges a request only once its work has succeeded, when the audio or the transcript is ready, so a request that fails with an error costs nothing, and retrying it is safe.
The SDKs retry for you, by these rules. They retry 429, 500, 502, 503 and 504 twice by default, after the API's Retry-After when it sends one (a minute at most) and with exponential backoff otherwise, and they send again a request whose connection failed before it reached Voice213. They don't retry what won't clear within a few attempts: a 429 for your account's daily limit (RATE_LIMIT_DAY), or a 503 for a paused model (MODEL_DISABLED), where you should send the voice-over with another model instead. And when a voice-over or a transcription may have reached Voice213 but no answer came back, they don't send it again: Voice213 may still be working on it. See When your client gives up. Set the number of retries and the timeout on the client, and handle what's left after the retries:
from voice213 import InsufficientCreditError, RateLimitError, Voice213, Voice213Error
# Up to 4 retries instead of 2, and up to 15 minutes for an answer
client = Voice213(max_retries=4, timeout=15 * 60)
try:
speech = client.text_to_speech.create("مرحبا بيكم في Voice213", voice="nariman")
print(speech.audio_url)
except InsufficientCreditError as error:
print(f"Top up: {error.required} DA needed, {error.balance} DA available")
except RateLimitError as error:
print("Daily limit reached: try again tomorrow" if error.code == "RATE_LIMIT_DAY" else error.message)
except Voice213Error as error:
print(error.code, error.message) # what's left after the retriesimport Voice213, { InsufficientCreditError, RateLimitError, Voice213Error } from "@voice213/sdk";
// Up to 4 retries instead of 2, and up to 15 minutes for an answer
const voice213 = new Voice213({ maxRetries: 4, timeout: 15 * 60 * 1000 });
try {
const speech = await voice213.textToSpeech.create({ text: "مرحبا بيكم في Voice213", voice: "nariman" });
console.log(speech.audioUrl);
} catch (error) {
if (error instanceof InsufficientCreditError) {
console.log(`Top up: ${error.required} DA needed, ${error.balance} DA available`);
} else if (error instanceof RateLimitError) {
console.log(error.code === "RATE_LIMIT_DAY" ? "Daily limit reached: try again tomorrow" : error.message);
} else if (error instanceof Voice213Error) {
console.log(error.code, error.message); // what's left after the retries
} else {
throw error;
}
}Every method also takes these options for a single request: { maxRetries, timeout } as its last argument in JavaScript, and max_retries= and timeout= in Python. Errors come as one class per status, with a code to branch on: see JavaScript & TypeScript and Python.
If you call the API another way, follow the same rules. Retry 429, 500, 502 and 503 with exponential backoff, and honor Retry-After when it's sent, but wait at most a minute between attempts: during maintenance it can be long. Stop on a 429 whose message says Daily limit exceeded, and on a 503 with the code MODEL_DISABLED. Send a transcription's file again with each attempt: a file you've uploaded once can't be read a second time from the same stream.
Set generous timeouts
Generation time grows with the length of the text, and with the model: a short voice-over is ready in seconds, while a long script with a Pro model can take minutes. Transcription time grows with the length of the audio: a voice note comes back in seconds, while a recording near the 30-minute limit can take a few minutes, on top of the time its upload takes. Voice213 doesn't cut long requests short.
The SDKs wait up to 10 minutes for an answer by default, which covers long voice-overs and long recordings, and in Node.js the JavaScript SDK isn't cut off after 5 minutes, as the built-in fetch is. Raise timeout when you upload large files over a slow connection. With another HTTP client, set the timeout in minutes, not seconds: 5 minutes for long voice-overs, and 10 for long recordings. In Node.js, the built-in fetch stops waiting for the answer after 5 minutes, even with a longer AbortSignal.timeout().
When your client gives up
If your client cancels a request or times out, Voice213 still finishes the generation, and charges it, even though you never receive the result. A retry after a timeout can therefore cost twice, which is why generous timeouts matter more than fast retries. For the same reason, the SDKs never retry a voice-over or a transcription Voice213 may have received: when its answer doesn't come, you get an APITimeoutError, or an APIConnectionError when the connection dropped. Until it finishes, the abandoned voice-over also counts toward your 20 requests at once, and its price stays set aside from your API credit. Voice-overs in the studio format are saved to your History in the web app, so you can still download one that finished after your client stopped waiting.
A transcription works the same way once Voice213 has your file: it runs to the end, and is charged, even after your client has stopped waiting. Its text only comes back in the response, so a transcription your client gave up on can't be fetched again, and sending the file again pays for it twice. A KhasbhaSTT LIVE session whose socket drops ends with the reason connection_lost, and is charged for the audio it received until then.
Stay within the limits
- Requests per minute and per day: 600 a minute and 1,000 a day for every account, all its keys together, whatever your plan.
- Requests at once: run at most 20 voice-overs and transcriptions at the same time, together. The next one gets
429until one of them ends. - Live sessions at once: 5 per account. The next token request gets
429 SESSION_LIMITuntil a session ends. - Live session length: up to 60 minutes, or the
maxSecondsyour server set on the token. Watch for theENDING_SOONwarning 30 seconds before the end, and open a new session if the conversation goes on. - Words per voice-over: up to 5,000 in either format, tone directions included.
- Tone directions: free, but they can't outweigh the spoken text. A text may be at most twice its billable characters plus 1,000 characters long, or it's refused with
400 TEXT_TOO_LONG. - Very short requests: every voice-over is billed at least 100 characters, so batch short lines into one request when you can. Every file you transcribe is billed at least 30 seconds.
- Long scripts: split them at sentence boundaries and join the audio afterwards. Shorter requests also come back sooner:
import re
def split_text(text, limit=3000):
"""Split text into pieces of at most `limit` characters, at sentence ends."""
pieces, current = [], ""
for sentence in re.split(r"(?<=[.!?؟\n])\s+", text.strip()):
if len(current) + len(sentence) + 1 <= limit:
current = f"{current} {sentence}" if current else sentence
continue
if current:
pieces.append(current)
while len(sentence) > limit: # one sentence longer than the limit
pieces.append(sentence[:limit])
sentence = sentence[limit:]
current = sentence
if current:
pieces.append(current)
return piecesRecordings need the same care. A file can hold up to 30 minutes of audio, in at most 100 MB: compress large files before you send them, and split longer ones into parts, at a pause if you can. With ffmpeg, for example:
# Mono MP3 at 64 kbps: about 14 MB for 30 minutes
ffmpeg -i meeting.wav -ac 1 -b:a 64k meeting.mp3
# Parts of 25 minutes, without re-encoding
ffmpeg -i meeting.mp3 -f segment -segment_time 1500 -c copy part-%03d.mp3See Rate Limits for the details.
Keep an eye on your API credit
When your API credit can't cover a request, it fails with 402 and INSUFFICIENT_CREDIT. To avoid surprises:
- Read
remainingCreditfrom every paid response and from theendedmessage of every live session, or callGET /me, and raise an alert when it drops below what a busy day costs you. - Before a big batch, price it with
POST /tts/estimatefor voice-overs, orPOST /stt/estimatefor recordings: theirenoughfield tells you whether your credit covers it. - Voice-overs and transcriptions you run at the same time each set their price aside from your credit while they run, and each live session sets aside the price of its audio so far plus the next two minutes. A batch run in parallel can therefore get
402before any of it is charged, once the running requests hold what's left. - A live session your credit can no longer cover ends early, with the reason
credit_limit. Keep a margin above what your sessions use. - Read prices from
GET /modelsandGET /stt/modelsrather than hard-coding them, so a price change reaches your own price display on its own. - Watch your balance, spend and calls on the Developer Dashboard.
- Top up before a launch or a campaign.
Save what you want to keep
The same text with the same voice, dialect and model doesn't need to be generated twice. Store the audio you get back (for example in your own object storage, keyed by a hash of the request) and serve repeat requests from there. It's faster for your users and costs nothing.
Download the files behind the URLs the API returns as soon as you get them, rather than linking to Voice213's copies forever.
Transcripts come back only in the response, or in the messages of a live session: there's no endpoint to fetch them again. Store the text you need, and don't transcribe the same recording twice.
Launch checklist
- The API key lives only on your server, in an environment variable or secret manager.
- Browsers that transcribe live get a single-use live token from your server, with
originset to your site, never the key. - Requests go through the SDKs, which retry safely, or your own code retries
429,500,502and503with backoff, and stops on a daily limit or a paused model (MODEL_DISABLED). - Timeouts are generous for long scripts, Pro models and long recordings: the SDKs' 10 minutes, or minutes rather than seconds in your own client.
- Long scripts are split into shorter pieces, and recordings into files of at most 30 minutes and 100 MB.
- Generated audio and transcripts are stored on your side.
- Live sessions handle the
ENDING_SOONwarning and theendedmessage. - No code still calls a removed endpoint.
- Someone gets alerted when
remainingCreditruns low or a402comes back, and the credit is topped up.
Was this page helpful?