Álefe Nascimento da Silva
1 min readDec 17, 2024

--

Since you asked, here’s my advice:

This code is clean, readable, extensible, and easy to test, but unfortunately, it has a flaw. Let me explain why:

- You first check if a user with the provided email already exists.

- If no user with that email is found, you proceed to create a new user.

However, there's a potential issue: what if a user with the same email gets created between the check and the saving in the database (for example, by a different goroutine, container, etc.)? Even if you have an index in your database to prevent duplicates, it's better to handle this in your code rather than relying solely on the database.

One way to do this is by using the Unit of Work pattern, which combines these operations into an "atomic" operation (like a transaction) where both the check and the save either succeed or fail together. While there are scenarios where you might not want to use the Unit of Work pattern, in this specific case, I believe it makes sense to ensure that this problem doesn't happen.

What do you think?

--

--

Álefe Nascimento da Silva
Álefe Nascimento da Silva

Written by Álefe Nascimento da Silva

A Software Engineer who loves to learn new things.

Responses (1)