Last active
June 10, 2025 20:51
-
-
Save DArmstrong87/f940721c4beb70c1554e185ddf35dbbb to your computer and use it in GitHub Desktop.
Django concurrency safety during migrations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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