Nov 23, 20268 min read

Product Catalog Import Backend: Supplier CSV Feeds into Postgres

How to import supplier and merchant product feeds into an ecommerce catalog: direct uploads to object storage, background parsing, row-level validation with error reports, bulk upserts that skip unchanged rows and safe handling of missing products, with a TypeScript example on Encore.

Illustration for Product Catalog Import Backend: Supplier CSV Feeds into Postgres

Most ecommerce catalogs are fed by files: supplier price lists, marketplace exports and the merchandising spreadsheet. The import looks easy until an 80 MB file times out the request, one stray comma rejects the whole upload and a truncated feed hides half the store.

This guide covers direct uploads, background parsing, row-level errors and safe handling of missing products, with a TypeScript example on Postgres.

Why upload to storage instead of the API?

Large files and API servers do not mix: request size limits, timeouts and memory spikes all show up at once. Give the client a short-lived signed upload URL to a private bucket, let it upload directly, and start processing once the upload finishes. The original file stays in the bucket, which is useful when a supplier asks what they sent last Tuesday.

How do you parse supplier CSV files safely?

CSV has a standard, RFC 4180, and suppliers ignore parts of it: quoted fields with embedded newlines, semicolon delimiters from European spreadsheet exports, a byte order mark in front of the first header, and trailing empty columns. Use a CSV parser such as csv-parse with header mapping and BOM handling instead of splitting on commas. Map columns by header name rather than position, since suppliers reorder columns without notice.

How do you validate rows without failing the file?

Validate every row on its own: SKU present, price a valid decimal, stock a non-negative integer, title within length limits. Store each failure with its line number, column and message, and continue. At the end the import has three numbers, rows imported, rows unchanged and rows rejected, plus a downloadable error list the supplier can fix. Decide up front when to stop instead: if more than, say, 20% of rows fail, the file is probably in the wrong format, and importing the remaining 80% helps nobody.

How do you upsert thousands of rows efficiently?

Upsert in chunks of 1,000 to 5,000 rows with one statement per chunk. Passing each column as an array and expanding it with unnest keeps the statement the same size no matter how many rows it carries, and in our local Postgres 17 benchmark, inserting 100,000 rows this way took 0.23 seconds against several seconds row by row (see the Postgres bulk insert guide). Add a WHERE clause to the ON CONFLICT DO UPDATE so rows whose values did not change are skipped. updated_at then tells you which products changed, and downstream jobs such as search reindexing only see changed rows.

What about products missing from the feed?

Record on each product the import that last saw it. After a successful full feed, products that were not in it are candidates for hiding, not deletion, and only when the feed passed validation and the row count looks normal. Partial feeds, such as a daily price-only update, must never trigger this step, so mark each import as full or partial.

Catalog imports with Encore

Encore

Encore is a backend framework with built-in infrastructure, and the upload bucket, the import queue and the catalog database are declared in the TypeScript service below. Files land in an Encore object storage bucket through signed upload URLs, the import runs in a Pub/Sub subscriber with its own retries, and products and import results live in an Encore Postgres database. Encore provisions the bucket, topic and database in your own AWS or GCP account. Encore provisions an IAM role for the service, or a service account on GCP. Groupon says "Encore is our foundation for all new development."

Set up the app

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

Run in your terminal to get started locally.

