Nov 20, 202610 min read

Buy Now, Pay Later Backend: Installment Plans, Collections and Retries

Design the backend behind pay-in-four installments: exact schedules in integer cents, a daily collection run, charges that cannot double under retries and crashes, decline retries, delinquency and events for reminders, then build it in TypeScript with Encore.

Illustration for Buy Now, Pay Later Backend: Installment Plans, Collections and Retries

A pay-in-four plan looks like four rows and a scheduled job. Then production traffic finds the edges: an order total that does not divide by four, a collection run that crashes after the charge but before the write, and a retry that charges the customer twice.

The money is the customer's, so each edge is a support ticket or a refund. This guide designs the installment backend that handles them, then builds it in TypeScript with Encore.

The installment backend at a glance

JobPatternWhat goes wrong without it
ScheduleInteger cents, remainder on the first installmentSums off by a cent
Create planUnique on the merchant order IDCheckout retries create two plans
CollectionDaily job over due installmentsMissed or late charges
ChargeClaim the row, idempotency key per attemptDouble charges after crashes
DeclinesRetry after 1, 3 and 7 days, then delinquentEndless retries or silent failures
EventsTopic for paid, failed and delinquentReminders and receipts coupled to collection

How do you build an exact schedule?

The CFPB's study of the BNPL market describes the common product: four payments, the first at checkout and the rest every two weeks. Store amounts as integer minor units, never floats. Divide, round down and put the remainder on the first installment, so the four always add up to the order total and the customer pays the odd cent up front rather than at the end.

// installments/schedule.ts export interface Slot { seq: number; dueOn: string; // YYYY-MM-DD amountCents: number; } // Pay in 4: one installment today, then every 14 days. Amounts are integer // cents, and the remainder goes to the first installment so the sum is exact. export function payInFour(totalCents: number, start: Date): Slot[] { const base = Math.floor(totalCents / 4); const remainder = totalCents - base * 4; return [0, 1, 2, 3].map((i) => { const due = new Date(start); due.setUTCDate(due.getUTCDate() + 14 * i); return { seq: i + 1, dueOn: due.toISOString().slice(0, 10), amountCents: base + (i === 0 ? remainder : 0), }; }); } // Retry a failed installment after 1, 3 and 7 days, then give up. export const RETRY_DAYS = [1, 3, 7];

Store the due date as a date rather than a timestamp, since collection runs once a day and "due on December 4" is what the customer sees in their app.

How do you charge without charging twice?

A customer can be charged twice in two independent ways: two workers pick up the same installment, or one worker crashes between the provider's response and the database write and then retries.

Claim the row first with a conditional UPDATE that moves it to processing, so only one worker gets it. Then send the provider an idempotency key built from the installment ID and the attempt number. If the process dies after the charge, the row stays processing, and the next run picks it up after 15 minutes and sends the same key. The provider returns the original result instead of charging again. Stripe's idempotency docs note that keys can be pruned once they are at least 24 hours old, so the stuck-row recovery has to run well inside that window.

Only a decline increments the attempt count, which gives the next retry a new key. A timeout or a 5xx from the provider does not, because the original request may still have gone through.

What happens after a decline?

Off-session charges against a saved card fail for ordinary reasons: insufficient funds, an expired card, a bank that wants the customer present. Stripe's guide to charging saved payment methods covers the off_session flag and how authentication-required declines surface.

Retry on a schedule that gives the customer time to fix it, here after 1, 3 and 7 days, and send a reminder after each failure. After the last retry the plan moves to delinquent, and from there it belongs to a collections process with people in it, not to the scheduler.

Why publish events?

Reminders, receipts, the merchant dashboard and collections all react to installment outcomes. Publishing paid, failed and delinquent events keeps those consumers out of the collection loop, so a slow email provider cannot delay charges. Delivery is at least once, so each consumer records what it already sent, as described in idempotent message consumers.

How do you build it with Encore?

Encore

Encore is a backend framework with built-in infrastructure, and the installments service declares its database, the payment provider key as a secret, an events Pub/Sub topic and a daily cron job in TypeScript, and Encore provisions them in your AWS or GCP account. Pave Bank built a bank in 9 months with Encore.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Encore provisions the infrastructure your application needs in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create bnpl --example=ts/hello-world$ cd bnpl && mkdir -p installments/migrations$ encore secret set --type dev,local,pr StripeSecretKey$ encore secret set --type prod StripeSecretKey

Use a test-mode key for development, local and preview environments and the live key only for production. The secret values are stored by Encore, not in the repository.

The schema

