Flutter HTTP request fails with Connection refused errno 111 when connecting to Django REST API

I have a Flutter mobile app that connects to a Django REST framework backend. When I test my user registration endpoint in Postman everything works perfectly fine. However, after a few successful registrations through the Flutter app, I start getting a connection refused error.

My Flutter code:

var userData = {
  'username': emailInputController.text,
  'password': passwordInputController.text,
  'confirm_password': confirmPasswordInputController.text,
};

try {
  var response = await http.post(
    Uri.parse(registrationApiUrl),
    headers: apiHeaders,
    body: jsonEncode(userData)
  );
  print(response.body);
} catch (error) {
  print(error.toString());
}

Error message:

SocketException: OS Error: Connection refused, errno = 111

I already tried removing CSRF protection but that didn’t help. The API calls are made to an HTTPS endpoint. I’m expecting to receive a JSON response with user details and authentication token. What could be causing this intermittent connection issue?

sounds like your django server might be droppin connections after a while. try adding a connection timeout to your flutter http client and see if that helps - i had this issue before and it was becuz the server wasn’t properly closin connections.

hmm interesting - have you checked if its happening at specific intervals? like does it fail after exactly the same number of requests each time? also what happens if you wait a bit and try again - does it start working? wondering if theres some rate limiting going on that you might not be aware of

This intermittent connection issue typically occurs when your Django server reaches its connection limit or experiences resource exhaustion. I encountered similar behavior when my Django development server was overwhelmed by concurrent requests. The problem often stems from connection pooling exhaustion or the server temporarily refusing new connections due to high load. Check your Django server logs during the failure periods to identify any resource constraints or connection timeouts. Consider implementing connection timeout and retry logic in your Flutter HTTP client configuration. Additionally, verify that your Django server configuration can handle the expected concurrent connections, and ensure proper database connection pooling if your registration process involves heavy database operations. Running your Django app with a production-grade server like Gunicorn instead of the development server can also resolve these intermittent connection refusals.