A backend for selling products before they are in stock: saving the payment method at checkout instead of an authorization that expires, allocating inbound units to preorders in order, charging off-session when stock arrives, handling declines, and sending the delay notices and automatic cancellations the FTC Mail Order Rule requires.

A preorder sells something that is not in the warehouse yet, with a ship date attached. The backend has to decide whose order ships first when a partial container arrives, charge a card weeks after checkout, and tell people when the date slips.
This guide builds that backend, from checkout to the delay notice.
An authorization holds funds without capturing them, and it does not last. Stripe's authorization validity table lists 7 days for customer-initiated online payments on Visa, Mastercard, American Express and Discover, and about 5 days for Visa merchant-initiated ones. A preorder shipping in six weeks would see its authorization lapse long before then.
The usual flow saves the payment method at checkout, with the customer agreeing to be charged later, using something like a Stripe SetupIntent, and creates a new off-session payment when the unit is allocated. That payment can be declined, so the backend needs a recovery path that a capture would not.
In the US, the FTC Mail, Internet, or Telephone Order Merchandise Rule applies to preorders like any other order:
For a backend this means two dates per order, the promised date and an optional revised one, a record of each notice and consent, and a job that acts on them. Check the details with counsel for your situation, and the rules in other countries where you sell.
When units arrive, the fair rule is first come, first served by order time. Allocation should take a row lock on the oldest open preorders and skip rows another allocation is already handling, which is what FOR UPDATE SKIP LOCKED in Postgres does, as the Postgres locking docs describe. An allocated unit stays reserved while the charge runs, and a declined charge gives the customer a few days to fix the card before the unit goes back into the pool.
Encore is a backend framework with built-in infrastructure, and the preorder service declares its Postgres database, a Pub/Sub topic for charges, the payment provider key as a secret and a cron job for delay notices in its own code, and Encore provisions them in your own AWS or GCP account. As Groupon Engineering Director Josef Sima put it, "Since adopting it, we've seen a 3x increase in development speed and 90% shorter project lead times."

