|
| 1 | +# Request Flow — Inventory Reservation |
| 2 | + |
| 3 | +Sequence diagram showing the complete inventory reservation flow including rate limiting, idempotency, and ARQ cleanup. |
| 4 | + |
| 5 | +```mermaid |
| 6 | +sequenceDiagram |
| 7 | + autonumber |
| 8 | + participant C as Client |
| 9 | + participant N as Nginx Gateway |
| 10 | + participant A as FastAPI App |
| 11 | + participant R as Redis |
| 12 | + participant DB as Postgres |
| 13 | +
|
| 14 | + Note over C,N: Rate Limiting Nginx layer |
| 15 | + C->>N: POST /api/v1/inventory/reserve |
| 16 | + N->>N: limit_req_zone 20r/s global |
| 17 | + alt Rate exceeded at Nginx |
| 18 | + N-->>C: 429 Too Many Requests |
| 19 | + else OK |
| 20 | + N->>A: Forward to app port 8000 |
| 21 | + end |
| 22 | +
|
| 23 | + Note over A,R: Rate Limiting Lua layer |
| 24 | + A->>R: Lua script per-user and global |
| 25 | + R-->>A: OK limit not reached |
| 26 | +
|
| 27 | + Note over A,R: Idempotency check |
| 28 | + A->>R: GET idempotency key 24h TTL |
| 29 | + alt Key exists |
| 30 | + R-->>A: Return cached response |
| 31 | + A-->>C: 200 OK cached |
| 32 | + else |
| 33 | + A->>R: SET idempotency key |
| 34 | + end |
| 35 | +
|
| 36 | + Note over A,DB: Reserve transaction |
| 37 | + A->>DB: BEGIN Transaction |
| 38 | + A->>DB: SELECT Product FOR UPDATE |
| 39 | + alt Stock Available |
| 40 | + A->>DB: INSERT Reservation status PENDING expires 15 min |
| 41 | + A->>DB: UPDATE Product qty_available minus qty_reserved |
| 42 | + A->>DB: COMMIT Transaction |
| 43 | + A->>R: Cache response |
| 44 | + A-->>C: 201 Created reserved 15 min |
| 45 | + else Out of Stock |
| 46 | + A->>DB: ROLLBACK |
| 47 | + A-->>C: 409 Conflict Sold Out |
| 48 | + end |
| 49 | +
|
| 50 | + Note over A,DB: ARQ Worker cleanup expired reservations |
| 51 | + loop Cron every 60 seconds |
| 52 | + A->>DB: SELECT Reservation status PENDING expired |
| 53 | + alt Found expired |
| 54 | + A->>DB: FOR UPDATE Reservation plus Product |
| 55 | + A->>DB: Product.qty_available plus Reservation.qty_reserved |
| 56 | + A->>DB: Reservation.status equals EXPIRED |
| 57 | + opt order_id is set |
| 58 | + A->>DB: cancel_order_by_system |
| 59 | + end |
| 60 | + A->>DB: COMMIT |
| 61 | + end |
| 62 | + end |
| 63 | +``` |
| 64 | + |
| 65 | +## Flow Steps |
| 66 | + |
| 67 | +1. **Nginx rate limit** — global 20r/s filter at gateway level |
| 68 | +2. **Lua rate limit** — per-user 10 RPS + global 1000 RPS in Redis |
| 69 | +3. **Idempotency check** — Redis cache with 24h TTL prevents duplicate orders |
| 70 | +4. **Reserve transaction** — `SELECT FOR UPDATE` locks product row, creates PENDING reservation for 15 min |
| 71 | +5. **ARQ cleanup** — cron job runs every 60 seconds, releases expired reservations and returns stock |
0 commit comments