Django DB issue (Interface error: connection closed)

Calling all Pythonistas! I’m embarrassed to say, but this issue has been plaguing us for 3 weeks! It’s intermittent with no rhyme or reason.

Ubuntu 22.04 running Docker containers (uses the solid cookiecutter-django) as a base which we’ve used successfully for many years.

django==4.1.9
gunicorn==20.1.0 (4 workers, threads 1)
psycopg2==2.9.6

When submitting a simple registration form, randomly, but very frequently we get the following error:

InterfaceError
connection already closed

This issue is ALWAYS at django/db/backends/postgresql/base.py in create_cursor at line 269 which is cursor = self.connection.cursor()

In Sentry it shows as a “System” error, not an “In-App” error (ie - code flaw).
enter image description here

The form:

class GuestForm(forms.ModelForm):
    time = forms.ChoiceField(choices=[])
    # time = forms.ChoiceField(choices=[("18:30", "6:30 PM")])

    class Meta:
        model = Guest
        fields = ["first_name", "last_name", "email", "opt_in"]

    def __init__(self, *args, **kwargs):
        logger.debug("=> Init GuestForm")
        super().__init__(*args, **kwargs)
        self.fields["time"].choices = get_choices()
    
    def clean_time(self):
        """Return a time."""
        cleaned_data = super().clean()
        hours, minutes = cleaned_data["time"].split(":")
        try:
            return datetime.time(int(hours), int(minutes))
        except ValueError as exc:
            raise ValidationError(
                "Invalid value: %(hours)s %(minutes)", code="invalid", params={"hours": hours, "minutes": minutes}
            ) from exc


The view:

class RegisterView(FormView):
    form_class = GuestForm
    template_name = "tour/register.html"

    tourgroup = None

    def form_valid(self, form):
        """While we are creating a Guest, we are ultimately creating a TourGroup."""
        # Create or get TourGroup for today
        est = ZoneInfo(settings.TIME_ZONE)
        today = datetime.datetime.now().astimezone(est)
        date = today.date()
        time_ = form.cleaned_data["time"]

        try:
            tourgroup = TourGroup.create(date=date, time=time_)
        except MaxCapacityError:
            tourgroup = TourGroup.objects.get(date=date, time=time_)
            form.add_error(None, f"{tourgroup} tour is at capacity.")
            return super().form_invalid(form)

        # Save guest along with the selected tour
        guest = form.save(commit=False)
        guest.tourgroup = tourgroup
        guest.save()

        self.tourgroup = tourgroup

        return super().form_valid(form)

    def get_success_url(self) -> str:
        """Redirect to the thanks page for the tour created."""
        return reverse("tour:thanks", args=(self.tourgroup.pk,))

Interestingly we also get it in random out-of-the-box Django views like a simple “list” view for the TourGroup model. It will occur on almost any database query when using Django views, one request, 500 error, refresh, works fine. No pattern we see. Even something as simple as accessing a request.session can cause it to fail.

We’ve been spinning wheels, even rebuilt the simple Django app from scratch. All dependencies match stable stacks we have in the wild and this is the only project with the issue and it’s actually a very simple registration site.

Any help would be GREATLY appreciated!

Right in the middle of a simple SELECT query.

Same issue here. Also using a django cookiecutter template.

My versions:
django==4.2.1
gunicorn==20.1.0
psycopg2==2.9.6

Did you find a solution or a workaround ?

Same issue, posted details here: Seemingly random PostgreSQL connection drops while handling Django requests - #19 by lv16

Any solutions so far?