Db race condition
Is there any tool with drizzle that can help with handling race conditions?
17 Replies
that's incredibly vague. what problem are you trying to solve?
likely outside the scope of drizzle though. depends on the db you're using and application requirements
I have an endpoint that create a db journey for a customer. A customer should only ever have 1 journey.
What I'm seeing is that If I call this endpoint twice in very fast succession.
1st request will not get an existingJourney and proceeed to insert one.
2nd request will query existingJourney but will still be undefined as the inserted one from request 1 is not complete or committed (not sure how it works).
I don't know if I'm remotely using db transactions for what they are supposed to be for.
Has that given you context? 🙂
@Raphaël M (@rphlmr) ⚡ Boss, can you help me with this? 😘
I would first try to wrap all in the same transaction?
A transaction is to tell: do all of this or rollback if one of the request fail
Is this request fired from UI? Do you have disabled submit button?
One thing I don't understand: do you have a unique constraint saying that one user could only have 1 journey?
because even on race conditions there should be only one winner. The slowest would return an error.
I do not its simply a text property in the table, so maybe that's what I should do
For cases where you can insert multiple rows (1:n like payment), you have to go on the idempotent way (client send an idempotent key with every request, preventing double fire to write twice)
Can you share it? or just a quick example of your shcemas?
Nothing stopping a user with email "[email protected]" to have 2 journeys atm
(I don't want that)
So you are okay if a user has 2 journeys?
Na I don't want them to
only 1
So would a unique col sort this?
you can add customer_id has a reference to this table too
or maybe these data are not related to a user table?
I currently don't have a user table 😛
ok I see, it's just a 'save a given customer payload attached to a journey'
Yes exactly
The intresting thing about changing the col to unique. I wonder if i will still run into the issues
I guess you can't, ill do some testing
With unique it should add the missing constraint
I would try:
await tx.rollback()
added in the if
+ wrapping all in the same transactionThen, transaction behavior config exists too: https://orm.drizzle.team/docs/transactions (end of page). Not sure if it is required and what to change from the default
Transactions – DrizzleORM
Drizzle ORM | %s
Yeah the unique thing seems to have solved it. Will try without transaction too to see if its even needed
I would suggest to keep transaction
when you insert related things, it's better to wrap that in transaction to prevent inconsistent insert
True, thank you bro