← Statpro dev log

Promise-caching killed my duplicate rows (and made the merge 8x faster)

#data#automation#infra

Two lines from separate callers converge on one glowing amber node, and a single row comes out beside a dashed duplicate that never formed.

My merge job, which loads a whole season of source rows into my database, took about six minutes per season, and the obvious way to speed it up would have corrupted the data. Every row waited on its own database round trip. Running rows in parallel was the easy win, and it also minted duplicates.

That merge feeds the shared tables of games, players and teams behind Statpro, my sports stats site, so a duplicate player is worse than a slow job. I got the speed and kept the correctness by changing one type.

Why the sequential merge was slow

The merge walks rows from a source and resolves each one to the single shared record for that team, player and game. Each resolution is a lookup and sometimes an insert, and each one cost 30 to 80 milliseconds of round trip. Taken one at a time, thousands of rows deep, that added up to roughly six minutes for a single season. Nothing was computing. The job spent its life waiting on the network.

Why naive concurrency makes duplicates

Run those rows concurrently and a race shows up at once. Two rows mention the same player, one the database has never seen. Both ask whether the player exists, and both hear no. Both insert. Now there are two canonical rows for one person. A slug is the URL-safe name each player gets, and it has to be unique, so whichever insert loses the race for it is left stranded as an orphan.

The resolver already had a cache, but it held resolved IDs. A cache of values only helps after the first resolution finishes, and the race lives in the gap before that.

Cache the promise, not the value

The fix was to change what the cache stores. This is the whole type change, and everything else follows from it:

// before: resolved ids
playerIds: Map<string, number>
// after: in-flight resolutions
playerIds: Map<string, Promise<number>>

The first caller to miss the cache starts the resolution and stores the in-flight promise straight away. A second caller that needs the same player finds that promise already there and awaits it. Both get the same ID back, and one insert happens. There's no race, no orphan and no stolen slug.

BEFORE the cache holds resolved IDs Rows A and B both need player X Both look it up: not found Both insert two canonical rows for one player, and an orphan AFTER the cache holds promises Row A stores an in-flight promise Row B finds it and awaits it One insert 8 writes in flight: about 6 minutes per season became under 1
The second caller no longer asks the database. It waits on the first caller's answer.

One detail keeps the cache honest. A failed resolution has to leave the cache, or every later caller inherits a transient error for the rest of the run. Deleting the entry means the next caller misses the cache and starts a clean attempt:

const pending = resolveOrCreate(externalId).catch((error: unknown) => {
  cache.delete(externalId); // don't poison the cache with a transient failure
  throw error;
});
cache.set(externalId, pending);
return pending;

Bounded concurrency in twelve lines

With resolution race-proof, the merge stages could run concurrently. An unbounded Promise.all over thousands of rows would hammer the database's connection limits, so a tiny chunked runner keeps eight writes in flight:

const WRITE_CONCURRENCY = 8;

function chunks<T>(items: T[], size: number): T[][] {
  const out: T[][] = [];
  for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
  return out;
}

async function eachConcurrent<T>(items: T[], run: (item: T) => Promise<void>) {
  for (const group of chunks(items, WRITE_CONCURRENCY)) {
    await Promise.all(group.map(run));
  }
}

It's about twelve lines and needs no library. Eight at a time took the season merge from six minutes to under a minute, roughly 8x.

Proving the fast run matches the slow one

A faster merge that changes the answer is a bug with good benchmarks. So I compared the concurrent run against the old sequential one. Every player slug was distinct, and the counts were identical: 1,453 players, 2,473 games, 929 roster lines (a player on a team) and 0 flags.

The promise cache lives inside one process, so two separate processes could still race each other. For that case the crosswalk table, which maps a source's IDs to canonical ones, inserts with ON CONFLICT DO NOTHING and then re-reads. Whichever writer lost adopts the winner's mapping.

Where else this fits

That same week NBA and NFL joined MLB in the merge. The pattern reaches well past sports data, though. It fits anywhere a "check, then create" step can run twice at once: signup by email, webhook deduplication, idempotent API handlers. If two callers can ask the same question in the same moment, hand the second one the first one's promise.

This is the build log for Statpro (statpro.io) · All entries · Weekly essays