Lock Pay::Customer while creating a Stripe customer #1027
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Pull Request
Summary:
Lock the
Pay::Customer
while creating its associated Stripe customer. This is to prevent a race condition where more than one Stripe customers can be created for a singlePay::Customer
.Related Issue:
See discussion: #857
Description:
We have twice now encountered a race condition where more than one Stripe customer was created for a single
Pay::Customer
. This was discovered because of bugs in our React frontend which caused it to accidentally fire multiple API requests to the backend at the same time. Two requests (two threads) would enter thecustomer
method at the same time. Both would see that no Stripe customer yet existed and both would begin creating one. The last one to complete would overwrite the previous one in the database. This was especially bad in our app because we use Stripe checkout. In our case our user ended up checking out with a Stripe customer that was no longer associated with theirPay::Customer
. With this change we now lock thePay::Customer
while creating a Stripe customer to prevent more than one from being created.The change simply updates the
customer
method by moving the existing code inside a top levelwith_lock
block on thePay::Customer
.Testing:
I didn't add any new tests as I didn't see an existing pattern for verifying this type of locking code (which is difficult) or an existing tests for similar locking code. I did some manual testing though (using log statements and sleep statements) to verify that only one thread will run the critical section at a time.
Screenshots (if applicable):
Checklist:
Additional Notes: