O1SoftwareNetwork / repairs

0 stars 6 forks source link

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

Closed aksafan closed 3 weeks ago

aksafan commented 3 weeks 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 3 weeks ago

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