Run in your terminal to get started locally.
Each preorder keeps its saved payment method, its dates and its notice history:
-- preorders/migrations/1_preorders.up.sql
CREATE TABLE preorders (
id BIGSERIAL PRIMARY KEY,
sku TEXT NOT NULL,
customer_id TEXT NOT NULL, -- payment provider customer
payment_method_id TEXT NOT NULL, -- saved with consent at checkout
amount_minor BIGINT NOT NULL,
currency TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'open',
-- open, allocated, charged, payment_failed, cancelled
promised_date DATE NOT NULL,
revised_date DATE,
notice_sent_at TIMESTAMPTZ,
consented_at TIMESTAMPTZ,
allocated_at TIMESTAMPTZ,
payment_intent_id TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX ON preorders (sku, created_at) WHERE status = 'open';
CREATE INDEX ON preorders (promised_date) WHERE status = 'open';
// preorders/preorders.ts
import { api, APIError } from "encore.dev/api";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { Topic } from "encore.dev/pubsub";
export const db = new SQLDatabase("preorders", { migrations: "./migrations" });
export interface PreorderAllocated {
preorderID: number;
}
export const allocated = new Topic<PreorderAllocated>("preorder-allocated", {
deliveryGuarantee: "at-least-once",
});
interface CreateParams {
sku: string;
customerID: string;
paymentMethodID: string;
amountMinor: number;
currency: string;
promisedDate: string; // the ship date shown at checkout, YYYY-MM-DD
}
export const createPreorder = api(
{ expose: false, method: "POST", path: "/preorders" },
async (p: CreateParams): Promise<{ id: number }> => {
if (p.amountMinor <= 0) throw APIError.invalidArgument("amount must be positive");
const row = await db.queryRow<{ id: number }>`
INSERT INTO preorders (sku, customer_id, payment_method_id, amount_minor, currency, promised_date)
VALUES (${p.sku}, ${p.customerID}, ${p.paymentMethodID}, ${p.amountMinor}, ${p.currency}, ${p.promisedDate})
RETURNING id
`;
return { id: row!.id };
},
);
// Called by the warehouse system when inbound units for a SKU are received.
export const receiveStock = api(
{ expose: false, method: "POST", path: "/stock/:sku/received" },
async ({ sku, quantity }: { sku: string; quantity: number }): Promise<{ allocated: number }> => {
const ids: number[] = [];
for await (const row of db.query<{ id: number }>`
WITH next AS (
SELECT id FROM preorders
WHERE sku = ${sku} AND status = 'open'
ORDER BY created_at, id
LIMIT ${quantity}
FOR UPDATE SKIP LOCKED
)
UPDATE preorders p SET status = 'allocated', allocated_at = now()
FROM next WHERE p.id = next.id
RETURNING p.id
`) {
ids.push(row.id);
}
for (const preorderID of ids) {
await allocated.publish({ preorderID });
}
return { allocated: ids.length };
},
);
// The customer's answer to a delay-option notice.
export const answerDelay = api(
{ expose: true, method: "POST", path: "/preorders/:id/delay" },
async ({ id, accept }: { id: number; accept: boolean }): Promise<{ status: string }> => {
const row = accept
? await db.queryRow<{ status: string }>`
UPDATE preorders SET consented_at = now()
WHERE id = ${id} AND status = 'open' AND notice_sent_at IS NOT NULL
RETURNING status`
: await db.queryRow<{ status: string }>`
UPDATE preorders SET status = 'cancelled'
WHERE id = ${id} AND status IN ('open', 'payment_failed')
RETURNING status`;
if (!row) throw APIError.failedPrecondition("preorder can no longer be changed");
return { status: row.status };
},
);
The allocation is one statement, so two warehouse events for the same SKU at once each take different rows and neither allocates a unit twice. A preorder customer who cancels before allocation needs no refund, since nothing was charged.
// preorders/charges.ts
import { api } from "encore.dev/api";
import { Subscription } from "encore.dev/pubsub";
import { CronJob } from "encore.dev/cron";
import { secret } from "encore.dev/config";
import log from "encore.dev/log";
import { db, allocated } from "./preorders";
const stripeKey = secret("StripeSecretKey");
const _ = new Subscription(allocated, "charge-preorder", {
retryPolicy: { maxRetries: 5, minBackoff: "30s" },
handler: async ({ preorderID }) => {
const p = await db.queryRow<{
customer_id: string; payment_method_id: string; amount_minor: number; currency: string; status: string;
}>`SELECT customer_id, payment_method_id, amount_minor, currency, status FROM preorders WHERE id = ${preorderID}`;
if (!p || p.status !== "allocated") return; // charged or cancelled already
const res = await fetch("https://api.stripe.com/v1/payment_intents", {
method: "POST",
headers: {
Authorization: `Bearer ${stripeKey()}`,
"Content-Type": "application/x-www-form-urlencoded",
// The same key on every retry, so the customer is charged at most once.
"Idempotency-Key": `preorder-${preorderID}`,
},
body: new URLSearchParams({
amount: String(p.amount_minor),
currency: p.currency,
customer: p.customer_id,
payment_method: p.payment_method_id,
off_session: "true",
confirm: "true",
}),
});
const body = await res.json();
if (res.ok && body.status === "succeeded") {
await db.exec`
UPDATE preorders SET status = 'charged', payment_intent_id = ${body.id}
WHERE id = ${preorderID} AND status = 'allocated'
`;
return;
}
if (res.status === 402) {
// A decline: ask the customer for a new card, keep the unit for now.
await db.exec`UPDATE preorders SET status = 'payment_failed' WHERE id = ${preorderID} AND status = 'allocated'`;
log.warn("preorder charge declined", { preorderID, code: body.error?.decline_code });
return;
}
throw new Error(`payment provider returned ${res.status}`); // retried by the subscription
},
});
// Daily: send delay-option notices, cancel unconsented long delays, release stale declines.
export const runDelays = api({ expose: false }, async (): Promise<void> => {
const due = await db.queryAll<{ id: number; customer_id: string }>`
SELECT id, customer_id FROM preorders
WHERE status = 'open' AND notice_sent_at IS NULL AND promised_date <= current_date + 3
`;
for (const p of due) {
// Send the notice with the revised date, the right to cancel and a cancel link,
// and let a send failure throw, so the order stays unmarked for tomorrow's run.
log.info("delay-option notice", { preorderID: p.id, customerID: p.customer_id });
await db.exec`
UPDATE preorders SET notice_sent_at = now(), revised_date = promised_date + 45
WHERE id = ${p.id} AND notice_sent_at IS NULL
`;
}
// A revised date more than 30 days out needs consent within 30 days of the original date.
await db.exec`
UPDATE preorders SET status = 'cancelled'
WHERE status = 'open' AND consented_at IS NULL AND notice_sent_at IS NOT NULL
AND revised_date > promised_date + 30
AND current_date > promised_date + 30
`;
// Declined charges get five days before the unit goes back to the queue.
await db.exec`
UPDATE preorders SET status = 'cancelled'
WHERE status = 'payment_failed' AND allocated_at < now() - interval '5 days'
`;
});
const _delays = new CronJob("preorder-delays", {
title: "Delay notices, automatic cancellations and stale declines",
schedule: "0 8 * * *",
endpoint: runDelays,
});
The idempotency key is derived from the preorder ID, so a subscription retry after a timeout returns the original payment instead of charging twice, which the idempotency keys guide covers in depth. The 45-day revised date is a placeholder for the date from your supplier, and a revised date within 30 days of the original would not trigger the automatic cancellation. A cancelled payment-failed order frees its unit, so the next receiveStock call, or a small job that reallocates freed units, gives it to the next customer in line.
Set the test key with encore secret set --type local StripeSecretKey and paste it when prompted. encore run starts Postgres and the charge subscription, so creating preorders and calling receiveStock shows allocation and the test-mode charge in the local dashboard trace. The delay job is an Encore platform Managed cron job that runs in deployed environments, not locally or in preview environments, so call runDelays from the local dashboard to test it.
A coding agent adding partial shipments, for example releasing half a backorder when a first pallet arrives, changes the allocation query and tests it against local data in one change, with no queue or schedule to set up in a console.
Best fit: Ecommerce teams selling limited drops, crowdfunded products or seasonal stock before it lands, who want allocation, charging and delay handling in one service in their own AWS or GCP account.
No, not usually. Charging at checkout means refunding every cancellation and holding money for goods you cannot ship yet. Most preorder flows save the payment method with the customer's consent at checkout and charge it when the order is ready to ship.
No, not for long preorders. A card authorization for an online payment is valid for about 7 days on the major networks, and Visa merchant-initiated authorizations for less, so a preorder that ships in six weeks needs a saved payment method and a new charge at shipping time.
You need a reasonable basis for the ship date you state, or 30 days if you state none, or 50 days if the buyer applies to you for credit at the time of the order. If you cannot ship on time, you must offer the choice to consent to the delay or cancel for a prompt refund, meaning within 7 working days, or within one billing cycle for credit sales. For a delay of more than 30 days or an indefinite delay, the order is cancelled automatically unless you ship within 30 days of the applicable date or receive the buyer's express consent within those 30 days.
Yes. Encore deploys the preorder service, its Postgres database, the charge queue and the delay notice cron job to your own AWS or GCP account.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.