It is useful to retry write queries from your application when you encounter a transient error. From the list of D1_ERRORs, refer to the Recommended action column to determine if a query should be retried.
Consider the following example of a shouldRetry(...) function, taken from the D1 read replication starter template ↗.
You should make sure your retries apply an exponential backoff with jitter strategy for more successful retries.
You can use libraries abstracting that already like @cloudflare/actors ↗, or copy the retry logic ↗ in your own code directly.
import { tryWhile } from "@cloudflare/actors";
function queryD1Example(d1: D1Database, sql: string) {
return await tryWhile(async () => {
return await d1.prepare(sql).run();
}, shouldRetry);
}
function shouldRetry(err: unknown, nextAttempt: number) {
const errMsg = String(err);
const isRetryableError =
errMsg.includes("Network connection lost") ||
errMsg.includes("storage caused object to be reset") ||
errMsg.includes("reset because its code was updated");
if (nextAttempt <= 5 && isRetryableError) {
return true;
}
return false;
}