Project Workshop — Async Report Generator
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 · Celery · Redis · WebSocket · Beat
Expected effort: 4–7 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 | @app.task vs @shared_task produces the specified behavior inside Task definition & calling | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.2 | delay() vs apply_async() (countdown/eta/expires) produces the specified behavior inside Task definition & calling | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.3 | task states: PENDING→STARTED→SUCCESS/FAILURE produces the specified behavior inside Task definition & calling | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.1 | Redis broker: config + pooling produces the specified behavior inside Brokers & result backends | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.2 | CELERY_BROKER_URL and CELERY_RESULT_BACKEND produces the specified behavior inside Brokers & result backends | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.3 | AsyncResult: state/result/get()/ready() produces the specified behavior inside Brokers & result backends | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.4 | result_expires setting produces the specified behavior inside Brokers & result backends | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.1 | crontab() syntax examples produces the specified behavior inside Celery Beat (periodic tasks) | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.2 | django-celery-beat DB scheduler produces the specified behavior inside Celery Beat (periodic tasks) | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.3 | PeriodicTask model: enable/disable via admin produces the specified behavior inside Celery Beat (periodic tasks) | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.1 | Flower real-time UI produces the specified behavior inside Monitoring | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.2 | task events and task_id tracking produces the specified behavior inside Monitoring | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.3 | Prometheus metrics for Celery produces the specified behavior inside Monitoring | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.1 | config/celery.py application bootstrap produces the specified behavior inside Complete Django integration | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.2 | autodiscover_tasks and Django settings namespace produces the specified behavior inside Complete Django integration | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.3 | worker/beat/Flower process commands produces the specified behavior inside Complete Django integration | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.4 | Redis visibility and connection-pool settings produces the specified behavior inside Complete Django integration | 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 | Task definition & calling | @app.task vs @shared_task; delay() vs apply_async() (countdown/eta/expires); task states: PENDING→STARTED→SUCCESS/FAILURE | Demonstration plus focused tests |
| 2 | Brokers & result backends | Redis broker: config + pooling; CELERY_BROKER_URL and CELERY_RESULT_BACKEND; AsyncResult: state/result/get()/ready() | Demonstration plus focused tests |
| 3 | Celery Beat (periodic tasks) | crontab() syntax examples; django-celery-beat DB scheduler; PeriodicTask model: enable/disable via admin | Demonstration plus focused tests |
| 4 | Monitoring | Flower real-time UI; task events and task_id tracking; Prometheus metrics for Celery | Demonstration plus focused tests |
| 5 | Complete Django integration | config/celery.py application bootstrap; autodiscover_tasks and Django settings namespace; worker/beat/Flower process commands | Demonstration plus focused tests |
| 6 | 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 celery import Celery2from celery.schedules import crontab3
4app = Celery("reports")5app.conf.update(6 broker_url="redis://redis:6379/0",7 result_backend="redis://redis:6379/1",8 result_expires=3600,9 beat_schedule={10 "daily-summary": {11 "task": "reports.daily_summary",12 "schedule": crontab(hour=9, minute=0),13 }14 },15)16
17@app.task(bind=True, autoretry_for=(TimeoutError,), retry_backoff=True, max_retries=4)18def build_report(self, report_id: str) -> str:19 report = load_report(report_id)20 if report.status == "complete":21 return report.location22 return generate_and_store(report)Expected result
1Beat publishes the scheduled task; repeated report delivery returns the already completed location.Code reading
| Line | Code | Explanation |
|---|---|---|
| 1 | from celery import Celery | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 2 | from celery.schedules import crontab | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 4 | app = Celery("reports") | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 5 | app.conf.update( | Implements the next python statement in the example's data flow. |
| 6 | broker_url="redis://redis:6379/0", | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 7 | result_backend="redis://redis:6379/1", | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 8 | result_expires=3600, | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 9 | beat_schedule={ | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 10 | "daily-summary": { | Implements the next python statement in the example's data flow. |
| 11 | "task": "reports.daily_summary", | Implements the next python statement in the example's data flow. |
| 12 | "schedule": crontab(hour=9, minute=0), | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 13 | } | Implements the next python statement in the example's data flow. |
| 14 | }, | Implements the next python statement in the example's data flow. |
| 15 | ) | Implements the next python statement in the example's data flow. |
| 17 | @app.task(bind=True, autoretry_for=(TimeoutError,), retry_backoff=True, max_retries=4) | Applies a decorator or framework annotation before the following definition is bound. |
| 18 | def build_report(self, report_id: str) -> str: | Defines a function; its parameters form the explicit input boundary. |
| 19 | report = load_report(report_id) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 20 | if report.status == "complete": | Evaluates the condition and enters this branch only when it is truthy. |
| 21 | return report.location | Returns the observable result to the caller and ends this invocation. |
| 22 | return generate_and_store(report) | Returns the observable result to the caller and ends this invocation. |
Risk register
| Area | Failure to reproduce | Required design response |
|---|---|---|
| Task definition & calling | Waiting synchronously on a task result inside a request defeats decoupling and can deadlock workflows. | Pass small JSON-compatible arguments and track a domain job record when user-visible state matters. |
| Brokers & result backends | Do not use a result backend as the only system of record. | Expire unneeded results and encrypt or avoid sensitive payloads. |
| Celery Beat (periodic tasks) | Multiple beat instances can duplicate work. | Make periodic tasks idempotent and protect against overlapping runs. |
| Monitoring | Event monitoring adds overhead and may be incomplete; reconcile with domain records. | Alert on sustained backlog age and failure rate, not on a single retry. |
| Complete Django integration | A timeout shorter than legitimate work duplicates long tasks; an enormous timeout delays recovery after a worker dies. | Set the timeout above expected task runtime or use task designs that checkpoint safely, bound pools across all processes, and monitor redelivery plus connection pressure. |
Engineering checklist for this stack
- To do: assign stable message and operation identities
- To do: acknowledge only after the intended durable outcome
- To do: make handlers idempotent
- To do: bound retry and route terminal failures
- To do: monitor age, lag, duplicates, and stranded work
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?