"""Shared lock order for subscription counters; daily rows remain the ledger.""" from django.db import connection from .models import Subscription def non_key_lock_options(): # PostgreSQL FOR UPDATE conflicts with FK key-share checks on new ledger # rows. We change counters, not primary keys, so NO KEY UPDATE is sufficient. return {"no_key": True} if connection.features.has_select_for_no_key_update else {} def lock_usage_subscriptions(subscription_ids): # Call inside an atomic transaction, before aggregation or ledger updates. # A consistent order is necessary when two nodes report the same accounts # in opposite payload orders. return list(Subscription.objects.filter(pk__in=set(subscription_ids)).order_by("pk") .select_for_update(**non_key_lock_options()))