Project Workshop — Order System + Redis Streams
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
Redis Streams · Lua · aioredis · FastAPI
Expected effort: 30–48 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 | hash slots (16384) and slot assignment produces the specified behavior inside Redis Cluster & Sentinel | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.2 | CLUSTER INFO/NODES commands produces the specified behavior inside Redis Cluster & Sentinel | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.3 | RedisCluster client in redis-py produces the specified behavior inside Redis Cluster & Sentinel | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.4 | Sentinel quorum and automatic failover produces the specified behavior inside Redis Cluster & Sentinel | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.1 | XADD/XREAD/XREADGROUP/XACK produces the specified behavior inside Redis Streams | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.2 | consumer groups in Streams (vs Pub/Sub) produces the specified behavior inside Redis Streams | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.3 | Pending Entry List (PEL) for at-least-once produces the specified behavior inside Redis Streams | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.4 | XAUTOCLAIM for stale messages produces the specified behavior inside Redis Streams | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.1 | EVAL and EVALSHA produces the specified behavior inside Lua scripting | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.2 | why Lua scripts are atomic produces the specified behavior inside Lua scripting | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.3 | SCRIPT LOAD for caching produces the specified behavior inside Lua scripting | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.4 | atomic rate limiter in Lua produces the specified behavior inside Lua scripting | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.1 | online cluster resharding and slot migration produces the specified behavior inside Operations & testing | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.2 | Lua atomic stock deduction with non-negative invariant produces the specified behavior inside Operations & testing | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.3 | redis-py asyncio lifecycle produces the specified behavior inside Operations & testing | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.4 | fakeredis unit tests vs real Redis integration tests produces the specified behavior inside Operations & testing | 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 | Redis Cluster & Sentinel | hash slots (16384) and slot assignment; CLUSTER INFO/NODES commands; RedisCluster client in redis-py | Demonstration plus focused tests |
| 2 | Redis Streams | XADD/XREAD/XREADGROUP/XACK; consumer groups in Streams (vs Pub/Sub); Pending Entry List (PEL) for at-least-once | Demonstration plus focused tests |
| 3 | Lua scripting | EVAL and EVALSHA; why Lua scripts are atomic; SCRIPT LOAD for caching | Demonstration plus focused tests |
| 4 | Operations & testing | online cluster resharding and slot migration; Lua atomic stock deduction with non-negative invariant; redis-py asyncio lifecycle | 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
1-- Atomic fixed-window limit; KEYS[1] is already hash-slot safe.2local current = redis.call('INCR', KEYS[1])3if current == 1 then4 redis.call('PEXPIRE', KEYS[1], ARGV[1])5end6if current > tonumber(ARGV[2]) then7 return {0, current, redis.call('PTTL', KEYS[1])}8end9return {1, current, redis.call('PTTL', KEYS[1])}Expected result
1Returns allowed flag, observed count, and remaining window TTL as one atomic result.Code reading
| Line | Code | Explanation |
|---|---|---|
| 1 | -- Atomic fixed-window limit; KEYS[1] is already hash-slot safe. | Implements the next lua statement in the example's data flow. |
| 2 | local current = redis.call('INCR', KEYS[1]) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 3 | if current == 1 then | Evaluates the condition and enters this branch only when it is truthy. |
| 4 | redis.call('PEXPIRE', KEYS[1], ARGV[1]) | Implements the next lua statement in the example's data flow. |
| 5 | end | Implements the next lua statement in the example's data flow. |
| 6 | if current > tonumber(ARGV[2]) then | Evaluates the condition and enters this branch only when it is truthy. |
| 7 | return {0, current, redis.call('PTTL', KEYS[1])} | Returns the observable result to the caller and ends this invocation. |
| 8 | end | Implements the next lua statement in the example's data flow. |
| 9 | return {1, current, redis.call('PTTL', KEYS[1])} | Returns the observable result to the caller and ends this invocation. |
Risk register
| Area | Failure to reproduce | Required design response |
|---|---|---|
| Redis Cluster & Sentinel | Asynchronous replication can lose acknowledged writes during failover. | Use hash tags only for deliberate multi-key colocation and test failover behavior. |
| Redis Streams | Redis Stream consumer groups are not Kafka partition groups: several consumers can own different entry IDs without persistent partition ownership. | Bound retention, monitor pending age, make handlers idempotent, and recover pending entries before reading only new ones. |
| Lua scripting | Application throttles are not a substitute for edge protection, and offset pagination drifts under concurrent writes. | Use deterministic unique ordering and return retry metadata. |
| Operations & testing | The word migration here means moving Redis slots or topology state, not a Django schema migration. | Test topology changes with production-compatible clients, assert timeouts and retry bounds, and distinguish fast unit fakes from real integration behavior. |
Engineering checklist for this stack
- To do: protect invariants with constraints and transactions
- To do: parameterize every value
- To do: measure representative plans and memory
- To do: bound cardinality and retention
- To do: document recovery, backup, or rebuild 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.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?