O1SoftwareNetwork / repairs

0 stars 5 forks source link

Possible race condition in select-update chain while updating zipcode counter #1

Closed aksafan closed 5 months ago

aksafan commented 5 months ago

There is a possible race condition here, when there are several users searching for the same zipcode.

I propose to address this issue through implementing atomic incrementing operation (and a little simplifying by replacing if statement with upsert operation:

        const upsertUser = await db.zipcode.upsert({
            where: {
                zipcode: zip,
            },
            update: {
                count: {
                    increment: 1,
                  },
            },
            create: {
              zipcode: zip,
              count: 1,
            },
        })
        if (upsertUser.count !== 1) {
            console.log('Something went wrong with upserting counter for zipcode: ' + zip)
        }

Here we either update counter for a given zipcode (if it was found) or create a new record (if it was not found).

jaygabe commented 5 months ago

We changed the code together on 6/12/2024 pair programming session