This guide will help you deploy the race condition fixes to your Tronline Bazar application safely.
- Backup your current database
- Test the fixes in a staging environment first
- Ensure you have admin access to your Supabase project
- Notify users of potential brief maintenance (optional)
Execute these SQL scripts in order in your Supabase SQL Editor:
-- Copy and paste the content from migration-part1.sql
-- This adds missing columns and creates atomic functions-- Copy and paste the content from migration-part2.sql
-- This adds performance indexes and data constraints-- Copy and paste the content from migration-part3.sql
-- This updates RLS policies for proper securityRun these queries to verify the migration worked:
-- Check if new columns exist
SELECT column_name FROM information_schema.columns
WHERE table_name = 'product_codes' AND column_name = 'used_at';
-- Check if functions exist
SELECT routine_name FROM information_schema.routines
WHERE routine_name = 'claim_product_codes_atomic';
-- Test sample promo codes
SELECT * FROM promo_codes WHERE code IN ('WELCOME10', 'SAVE50');The following files have been updated and need to be deployed:
Critical Files:
src/app/(shop)/checkout/CheckoutClient.tsx- Fixed promo race conditionssrc/app/api/orders/create/route.ts- Enhanced order creation with rollbackssrc/app/api/promo/validate/route.ts- New atomic promo validation API
Enhanced Files:
src/lib/providers/AuthProvider.tsx- Fixed auth state race conditionssrc/contexts/CartContext.tsx- Improved cart state management- All auth forms - Added double-submission prevention
New Files:
src/app/(shop)/order-success/page.tsx- Order completion page
# Build and deploy your Next.js application
npm run build
npm run start
# Or deploy to your hosting platform (Vercel, etc.)-
Promo Code Test:
- Apply the same promo code from multiple browser tabs simultaneously
- Verify only one application succeeds
- Test both percentage and fixed discount codes
-
Product Code Assignment Test:
- Create multiple orders for the same digital product simultaneously
- Verify each order gets unique product codes
- Check that no codes are duplicated or lost
-
Wallet Payment Test:
- Make multiple wallet payments simultaneously
- Verify wallet balance is correctly decremented
- Test insufficient balance scenarios
-
Form Submission Test:
- Try submitting login/register forms multiple times rapidly
- Verify only one submission is processed
- Check loading states work correctly
-
Concurrent Users:
- Test with 10+ simultaneous checkout processes
- Monitor database performance during peak usage
- Verify response times remain acceptable
-
Database Locks:
- Check that
SKIP LOCKEDprevents deadlocks - Monitor for any hanging transactions
- Verify atomic operations complete successfully
- Check that
Monitor these metrics post-deployment:
- Transaction Deadlocks: Should be eliminated
- Lock Wait Times: Should be minimal with SKIP LOCKED
- Function Execution Times: Monitor performance of new atomic functions
- Constraint Violations: Should catch any data integrity issues
- API Response Times:
/api/promo/validateand/api/orders/create - Error Rates: Should decrease for race condition related errors
- Order Success Rate: Should improve with better error handling
- User Experience: Monitor checkout completion rates
If issues occur, follow this rollback procedure:
-- 1. Drop new functions
DROP FUNCTION IF EXISTS claim_product_codes_atomic(uuid, integer, uuid);
DROP FUNCTION IF EXISTS increment_promo_usage(uuid);
-- 2. Remove new columns (OPTIONAL - data will be preserved)
-- ALTER TABLE product_codes DROP COLUMN IF EXISTS used_at;
-- 3. Restore original policies if needed
-- (Refer to your backup)# Revert to previous deployment
git revert <commit-hash>
npm run build && npm run startEnsure these are set in your production environment:
# Supabase Configuration
NEXT_PUBLIC_SUPABASE_URL=your_supabase_url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_anon_key
SUPABASE_SERVICE_ROLE_KEY=your_service_role_key
# Email Configuration (for order confirmations)
RESEND_API_KEY=your_resend_keyVerify these settings in your Supabase dashboard:
- Database: Connection pooling enabled
- Auth: Email confirmations configured
- Storage: Payment screenshots bucket configured
- RLS: All policies enabled and working
After deployment, you should see:
✅ Zero race condition errors in your logs ✅ Improved order success rate (target: 99%+) ✅ Faster response times for checkout operations ✅ Better user experience with proper loading states ✅ Data integrity maintained with no duplicate orders/codes
- Monitor error logs for any new issues
- Check database performance metrics
- Verify sample transactions work correctly
- Test all payment methods (wallet, bank transfer, etc.)
- Analyze checkout conversion rates
- Review user feedback for any UX issues
- Monitor database growth and performance
- Optimize any slow queries if identified
- Review system performance under peak load
- Consider additional optimizations based on usage patterns
- Plan for scaling if needed
- Document any lessons learned
-
Function Permission Errors:
GRANT EXECUTE ON FUNCTION function_name TO authenticated;
-
RLS Policy Conflicts:
- Check existing policies don't conflict with new ones
- Use
DROP POLICY IF EXISTSbefore creating new ones
-
Index Creation Timeouts:
- Run index creation during low-traffic periods
- Consider creating indexes separately if needed
If you encounter issues:
- Check the error logs in Supabase dashboard
- Review the database query performance
- Verify all migration steps were completed
- Test in isolation to identify the specific issue
Your Tronline Bazar application is now race-condition free and ready for high-traffic scenarios!
The fixes implemented include:
- ⚡ Atomic database operations
- 🔒 Proper concurrency handling
- 🛡️ Data integrity constraints
- 📈 Performance optimizations
- 🔧 Better error handling
Your digital marketplace can now handle concurrent users safely and reliably.