JavaScript · Track 3 · Tutorial 2 of 6
Send it safely more than once
Make sending a month safe to repeat: a retry that never counts twice, and code that waits when BrizoConsol asks it to.
1Why sending twice happens
A network drops, a script is run twice, a scheduler fires again. Your code needs to send a month again without it counting twice - and to know when BrizoConsol simply asks it to wait.
2Use an Idempotency-Key
month.mjs sends a header made of the company, the month and a version:
{ 'Idempotency-Key': `${companyId}-${period}-${version}` }Send it again and BrizoConsol finds the key, answers with the first request, and writes nothing.
node month.mjsCheck
Trial balance: request 92 - 6 created, 0 updated, 0 unchanged, 0 refused
Recalculation: pendingThe same request number as before: nothing was written the second time.
3Change the key when the figures change
A key that was already used never writes again - even if the figures in the body are different. When a month's figures change, change version - v2, v3 - so the new figures are written.
4Let the client wait when a company is busy
BrizoConsol writes one request at a time for a company. A second one arriving meanwhile is turned away with 429 and write_in_flight; nothing was written, and Retry-After says how many seconds to wait. call() already does this, up to five attempts:
brizo.mjs
// Every call after sign-in goes through here. It sends the access token, and handles the two answers that mean
// "send it again": 401 (the token expired) and 429 (the company is busy, or the minute's requests are used up).
const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
export async function call(method, path, body = null, headers = {}) {
if (tokens === null) {
await getToken();
}
let refreshed = false;
for (let attempt = 1; attempt <= 5; attempt++) {
const answer = await send(method, path, body, { Authorization: `Bearer ${tokens.access_token}`, ...headers });
if (answer.status === 401 && !refreshed) {
await refreshToken();
refreshed = true;
continue;
}
if (answer.status === 429) {
await sleep(Number(answer.headers['retry-after'] ?? 5));
continue; // nothing was written for this call
}
return answer;
}
throw new Error(`${method} ${path} is still answering 429 after five attempts.`);
}call() waits as asked and sends again.5Send in order, not at once
Send one company's requests one after another, not side by side: they'd only queue up behind each other's 429s. Different companies can be sent in parallel - but your group shares 60 requests a minute.
Want more detail? See the documentation