Retry a transient D1 error only if you can safely repeat the operation. For writes, use the patterns on this page to avoid applying the same change twice.
The D1 REST API does not support Idempotency-Key on the /query or /raw endpoints.
Generate an idempotency_key once per logical write. On each retry, send the same key and write parameters. Keep the key in the database for as long as you accept retries.
The examples on this page assume your application generates the keys. If you accept keys from users, scope each key to the authenticated user or account and reject reuse with different parameters.
Add a UNIQUE idempotency_key column to your table and pass a stable key (for example, a UUID generated once per logical request):
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
idempotency_key TEXT NOT NULL UNIQUE,
customer_id TEXT NOT NULL,
amount_cents INTEGER NOT NULL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);Run INSERT INTO ... ON CONFLICT(idempotency_key) DO NOTHING followed by a SELECT for that key inside a single batch() call. If an earlier attempt committed before a timeout, the retry skips the duplicate insert and returns the committed row:
export async function createOrder(db, idempotencyKey, customerId, amountCents) {
const [insertResult, selectResult] = await db.batch([
db
.prepare(
`INSERT INTO orders (idempotency_key, customer_id, amount_cents)
VALUES (?, ?, ?)
ON CONFLICT(idempotency_key) DO NOTHING`,
)
.bind(idempotencyKey, customerId, amountCents),
db
.prepare(
`SELECT id, idempotency_key, customer_id, amount_cents, created_at
FROM orders
WHERE idempotency_key = ?`,
)
.bind(idempotencyKey),
]);
const order = selectResult.results[0];
if (!order) {
throw new Error("Order not found after idempotent insert");
}
return {
order,
created: (insertResult.meta.changes ?? 0) === 1,
};
}interface Order {
id: number;
idempotency_key: string;
customer_id: string;
amount_cents: number;
created_at: string;
}
export async function createOrder(
db: D1Database,
idempotencyKey: string,
customerId: string,
amountCents: number,
): Promise<{ order: Order; created: boolean }> {
const [insertResult, selectResult] = await db.batch<Order>([
db
.prepare(
`INSERT INTO orders (idempotency_key, customer_id, amount_cents)
VALUES (?, ?, ?)
ON CONFLICT(idempotency_key) DO NOTHING`,
)
.bind(idempotencyKey, customerId, amountCents),
db
.prepare(
`SELECT id, idempotency_key, customer_id, amount_cents, created_at
FROM orders
WHERE idempotency_key = ?`,
)
.bind(idempotencyKey),
]);
const order = selectResult.results[0];
if (!order) {
throw new Error("Order not found after idempotent insert");
}
return {
order,
created: (insertResult.meta.changes ?? 0) === 1,
};
}An UPDATE that adds to a balance can apply the same credit twice. Instead, insert a row for the credit in a table with a unique idempotency key. An AFTER INSERT trigger adds the credit to the balance only when D1 inserts a new row.
Use a foreign key to require an existing account. Without it, the update could match no account and the insert could still save the key, preventing a later retry from applying the credit.
CREATE TABLE accounts (
id TEXT PRIMARY KEY NOT NULL,
balance_cents INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE balance_credits (
idempotency_key TEXT PRIMARY KEY NOT NULL,
account_id TEXT NOT NULL REFERENCES accounts(id),
amount_cents INTEGER NOT NULL
);
CREATE TRIGGER apply_balance_credit
AFTER INSERT ON balance_credits
BEGIN
UPDATE accounts
SET balance_cents = balance_cents + NEW.amount_cents
WHERE id = NEW.account_id;
END;Use ON CONFLICT(idempotency_key) DO NOTHING to skip a duplicate credit without running the trigger. RETURNING yields the key only when D1 inserts the row. If D1 rejects the write, such as when the account does not exist, the query throws and D1 does not save the key.
The function returns applied: false if a previous attempt already applied the credit.
export async function applyBalanceCredit(
db,
idempotencyKey,
accountId,
amountCents,
) {
const insertedKey = await db
.prepare(
`INSERT INTO balance_credits (idempotency_key, account_id, amount_cents)
VALUES (?, ?, ?)
ON CONFLICT(idempotency_key) DO NOTHING
RETURNING idempotency_key`,
)
.bind(idempotencyKey, accountId, amountCents)
.first("idempotency_key");
return { applied: insertedKey !== null };
}export async function applyBalanceCredit(
db: D1Database,
idempotencyKey: string,
accountId: string,
amountCents: number,
): Promise<{ applied: boolean }> {
const insertedKey = await db
.prepare(
`INSERT INTO balance_credits (idempotency_key, account_id, amount_cents)
VALUES (?, ?, ?)
ON CONFLICT(idempotency_key) DO NOTHING
RETURNING idempotency_key`,
)
.bind(idempotencyKey, accountId, amountCents)
.first<string>("idempotency_key");
return { applied: insertedKey !== null };
}Use exponential backoff with jitter to space out retries. This example uses tryWhile() from @cloudflare/actors ↗︎ to retry a read-only query on transient errors. Before you apply this pattern to a write, make the write safe to retry.
import { tryWhile } from "@cloudflare/actors";
function queryD1ReadExample(db) {
return tryWhile(() => db.prepare("SELECT 1 AS result").first(), shouldRetry);
}
function shouldRetry(err, nextAttempt) {
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;
}import { tryWhile } from "@cloudflare/actors";
function queryD1ReadExample(db: D1Database) {
return tryWhile(() => db.prepare("SELECT 1 AS result").first(), 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;
}