-- installments/migrations/1_create_plans.up.sql CREATE TABLE plans ( id BIGSERIAL PRIMARY KEY, order_id TEXT NOT NULL UNIQUE, -- one plan per merchant order psp_customer_id TEXT NOT NULL, payment_method_id TEXT NOT NULL, total_cents BIGINT NOT NULL CHECK (total_cents > 0), currency TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'active', -- active | completed | delinquent created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE installments ( id BIGSERIAL PRIMARY KEY, plan_id BIGINT NOT NULL REFERENCES plans(id), seq INT NOT NULL, -- 1..4 due_on DATE NOT NULL, amount_cents BIGINT NOT NULL CHECK (amount_cents > 0), status TEXT NOT NULL DEFAULT 'scheduled', -- scheduled | processing | paid | failed attempts INT NOT NULL DEFAULT 0, -- failed attempts so far next_attempt_at TIMESTAMPTZ NOT NULL, charge_id TEXT, updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), UNIQUE (plan_id, seq) ); CREATE INDEX installments_due ON installments (next_attempt_at) WHERE status IN ('scheduled', 'failed', 'processing');

The service

// installments/installments.ts import { api, APIError } from "encore.dev/api"; import { secret } from "encore.dev/config"; import { CronJob } from "encore.dev/cron"; import { Topic } from "encore.dev/pubsub"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { payInFour, RETRY_DAYS } from "./schedule"; const db = new SQLDatabase("installments", { migrations: "./migrations" }); const stripeKey = secret("StripeSecretKey"); export interface InstallmentEvent { planId: number; installmentId: number; outcome: "paid" | "failed" | "delinquent"; amountCents: number; } // Reminders, receipts and collections subscribe to this topic. export const installmentEvents = new Topic<InstallmentEvent>("installment-events", { deliveryGuarantee: "at-least-once", }); interface CreatePlanRequest { orderId: string; pspCustomerId: string; paymentMethodId: string; totalCents: number; currency: string; } export const createPlan = api( { expose: false, method: "POST", path: "/plans" }, async (req: CreatePlanRequest): Promise<{ planId: number }> => { if (!Number.isInteger(req.totalCents) || req.totalCents < 4) { throw APIError.invalidArgument("totalCents must be an integer of at least 4"); } const tx = await db.begin(); let planId: number; try { const plan = await tx.queryRow<{ id: number }>` INSERT INTO plans (order_id, psp_customer_id, payment_method_id, total_cents, currency) VALUES (${req.orderId}, ${req.pspCustomerId}, ${req.paymentMethodId}, ${req.totalCents}, ${req.currency}) ON CONFLICT (order_id) DO NOTHING RETURNING id`; if (!plan) { // Checkout retried: return the plan that already exists. await tx.rollback(); const existing = await db.queryRow<{ id: number }>` SELECT id FROM plans WHERE order_id = ${req.orderId}`; return { planId: existing!.id }; } planId = plan.id; for (const s of payInFour(req.totalCents, new Date())) { await tx.exec` INSERT INTO installments (plan_id, seq, due_on, amount_cents, next_attempt_at) VALUES (${planId}, ${s.seq}, ${s.dueOn}, ${s.amountCents}, ${s.dueOn}::date)`; } await tx.commit(); } catch (err) { await tx.rollback(); throw err; } await charge(planId, 1); // the first installment is due at checkout return { planId }; }, ); // Charges one installment. Safe to call twice: the UPDATE claims the row, // and the idempotency key makes a repeated request return the first result. async function charge(planId: number, seq: number): Promise<void> { const inst = await db.queryRow<{ id: number; amount_cents: number; attempts: number; currency: string; psp_customer_id: string; payment_method_id: string; }>` UPDATE installments i SET status = 'processing', updated_at = now() FROM plans p WHERE i.plan_id = p.id AND i.plan_id = ${planId} AND i.seq = ${seq} AND ((i.status IN ('scheduled', 'failed') AND i.next_attempt_at <= now()) OR (i.status = 'processing' AND i.updated_at < now() - interval '15 minutes')) RETURNING i.id, i.amount_cents, i.attempts, p.currency, p.psp_customer_id, p.payment_method_id`; if (!inst) return; // not due, already paid, or another worker has it const res = await fetch("https://api.stripe.com/v1/payment_intents", { method: "POST", headers: { Authorization: `Bearer ${stripeKey()}`, "Content-Type": "application/x-www-form-urlencoded", // Same key for the same attempt, so a crash and retry cannot charge twice. "Idempotency-Key": `installment-${inst.id}-attempt-${inst.attempts}`, }, body: new URLSearchParams({ amount: String(inst.amount_cents), currency: inst.currency, customer: inst.psp_customer_id, payment_method: inst.payment_method_id, off_session: "true", confirm: "true", }), }); const body = (await res.json()) as { id?: string; status?: string; error?: { code?: string } }; if (res.ok && body.status === "succeeded") { await db.exec` UPDATE installments SET status = 'paid', charge_id = ${body.id!}, updated_at = now() WHERE id = ${inst.id}`; await db.exec` UPDATE plans SET status = 'completed' WHERE id = ${planId} AND NOT EXISTS (SELECT 1 FROM installments WHERE plan_id = ${planId} AND status <> 'paid')`; await installmentEvents.publish({ planId, installmentId: inst.id, outcome: "paid", amountCents: inst.amount_cents }); return; } if (res.status >= 500 || res.status === 429) { return; // leave it 'processing'; the next run retries with the same key } // A decline: count the attempt and schedule the next one, or give up. const attempts = inst.attempts + 1; const delayDays = RETRY_DAYS[attempts - 1]; if (delayDays === undefined) { await db.exec`UPDATE installments SET status = 'failed', attempts = ${attempts}, next_attempt_at = 'infinity', updated_at = now() WHERE id = ${inst.id}`; await db.exec`UPDATE plans SET status = 'delinquent' WHERE id = ${planId}`; await installmentEvents.publish({ planId, installmentId: inst.id, outcome: "delinquent", amountCents: inst.amount_cents }); return; } await db.exec`UPDATE installments SET status = 'failed', attempts = ${attempts}, next_attempt_at = now() + make_interval(days => ${delayDays}), updated_at = now() WHERE id = ${inst.id}`; await installmentEvents.publish({ planId, installmentId: inst.id, outcome: "failed", amountCents: inst.amount_cents }); } // Collects every installment that is due, due for a retry, or stuck in processing. export const collect = api( { expose: false, method: "POST", path: "/installments/collect" }, async (): Promise<{ attempted: number }> => { const due = await db.queryAll<{ plan_id: number; seq: number }>` SELECT plan_id, seq FROM installments WHERE (status IN ('scheduled', 'failed') AND next_attempt_at <= now()) OR (status = 'processing' AND updated_at < now() - interval '15 minutes') ORDER BY next_attempt_at LIMIT 500`; for (const d of due) { await charge(d.plan_id, d.seq); } return { attempted: due.length }; }, ); // Managed by the Encore platform in deployed environments. It does not run // under `encore run`, so call collect directly when testing locally. const _ = new CronJob("collect-installments", { title: "Collect due installments", schedule: "0 9 * * *", endpoint: collect, });

