Project Workshop — Real-Time Chat API
This is a portfolio submission, not a copy-and-run tutorial. A reviewer must be able to clone it, configure it without guessing, execute the critical path, observe a deliberate failure, run the tests, and understand the most important…
- What you are building
- Architecture
- Acceptance criteria
- Suggested repository structure
- Build plan: vertical slices
FastAPI · WebSocket · Redis · Celery · JWT · Docker
Expected effort: 30–48 focused hours · Minimum meaningful tests: 50What you are building
This is a portfolio submission, not a copy-and-run tutorial. A reviewer must be able to clone it, configure it without guessing, execute the critical path, observe a deliberate failure, run the tests, and understand the most important design decision from the README.
Architecture
Critical interaction
Ownership table
| Boundary | Owns | Must not own |
|---|---|---|
| Interface | Parsing, protocol validation, identity extraction, status or presentation mapping | Core business invariants |
| Application/domain | Authorization inputs, state transitions, orchestration, transaction intent | Framework globals or raw transport objects |
| Repository/gateway | One persistence or external protocol, bounded retries, error translation | Product policy |
| Background/UI projection | Recoverable derived state and delivery progress | Hidden authoritative truth |
| Operations | Configuration, health, deployment, telemetry, recovery | Business decisions encoded only in dashboards |
Acceptance criteria
| ID | Required behavior | Evidence |
|---|---|---|
| AC-1.1 | OAuth2PasswordBearer + OAuth2PasswordRequestForm produces the specified behavior inside OAuth2 & JWT | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.2 | JWT creation with python-jose produces the specified behavior inside OAuth2 & JWT | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.3 | refresh token rotation produces the specified behavior inside OAuth2 & JWT | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.4 | RBAC with scopes produces the specified behavior inside OAuth2 & JWT | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.1 | @app.websocket decorator produces the specified behavior inside WebSockets | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.2 | ConnectionManager for multiple clients produces the specified behavior inside WebSockets | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.3 | broadcasting to rooms produces the specified behavior inside WebSockets | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.4 | auth in WebSocket connections produces the specified behavior inside WebSockets | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.1 | CORSMiddleware/GZipMiddleware produces the specified behavior inside Middleware & CORS | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.2 | custom: request timing/correlation ID produces the specified behavior inside Middleware & CORS | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.3 | TrustedHostMiddleware produces the specified behavior inside Middleware & CORS | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.1 | TestClient sync vs AsyncClient (httpx) produces the specified behavior inside Testing | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.2 | overriding dependencies in tests produces the specified behavior inside Testing | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.3 | DB fixtures with SQLAlchemy produces the specified behavior inside Testing | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.4 | Factory Boy for test data produces the specified behavior inside Testing | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.1 | API key header authentication and scoped storage produces the specified behavior inside API keys & file uploads | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.2 | UploadFile spooled file behavior produces the specified behavior inside API keys & file uploads | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.3 | content length/type/signature validation produces the specified behavior inside API keys & file uploads | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.4 | streaming multipart upload to S3 with boto3 produces the specified behavior inside API keys & file uploads | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.5 | presigned URL vs server-proxied upload produces the specified behavior inside API keys & file uploads | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.6 | malware scanning and object quarantine produces the specified behavior inside API keys & file uploads | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.1 | TestClient websocket_connect produces the specified behavior inside Production WebSocket tests | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.2 | invalid-token handshake test produces the specified behavior inside Production WebSocket tests | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.3 | room authorization and cross-worker broadcast test produces the specified behavior inside Production WebSocket tests | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.4 | slow-client backpressure and reconnect test produces the specified behavior inside Production WebSocket tests | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
Suggested repository structure
1project/2├── app/3│ ├── main.py4│ ├── api/{routes.py,dependencies.py}5│ ├── domain/{models.py,services.py,errors.py}6│ ├── repositories/7│ ├── schemas/8│ ├── workers/9│ └── observability.py10├── migrations/11├── tests/{unit,integration,contract}/12├── pyproject.toml13├── Dockerfile14└── compose.yamlBuild plan: vertical slices
| Milestone | Capability | First implementation | Exit condition |
|---|---|---|---|
| 1 | OAuth2 & JWT | OAuth2PasswordBearer + OAuth2PasswordRequestForm; JWT creation with python-jose; refresh token rotation | Demonstration plus focused tests |
| 2 | WebSockets | @app.websocket decorator; ConnectionManager for multiple clients; broadcasting to rooms | Demonstration plus focused tests |
| 3 | Middleware & CORS | CORSMiddleware/GZipMiddleware; custom: request timing/correlation ID; TrustedHostMiddleware | Demonstration plus focused tests |
| 4 | Testing | TestClient sync vs AsyncClient (httpx); overriding dependencies in tests; DB fixtures with SQLAlchemy | Demonstration plus focused tests |
| 5 | API keys & file uploads | API key header authentication and scoped storage; UploadFile spooled file behavior; content length/type/signature validation | Demonstration plus focused tests |
| 6 | Production WebSocket tests | TestClient websocket_connect; invalid-token handshake test; room authorization and cross-worker broadcast test | Demonstration plus focused tests |
| 7 | Hardening and delivery | Security, recovery, telemetry, performance, documentation | Full acceptance suite and recorded demonstration |
For each milestone, first create a failing acceptance test or a reproducible command. Implement the thinnest path to an observable result, add the nearest durable invariant, inject one expected failure, and refactor only after evidence protects the behavior.
Reference vertical slice
1from fastapi import Depends, HTTPException, Security2from fastapi.security import OAuth2PasswordBearer, SecurityScopes3
4oauth2 = OAuth2PasswordBearer(5 tokenUrl="/auth/token",6 scopes={"chat:read": "Read rooms", "chat:write": "Send messages"},7)8
9async def current_user(10 scopes: SecurityScopes,11 token: str = Depends(oauth2),12) -> User:13 claims = verify_jwt(token, issuer=ISSUER, audience=AUDIENCE)14 missing = set(scopes.scopes) - set(claims.get("scope", "").split())15 if missing:16 raise HTTPException(403, "missing scope")17 return await users.get_required(claims["sub"])18
19@router.post("/rooms/{room_id}/messages")20async def send(room_id: UUID, body: MessageCreate, user=Security(current_user, scopes=["chat:write"])):21 return await chat.send(room_id, user.id, body.text)Expected result
1The endpoint accepts only a valid token with chat:write and still applies room membership inside chat.send.Code reading
| Line | Code | Explanation |
|---|---|---|
| 1 | from fastapi import Depends, HTTPException, Security | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 2 | from fastapi.security import OAuth2PasswordBearer, SecurityScopes | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 4 | oauth2 = OAuth2PasswordBearer( | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 5 | tokenUrl="/auth/token", | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 6 | scopes={"chat:read": "Read rooms", "chat:write": "Send messages"}, | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 7 | ) | Implements the next python statement in the example's data flow. |
| 9 | async def current_user( | Defines a coroutine function; calling it creates a coroutine object and await drives its execution. |
| 10 | scopes: SecurityScopes, | Implements the next python statement in the example's data flow. |
| 11 | token: str = Depends(oauth2), | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 12 | ) -> User: | Implements the next python statement in the example's data flow. |
| 13 | claims = verify_jwt(token, issuer=ISSUER, audience=AUDIENCE) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 14 | missing = set(scopes.scopes) - set(claims.get("scope", "").split()) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 15 | if missing: | Evaluates the condition and enters this branch only when it is truthy. |
| 16 | raise HTTPException(403, "missing scope") | Stops the happy path with a deliberate exception carrying the boundary failure. |
| 17 | return await users.get_required(claims["sub"]) | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
| 19 | @router.post("/rooms/{room_id}/messages") | Applies a decorator or framework annotation before the following definition is bound. |
| 20 | async def send(room_id: UUID, body: MessageCreate, user=Security(current_user, scopes=["chat:write"])): | Defines a coroutine function; calling it creates a coroutine object and await drives its execution. |
| 21 | return await chat.send(room_id, user.id, body.text) | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
Risk register
| Area | Failure to reproduce | Required design response |
|---|---|---|
| OAuth2 & JWT | Decoding is not validation, and a valid token does not grant every resource. | Enforce object ownership and roles on the server for every path. |
| WebSockets | Passing a JWT in an unprotected URL can leak it through logs, and slow clients can consume unbounded memory without backpressure. | Authorize the requested room before accept, use per-message schemas, and bound each connection's outbound queue. |
| Middleware & CORS | Order matters; broad exception swallowing and body buffering can break streaming. | Use it for correlation, security headers, timing, and protocol-level concerns. |
| Testing | Large factories with automatic related-object creation make tests slow and can silently satisfy a precondition that the test should state explicitly. | Keep defaults minimal and valid, expose traits for meaningful states, and avoid hiding the business fact a test is meant to arrange. |
| API keys & file uploads | Trusting filename extensions or Content-Type enables polyglot/malicious files; reading the entire upload into bytes defeats spooling. | Set body limits at the proxy and app, generate server-owned keys, quarantine until scanning completes, and store metadata/checksum transactionally. |
| Production WebSocket tests | A passing single-process echo test does not prove authorization, distributed broadcast, or memory safety under slow clients. | Test denied handshakes, malformed frames, stale membership, slow consumers, broker interruption, and bounded reconnect with deterministic timeouts. |
Engineering checklist for this stack
- To do: authenticate before object lookup where possible
- To do: authorize the action and object server-side
- To do: keep transactions in the application service
- To do: bound request, response, and query work
- To do: map typed domain failures to stable protocol errors
Test strategy
Implement at least 50 meaningful cases. A long list of shallow happy-path tests does not satisfy the requirement.
| Risk class | Minimum | Examples |
|---|---|---|
| Happy path and contract | 2 | Correct output, status/schema, durable state |
| Validation and boundaries | 2 | Empty, malformed, extreme, unsupported transition |
| Authorization or trust boundary | 1 | Missing identity, wrong tenant/role, injection or unsafe content |
| Failure and recovery | 2 | Timeout, retry, rollback, reconnect, dependency outage |
| Duplicate or concurrency | 1 | Same identity twice, racing update, redelivery |
| Performance and operations | 42 | Query bound, lag, p95, resource limit, telemetry |
Representative test scaffold
1@pytest.mark.anyio2async def test_duplicate_request_is_idempotent(client, auth_headers):3 headers = {**auth_headers, "Idempotency-Key": "stable-1"}4 first = await client.post("/resources", json={"name": "one"}, headers=headers)5 second = await client.post("/resources", json={"name": "one"}, headers=headers)6 assert first.status_code == 2017 assert second.status_code in {200, 201}8 assert first.json()["id"] == second.json()["id"]Failure drills
- Stop the primary external dependency during the critical path. Capture the failure, cleanup, telemetry, and recovery.
- Repeat the same operation with the same stable identity. Prove one logical outcome or document why repetition is forbidden.
- Crash after durable state changes but before the response, acknowledgement, or projection. Re-run and reconcile.
- Submit the largest supported input and one slightly larger input.
- Remove one permission and prove denial without state change or information leakage.
- Roll back the change or restore the dependency, then run a smoke test and reconciliation check.
Performance experiment
State the dataset, payload distribution, concurrency, rate, duration, cache state, and resource limits before measuring. Publish p50, p95, p99, throughput, error rate, and the technology-specific correctness signal such as query count, consumer lag, duplicate effects, rendered updates, token cost, or recall. Change one variable at a time and retain raw output.
Submission package
- Complete source with a locked/reproducible environment.
- README.md with problem, architecture, setup, commands, configuration, assumptions, and trade-offs.
- Acceptance and risk-focused tests with a short explanation of what mocks intentionally do not cover.
- One design record explaining the most consequential choice and a rejected alternative.
- Security notes, sample non-secret configuration, and cleanup commands.
- A demonstration record: terminal transcript, screenshots, trace, query plan, or metrics dashboard.
- A 5–8 minute walkthrough following input → validation → state → failure → evidence.
Grading rubric
| Dimension | Weight | Full-credit evidence |
|---|---|---|
| Product behavior | 25 | Acceptance criteria pass through real public boundaries |
| Architecture and ownership | 20 | Responsibilities and state authority are explicit |
| Tests and recovery | 20 | Important negative, duplicate, concurrent, and outage cases pass |
| Security and data correctness | 15 | Least privilege, validation, constraints, and secret handling are demonstrated |
| Performance and operations | 10 | Reproducible measurement, useful telemetry, and rollback/recovery |
| Documentation and explanation | 10 | A new reviewer can reproduce and defend the result |
Mastery check
How well can you recall this?
Finished this lesson?