-- catalog/migrations/1_create_catalog.up.sql CREATE TABLE imports ( id BIGSERIAL PRIMARY KEY, supplier TEXT NOT NULL, full_feed BOOLEAN NOT NULL, status TEXT NOT NULL DEFAULT 'uploading' CHECK (status IN ('uploading', 'processing', 'done', 'failed')), imported INT NOT NULL DEFAULT 0, unchanged INT NOT NULL DEFAULT 0, rejected INT NOT NULL DEFAULT 0, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE import_errors ( import_id BIGINT NOT NULL REFERENCES imports (id) ON DELETE CASCADE, line INT NOT NULL, message TEXT NOT NULL ); CREATE TABLE products ( sku TEXT PRIMARY KEY, title TEXT NOT NULL, price_cents INT NOT NULL, stock INT NOT NULL, last_import_id BIGINT REFERENCES imports (id), updated_at TIMESTAMPTZ NOT NULL DEFAULT now() );
// catalog/encore.service.ts import { Service } from "encore.dev/service"; export default new Service("catalog");
// catalog/import.ts import { api, APIError } from "encore.dev/api"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { Bucket } from "encore.dev/storage/objects"; import { Topic, Subscription } from "encore.dev/pubsub"; import { parse } from "csv-parse/sync"; const db = new SQLDatabase("catalog", { migrations: "./migrations" }); const uploads = new Bucket("catalog-imports"); const importJobs = new Topic<{ importId: number }>("catalog-import-jobs", { deliveryGuarantee: "at-least-once", }); const CHUNK = 2000; // Only signed-in catalog admins may import; check the role from the auth data here. export const createImport = api( { expose: true, auth: true, method: "POST", path: "/catalog/imports" }, async (p: { supplier: string; fullFeed: boolean }): Promise<{ importId: number; uploadUrl: string }> => { const row = await db.queryRow<{ id: number }>` INSERT INTO imports (supplier, full_feed) VALUES (${p.supplier}, ${p.fullFeed}) RETURNING id`; const { url } = await uploads.signedUploadUrl(`${row!.id}.csv`, { ttl: 900 }); return { importId: row!.id, uploadUrl: url }; }, ); // The client calls this once the upload to uploadUrl has finished. export const startImport = api( { expose: true, auth: true, method: "POST", path: "/catalog/imports/:importId/start" }, async ({ importId }: { importId: number }): Promise<void> => { if (!(await uploads.exists(`${importId}.csv`))) throw APIError.failedPrecondition("file not uploaded"); const row = await db.queryRow` UPDATE imports SET status = 'processing' WHERE id = ${importId} AND status = 'uploading' RETURNING id`; if (!row) throw APIError.failedPrecondition("import already started"); await importJobs.publish({ importId }); }, ); interface Valid { sku: string; title: string; priceCents: number; stock: number } function validate(rec: Record<string, string>): Valid | string { const sku = rec.sku?.trim(); if (!sku) return "sku is required"; const title = rec.title?.trim() ?? ""; if (title.length === 0 || title.length > 300) return "title must be 1 to 300 characters"; if (!/^\d+(\.\d{1,2})?$/.test(rec.price ?? "")) return `invalid price "${rec.price}"`; if (!/^\d+$/.test(rec.stock ?? "")) return `invalid stock "${rec.stock}"`; return { sku, title, priceCents: Math.round(Number(rec.price) * 100), stock: Number(rec.stock) }; } export const _runImport = new Subscription(importJobs, "run-catalog-import", { handler: async ({ importId }) => { const job = await db.queryRow<{ status: string; full_feed: boolean }>` SELECT status, full_feed FROM imports WHERE id = ${importId}`; if (job?.status !== "processing") return; // duplicate delivery of a finished job const records: { record: Record<string, string>; info: { lines: number } }[] = parse( await uploads.download(`${importId}.csv`), { columns: (header: string[]) => header.map((h) => h.trim().toLowerCase()), bom: true, skip_empty_lines: true, relax_column_count: true, info: true, // adds the file line number, which stays right with multi-line quoted fields }, ); const valid: Valid[] = []; const errors: { line: number; message: string }[] = []; for (const { record, info } of records) { const v = validate(record); if (typeof v === "string") errors.push({ line: info.lines, message: v }); else valid.push(v); } if (records.length === 0 || errors.length > records.length * 0.2) { await db.exec`UPDATE imports SET status = 'failed', rejected = ${errors.length} WHERE id = ${importId}`; return; } let imported = 0; for (let i = 0; i < valid.length; i += CHUNK) { const c = valid.slice(i, i + CHUNK); const res = await db.queryRow<{ changed: number }>` WITH up AS ( INSERT INTO products (sku, title, price_cents, stock, last_import_id) SELECT u.sku, u.title, u.price, u.stock, ${importId} FROM unnest(${c.map((v) => v.sku)}::text[], ${c.map((v) => v.title)}::text[], ${c.map((v) => v.priceCents)}::int[], ${c.map((v) => v.stock)}::int[]) AS u(sku, title, price, stock) ON CONFLICT (sku) DO UPDATE SET title = excluded.title, price_cents = excluded.price_cents, stock = excluded.stock, last_import_id = excluded.last_import_id, updated_at = now() WHERE (products.title, products.price_cents, products.stock) IS DISTINCT FROM (excluded.title, excluded.price_cents, excluded.stock) RETURNING 1) SELECT count(*)::int AS changed FROM up`; imported += res?.changed ?? 0; // Unchanged rows were skipped by the WHERE above, but they were still seen in this feed. await db.exec` UPDATE products SET last_import_id = ${importId} WHERE sku = ANY(${c.map((v) => v.sku)}::text[]) AND last_import_id IS DISTINCT FROM ${importId}`; } await using tx = await db.begin(); if (errors.length > 0) { await tx.exec` INSERT INTO import_errors (import_id, line, message) SELECT ${importId}, * FROM unnest(${errors.map((e) => e.line)}::int[], ${errors.map((e) => e.message)}::text[])`; } await tx.exec` UPDATE imports SET status = 'done', imported = ${imported}, unchanged = ${valid.length - imported}, rejected = ${errors.length} WHERE id = ${importId}`; await tx.commit(); }, });

Install the parser with npm install csv-parse. The handler downloads the whole file into memory, which works for feeds up to a few hundred megabytes. For larger catalogs, split the file into chunk messages, one per range of lines, and let several subscribers work in parallel. A retry after a crash reruns the whole file, and that is safe: the upsert skips rows that already match, so a rerun only rewrites what the first attempt never reached. Error rows and the final status are written in one transaction at the end, so a retry never duplicates them.

The hiding rule for missing products is a separate private endpoint that runs after a full feed and touches only products whose last_import_id is older than the last two successful full imports for that supplier. Keeping it out of the import handler means a broken feed can fail without ever reaching the step that hides products.

encore run gives you a local bucket, Postgres and Pub/Sub, so you can create an import, upload a CSV to the signed URL with curl -X PUT --data-binary @feed.csv, start it and follow parsing, each chunk upsert and the final counts in the local trace. When a supplier sends a new column layout, an agent can add the mapping and the validation rule in this file and run the supplier's sample through the full import locally before the change ships.

Best fit: Ecommerce and marketplace teams that ingest supplier or merchant product feeds and need imports that report bad rows clearly and never wipe the catalog on a bad file.

Frequently asked questions

How should an ecommerce backend import a large product CSV?

Upload the file straight to object storage with a signed URL, then parse it in a background job instead of the request. Validate each row, record errors with line numbers, and upsert valid rows in chunks keyed by SKU so a single bad row never blocks the rest of the file.

How do you avoid rewriting every product on each import?

Make the upsert conditional: ON CONFLICT (sku) DO UPDATE ... WHERE the incoming values differ from the stored ones. Unchanged rows are skipped, which keeps updated_at meaningful and avoids reindexing products that did not change.

What should happen to products missing from a new feed?

Do not delete them automatically. Mark them as not seen in the latest import and let a rule decide, for example hiding them after two consecutive missing feeds. A truncated file would otherwise wipe half the catalog.

How do I build a catalog import with Encore?

Declare a bucket for uploaded files, a Pub/Sub topic for import jobs and a Postgres database for products and import results in your Encore service. The subscriber downloads the file, validates rows and upserts them in chunks, and Encore provisions the bucket, topic and database in your own cloud 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.

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