Project Workshop — Async CLI Web Scraper
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
Python · asyncio · aiohttp · decorators
Expected effort: 5–8 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 | __iter__ and __next__ protocol produces the specified behavior inside Generators & iterators | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.2 | yield keyword and generator functions produces the specified behavior inside Generators & iterators | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.3 | generator expressions produces the specified behavior inside Generators & iterators | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.4 | yield from for delegation produces the specified behavior inside Generators & iterators | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.5 | lazy CSV reader example produces the specified behavior inside Generators & iterators | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.1 | @functools.wraps produces the specified behavior inside Decorators | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.2 | decorator factory pattern produces the specified behavior inside Decorators | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.3 | class-based decorators produces the specified behavior inside Decorators | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.4 | @timer/@retry/@cache real examples produces the specified behavior inside Decorators | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.1 | class-based __enter__/__exit__ produces the specified behavior inside Context managers | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.2 | @contextmanager from contextlib produces the specified behavior inside Context managers | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.3 | file locking / timer examples produces the specified behavior inside Context managers | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.1 | Optional/Union/Literal/TypeVar produces the specified behavior inside Type hints & mypy | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.2 | Generic classes produces the specified behavior inside Type hints & mypy | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.3 | running mypy and fixing errors produces the specified behavior inside Type hints & mypy | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.1 | event loop and coroutines produces the specified behavior inside asyncio basics | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.2 | async/await syntax produces the specified behavior inside asyncio basics | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.3 | asyncio.gather() concurrency produces the specified behavior inside asyncio basics | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.4 | aiohttp async HTTP example produces the specified behavior inside asyncio basics | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.1 | decorator stacking order produces the specified behavior inside Composition & performance | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.2 | list vs generator memory and latency produces the specified behavior inside Composition & performance | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.3 | sequential await vs gather vs TaskGroup produces the specified behavior inside Composition & performance | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.4 | cache key correctness and invalidation produces the specified behavior inside Composition & performance | 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 | Generators & iterators | __iter__ and __next__ protocol; yield keyword and generator functions; generator expressions | Demonstration plus focused tests |
| 2 | Decorators | @functools.wraps; decorator factory pattern; class-based decorators | Demonstration plus focused tests |
| 3 | Context managers | class-based __enter__/__exit__; @contextmanager from contextlib; file locking / timer examples | Demonstration plus focused tests |
| 4 | Type hints & mypy | Optional/Union/Literal/TypeVar; Generic classes; running mypy and fixing errors | Demonstration plus focused tests |
| 5 | asyncio basics | event loop and coroutines; async/await syntax; asyncio.gather() concurrency | Demonstration plus focused tests |
| 6 | Composition & performance | decorator stacking order; list vs generator memory and latency; sequential await vs gather vs TaskGroup | 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
1import asyncio2from collections.abc import AsyncIterator, Callable3from functools import wraps4from time import perf_counter5
6def timed(fn: Callable):7 @wraps(fn)8 async def wrapper(*args, **kwargs):9 started = perf_counter()10 try:11 return await fn(*args, **kwargs)12 finally:13 print(f"{fn.__name__}: {perf_counter() - started:.3f}s")14 return wrapper15
16async def values() -> AsyncIterator[int]:17 for value in range(3):18 await asyncio.sleep(0.01)19 yield value20
21@timed22async def main() -> list[int]:23 return [value * value async for value in values()]24
25print(asyncio.run(main()))Expected result
1main: approximately 0.030s2[0, 1, 4]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 collections.abc import AsyncIterator, Callable | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 3 | from functools import wraps | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 4 | from time import perf_counter | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 6 | def timed(fn: Callable): | Defines a function; its parameters form the explicit input boundary. |
| 7 | @wraps(fn) | Applies a decorator or framework annotation before the following definition is bound. |
| 8 | async def wrapper(args, *kwargs): | Defines a coroutine function; calling it creates a coroutine object and await drives its execution. |
| 9 | started = perf_counter() | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 10 | try: | Defines failure translation or cleanup that must run around the protected operation. |
| 11 | return await fn(args, *kwargs) | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
| 12 | finally: | Defines failure translation or cleanup that must run around the protected operation. |
| 13 | print(f"{fn.__name__}: {perf_counter() - started:.3f}s") | Emits the example's observable output. |
| 14 | return wrapper | Returns the observable result to the caller and ends this invocation. |
| 16 | async def values() -> AsyncIterator[int]: | Defines a coroutine function; calling it creates a coroutine object and await drives its execution. |
| 17 | for value in range(3): | Consumes the iterable one item at a time through the iterator protocol. |
| 18 | await asyncio.sleep(0.01) | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
| 19 | yield value | Emits one lazy value and suspends the generator frame for a later resume. |
| 21 | @timed | Applies a decorator or framework annotation before the following definition is bound. |
| 22 | async def main() -> list[int]: | Defines a coroutine function; calling it creates a coroutine object and await drives its execution. |
| 23 | return [value * value async for value in values()] | Returns the observable result to the caller and ends this invocation. |
| 25 | print(asyncio.run(main())) | Emits the example's observable output. |
Risk register
| Area | Failure to reproduce | Required design response | |
|---|---|---|---|
| Generators & iterators | A consumed iterator is exhausted; converting it to a list defeats streaming and may exhaust memory. | Use lazy iteration for streams or large datasets that do not need random access. | |
| Decorators | Keep retries bounded and restricted to transient, idempotent operations. | Use it for orthogonal policy such as timing, authorization, validation, retry, or caching. | |
| Context managers | Do not hide unexpected exceptions in __exit__; cleanup should be exception-safe. | Use it for files, transactions, locks, temporary settings, and spans. | |
| Type hints & mypy | Optional[T] means `T \ | None`; it does not mean an optional function parameter. | Annotate public boundaries and use precise unions or protocols. |
| asyncio basics | 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. | |
| Composition & performance | Omitting tenant or authorization scope from a key can return one user's data to another; relying only on TTL can violate correctness for the entire expiry window. | Document the source of truth, key schema, TTL, invalidation event, negative-cache policy, and stampede protection. |
Engineering checklist for this stack
- To do: validate CLI inputs before domain operations
- To do: use explicit exit codes and deterministic output
- To do: close files, sessions, and network clients
- To do: separate domain logic from input/printing
- To do: measure large-input memory behavior
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.parametrize(2 ("value", "expected"),3 [("valid", "success"), ("", "validation-error"), ("duplicate", "same-result")],4)5def test_contract(value, expected, service):6 result = service.execute(value)7 assert result.status == expected8
9def test_failure_rolls_back(repository, service):10 repository.fail_next_write()11 with pytest.raises(RepositoryError):12 service.execute("valid")13 assert repository.visible_changes() == []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?