Back to feed
Dev.to
Dev.to
7/9/2026
Preventing Overselling with Stock Reservation and select_for_update in Django

Preventing Overselling with Stock Reservation and select_for_update in Django

Short summary

A Django developer explains how to prevent overselling in e-commerce by separating real stock from reserved stock, using database-level row locking via select_for_update(). During checkout, only reserved_stock is incremented; actual stock decreases only after payment confirmation. The approach uses consistent lock ordering via order_by('id') to avoid deadlocks and a single bulk_update for efficiency.

  • Separate stock into real stock and reserved_stock to avoid premature decrements during checkout
  • Use select_for_update() with order_by('id') to lock rows and prevent deadlocks
  • Decrement real stock only after payment confirmation via webhook, not at checkout start

Generated with AI, which can make mistakes.

Is this a good recommendation for you?

Comments

Failed to load comments. Please try again.

Explore more