Skip to content

Instantly share code, notes, and snippets.

@DArmstrong87
Last active June 10, 2025 20:51
Show Gist options
  • Save DArmstrong87/f940721c4beb70c1554e185ddf35dbbb to your computer and use it in GitHub Desktop.
Save DArmstrong87/f940721c4beb70c1554e185ddf35dbbb to your computer and use it in GitHub Desktop.
Django concurrency safety during migrations
"""
Ensures only one instance runs migrations when multiple instances are spun up concurrently.
This prevents a deadlock scenario.
"""
from django.core.management.base import CommandError
from django.db import connection
from django.core.management.commands.migrate import Command as MigrateCommand
class Command(MigrateCommand):
help = "Wrapped migrate command with advisory lock for concurrency safety."
def handle(self, *args, **options):
lock_id = 987654321
with connection.cursor() as cursor:
self.stdout.write("Checking for migration lock...")
cursor.execute("SELECT pg_try_advisory_lock(%s)", [lock_id])
locked = cursor.fetchone()[0]
if locked:
self.stdout.write("✔ Acquired migration lock. Running migrate...")
try:
super().handle(*args, **options)
finally:
cursor.execute("SELECT pg_advisory_unlock(%s)", [lock_id])
self.stdout.write("✔ Migration lock released.")
else:
self.stdout.write("✗ Another instance is currently running migrations.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment