Yash Gupta

The same record, written twice, 13 milliseconds apart

We mirror each customer's WhatsApp message templates from the provider into our own database. Three different things ran that mirror, none of them knew about the others, and the result was 356 templates stored twice across 153 production companies. The fix is a lock, but the lock on its own would not have worked.

Role
Found it and fixed it
Stack
NestJS, PostgreSQL, Drizzle ORM
Status
Live in production, 27 Nov 2026
Scope
356 templates, 153 companies

How it surfaced

Not from an alert. I was looking at a templates screen in a different product that reads the same table, and one template was listed twice. Same name, same provider id, two rows, created 13 milliseconds apart.

Thirteen milliseconds is the useful part of that sentence. It rules out a user clicking twice and a cron running twice, and says two things were in flight at the same moment.

Three writers, none of them aware of the others

Loading the template list did two things: it kicked off a background refresh, and it also ran the same reconcile inline in the same request. A scheduled job in a separate process ran it too. So the function that decides "the provider has this template and we do not, insert it" could be running three times at once for one customer.

Each one read the customer's rows, found the template missing, and inserted it. All three reads were correct when they happened. There was no unique constraint on the pair of columns that identifies a template, so the database had no opinion either.

Before changing anything I measured it with a read-only query, because "there is a race" and "the race is doing damage" are different claims:

EnvironmentTemplates duplicatedExtra rowsCompanies affected
Staging2331,3933
Production356359153

The two shapes say different things. Production is broad and shallow: nearly every duplicate happened once, to many customers, which is what an occasional two-way race looks like. Staging is narrow and deep, up to six copies of one template, because a handful of test companies get their lists opened over and over.

The lock is the easy half

A Postgres advisory lock keyed on the customer, held until the transaction ends, serialises the callers across all three processes. That part is three lines.

The part that actually fixes the bug is what happens after the wait. A caller that waited for the lock is holding a list of templates it read before the first caller inserted anything. If it proceeds on that list, it does exactly what it was always going to do and inserts the duplicate, just more politely. So the rows have to be read again, inside the lock:

await db.transaction(async (tx) => {
  await tx.execute(
    sql`SELECT pg_advisory_xact_lock(
          hashtext(${`graph-template-sync:${companyId}`}))`
  )
  const currentTemplates = await tx
    .select({ graph_template_id: template.graph_template_id,
              name: template.name })
    .from(template)
    .where(and(eq(template.company_id, companyId),
               eq(template.flag_deleted, false)))
  // The caller's list can predate another caller's inserts;
  // the fresh read is the truth
  await this.insertMissingGraphTemplates(
    companyId, [...localTemplates, ...currentTemplates], ...
  )
})

The key is derived per customer rather than globally, so two different customers still sync in parallel. A single global lock would have fixed the bug and turned every template refresh into a queue.

Why not a unique constraint

A unique index on customer and provider template id is the stronger fix, and it is the one I would want. I did not ship it, for a reason worth stating plainly rather than hiding: you cannot add a unique constraint to a table that already violates it. There were 359 rows in the way.

Deleting them is not a delete. Those rows are referenced by campaigns, by the mapping table that records which template each sent message used, by template buttons and by scheduled campaign details. Picking which copy survives and re-pointing everything at it is its own piece of work with its own review and its own approval, and doing it in the same change as the race fix would have meant a risky migration riding along with an urgent one.

So the lock stops the bleeding now, and the constraint is what makes the bug impossible rather than unlikely. Shipping the first without the second is a deliberate, temporary position, and the only thing that makes it honest is saying so and tracking the rest.

Testing something that only happens sometimes

A race that needs two processes to interleave is not something a unit test reproduces by running the code twice. The spec uses a fake database that models the two properties the fix depends on: it runs one transaction at a time per lock key, the way the advisory lock does, and a read sees inserts committed before it.

Four tests, red before the fix and green after: two overlapping syncs holding the same stale list insert each template once; the lock is taken before the rows are read; a row another caller already inserted beats the caller's stale list; and a second sync after the first adds nothing.

That suite proves the logic given a database that behaves as described. It does not prove Postgres behaves that way, and a fake that serialises perfectly can hide an ordering bug a real engine would expose. So the fix also got a live check on staging: two concurrent list calls against a company with a deliberately deleted template recreated it exactly once. The unit tests tell you the reasoning is sound. Only the real thing tells you the reasoning was about the right database.

The third time I had written this

The same primitive, keyed the same way, is in two other places I built: the per-company contact analytics refresh, where overlapping cron runs and user-triggered rebuilds would otherwise double-count, and the enterprise billing owner, where two concurrent signups could create two owners for one account.

What they share is a shape rather than a feature: a read, a decision based on it, and a write, with nothing stopping a second caller from doing the same between the read and the write. Once you have seen it three times it stops reading as three bugs and starts reading as a thing to check for whenever code says "if it does not exist, create it".

What I would design differently

The lock is the right fix for the race, and it is still a fix to a symptom. One request that starts a background job and then does the same work inline is a strange shape, and removing one of those two writers would have left only the scheduled job contending with the request. The lock would still be needed for that pair, but a narrower version of it would have done, and the design would be easier to reason about.

The broader point is about ordering. A constraint in the schema is the guarantee you want, and it is the one hardest to add later, because by the time you want it the data has usually already learned to violate it. It is close to free on the day the table is created.

What I took from it

  • Measure the damage before fixing the cause. The two environments' different shapes told me more about the race than reading the code did.
  • A lock without a re-read is theatre. The waiting caller's view of the world is stale by definition, and that is the whole reason it waited.
  • Key the lock as narrowly as correctness allows, or you have traded a rare bug for permanent contention.
  • When the real fix is blocked by existing bad data, ship the containment, say that it is containment, and write down what is left.