Project Workshop — E-commerce Analytics 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
PostgreSQL · pgvector · Redis Cluster · Celery · FastAPI · Docker · locust
Expected effort: 10–16 focused hours · Minimum meaningful tests: 24What 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 | orders (range-partitioned by month) produces the specified behavior inside Schema design | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.2 | products (pgvector semantic search column) produces the specified behavior inside Schema design | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.3 | events (BRIN index on timestamp) produces the specified behavior inside Schema design | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.4 | materialized_reports table produces the specified behavior inside Schema design | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.1 | GET /dashboard → Redis cache <50ms, fallback <500ms produces the specified behavior inside Endpoints with targets | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.2 | GET /products/search → hybrid pgvector <100ms/50k produces the specified behavior inside Endpoints with targets | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.3 | GET /orders/analytics → window functions <2s/1yr produces the specified behavior inside Endpoints with targets | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.4 | POST /orders → Redlock 1000 req/sec produces the specified behavior inside Endpoints with targets | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.1 | Docker Compose: FastAPI/PostgreSQL/Redis Cluster/Celery produces the specified behavior inside Infrastructure | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.2 | Redis key schema documentation produces the specified behavior inside Infrastructure | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.3 | locust load test scripts produces the specified behavior inside Infrastructure | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.4 | EXPLAIN ANALYZE for all critical queries produces the specified behavior inside Infrastructure | 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 | Schema design | orders (range-partitioned by month); products (pgvector semantic search column); events (BRIN index on timestamp) | Demonstration plus focused tests |
| 2 | Endpoints with targets | GET /dashboard → Redis cache <50ms, fallback <500ms; GET /products/search → hybrid pgvector <100ms/50k; GET /orders/analytics → window functions <2s/1yr | Demonstration plus focused tests |
| 3 | Infrastructure | Docker Compose: FastAPI/PostgreSQL/Redis Cluster/Celery; Redis key schema documentation; locust load test scripts | Demonstration plus focused tests |
| 4 | 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
1CREATE TABLE orders (2 id bigint GENERATED ALWAYS AS IDENTITY,3 customer_id bigint NOT NULL,4 created_at timestamptz NOT NULL,5 total numeric(14,2) NOT NULL CHECK (total >= 0),6 PRIMARY KEY (created_at, id)7) PARTITION BY RANGE (created_at);8
9CREATE INDEX orders_customer_recent10 ON orders (customer_id, created_at DESC, id DESC);11
12CREATE INDEX events_time_brin13 ON events USING brin (occurred_at) WITH (pages_per_range = 32);Expected result
1Monthly child partitions can be pruned; customer history has a matching B-tree path; append-ordered events use a compact BRIN summary.Code reading
| Line | Code | Explanation |
|---|---|---|
| 1 | CREATE TABLE orders ( | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 2 | id bigint GENERATED ALWAYS AS IDENTITY, | Implements the next sql statement in the example's data flow. |
| 3 | customer_id bigint NOT NULL, | Implements the next sql statement in the example's data flow. |
| 4 | created_at timestamptz NOT NULL, | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 5 | total numeric(14,2) NOT NULL CHECK (total >= 0), | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 6 | PRIMARY KEY (created_at, id) | Implements the next sql statement in the example's data flow. |
| 7 | ) PARTITION BY RANGE (created_at); | Implements the next sql statement in the example's data flow. |
| 9 | CREATE INDEX orders_customer_recent | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 10 | ON orders (customer_id, created_at DESC, id DESC); | Implements the next sql statement in the example's data flow. |
| 12 | CREATE INDEX events_time_brin | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 13 | ON events USING brin (occurred_at) WITH (pages_per_range = 32); | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
Risk register
| Area | Failure to reproduce | Required design response |
|---|---|---|
| Schema design | Refreshing without idempotency or a source watermark can double-count events and serve a mixture of calculation versions. | Use it when freshness requirements allow derived state, and expose freshness/version so clients and operators can judge the result. |
| Endpoints with targets | A paused client can outlive its lease and still act; ownership tokens alone do not stop stale writes. | Prefer database constraints for data invariants; use leases for bounded coordination and add fencing for critical resources. |
| Infrastructure | A long transaction prevents cleanup, and EXPLAIN ANALYZE executes the statement. | Use EXPLAIN (ANALYZE, BUFFERS) safely on representative data and tune autovacuum per table when needed. |
Engineering checklist for this stack
- To do: deliver reviewable vertical slices
- To do: keep authoritative and derived state distinct
- To do: make every external effect retry-safe
- To do: integrate security and observability before the final sprint
- To do: publish reproducible demo and failure evidence
Test strategy
Implement at least 24 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 | 16 | 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?