← Weekly essays

Cache the promise, not the value: race-proof deduplication without locks

#data#infra#automation#solo-founder

Two callers follow separate lines into one glowing ring, which hands a single amber tile to the right while a second, dashed tile stays empty

A data merge of mine took six minutes per season, and the slow part was doing nothing. The merge is a job for Statpro, a sports stats site I build. It folds one season of games, players and teams into the site's stats database. Thousands of database round trips ran one after another, each spending 30 to 80 milliseconds waiting on the network. Running them concurrently was the obvious fix, and the obvious fix wrote duplicate rows. The repair turned out to be a single type signature, with no lock and no queue.

Why going parallel broke it

The merge resolves entities as it goes. An entity here is a team, a player or a game. Each arrives with an external ID, the identifier the incoming data uses for it. The merge asks the database for the canonical row, the one official row that represents that entity, and it creates one if none exists. Run two of those at once for the same entity, before either has seen it, and both lookups come back "not found." Both insert, and now one entity has two canonical rows.

The loser of that race strands an orphan in the foreign keys, and nothing complains. I'd find out months later, when a report double-counted something. So the merge stayed sequential, one round trip at a time, because I'd rather be slow than wrong. I spent an evening staring at that tradeoff before I noticed the tool I needed was already in the language.

The standard fixes are heavier than the problem

The textbook answer is a mutex. Take the lock, check whether the entity exists, create it if it doesn't, release the lock. It works, and every concurrent path now queues behind that lock. I would have rebuilt the sequential merge with a more complicated dependency graph.

The other common answer is a job queue that funnels every create through a single worker. That is also correct and also heavy. I'd be operating a queue, keeping a worker alive, and handling the night the worker dies and everything backs up behind it. Both fixes assume the problem deserves infrastructure, and for most single-process backend code it doesn't.

A Promise is a one-shot lock

The resolution cache was a Map from external ID to canonical ID. A caller checked the cache, missed, looked the entity up, created it if it was absent, and stored the ID. The whole change sits in the value type:

// Before: cache holds resolved values
teamIds: Map<string, number>

// After: cache holds in-flight promises
teamIds: Map<string, Promise<number>>

On a miss, the first caller starts the async resolution and stores the Promise itself in the Map, before any result exists. A second caller that needs the same entity a few milliseconds later finds that Promise and awaits it. Both callers get the same ID, and only one insert happens.

The Promise is doing a mutex's job. Whoever creates it owns the resolution, everyone who awaits it gets the same answer, and it settles exactly once. JavaScript ships this with the language, and most of us only use it to wait on API responses.

CACHE THE VALUE Caller A: cache miss Caller B: cache miss Both get "not found", both insert 2 rows one becomes an orphan CACHE THE PROMISE Caller A: miss, stores the Promise Caller B: finds it, awaits One insert 1 row
The same two callers hit the same cache miss, and the only difference is what the first caller leaves in the Map.

Three properties keep it safe

  1. Idempotency: the resolve-or-create path has to tolerate being called twice. A unique constraint on the external ID plus onConflictDoNothing turns a duplicate insert into a silent no-op, and the follow-up lookup returns the first caller's row.
  2. Failure cleanup: if resolution throws, the cache entry has to be deleted. A rejected Promise left in the Map poisons every later caller for that key. A .catch that removes the entry gives the next caller a fresh attempt.
  3. Single settlement: a Promise settles once, so there is no window where two callers both see "not started" and both proceed, because the second caller sees "in progress" and waits.

The limit is that all of this lives inside one process. It handles concurrency within a single Node event loop, which is how most backend JavaScript runs. Deduplicating across processes still needs a distributed lock or a database advisory lock. My bet is that most duplicate-row bugs come from concurrent calls in the same process, and those are the ones this pattern removes.

Six minutes became 45 seconds

The merge dropped from six minutes to about 45 seconds per season, an 8x speedup, and the audit afterward found zero duplicate rows. The cache kept working as a cache too. A resolved Promise holds its value, so later lookups for the same entity return immediately.

Where else it fits

Any resolve-or-create path keyed by an identifier can use it: a sign-in that finds or creates a user by email, webhook idempotency keyed by event ID, tag resolution, slug assignment. The constraints are narrow and common: the operation has to be idempotent, and the concurrency has to sit inside one process.

I think the pattern stays underknown because it falls between two habits. Engineers who came up through Java or Go reach for mutexes, since that's the vocabulary they carry. JavaScript engineers tend to treat Promises as async plumbing and never as a way to coordinate callers.

What I took from it is a rule about defaults. When a path is slow, my reflex is to add infrastructure: a queue, a worker, a cache layer, a lock service. Each of those is something I operate at 2am when it breaks. This time the fix was four lines and a changed type, and the lock I thought I had to build was sitting inside the Promise the whole time.