With an encore.service.ts file in installments/, encore run starts a local Postgres, applies the migration and serves the endpoints. The cron job is managed by the Encore platform and does not run locally or in preview environments, so locally you call collect from a test or the local development dashboard. On deploy, the database runs on RDS or Cloud SQL, the topic on SNS and SQS or GCP Pub/Sub, and Encore provisions an IAM role for the service.

A coding agent adding a reminder service subscribes to installment-events in TypeScript and runs it locally in the same change, without creating a queue or wiring permissions in a separate step.

How would you build it by hand?

On AWS the same design needs an RDS database, an ECS service for the API, an EventBridge Scheduler rule or ECS scheduled task for the daily run, an SNS topic with SQS queues per consumer, the provider key in Secrets Manager and IAM for each piece, all in Terraform. The application code stays close to the TypeScript above. The difference is the infrastructure definitions and keeping them in step with the code as consumers are added.

Things to decide early

  • Partial refunds. Decide whether a refund reduces the remaining installments, last first, or refunds paid ones, and note that customers usually expect the remaining installments to shrink.
  • Late fees. If you charge them, model them as separate line items with their own idempotency, never by changing an installment amount.
  • Card updates. Let customers change the payment method on a plan, and reset the retry schedule when they do.
  • Regulation. Disclosure and late fee rules for BNPL differ by country and are changing, so review them with counsel before launch.

Frequently asked questions

How do you split a BNPL purchase into installments without rounding errors?

Work in integer minor units. Divide the total by the number of installments, round down, and add the remainder to one installment, usually the first. 100.01 split in four becomes 25.01, 25.00, 25.00 and 25.00, and the sum always matches the order total.

How do you stop a BNPL backend from charging an installment twice?

Claim the installment with a conditional UPDATE before charging, so two workers cannot both take it, and send the payment provider an idempotency key built from the installment ID and attempt number. A crash after the charge leaves the row in processing, and the retry with the same key returns the first result instead of charging again.

How often should a BNPL backend retry a declined installment?

A common schedule is a few retries spread over about a week, for example after 1, 3 and 7 days, with a reminder to the customer after each failure. After the last retry the plan moves to delinquent and leaves the automated flow.

How do you build a BNPL backend with Encore?

With Encore, declare the database, the payment provider key as a secret, an installment events topic and a daily cron job in TypeScript next to the handlers. Deploys provision the database and topic in your own AWS or GCP account, and the cron job is managed by the Encore platform.

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.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders