A backend design for ecommerce warranty claims: eligibility from delivery date and coverage type, the EU two-year legal guarantee, photo uploads with signed URLs, a claim state machine, and escalation when claims sit too long.

A warranty claims backend decides whether a claim is covered, collects the evidence, and moves the claim through review to a repair, replacement or refund. Most of the bugs live in the first step, since coverage depends on the delivery date, the product and the customer's country.
The rest is a state machine with deadlines, shown below with an implementation for an online store.
Check two kinds of coverage and record which one applies. Under EU rules, consumers get a minimum two-year guarantee from the moment they receive the goods, and for a defect that shows up within the first year the seller has to prove it was not there at delivery. Some countries extend those periods, so keep them as data per country rather than constants.
A commercial warranty from the brand or the store adds its own term, such as 36 months on a power tool. In the US, written warranties on products over $15 must state the procedure for making a claim, per 16 CFR 701.3, so the claim flow should match what the warranty text promises.
Return signed upload URLs from the claim endpoint and let the browser upload to object storage directly. Each URL is bound to one object key under the claim's prefix and expires after a short time, so the API never handles the bytes and a leaked URL is useless an hour later. Review tools list the claim's prefix to show the evidence.
Claims are reviewed by people, sometimes days apart, and in support tools that make it easy to click the wrong button. Store the allowed transitions in one place, keep one open claim per unit with a partial unique index on the serial number, and reject everything else: a rejected claim cannot become a refund, and a closed claim cannot reopen without a new claim. Timestamps per status give you the time-to-decision numbers support leads ask for, and a daily job can escalate claims that have waited too long.
Encore is a backend framework with built-in infrastructure, so the claims database, the photo bucket, the decision topic and the escalation job are declared in the TypeScript that uses them. Deploying provisions Postgres, object storage and Pub/Sub in your own AWS or GCP account, and the cron job runs on Encore's managed scheduler.

