Project Workshop — Real-time Notifications
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
Django · Celery · Redis · Channels
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 | pre/post_save, pre/post_delete, m2m_changed produces the specified behavior inside Signals | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.2 | @receiver decorator vs connect() produces the specified behavior inside Signals | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.3 | infinite loop prevention (update_fields guard) produces the specified behavior inside Signals | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.1 | middleware order and onion model produces the specified behavior inside Middleware | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.2 | class-based middleware produces the specified behavior inside Middleware | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.3 | RequestLoggingMiddleware/CorrelationIDMiddleware produces the specified behavior inside Middleware | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.1 | BaseCommand/handle()/add_arguments() produces the specified behavior inside Custom management commands | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.2 | tqdm progress bars produces the specified behavior inside Custom management commands | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.3 | expire_old_listings example produces the specified behavior inside Custom management commands | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.1 | CELERY_BROKER_URL/RESULT_BACKEND setup produces the specified behavior inside Celery integration | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.2 | @shared_task decorator produces the specified behavior inside Celery integration | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.3 | Flower monitoring produces the specified behavior inside Celery integration | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.4 | Celery Beat crontab produces the specified behavior inside Celery integration | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.5 | autoretry_for + exponential backoff produces the specified behavior inside Celery integration | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.1 | ASGI vs WSGI produces the specified behavior inside Django Channels (WebSockets) | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.2 | channel layers with Redis produces the specified behavior inside Django Channels (WebSockets) | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.3 | WebSocketConsumer: connect/disconnect/receive produces the specified behavior inside Django Channels (WebSockets) | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.4 | Groups and broadcasting produces the specified behavior inside Django Channels (WebSockets) | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
Suggested repository structure
1project/2├── manage.py3├── config/{settings,urls,asgi,celery}.py4├── domain/5│ ├── models.py6│ ├── services.py7│ ├── selectors.py8│ ├── serializers-or-schema.py9│ ├── views-or-resolvers.py10│ ├── permissions.py11│ ├── tasks.py12│ └── consumers.py13├── templates/14├── tests/{unit,api,integration}/15├── pyproject.toml16└── compose.yamlBuild plan: vertical slices
| Milestone | Capability | First implementation | Exit condition |
|---|---|---|---|
| 1 | Signals | pre/post_save, pre/post_delete, m2m_changed; @receiver decorator vs connect(); infinite loop prevention (update_fields guard) | Demonstration plus focused tests |
| 2 | Middleware | middleware order and onion model; class-based middleware; RequestLoggingMiddleware/CorrelationIDMiddleware | Demonstration plus focused tests |
| 3 | Custom management commands | BaseCommand/handle()/add_arguments(); tqdm progress bars; expire_old_listings example | Demonstration plus focused tests |
| 4 | Celery integration | CELERY_BROKER_URL/RESULT_BACKEND setup; @shared_task decorator; Flower monitoring | Demonstration plus focused tests |
| 5 | Django Channels (WebSockets) | ASGI vs WSGI; channel layers with Redis; WebSocketConsumer: connect/disconnect/receive | 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
1# signals.py2from django.db import transaction3from django.db.models.signals import post_save4from django.dispatch import receiver5
6@receiver(post_save, sender=Task)7def publish_assignment(sender, instance: Task, created: bool, **kwargs):8 if not instance.assignee_id:9 return10 transaction.on_commit(11 lambda: notify_assignment.delay(str(instance.pk), instance.assignee_id)12 )13
14# tasks.py15@shared_task(autoretry_for=(TimeoutError,), retry_backoff=True, max_retries=5)16def notify_assignment(task_id: str, user_id: int) -> None:17 notification, created = Notification.objects.get_or_create(18 event_key=f"task-assigned:{task_id}:{user_id}",19 defaults={"user_id": user_id, "message": "A task was assigned"},20 )21 if created:22 send_realtime(notification)Expected result
1After commit, one idempotent notification is stored and broadcast; transient failures retry.Code reading
| Line | Code | Explanation |
|---|---|---|
| 1 | # signals.py | Implements the next python statement in the example's data flow. |
| 2 | from django.db import transaction | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 3 | from django.db.models.signals import post_save | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 4 | from django.dispatch import receiver | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 6 | @receiver(post_save, sender=Task) | Applies a decorator or framework annotation before the following definition is bound. |
| 7 | def publish_assignment(sender, instance: Task, created: bool, **kwargs): | Defines a function; its parameters form the explicit input boundary. |
| 8 | if not instance.assignee_id: | Evaluates the condition and enters this branch only when it is truthy. |
| 9 | return | Returns the observable result to the caller and ends this invocation. |
| 10 | transaction.on_commit( | Implements the next python statement in the example's data flow. |
| 11 | lambda: notify_assignment.delay(str(instance.pk), instance.assignee_id) | Implements the next python statement in the example's data flow. |
| 12 | ) | Implements the next python statement in the example's data flow. |
| 14 | # tasks.py | Implements the next python statement in the example's data flow. |
| 15 | @shared_task(autoretry_for=(TimeoutError,), retry_backoff=True, max_retries=5) | Applies a decorator or framework annotation before the following definition is bound. |
| 16 | def notify_assignment(task_id: str, user_id: int) -> None: | Defines a function; its parameters form the explicit input boundary. |
| 17 | notification, created = Notification.objects.get_or_create( | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 18 | event_key=f"task-assigned:{task_id}:{user_id}", | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 19 | defaults={"user_id": user_id, "message": "A task was assigned"}, | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 20 | ) | Implements the next python statement in the example's data flow. |
| 21 | if created: | Evaluates the condition and enters this branch only when it is truthy. |
| 22 | send_realtime(notification) | Implements the next python statement in the example's data flow. |
Risk register
| Area | Failure to reproduce | Required design response |
|---|---|---|
| Signals | Recursive saves, hidden control flow, and work published before commit cause subtle failures. | Use signals sparingly for secondary effects and make receivers idempotent. |
| Middleware | Order matters; broad exception swallowing and body buffering can break streaming. | Use it for correlation, security headers, timing, and protocol-level concerns. |
| Custom management commands | Do not load an unbounded table into memory or make partial failure impossible to resume. | Make reruns safe, support dry-run and batching, and emit progress. |
| Celery integration | Retrying validation errors or non-idempotent external writes can amplify damage. | Retry transient failures only and cap attempts and total age. |
| Django Channels (WebSockets) | Never assume one process owns every room or trust a room identifier supplied by the client. | Authenticate during connection establishment and design reconnect, heartbeat, and backpressure behavior. |
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
1def test_list_is_authorized_and_query_bounded(api_client, member, project, django_assert_num_queries):2 api_client.force_authenticate(member)3 with django_assert_num_queries(3):4 response = api_client.get("/api/resources/")5 assert response.status_code == 2006 assert all(item["project_id"] == str(project.id) for item in response.data["results"])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?