Connection Issues with Real-Time Events in FastAPI + IIS + Angular

Maria Natalia Benavides Sanabria 10 Puntos de reputación
2025-03-06T16:38:45.24+00:00

Hello everyone,

I'm encountering a connection issue with my implementation of real-time events. The problem is that network requests remain in a "pending" state in the browser's network tab, and the connection necessary for receiving real-time updates is never fully established.

Here are the details of my environment:

  • Server: IIS v10
  • Backend: FastAPI 0.112.0, Pydantic 2.8.2, Uvicorn (>=0.15.0) running on Python 3.13.2
  • Frontend: Angular 17

Has anyone experienced similar issues or have suggestions on what might be causing this? Could it be due to a misconfiguration or incompatibility between IIS, FastAPI, Uvicorn, or Python 3.13.2? Or is there perhaps something in the web.config file that needs adjusting?

Windows para empresas | Windows Server | Experiencia del usuario | Otros
0 comentarios No hay comentarios
{count} votos

3 respuestas

Ordenar por: Muy útil
  1. Jonathan Pereira Castillo 17,170 Puntos de reputación Personal externo de Microsoft Moderador
    2025-03-06T18:25:30.25+00:00

    ¡Hola Maria Natalia Benavides Sanabria!

    Bienvenido a Microsoft Q&A.

    The issue you're experiencing, where network requests remain in a "pending" state and the real-time connection is not established, could be caused by several factors. Below is a detailed analysis and troubleshooting guide tailored to your environment:


    1. WebSocket or Long-Polling Configuration

    FastAPI and Uvicorn support WebSockets for real-time communication, but IIS may require additional configuration to handle WebSocket connections properly.

    Steps to Check:

    Enable WebSockets in IIS:

    1. Open IIS Manager.
      1. Select your server in the left-hand Connections pane.
        1. Double-click "WebSocket Protocol" in the Features pane.
          1. Ensure WebSocket Protocol is enabled for your site.
          Verify WebSocket Support in FastAPI: Ensure your FastAPI application is correctly configured to handle WebSocket routes. For example:
                      from fastapi import FastAPI, WebSocket
          
          

    app = FastAPI()

    @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() await websocket.send_text("Hello WebSocket!") await websocket.close() ```

            **Check Uvicorn Version**: Ensure you're using a compatible version of Uvicorn (>=0.15.0). If you're using WebSockets, Uvicorn must be started with the `--ws` flag:
            
            ```yaml
            uvicorn app:app --host 0.0.0.0 --port 8000 --ws websockets
            ```
            
    

    1. IIS Reverse Proxy Configuration

    If IIS is acting as a reverse proxy for your FastAPI application, misconfigurations in the web.config file could block WebSocket or HTTP/2 connections.

    Steps to Check:

    Update web.config: Ensure your web.config file allows WebSocket traffic and properly forwards requests to Uvicorn. Example configuration:

    <configuration>
      <system.webServer>
        <webSocket enabled="true" />
        <rewrite>
          <rules>
            <rule name="ReverseProxyInboundRule1" stopProcessing="true">
              <match url="(.*)" />
              <action type="Rewrite" url="http://127.0.0.1:8000/{R:1}" />
            </rule>
          </rules>
        </rewrite>
      </system.webServer>
    </configuration>
    

    Check Timeouts: IIS may terminate long-running connections prematurely. Increase the timeout settings for WebSocket connections:

    <webSocket enabled="true" receiveTimeout="00:20:00" />
    

    1. FastAPI and Python Compatibility

    You're using Python 3.13.2, which is a very recent version. Some libraries, including FastAPI or Uvicorn, might not yet be fully compatible with this version.

    Steps to Check:

    Test with Python 3.11 or 3.12: Downgrade to a stable Python version (e.g., 3.11.x) and test your application to rule out compatibility issues.

    Update Dependencies: Ensure all dependencies are up to date:

    pip install --upgrade fastapi uvicorn pydantic
    

    1. Frontend (Angular) Configuration

    Angular's HTTP client or WebSocket implementation might not be correctly configured to handle real-time connections.

    Steps to Check:

    CORS Configuration: Ensure your FastAPI backend allows CORS requests from your Angular frontend:

    from fastapi.middleware.cors import CORSMiddleware
    
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["http://your-angular-app.com"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    

    WebSocket Implementation: Verify that your Angular application is correctly initiating WebSocket connections. Example:

    const socket = new WebSocket('ws://your-backend-url/ws');
    socket.onmessage = (event) => {
      console.log(event.data);
    };
    

    1. Network and Firewall Issues

    Network configurations or firewalls might block WebSocket or long-polling connections.

    Steps to Check:

    Firewall Rules: Ensure that ports used by Uvicorn (e.g., 8000) are open and accessible.

    Inspect Network Traffic: Use browser developer tools or tools like Wireshark to inspect network traffic and identify where the connection is being blocked.


    1. Debugging Tools

    Browser Developer Tools: Check the "Network" tab in your browser's developer tools for more details about the "pending" requests. Look for:

    • HTTP status codes (e.g., 403, 500).
      • Errors in the WebSocket handshake.
    • Uvicorn Logs: Run Uvicorn with verbose logging to capture detailed error messages:
        uvicorn app:app --host 0.0.0.0 --port 8000 --log-level debug
      

    Espero que estos consejos ayuden a resolver el problema. Si necesitas más asistencia, estoy a tu disposición.

    Saludos,

    Jonathan.

    ----------*

    Tu opinión es muy importante para nosotros! Si esta respuesta resolvió tu consulta, por favor haz clic en ''. Esto nos ayuda a mejorar continuamente la calidad y relevancia de nuestras soluciones.


  2. Jonathan Pereira Castillo 17,170 Puntos de reputación Personal externo de Microsoft Moderador
    2025-03-19T17:27:22.7666667+00:00

    Hola Maria Natalia Benavides Sanabria!,

    El propósito de este mensaje es verificar la información proporcionada. Si tienes más actualizaciones sobre este tema, no dudes en responder en este mismo hilo.

    Respetuosamente,

    Jonathan

    ---------

    Tu opinión es muy importante para nosotros! Si esta respuesta resolvió tu consulta, por favor haz clic en ‘Sí’. Esto nos ayuda a mejorar continuamente la calidad y relevancia de nuestras soluciones. ¡Gracias por tu colaboración!

    0 comentarios No hay comentarios

  3. Jonathan Pereira Castillo 17,170 Puntos de reputación Personal externo de Microsoft Moderador
    2025-03-25T18:54:13.4866667+00:00

    Buenos día Maria Natalia Benavides Sanabria!,

    Conforme a la información previamente proporcionada, el objetivo de este mensaje es verificar la misma. Si tienes nuevas actualizaciones relacionadas con este asunto, por favor, siéntete libre de responder en este mismo hilo.

    Atentamente,

    Jonathan

    -----------

    Tu opinión es muy importante para nosotros! Si esta respuesta resolvió tu consulta, por favor haz clic en ‘Sí’. Esto nos ayuda a mejorar continuamente la calidad y relevancia de nuestras soluciones. ¡Gracias por tu colaboración!


Su respuesta

Las respuestas se pueden marcar como respuestas aceptadas por el autor de la pregunta, lo que ayuda a los usuarios a conocer la respuesta que resolvió el problema del autor.