Project Workshop — Async News Aggregator
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 · asyncio · aiohttp · aioredis
Expected effort: 25–40 focused hours · Minimum meaningful tests: 12What 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 | event loop mechanics produces the specified behavior inside async/await patterns | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.2 | async def vs def in FastAPI produces the specified behavior inside async/await patterns | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.3 | blocking vs non-blocking operations produces the specified behavior inside async/await patterns | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.4 | run_in_executor for sync code produces the specified behavior inside async/await patterns | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.1 | asyncio.gather() for concurrency produces the specified behavior inside asyncio deep dive | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.2 | asyncio.wait_for() timeout produces the specified behavior inside asyncio deep dive | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.3 | asyncio.Queue producer-consumer produces the specified behavior inside asyncio deep dive | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.1 | create_async_engine and AsyncSession produces the specified behavior inside Async SQLAlchemy | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.2 | async_sessionmaker produces the specified behavior inside Async SQLAlchemy | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.3 | async repository pattern produces the specified behavior inside Async SQLAlchemy | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.4 | Alembic with async engine produces the specified behavior inside Async SQLAlchemy | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.1 | lifespan startup/shutdown and app.state injection produces the specified behavior inside Lifespan, diagnosis & load | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.2 | asyncio debug mode and slow callback detection produces the specified behavior inside Lifespan, diagnosis & load | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.3 | structured concurrency with TaskGroup produces the specified behavior inside Lifespan, diagnosis & load | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.4 | Locust user/wait_time/task and p95 benchmarking produces the specified behavior inside Lifespan, diagnosis & load | 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 | async/await patterns | event loop mechanics; async def vs def in FastAPI; blocking vs non-blocking operations | Demonstration plus focused tests |
| 2 | asyncio deep dive | asyncio.gather() for concurrency; asyncio.wait_for() timeout; asyncio.Queue producer-consumer | Demonstration plus focused tests |
| 3 | Async SQLAlchemy | create_async_engine and AsyncSession; async_sessionmaker; async repository pattern | Demonstration plus focused tests |
| 4 | Lifespan, diagnosis & load | lifespan startup/shutdown and app.state injection; asyncio debug mode and slow callback detection; structured concurrency with TaskGroup | Demonstration plus focused tests |
| 5 | 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
1import asyncio2from fastapi import HTTPException3
4async def fetch_all(client, urls: list[str]) -> list[dict]:5 async def one(url: str) -> dict:6 try:7 async with asyncio.timeout(2.0):8 response = await client.get(url)9 response.raise_for_status()10 return response.json()11 except TimeoutError as exc:12 raise HTTPException(504, f"upstream timeout: {url}") from exc13
14 async with asyncio.TaskGroup() as group:15 tasks = [group.create_task(one(url)) for url in urls]16 return [task.result() for task in tasks]Expected result
1All upstream calls run concurrently; a failed child cancels the remaining TaskGroup children.Code reading
| Line | Code | Explanation |
|---|---|---|
| 1 | import asyncio | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 2 | from fastapi import HTTPException | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 4 | async def fetch_all(client, urls: list[str]) -> list[dict]: | Defines a coroutine function; calling it creates a coroutine object and await drives its execution. |
| 5 | async def one(url: str) -> dict: | Defines a coroutine function; calling it creates a coroutine object and await drives its execution. |
| 6 | try: | Defines failure translation or cleanup that must run around the protected operation. |
| 7 | async with asyncio.timeout(2.0): | Implements the next python statement in the example's data flow. |
| 8 | response = await client.get(url) | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
| 9 | response.raise_for_status() | Implements the next python statement in the example's data flow. |
| 10 | return response.json() | Returns the observable result to the caller and ends this invocation. |
| 11 | except TimeoutError as exc: | Defines failure translation or cleanup that must run around the protected operation. |
| 12 | raise HTTPException(504, f"upstream timeout: {url}") from exc | Stops the happy path with a deliberate exception carrying the boundary failure. |
| 14 | async with asyncio.TaskGroup() as group: | Implements the next python statement in the example's data flow. |
| 15 | tasks = [group.create_task(one(url)) for url in urls] | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 16 | return [task.result() for task in tasks] | Returns the observable result to the caller and ends this invocation. |
Risk register
| Area | Failure to reproduce | Required design response |
|---|---|---|
| async/await patterns | A blocking library call freezes the loop; move unavoidable sync work to a bounded executor. | Use it for many independent I/O operations with async-compatible drivers. |
| asyncio deep dive | A blocking library call freezes the loop; move unavoidable sync work to a bounded executor. | Use it for many independent I/O operations with async-compatible drivers. |
| Async SQLAlchemy | Lazy relationship access can attempt I/O in an invalid context; bound pools and avoid concurrent session use. | Use one session per request or unit of work and explicit eager loading. |
| Lifespan, diagnosis & load | Do not create connection pools or SDK clients on every request. | Scope database sessions to requests and clients/pools to lifespan. |
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 12 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 | 4 | 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?