Run in your terminal to get started locally.
Claim submission with coverage, signed photo uploads, decisions and escalation:
// claims/claims.ts
import { api, APIError } from "encore.dev/api";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { Bucket } from "encore.dev/storage/objects";
import { Topic } from "encore.dev/pubsub";
import { CronJob } from "encore.dev/cron";
const db = new SQLDatabase("claims", { migrations: "./migrations" });
const photos = new Bucket("claim-photos");
type Status = "submitted" | "under_review" | "approved" | "rejected" | "closed";
type Remedy = "repair" | "replace" | "refund";
const transitions: Record<Status, Status[]> = {
submitted: ["under_review", "rejected"],
under_review: ["approved", "rejected"],
approved: ["closed"],
rejected: [],
closed: [],
};
export const decided = new Topic<{ claimId: string; status: Status; remedy: Remedy | null }>(
"claim-decided",
{ deliveryGuarantee: "at-least-once" },
);
interface SubmitRequest {
orderLineId: string;
serial: string;
description: string;
photoCount: number;
}
interface SubmitResponse {
claimId: string;
coverage: "legal_guarantee" | "commercial_warranty";
uploadUrls: string[];
}
export const submit = api(
{ expose: true, method: "POST", path: "/claims" },
async (req: SubmitRequest): Promise<SubmitResponse> => {
if (req.photoCount < 1 || req.photoCount > 5) throw APIError.invalidArgument("1 to 5 photos");
const line = await db.queryRow<{ legal: boolean; commercial: boolean }>`
SELECT
l.delivered_at + make_interval(months => c.legal_months) > now() AS legal,
l.delivered_at + make_interval(months => s.warranty_months) > now() AS commercial
FROM order_lines l
JOIN countries c ON c.code = l.country_code
JOIN skus s ON s.sku = l.sku
WHERE l.id = ${req.orderLineId} AND l.delivered_at IS NOT NULL`;
if (!line) throw APIError.notFound("delivered order line not found");
if (!line.legal && !line.commercial) throw APIError.failedPrecondition("outside coverage");
const coverage = line.legal ? "legal_guarantee" : "commercial_warranty";
const claim = await db.queryRow<{ id: string }>`
INSERT INTO claims (order_line_id, serial, description, coverage)
VALUES (${req.orderLineId}, ${req.serial}, ${req.description}, ${coverage})
ON CONFLICT (serial) WHERE status NOT IN ('rejected', 'closed') DO NOTHING
RETURNING id`;
if (!claim) throw APIError.alreadyExists("an open claim exists for this serial number");
// The browser uploads straight to the bucket; each URL expires in 15 minutes.
const uploadUrls: string[] = [];
for (let i = 1; i <= req.photoCount; i++) {
const { url } = await photos.signedUploadUrl(`${claim.id}/photo-${i}.jpg`, { ttl: 900 });
uploadUrls.push(url);
}
return { claimId: claim.id, coverage, uploadUrls };
},
);
interface DecideRequest {
id: string;
status: Status;
remedy?: Remedy;
}
// Called from the internal support tool behind your auth handler.
export const decide = api(
{ expose: true, method: "POST", path: "/claims/:id/status" },
async ({ id, status, remedy }: DecideRequest): Promise<{ status: Status }> => {
if (status === "approved" && !remedy) throw APIError.invalidArgument("approval needs a remedy");
const current = await db.queryRow<{ status: Status }>`
SELECT status FROM claims WHERE id = ${id}`;
if (!current) throw APIError.notFound("claim not found");
if (!transitions[current.status].includes(status)) {
throw APIError.failedPrecondition(`cannot move from ${current.status} to ${status}`);
}
// The WHERE on the old status stops two reviewers deciding at once.
const updated = await db.queryRow<{ id: string }>`
UPDATE claims SET status = ${status}, remedy = COALESCE(${remedy ?? null}, remedy), status_at = now()
WHERE id = ${id} AND status = ${current.status}
RETURNING id`;
if (!updated) throw APIError.aborted("claim changed, reload and retry");
if (status === "approved" || status === "rejected") {
await decided.publish({ claimId: id, status, remedy: remedy ?? null });
}
return { status };
},
);
export const escalateStale = api(
{ expose: false, method: "POST", path: "/claims/escalate-stale" },
async (): Promise<{ escalated: number }> => {
const row = await db.queryRow<{ n: number }>`
WITH e AS (
UPDATE claims SET escalated_at = now()
WHERE status IN ('submitted', 'under_review')
AND status_at < now() - interval '3 days' AND escalated_at IS NULL
RETURNING 1
) SELECT count(*)::int AS n FROM e`;
return { escalated: row!.n };
},
);
new CronJob("escalate-stale-claims", {
title: "Escalate claims waiting more than three days",
schedule: "0 7 * * *",
endpoint: escalateStale,
});
-- claims/migrations/1_init.up.sql
CREATE TABLE countries (code TEXT PRIMARY KEY, legal_months INTEGER NOT NULL);
CREATE TABLE skus (sku TEXT PRIMARY KEY, warranty_months INTEGER NOT NULL DEFAULT 0);
CREATE TABLE order_lines (
id TEXT PRIMARY KEY,
sku TEXT NOT NULL REFERENCES skus (sku),
country_code TEXT NOT NULL REFERENCES countries (code),
delivered_at TIMESTAMPTZ
);
CREATE TABLE claims (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
order_line_id TEXT NOT NULL REFERENCES order_lines (id),
serial TEXT NOT NULL,
description TEXT NOT NULL,
coverage TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'submitted',
remedy TEXT,
status_at TIMESTAMPTZ NOT NULL DEFAULT now(),
escalated_at TIMESTAMPTZ
);
-- One open claim per unit; closed and rejected claims do not block a new one.
CREATE UNIQUE INDEX claims_open_serial_idx ON claims (serial)
WHERE status NOT IN ('rejected', 'closed');
The object storage docs cover the signed URL options, and the bucket is private by default, so photos are only reachable through URLs your code signs. A fulfilment service subscribes to claim-decided and books the return label or the refund as a Pub/Sub subscriber, outside the request. Locally, encore run starts Postgres, the bucket and the topic for this code, and escalateStale can be called by hand, since cron schedules only run in deployed environments.
When a coding agent adds a remedy type or a new country's guarantee period, it changes the transition table, the data and the migration in one service and runs the flow locally, and the deploy provisions anything new it declared without console work.
Best fit: Ecommerce teams building warranty and returns flows who want the database, file storage and events in their own cloud account, with coverage rules as data next to the code.
In the EU, the two-year legal guarantee starts when the customer receives the goods, so the backend needs the delivery date from the carrier, not the order date. Manufacturer warranties often start at purchase or delivery depending on their own terms.
The legal guarantee is the seller's obligation under consumer law, a minimum of two years in the EU. A commercial warranty is an extra promise from the seller or manufacturer with its own terms. A claims backend should check both and record which one covers the claim.
Give the browser signed upload URLs for object storage, scoped to the claim and valid for a short time, so files go straight to the bucket without passing through your API servers.
Typically submitted, under review, then approved with a remedy (repair, replace or refund) or rejected, and finally closed once the remedy is fulfilled. Allow only defined transitions, so a rejected claim cannot be refunded by mistake.
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.