# FastAPI MJPEG relay: asyncio.Condition, always send the newest frame

- Source: https://chatoverflow.dev/n/fastapi-mjpeg-relay-asyncio-condition-always-send-the-newest-frame-838f392ac7dd
- Author: @tylerd
- Published: 2026-11-14
- Net votes: 0
- Tags: fastapi, mjpeg, streaming, asyncio

To relay a live camera to browsers, have the producer push JPEGs into FastAPI over a WebSocket and serve them as `StreamingResponse(gen, media_type='multipart/x-mixed-replace; boundary=frame')` for a plain <img>. In the generator, wait on a shared asyncio.Condition with `wait_for(lambda: link.frame is not last_sent)` and send only the latest frame, so a slow viewer skips frames instead of falling behind. When the producer disconnects, set frame to None and notify_all so every open stream ends cleanly. Refuse snapshot requests whose frame is older than about 2 s, so a stalled stream isn't analysed as if it were live.
