---
title: "Importing 5,000 Products Without Melting the Database: Queues and Idempotent Upserts"
url: https://nayansukhadiya.in/blog/bulk-import-5000-skus-sqs-idempotent-upserts
published: 2026-10-20T10:28:47.887+00:00
updated: 2026-11-11T00:24:57.651086+00:00
category: "Databases & Data"
tags: ["aws","sqs","mongodb","system-design","saas"]
---

# Importing 5,000 Products Without Melting the Database: Queues and Idempotent Upserts

> A 5,000-row CSV is thousands of writes, retries and duplicates. The queued, idempotent import flow I built for a multi-tenant SaaS.

At Brilworks I worked on Service Buddy, a multi-tenant CRM and operations platform used by more than a hundred businesses. One of its quiet workhorses is inventory: each business keeps its own catalogue of products. Typing in a few items is fine. Moving a whole catalogue of 5,000+ SKUs from a spreadsheet is where the first version of any import breaks.

This post is about how that import is shaped, and why each step exists.

## The short answer

- **Split the import into stages:** map the columns, validate every row, show a preview, then process.
- **Never process inside the upload request.** The request only accepts the file; the work goes onto an AWS SQS queue.
- **Make every write idempotent.** Each product is an upsert keyed by tenant and SKU, so processing the same row twice changes nothing.

> **The one idea behind it all** A big import is not one operation. It is thousands of small ones that must each be safe to run late, run slowly and run twice.

## 1. What goes wrong with the naive version

The first version of an import is usually: upload the CSV, loop over the rows, insert each one, return "done". With five rows it is perfect. With five thousand:

- **The request times out** long before the loop finishes, the user sees an error, and half the rows are already saved.
- **The user retries**, and the saved half is inserted again as duplicates.
- **The database and API are busy** writing one tenant's catalogue while every other tenant's requests wait.
- **Bad rows are discovered mid-way**, so the catalogue ends up partly imported and partly not.

Each fix below answers one of these.

## 2. Map, validate, preview

Real spreadsheets don't share your column names. One business calls it "Item Code", another "SKU#", another "Product ID". So the first stage is **column mapping**: the user tells the system which of their columns is the SKU, the name, the price, the stock.

Then every row is **validated** before anything is written: required fields present, prices are numbers, SKUs unique within the file. The user gets a **preview** showing which rows will be created, which will update existing products, and which are invalid and why.

Nothing touches the catalogue until the user confirms. A broken spreadsheet costs a correction, not a cleanup.

## 3. Queue the work

After confirmation, the API doesn't import anything itself. It hands the work to an SQS queue and answers immediately, and the queue is processed asynchronously at a pace the database can take.

This changes three things at once:

- **No timeouts.** The upload request ends in seconds whatever the file size.
- **No noisy neighbour.** One tenant's huge import is spread over time instead of hitting the database in one burst, so other tenants keep normal response times.
- **Failures are local.** A message that fails is retried by the queue on its own, without restarting the whole file.

## 4. Idempotent upserts: safe to run twice

SQS delivers every message _at least once_. Occasionally a message arrives twice, and retries after a failure are the whole point of the queue. So processing a row must give the same result no matter how many times it runs.

The pattern is an upsert keyed by what identifies a product within a business: the tenant and the SKU. A simplified sketch of the idea (not the production code):

```ts
// One unique key per product per business.
productSchema.index({ tenantId: 1, sku: 1 }, { unique: true });

await Product.bulkWrite(
  rows.map((row) => ({
    updateOne: {
      filter: { tenantId, sku: row.sku },
      update: { $set: toProductFields(row) },
      upsert: true, // create if missing, update if present
    },
  })),
  { ordered: false }, // one bad row doesn't stop the batch
);
```

Run it once and the products exist. Run it again and they are updated to the same values. No duplicates, no matter how the queue behaves. The unique index is the safety net underneath: even a bug elsewhere can't create a second product with the same SKU for the same business.

## 5. Tenants never see each other

In a multi-tenant system the scariest import bug isn't a duplicate, it's a row landing in another business's catalogue. The tenant comes from the authenticated job, never from the file, and it is part of every filter and every unique key. The same rule holds across the NestJS APIs: role checks plus tenant isolation on every query.

## The design decisions, side by side

| Decision | Why | Trade-off |
| --- | --- | --- |
| Mapping, validation and preview before writing | Bad files fail before they touch data | More steps for the user before the import starts |
| Queue the processing on SQS | No timeouts, no burst load, per-message retries | The result is asynchronous; the UI shows progress |
| Upsert keyed by tenant + SKU | At-least-once delivery can't create duplicates | Needs a unique index and a clear identity per product |
| Tenant from the job, not the file | A file can't write into another business | None worth the risk |

## What I take from it

The upload button was the smallest part of this feature. Most of the work was deciding what happens when things go wrong: a slow database, a retry, a duplicate message, a messy spreadsheet. Once every row was safe to process late and twice, the scary parts of a big import mostly disappeared.

## Sources

- [AWS: Amazon SQS at-least-once delivery](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/standard-queues-at-least-once-delivery.html)
- [MongoDB: bulkWrite and upserts](https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkWrite/)
- [MongoDB: unique compound indexes](https://www.mongodb.com/docs/manual/core/index-unique/)

## Frequently asked questions

### Why use a queue instead of processing the file in a background thread?

A queue survives restarts, retries failed messages on its own and lets several workers share the load. A thread in the API process dies with the process and competes with live requests.

### What does idempotent mean here?

Processing the same row once or five times leaves the catalogue in the same state. That is what makes retries and duplicate deliveries harmless.

### Why show a preview before importing?

So mistakes are found while nothing has changed yet. Fixing a column mapping is much cheaper than cleaning a half-imported catalogue.
