# RuntimeError: Cannot add middleware after an application has started

- **ID:** `python/starlette-middleware-order-matters`
- **Domain:** python
- **Category:** config_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

Calling app.add_middleware() after the ASGI application has begun serving requests (e.g. inside a request handler).

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 0.30.x | active | — | — |
| 0.36.x | active | — | — |

## Workarounds

1. **** (97% success)
   ```
   app = FastAPI()\napp.add_middleware(CORSMiddleware, allow_origins=['*'])
   ```
2. **** (90% success)
   ```
   app = MyMiddleware(app)
   ```

## Dead Ends

- **** — Startup events run after middleware stack is built. (85% fail)
- **** — Existing routes and state are lost. (80% fail)
