CoreyWarren / coldcmerch.com

Creating a Django/React/JWT/Redux E-Commerce store for my good friends in Cold Cut. Shout out to Elmar, Lou, and Brian.
1 stars 0 forks source link

Implement Task Queue for Inventory Management and Stripe Webhook Event Handling #100

Open CoreyWarren opened 1 year ago

CoreyWarren commented 1 year ago

Problem:

Our current system for handling Stripe webhook events and managing inventory has a potential race condition that could lead to over-selling our products. This is due to the fact that we check inventory and modify it within the same transaction. If two customers attempt to purchase the same product at the same time, it's possible that they could both pass the inventory check before either transaction has been committed, leading to a situation where we sell more units of a product than we actually have in stock.

This issue is of low probability for our current scale of operations (approximately 100 orders per month), but it could become significant as we grow.

Potential Solution

The solution to this problem involves implementing a task queue to handle the process of updating our inventory and managing Stripe payment confirmation. This will allow us to defer these operations, ensuring that they are executed in the order they were received and thus preventing race conditions. One popular task queue system for Python is Celery, which can be used with Django and supports multiple message brokers, including RabbitMQ and Redis.

Here's a simple example of how you might use Celery in your Django application:

from celery import Celery

# Initialize Celery with your Django settings
app = Celery('myapp')
app.config_from_object('django.conf:settings')

@app.task
def update_database(cart_id):
    # Update your database here
    pass

In your Stripe webhook handling code, instead of directly updating the database after the payment is confirmed, you would add a task to the queue:|

update_database.delay(cart_id)

Please note that adding a task queue introduces additional complexity and infrastructure requirements to our application. Therefore, this solution should be considered in light of our future scale and the potential impact of race conditions on our business operations.

Further Steps:

  1. Investigate the feasibility and implications of adding a task queue to our application, considering our current infrastructure and future growth plans.
  2. If the decision is made to proceed, select a task queue system (Celery is one option) and a message broker.
  3. Implement the task queue in our Stripe webhook event handling code, ensuring that inventory updates are executed asynchronously and in the order they were received.
  4. Test the new system thoroughly under various scenarios to ensure it resolves the issue and doesn't introduce new problems.
  5. Plan for monitoring and managing the task queue in production.

This issue will be addressed in future development iterations of the project.